| 1 | import chalk from "chalk"; |
| 2 | |
| 3 | import { env } from "../env.js"; |
| 4 | import { formatError } from "../util/formatError.js"; |
| 5 | import { getGitDiffSnapshot } from "../util/git.js"; |
| 6 | import { logger } from "../util/logger.js"; |
| 7 | |
| 8 | import type { StorageSyncServiceState } from "./types.js"; |
| 9 | |
| 10 | const DEFAULT_UPLOAD_INTERVAL_MS = 30_000; |
| 11 | |
| 12 | type StoragePresignedLocation = { |
| 13 | key: string; |
| 14 | putUrl: string; |
| 15 | }; |
| 16 | |
| 17 | type StoragePresignResponse = { |
| 18 | session?: StoragePresignedLocation; |
| 19 | diff?: StoragePresignedLocation; |
| 20 | }; |
| 21 | |
| 22 | type StorageTargets = { |
| 23 | sessionUrl: string; |
| 24 | diffUrl: string; |
| 25 | }; |
| 26 | |
| 27 | export interface StorageSyncStartOptions { |
| 28 | storageId: string; |
| 29 | accessToken: string; |
| 30 | intervalMs?: number; |
| 31 | syncSessionHistory: () => void; |
| 32 | getSessionSnapshot: () => unknown; |
| 33 | isActive?: () => boolean; |
| 34 | } |
| 35 | |
| 36 | export class StorageSyncService { |
| 37 | private state: StorageSyncServiceState = { |
| 38 | isEnabled: false, |
| 39 | lastError: null, |
| 40 | }; |
| 41 | |
| 42 | private intervalHandle: NodeJS.Timeout | null = null; |
| 43 | private stopped = true; |
| 44 | private uploadInFlight = false; |
| 45 | private missingRepoLogged = false; |
| 46 | private targets: StorageTargets | null = null; |
| 47 | private options: StorageSyncStartOptions | null = null; |
| 48 | |
| 49 | async initialize(): Promise<StorageSyncServiceState> { |
| 50 | this.stop(); |
| 51 | return this.getState(); |
| 52 | } |
| 53 | |
| 54 | getState(): StorageSyncServiceState { |
| 55 | return { ...this.state }; |
| 56 | } |
| 57 | |
| 58 | getDefaultInterval(): number { |
| 59 | return DEFAULT_UPLOAD_INTERVAL_MS; |
| 60 | } |
| 61 | |
| 62 | async startFromOptions( |
| 63 | options: { |
| 64 | storageOption?: string; |
| 65 | accessToken?: string | null; |
| 66 | } & Omit<StorageSyncStartOptions, "storageId" | "accessToken">, |
| 67 | ): Promise<boolean> { |
| 68 | const { storageOption, accessToken, ...rest } = options; |
| 69 | |
| 70 | if (!storageOption) { |
| 71 | return false; |
| 72 | } |
| 73 | |
| 74 | const storageId = storageOption.trim(); |
| 75 | if (!storageId) { |
| 76 | logger.warn( |
| 77 | "Storage sync requested but the provided storage identifier was empty; skipping uploads.", |
| 78 | ); |
| 79 | return false; |
| 80 | } |
| 81 | |
| 82 | if (!accessToken) { |
| 83 | logger.warn( |
| 84 | "Storage sync requested but no Continue API key is available; skipping uploads.", |
| 85 | ); |
| 86 | return false; |
| 87 | } |
| 88 | |
| 89 | return this.start({ |
| 90 | storageId, |
| 91 | accessToken, |
| 92 | ...rest, |
| 93 | }); |
| 94 | } |
| 95 | |
| 96 | async start(options: StorageSyncStartOptions): Promise<boolean> { |
| 97 | // Ensure any existing sync loop is stopped before starting a new one |
| 98 | this.stop(); |
| 99 | |
| 100 | const targets = await this.requestStorageTargets( |
| 101 | options.storageId, |
| 102 | options.accessToken, |
| 103 | ); |
| 104 | |
| 105 | if (!targets) { |
| 106 | this.setState({ |
| 107 | isEnabled: false, |
| 108 | storageId: options.storageId, |
| 109 | lastError: "Failed to obtain presigned URLs", |
| 110 | }); |
| 111 | return false; |
| 112 | } |
| 113 | |
| 114 | this.targets = targets; |
| 115 | this.options = options; |
| 116 | this.stopped = false; |
| 117 | this.uploadInFlight = false; |
| 118 | this.missingRepoLogged = false; |
| 119 | this.setState({ |
| 120 | isEnabled: true, |
| 121 | storageId: options.storageId, |
| 122 | lastError: null, |
| 123 | lastUploadAt: undefined, |
| 124 | }); |
| 125 | |
| 126 | const intervalMs = options.intervalMs ?? DEFAULT_UPLOAD_INTERVAL_MS; |
| 127 | logger.info( |
| 128 | chalk.dim( |
| 129 | `Storage sync enabled (uploading every ${Math.round(intervalMs / 1000)}s)`, |
| 130 | ), |
| 131 | ); |
| 132 | |
| 133 | await this.performUpload(); |
| 134 | |
| 135 | this.intervalHandle = setInterval(() => { |
| 136 | void this.performUpload(); |
| 137 | }, intervalMs); |
| 138 | |
| 139 | return true; |
| 140 | } |
| 141 | |
| 142 | stop(): void { |
| 143 | this.stopped = true; |
| 144 | this.targets = null; |
| 145 | this.options = null; |
| 146 | this.uploadInFlight = false; |
| 147 | |
| 148 | if (this.intervalHandle) { |
| 149 | clearInterval(this.intervalHandle); |
| 150 | this.intervalHandle = null; |
| 151 | } |
| 152 | |
| 153 | if (this.state.isEnabled) { |
| 154 | this.setState({ |
| 155 | isEnabled: false, |
| 156 | storageId: this.state.storageId, |
| 157 | lastError: null, |
| 158 | lastUploadAt: this.state.lastUploadAt, |
| 159 | }); |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | private setState(next: StorageSyncServiceState): void { |
| 164 | this.state = { ...next }; |
| 165 | } |
| 166 | |
| 167 | private async requestStorageTargets( |
| 168 | storageId: string, |
| 169 | accessToken: string, |
| 170 | ): Promise<StorageTargets | null> { |
| 171 | const url = new URL("agents/storage/presigned-url", env.apiBase); |
| 172 | |
| 173 | try { |
| 174 | const response = await fetch(url, { |
| 175 | method: "POST", |
| 176 | headers: { |
| 177 | "Content-Type": "application/json", |
| 178 | Authorization: `Bearer ${accessToken}`, |
| 179 | }, |
| 180 | body: JSON.stringify({ storageId }), |
| 181 | }); |
| 182 | |
| 183 | if (!response.ok) { |
| 184 | const statusText = `${response.status} ${response.statusText}`.trim(); |
| 185 | logger.warn( |
| 186 | `Storage sync presign request failed (${statusText}). Storage uploads disabled for this session.`, |
| 187 | ); |
| 188 | return null; |
| 189 | } |
| 190 | |
| 191 | const body = (await response.json()) as StoragePresignResponse; |
| 192 | |
| 193 | if (!body.session?.putUrl || !body.diff?.putUrl) { |
| 194 | logger.warn( |
| 195 | "Storage sync presign response missing required URLs. Storage uploads disabled for this session.", |
| 196 | ); |
| 197 | return null; |
| 198 | } |
| 199 | |
| 200 | return { |
| 201 | sessionUrl: body.session.putUrl, |
| 202 | diffUrl: body.diff.putUrl, |
| 203 | }; |
| 204 | } catch (error) { |
| 205 | logger.warn( |
| 206 | `Storage sync presign request failed: ${formatError(error)}. Storage uploads disabled for this session.`, |
| 207 | ); |
| 208 | return null; |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | private async uploadToPresignedUrl( |
| 213 | url: string, |
| 214 | body: string, |
| 215 | contentType: string, |
| 216 | ): Promise<void> { |
| 217 | const response = await fetch(url, { |
| 218 | method: "PUT", |
| 219 | headers: { |
| 220 | "Content-Type": contentType, |
| 221 | }, |
| 222 | body, |
| 223 | }); |
| 224 | |
| 225 | if (!response.ok) { |
| 226 | const statusText = `${response.status} ${response.statusText}`.trim(); |
| 227 | throw new Error(`Storage upload failed (${statusText})`); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | private async performUpload(): Promise<void> { |
| 232 | if (this.stopped || this.uploadInFlight || !this.targets || !this.options) { |
| 233 | return; |
| 234 | } |
| 235 | |
| 236 | if (this.options.isActive && !this.options.isActive()) { |
| 237 | return; |
| 238 | } |
| 239 | |
| 240 | this.uploadInFlight = true; |
| 241 | |
| 242 | try { |
| 243 | this.options.syncSessionHistory(); |
| 244 | const snapshot = this.options.getSessionSnapshot(); |
| 245 | const sessionPayload = JSON.stringify(snapshot, null, 2); |
| 246 | await this.uploadToPresignedUrl( |
| 247 | this.targets.sessionUrl, |
| 248 | sessionPayload, |
| 249 | "application/json", |
| 250 | ); |
| 251 | |
| 252 | const diffResult = await getGitDiffSnapshot(); |
| 253 | if (!diffResult.repoFound && !this.missingRepoLogged) { |
| 254 | logger.debug( |
| 255 | "Storage sync diff upload skipped: not in a git repository or main branch missing.", |
| 256 | ); |
| 257 | this.missingRepoLogged = true; |
| 258 | } |
| 259 | await this.uploadToPresignedUrl( |
| 260 | this.targets.diffUrl, |
| 261 | diffResult.diff, |
| 262 | "text/plain", |
| 263 | ); |
| 264 | |
| 265 | this.setState({ |
| 266 | isEnabled: true, |
| 267 | storageId: this.state.storageId, |
| 268 | lastUploadAt: Date.now(), |
| 269 | lastError: null, |
| 270 | }); |
| 271 | } catch (error) { |
| 272 | this.setState({ |
| 273 | isEnabled: true, |
| 274 | storageId: this.state.storageId, |
| 275 | lastUploadAt: this.state.lastUploadAt, |
| 276 | lastError: formatError(error), |
| 277 | }); |
| 278 | logger.warn(`Storage sync upload failed: ${formatError(error)}`); |
| 279 | } finally { |
| 280 | this.uploadInFlight = false; |
| 281 | } |
| 282 | } |
| 283 | } |