| 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 | getCompleteStateSnapshot: () => 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 | async markAgentStatusUnread(): Promise<void> { |
| 143 | const storageId = this.options?.storageId; |
| 144 | const accessToken = this.options?.accessToken; |
| 145 | |
| 146 | if (!storageId || !accessToken) { |
| 147 | return; |
| 148 | } |
| 149 | |
| 150 | const url = new URL( |
| 151 | `agents/${encodeURIComponent(storageId)}/read-status`, |
| 152 | env.apiBase, |
| 153 | ); |
| 154 | |
| 155 | try { |
| 156 | const response = await fetch(url, { |
| 157 | method: "POST", |
| 158 | headers: { |
| 159 | "Content-Type": "application/json", |
| 160 | Authorization: `Bearer ${accessToken}`, |
| 161 | }, |
| 162 | body: JSON.stringify({ unread: true }), |
| 163 | }); |
| 164 | |
| 165 | if (!response.ok) { |
| 166 | const statusText = `${response.status} ${response.statusText}`.trim(); |
| 167 | logger.debug( |
| 168 | `Failed to mark agent session unread (${statusText || "unknown error"}).`, |
| 169 | ); |
| 170 | } |
| 171 | } catch (error) { |
| 172 | logger.debug( |
| 173 | `Failed to mark agent session unread: ${formatError(error)}`, |
| 174 | ); |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | stop(): void { |
| 179 | this.stopped = true; |
| 180 | this.targets = null; |
| 181 | this.options = null; |
| 182 | this.uploadInFlight = false; |
| 183 | |
| 184 | if (this.intervalHandle) { |
| 185 | clearInterval(this.intervalHandle); |
| 186 | this.intervalHandle = null; |
| 187 | } |
| 188 | |
| 189 | if (this.state.isEnabled) { |
| 190 | this.setState({ |
| 191 | isEnabled: false, |
| 192 | storageId: this.state.storageId, |
| 193 | lastError: null, |
| 194 | lastUploadAt: this.state.lastUploadAt, |
| 195 | }); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | private setState(next: StorageSyncServiceState): void { |
| 200 | this.state = { ...next }; |
| 201 | } |
| 202 | |
| 203 | private async requestStorageTargets( |
| 204 | storageId: string, |
| 205 | accessToken: string, |
| 206 | ): Promise<StorageTargets | null> { |
| 207 | const url = new URL("agents/storage/presigned-url", env.apiBase); |
| 208 | |
| 209 | try { |
| 210 | const response = await fetch(url, { |
| 211 | method: "POST", |
| 212 | headers: { |
| 213 | "Content-Type": "application/json", |
| 214 | Authorization: `Bearer ${accessToken}`, |
| 215 | }, |
| 216 | body: JSON.stringify({ storageId }), |
| 217 | }); |
| 218 | |
| 219 | if (!response.ok) { |
| 220 | const statusText = `${response.status} ${response.statusText}`.trim(); |
| 221 | logger.warn( |
| 222 | `Storage sync presign request failed (${statusText}). Storage uploads disabled for this session.`, |
| 223 | ); |
| 224 | return null; |
| 225 | } |
| 226 | |
| 227 | const body = (await response.json()) as StoragePresignResponse; |
| 228 | |
| 229 | if (!body.session?.putUrl || !body.diff?.putUrl) { |
| 230 | logger.warn( |
| 231 | "Storage sync presign response missing required URLs. Storage uploads disabled for this session.", |
| 232 | ); |
| 233 | return null; |
| 234 | } |
| 235 | |
| 236 | return { |
| 237 | sessionUrl: body.session.putUrl, |
| 238 | diffUrl: body.diff.putUrl, |
| 239 | }; |
| 240 | } catch (error) { |
| 241 | logger.warn( |
| 242 | `Storage sync presign request failed: ${formatError(error)}. Storage uploads disabled for this session.`, |
| 243 | ); |
| 244 | return null; |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | private async uploadToPresignedUrl( |
| 249 | url: string, |
| 250 | body: string, |
| 251 | contentType: string, |
| 252 | ): Promise<void> { |
| 253 | // Parse the URL to extract any required headers from the query parameters |
| 254 | const parsedUrl = new URL(url); |
| 255 | const headers: Record<string, string> = { |
| 256 | "Content-Type": contentType, |
| 257 | }; |
| 258 | |
| 259 | // Check if the presigned URL includes server-side encryption in signed headers |
| 260 | const signedHeaders = parsedUrl.searchParams.get("X-Amz-SignedHeaders"); |
| 261 | if (signedHeaders?.includes("x-amz-server-side-encryption")) { |
| 262 | headers["x-amz-server-side-encryption"] = "AES256"; |
| 263 | } |
| 264 | |
| 265 | const response = await fetch(url, { |
| 266 | method: "PUT", |
| 267 | headers, |
| 268 | body, |
| 269 | }); |
| 270 | |
| 271 | if (!response.ok) { |
| 272 | const statusText = `${response.status} ${response.statusText}`.trim(); |
| 273 | const responseBody = await response.text(); |
| 274 | throw new Error(`Storage upload failed (${statusText}): ${responseBody}`); |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | private async performUpload(): Promise<void> { |
| 279 | if (this.stopped || this.uploadInFlight || !this.targets || !this.options) { |
| 280 | return; |
| 281 | } |
| 282 | |
| 283 | if (this.options.isActive && !this.options.isActive()) { |
| 284 | return; |
| 285 | } |
| 286 | |
| 287 | // Capture references to prevent race condition with stop() |
| 288 | const targets = this.targets; |
| 289 | const options = this.options; |
| 290 | |
| 291 | this.uploadInFlight = true; |
| 292 | |
| 293 | try { |
| 294 | options.syncSessionHistory(); |
| 295 | const snapshot = options.getCompleteStateSnapshot(); |
| 296 | const sessionPayload = JSON.stringify(snapshot, null, 2); |
| 297 | await this.uploadToPresignedUrl( |
| 298 | targets.sessionUrl, |
| 299 | sessionPayload, |
| 300 | "application/json", |
| 301 | ); |
| 302 | |
| 303 | const diffResult = await getGitDiffSnapshot(); |
| 304 | if (!diffResult.repoFound && !this.missingRepoLogged) { |
| 305 | logger.debug( |
| 306 | "Storage sync diff upload skipped: not in a git repository or main branch missing.", |
| 307 | ); |
| 308 | this.missingRepoLogged = true; |
| 309 | } |
| 310 | await this.uploadToPresignedUrl( |
| 311 | targets.diffUrl, |
| 312 | diffResult.diff, |
| 313 | "text/plain", |
| 314 | ); |
| 315 | |
| 316 | this.setState({ |
| 317 | isEnabled: true, |
| 318 | storageId: this.state.storageId, |
| 319 | lastUploadAt: Date.now(), |
| 320 | lastError: null, |
| 321 | }); |
| 322 | } catch (error) { |
| 323 | this.setState({ |
| 324 | isEnabled: true, |
| 325 | storageId: this.state.storageId, |
| 326 | lastUploadAt: this.state.lastUploadAt, |
| 327 | lastError: formatError(error), |
| 328 | }); |
| 329 | logger.warn(`Storage sync upload failed: ${formatError(error)}`); |
| 330 | } finally { |
| 331 | this.uploadInFlight = false; |
| 332 | } |
| 333 | } |
| 334 | } |