Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

client.ts

816 lines27.3 KB

1/**
2 * Thin client over the Sprites control plane. Sprites has no published SDK, so
3 * this talks the REST + WebSocket API
4 * directly: lifecycle (create/get/delete), URL auth, filesystem, and process
5 * execution all go through the authenticated cloud endpoint at `baseUrl`.
6 *
7 * Dependency-free: uses the global `fetch` and `WebSocket` (undici). The exec
8 * control socket needs an `Authorization` header on the upgrade request —
9 * supported via undici's non-standard `headers` constructor option, which the
10 * WHATWG `WebSocket` spec does not define — so this targets the Node runtime
11 * (>= 22.4, where the global `WebSocket` is unflagged), not spec-compliant
12 * `WebSocket` environments (browsers, Deno, edge).
13 */
14​
15export const SPRITES_DEFAULT_BASE_URL = 'https://api.sprites.dev'
16​
17/** URL authentication mode for a Sprite's always-on public URL. */
18export type SpriteUrlAuth = 'public' | 'sprite'
19​
20/** A Sprite as returned by the control-plane API. */
21export interface SpriteResource {
22 id: string
23 name: string
24 status: string
25 /** Public URL, e.g. `https://<name>-<suffix>.sprites.app`. */
26 url: string
27 urlAuth?: SpriteUrlAuth
29​
30/** One entry returned by {@link SpritesClient.fsList}. */
31export interface SpriteFsEntry {
32 name: string
33 path: string
34 type: 'file' | 'dir'
36​
37/** A Sprite checkpoint (filesystem-overlay save point). */
38export interface SpriteCheckpoint {
39 /** Sequential version id, e.g. `v3`. The live overlay lists as `Current`. */
40 id: string
41 createTime?: string
42 comment?: string
43 /** `true` for platform-created automatic checkpoints. */
44 isAuto: boolean
46​
47/** Options for {@link SpritesClient.exec}. */
48export interface SpritesExecOptions {
49 /** Argument vector; `argv[0]` is the executable. */
50 argv: Array<string>
51 /** Working directory; defaults to the Sprite login dir when omitted. */
52 cwd?: string
53 /** Extra environment variables, merged over the Sprite defaults. */
54 env?: Record<string, string>
55 signal?: AbortSignal
56 /**
57 * Max ms to wait for the control socket to open before failing. Bounds the
58 * `CONNECTING`-stall case (e.g. probing a Sprite that is still restarting) so
59 * `wait()` cannot hang forever when no `signal` is supplied. Defaults to 30s.
60 */
61 connectTimeoutMs?: number
63​
64/** A live exec stream over the control WebSocket. */
65export interface SpritesExecStream {
66 stdout: AsyncIterable<string>
67 stderr: AsyncIterable<string>
68 /** Resolves with the exit code, or rejects on an abnormal close / abort. */
69 wait: () => Promise<number>
70 kill: () => Promise<void>
72​
73/** The subset of the client the {@link import('./handle').SpritesHandle} needs. */
74export interface SpritesClientLike {
75 readonly baseUrl: string
76 /** Authorization header for control-plane and authenticated proxy requests. */
77 authHeader: () => Record<string, string>
78 getSprite: (name: string, signal?: AbortSignal) => Promise<SpriteResource>
79 deleteSprite: (name: string, signal?: AbortSignal) => Promise<void>
80 setUrlAuth: (
81 name: string,
82 auth: SpriteUrlAuth,
83 signal?: AbortSignal,
84 ) => Promise<void>
85 fsRead: (name: string, path: string) => Promise<Uint8Array>
86 fsWrite: (name: string, path: string, data: Uint8Array) => Promise<void>
87 fsList: (name: string, path: string) => Promise<Array<SpriteFsEntry>>
88 exec: (name: string, options: SpritesExecOptions) => SpritesExecStream
89 createCheckpoint: (
90 name: string,
91 options?: { comment?: string; signal?: AbortSignal },
92 ) => Promise<string>
93 listCheckpoints: (
94 name: string,
95 signal?: AbortSignal,
96 ) => Promise<Array<SpriteCheckpoint>>
97 restoreCheckpoint: (
98 name: string,
99 id: string,
100 options?: {
101 signal?: AbortSignal
102 readyTimeoutMs?: number
103 probePath?: string
104 },
105 ) => Promise<void>
107​
108const WS_FRAME_STDOUT = 0x01
109const WS_FRAME_STDERR = 0x02
110const WS_FRAME_EXIT = 0x03
111​
112/** Constructor shape for the undici `WebSocket` with the `headers` option. */
113type WsCtor = new (
114 url: string,
115 options: { headers: Record<string, string> },
116) => WebSocket
117​
118/**
119 * A push-driven async iterable of decoded chunks. The producer pushes and calls
120 * `end()` once; consumers `for await` and terminate cleanly.
121 */
122class AsyncChunkQueue implements AsyncIterable<string> {
123 private readonly chunks: Array<string> = []
124 private readonly waiters: Array<(r: IteratorResult<string>) => void> = []
125 private ended = false
126​
127 push(chunk: string): void {
128 if (chunk === '') return
129 const waiter = this.waiters.shift()
130 if (waiter) waiter({ value: chunk, done: false })
131 else this.chunks.push(chunk)
132 }
133​
134 end(): void {
135 this.ended = true
136 let waiter = this.waiters.shift()
137 while (waiter) {
138 waiter({ value: undefined, done: true })
139 waiter = this.waiters.shift()
140 }
141 }
142​
143 [Symbol.asyncIterator](): AsyncIterator<string> {
144 return {
145 next: () => {
146 const chunk = this.chunks.shift()
147 if (chunk !== undefined) {
148 return Promise.resolve({ value: chunk, done: false })
149 }
150 if (this.ended) {
151 return Promise.resolve({ value: undefined, done: true })
152 }
153 return new Promise((resolve) => this.waiters.push(resolve))
154 },
155 }
156 }
158​
159export interface SpritesClientConfig {
160 apiKey: string
161 baseUrl?: string
163​
164export class SpritesClient implements SpritesClientLike {
165 readonly baseUrl: string
166 private readonly apiKey: string
167​
168 constructor(config: SpritesClientConfig) {
169 this.apiKey = config.apiKey
170 this.baseUrl = (config.baseUrl ?? SPRITES_DEFAULT_BASE_URL).replace(
171 /\/+$/,
172 '',
173 )
174 }
175​
176 private headers(extra?: Record<string, string>): Record<string, string> {
177 return { authorization: `Bearer ${this.apiKey}`, ...extra }
178 }
179​
180 authHeader(): Record<string, string> {
181 return { authorization: `Bearer ${this.apiKey}` }
182 }
183​
184 private spritePath(name: string, suffix = ''): string {
185 return `${this.baseUrl}/v1/sprites/${encodeURIComponent(name)}${suffix}`
186 }
187​
188 async createSprite(
189 name: string,
190 options: { waitForCapacity?: boolean; signal?: AbortSignal } = {},
191 ): Promise<SpriteResource> {
192 const response = await fetch(`${this.baseUrl}/v1/sprites`, {
193 method: 'POST',
194 headers: this.headers({ 'content-type': 'application/json' }),
195 body: JSON.stringify({
196 name,
197 ...(options.waitForCapacity !== undefined
198 ? { wait_for_capacity: options.waitForCapacity }
199 : {}),
200 }),
201 ...(options.signal ? { signal: options.signal } : {}),
202 })
203 if (!response.ok) {
204 await this.fail('POST', `${this.baseUrl}/v1/sprites`, response)
205 }
206 return parseSprite(await response.text())
207 }
208​
209 async getSprite(name: string, signal?: AbortSignal): Promise<SpriteResource> {
210 const response = await fetch(this.spritePath(name), {
211 method: 'GET',
212 headers: this.headers(),
213 ...(signal ? { signal } : {}),
214 })
215 if (!response.ok) await this.fail('GET', this.spritePath(name), response)
216 return parseSprite(await response.text())
217 }
218​
219 async deleteSprite(name: string, signal?: AbortSignal): Promise<void> {
220 const response = await fetch(this.spritePath(name), {
221 method: 'DELETE',
222 headers: this.headers(),
223 ...(signal ? { signal } : {}),
224 })
225 // A missing Sprite is already deleted.
226 if (!response.ok && response.status !== 404) {
227 await this.fail('DELETE', this.spritePath(name), response)
228 }
229 await response.body?.cancel()
230 }
231​
232 async setUrlAuth(
233 name: string,
234 auth: SpriteUrlAuth,
235 signal?: AbortSignal,
236 ): Promise<void> {
237 const response = await fetch(this.spritePath(name), {
238 method: 'PUT',
239 headers: this.headers({ 'content-type': 'application/json' }),
240 body: JSON.stringify({ url_settings: { auth } }),
241 ...(signal ? { signal } : {}),
242 })
243 if (!response.ok) await this.fail('PUT', this.spritePath(name), response)
244 await response.body?.cancel()
245 }
246​
247 async fsRead(name: string, path: string): Promise<Uint8Array> {
248 const url = this.spritePath(
249 name,
250 `/fs/read?path=${encodeURIComponent(path)}`,
251 )
252 const response = await fetch(url, {
253 method: 'GET',
254 headers: this.headers(),
255 })
256 if (!response.ok) await this.fail('GET', url, response)
257 return new Uint8Array(await response.arrayBuffer())
258 }
259​
260 async fsWrite(name: string, path: string, data: Uint8Array): Promise<void> {
261 const url = this.spritePath(
262 name,
263 `/fs/write?path=${encodeURIComponent(path)}`,
264 )
265 // Copy into a fresh ArrayBuffer-backed view so the body is a plain BodyInit.
266 const response = await fetch(url, {
267 method: 'PUT',
268 headers: this.headers({ 'content-type': 'application/octet-stream' }),
269 body: data.slice(),
270 })
271 if (!response.ok) await this.fail('PUT', url, response)
272 await response.body?.cancel()
273 }
274​
275 async fsList(name: string, path: string): Promise<Array<SpriteFsEntry>> {
276 const url = this.spritePath(
277 name,
278 `/fs/list?path=${encodeURIComponent(path)}`,
279 )
280 const response = await fetch(url, {
281 method: 'GET',
282 headers: this.headers(),
283 })
284 if (!response.ok) await this.fail('GET', url, response)
285 const body = (await response.json()) as {
286 entries?: Array<{ name?: unknown; path?: unknown; isDir?: unknown }>
287 }
288 return (body.entries ?? []).map((entry) => ({
289 name: String(entry.name ?? ''),
290 path: String(entry.path ?? ''),
291 type: entry.isDir === true ? ('dir' as const) : ('file' as const),
292 }))
293 }
294​
295 async listCheckpoints(
296 name: string,
297 signal?: AbortSignal,
298 ): Promise<Array<SpriteCheckpoint>> {
299 const url = this.spritePath(name, '/checkpoints')
300 const response = await fetch(url, {
301 method: 'GET',
302 headers: this.headers(),
303 ...(signal ? { signal } : {}),
304 })
305 if (!response.ok) await this.fail('GET', url, response)
306 const body = (await response.json()) as Array<{
307 id?: unknown
308 create_time?: unknown
309 comment?: unknown
310 is_auto?: unknown
311 }>
312 return body.map((entry) => ({
313 id: String(entry.id ?? ''),
314 ...(typeof entry.create_time === 'string'
315 ? { createTime: entry.create_time }
316 : {}),
317 ...(typeof entry.comment === 'string' ? { comment: entry.comment } : {}),
318 isAuto: entry.is_auto === true,
319 }))
320 }
321​
322 /**
323 * Create a checkpoint and return its new version id (e.g. `v3`). The create
324 * endpoint streams NDJSON progress; we drain it to completion, then resolve
325 * the new id as the highest sequential `vN` checkpoint (autos and the live
326 * `Current` pointer are ignored).
327 */
328 async createCheckpoint(
329 name: string,
330 options: { comment?: string; signal?: AbortSignal } = {},
331 ): Promise<string> {
332 // Snapshot the existing versions first so we can identify the one THIS call
333 // creates, rather than blindly returning the current max (which a concurrent
334 // create — e.g. handle.snapshot() racing an after-run snapshot — would make
335 // ambiguous, or an eventually-consistent list would make stale).
336 const before = new Set(await this.checkpointVersions(name, options.signal))
337​
338 const url = this.spritePath(name, '/checkpoint')
339 const response = await fetch(url, {
340 method: 'POST',
341 headers: this.headers({ 'content-type': 'application/json' }),
342 body: JSON.stringify(
343 options.comment !== undefined ? { comment: options.comment } : {},
344 ),
345 ...(options.signal ? { signal: options.signal } : {}),
346 })
347 if (!response.ok) await this.fail('POST', url, response)
348 // The create stream closes promptly; drain it so the checkpoint is committed
349 // before we read the list back, and mine it for the new version id.
350 const streamText = await response.text()
351 const streamVersions = [...streamText.matchAll(/\bv(\d+)\b/g)].map((m) =>
352 Number(m[1]),
353 )
354​
355 const after = await this.checkpointVersions(name, options.signal)
356 const fresh = after.filter((v) => !before.has(v))
357 // Prefer a version that did not exist before this call; fall back to the
358 // stream-reported version, then to the overall max.
359 const candidates = fresh.length > 0 ? fresh : streamVersions
360 const pool = candidates.length > 0 ? candidates : after
361 if (pool.length === 0) {
362 throw new Error(
363 `Sprites: checkpoint created for "${name}" but no versioned checkpoint was found.`,
364 )
365 }
366 return `v${Math.max(...pool)}`
367 }
368​
369 /** Numeric ids of the Sprite's non-auto `vN` checkpoints. */
370 private async checkpointVersions(
371 name: string,
372 signal?: AbortSignal,
373 ): Promise<Array<number>> {
374 return (await this.listCheckpoints(name, signal))
375 .filter((c) => !c.isAuto)
376 .map((c) => /^v(\d+)$/.exec(c.id))
377 .filter((m): m is RegExpExecArray => m !== null)
378 .map((m) => Number(m[1]))
379 }
380​
381 /**
382 * Restore a checkpoint in place. The Sprite's writable overlay is replaced and
383 * the environment restarts, so the agent is briefly unreachable.
384 *
385 * The restore endpoint streams progress but holds the connection open across
386 * the restart (it does not close cleanly), so we must NOT drain it — we cancel
387 * the body once the restore is accepted, then poll the filesystem until the
388 * Sprite is ready again (or `readyTimeoutMs`, default 600s, elapses). Restart
389 * can take minutes; raise `readyTimeoutMs` for large overlays. The caller's
390 * `signal` cancels the wait, not just the initial request.
391 */
392 async restoreCheckpoint(
393 name: string,
394 id: string,
395 options: {
396 signal?: AbortSignal
397 readyTimeoutMs?: number
398 /** Directory on the restored overlay used for the readiness probe. */
399 probePath?: string
400 } = {},
401 ): Promise<void> {
402 const url = this.spritePath(
403 name,
404 `/checkpoints/${encodeURIComponent(id)}/restore`,
405 )
406 const response = await fetch(url, {
407 method: 'POST',
408 headers: this.headers(),
409 ...(options.signal ? { signal: options.signal } : {}),
410 })
411 if (!response.ok) await this.fail('POST', url, response)
412 // The restore is server-side and asynchronous; the open NDJSON stream would
413 // block indefinitely, so release it and wait for readiness by polling.
414 await response.body?.cancel().catch(() => undefined)
415 // Let the restart begin before probing, so we don't get a stale success from
416 // the pre-restart agent.
417 await delay(3000, options.signal)
418 await this.waitUntilReady(
419 name,
420 options.readyTimeoutMs ?? 600_000,
421 options.probePath ?? '/',
422 options.signal,
423 )
424 }
425​
426 /**
427 * Poll the filesystem until the restored overlay actually serves reads, or
428 * time out. Uses `fetch` (not the exec WebSocket) so each attempt is reliably
429 * bounded by its abort signal — during a restart the socket can stall in
430 * CONNECTING without opening or closing.
431 *
432 * Probes a write→read round-trip of a sentinel under `probePath` rather than a
433 * directory listing: right after a restore the overlay becomes *listable
434 * before file reads work* (a transient I/O error), so listing alone reports
435 * ready too early. Two consecutive round-trips are required before the sentinel
436 * is removed and the Sprite is declared ready.
437 */
438 private async waitUntilReady(
439 name: string,
440 timeoutMs: number,
441 probePath: string,
442 signal?: AbortSignal,
443 ): Promise<void> {
444 const deadline = Date.now() + timeoutMs
445 const sentinel = `${probePath.replace(/\/$/, '')}/.tanstack-restore-probe`
446 const marker = `ready-${Date.now()}`
447 let lastError: unknown
448 let consecutive = 0
449 while (Date.now() < deadline) {
450 signal?.throwIfAborted()
451 try {
452 await this.probeReadWrite(name, sentinel, marker, signal)
453 consecutive += 1
454 if (consecutive >= 2) {
455 // Best-effort cleanup; ignore failures.
456 await this.deleteSentinel(name, sentinel).catch(() => undefined)
457 return
458 }
459 } catch (error) {
460 if (error instanceof Error && error.name === 'AbortError') throw error
461 consecutive = 0
462 lastError = error
463 }
464 await delay(2000, signal)
465 }
466 throw new Error(
467 `Sprites: "${name}" did not become ready within ${timeoutMs}ms after restore${
468 lastError instanceof Error ? ` (last error: ${lastError.message})` : ''
469 }.`,
470 )
471 }
472​
473 /** Write a sentinel and read it back; throws unless the round-trip matches. */
474 private async probeReadWrite(
475 name: string,
476 path: string,
477 marker: string,
478 signal?: AbortSignal,
479 ): Promise<void> {
480 const attemptSignal = signal
481 ? AbortSignal.any([signal, AbortSignal.timeout(8000)])
482 : AbortSignal.timeout(8000)
483 const writeUrl = this.spritePath(
484 name,
485 `/fs/write?path=${encodeURIComponent(path)}`,
486 )
487 const writeRes = await fetch(writeUrl, {
488 method: 'PUT',
489 headers: this.headers({ 'content-type': 'application/octet-stream' }),
490 body: new TextEncoder().encode(marker),
491 signal: attemptSignal,
492 })
493 await writeRes.body?.cancel()
494 if (!writeRes.ok) throw new Error(`probe write HTTP ${writeRes.status}`)
495​
496 const readUrl = this.spritePath(
497 name,
498 `/fs/read?path=${encodeURIComponent(path)}`,
499 )
500 const readRes = await fetch(readUrl, {
501 method: 'GET',
502 headers: this.headers(),
503 signal: attemptSignal,
504 })
505 if (!readRes.ok) {
506 await readRes.body?.cancel()
507 throw new Error(`probe read HTTP ${readRes.status}`)
508 }
509 if ((await readRes.text()) !== marker) {
510 throw new Error('probe read mismatch')
511 }
512 }
513​
514 private async deleteSentinel(name: string, path: string): Promise<void> {
515 const res = await fetch(
516 this.spritePath(name, `/fs/write?path=${encodeURIComponent(path)}`),
517 {
518 method: 'PUT',
519 headers: this.headers({ 'content-type': 'application/octet-stream' }),
520 body: new Uint8Array(0),
521 },
522 ).catch(() => undefined)
523 await res?.body?.cancel()
524 }
525​
526 private async killSession(name: string, sessionId: string): Promise<void> {
527 const response = await fetch(
528 this.spritePath(name, `/exec/${encodeURIComponent(sessionId)}/kill`),
529 { method: 'POST', headers: this.headers() },
530 ).catch(() => undefined)
531 await response?.body?.cancel()
532 }
533​
534 exec(name: string, options: SpritesExecOptions): SpritesExecStream {
535 const query = new URLSearchParams()
536 for (const arg of options.argv) query.append('cmd', arg)
537 if (options.cwd !== undefined) query.set('dir', options.cwd)
538 if (options.env) {
539 for (const [key, value] of Object.entries(options.env)) {
540 query.append('env', `${key}=${value}`)
541 }
542 }
543​
544 const wsBase = this.baseUrl.replace(/^http(s?):\/\//, 'ws$1://')
545 const url = `${wsBase}/v1/sprites/${encodeURIComponent(name)}/exec?${query.toString()}`
546 // The query carries cmd/env (possibly secrets); never surface it in errors.
547 const safeUrl = `${wsBase}/v1/sprites/${encodeURIComponent(name)}/exec`
548​
549 const stdoutQ = new AsyncChunkQueue()
550 const stderrQ = new AsyncChunkQueue()
551 const outDecoder = new TextDecoder()
552 const errDecoder = new TextDecoder()
553​
554 let sessionId: string | undefined
555 let exitCode: number | undefined
556 let exitObserved = false
557 let killedByCaller = false
558 let opened = false
559 let settled = false
560 let socketError: Error | undefined
561 let onAbort: (() => void) | undefined
562 let resolveClosed!: () => void
563 const closed = new Promise<void>((resolve) => {
564 resolveClosed = resolve
565 })
566 // Resolves when the session id is known (or the socket closes without one),
567 // so kill() can reach the server-side kill endpoint even if it is called
568 // before the `session_info` frame arrives.
569 let resolveSession!: (id: string | undefined) => void
570 const sessionReady = new Promise<string | undefined>((resolve) => {
571 resolveSession = resolve
572 })
573​
574 // The global (undici) WebSocket accepts a `headers` constructor option at
575 // runtime, but the WHATWG type only declares `(url, protocols?)`, so the two
576 // constructor signatures don't structurally overlap — bridge via `unknown`.
577 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- undici headers option not in the DOM WebSocket type
578 const WebSocketCtor = WebSocket as unknown as WsCtor
579 const ws = new WebSocketCtor(url, { headers: this.headers() })
580 ws.binaryType = 'arraybuffer'
581​
582 // Bound the connect phase: if the socket never opens (e.g. the Sprite is
583 // restarting and stalls in CONNECTING), fail instead of hanging wait().
584 const connectTimer: ReturnType<typeof setTimeout> = setTimeout(() => {
585 if (!opened) {
586 socketError ??= new Error(
587 `Sprites exec WebSocket did not connect within ${options.connectTimeoutMs ?? 30_000}ms (${safeUrl}).`,
588 )
589 try {
590 ws.close()
591 } catch {
592 // ignore
593 }
594 finish()
595 }
596 }, options.connectTimeoutMs ?? 30_000)
597 connectTimer.unref()
598​
599 function finish(): void {
600 if (settled) return
601 settled = true
602 clearTimeout(connectTimer)
603 if (onAbort && options.signal) {
604 options.signal.removeEventListener('abort', onAbort)
605 }
606 resolveSession(sessionId)
607 stdoutQ.push(outDecoder.decode())
608 stderrQ.push(errDecoder.decode())
609 stdoutQ.end()
610 stderrQ.end()
611 resolveClosed()
612 }
613​
614 ws.addEventListener('open', () => {
615 opened = true
616 clearTimeout(connectTimer)
617 })
618​
619 ws.addEventListener('message', (event: MessageEvent) => {
620 const data: unknown = event.data
621 if (typeof data === 'string') {
622 // Parse the small control JSON synchronously so the session id / exit
623 // code are set before any subsequent `close` runs `finish()` — an async
624 // parse here would let `finish()` read a stale (undefined) session id.
625 const message = parseControlMessage(data)
626 if (message === undefined) return
627 if (message.type === 'session_info') {
628 if (typeof message.session_id === 'string') {
629 sessionId = message.session_id
630 resolveSession(sessionId)
631 }
632 } else if (message.type === 'exit') {
633 if (typeof message.exit_code === 'number') {
634 exitCode = message.exit_code
635 exitObserved = true
636 }
637 }
638 return
639 }
640 if (data instanceof ArrayBuffer && data.byteLength > 0) {
641 const bytes = new Uint8Array(data)
642 const kind = bytes[0]
643 const payload = bytes.subarray(1)
644 if (kind === WS_FRAME_STDOUT) {
645 stdoutQ.push(outDecoder.decode(payload, { stream: true }))
646 } else if (kind === WS_FRAME_STDERR) {
647 stderrQ.push(errDecoder.decode(payload, { stream: true }))
648 } else if (kind === WS_FRAME_EXIT) {
649 exitObserved = true
650 exitCode = payload[0] ?? 0
651 }
652 }
653 })
654​
655 ws.addEventListener('error', (event: Event) => {
656 const message = (event as Partial<ErrorEvent>).message
657 socketError ??= new Error(
658 `Sprites exec WebSocket error for ${safeUrl}: ${message ?? 'unknown error'}`,
659 )
660 })
661​
662 ws.addEventListener('close', () => finish())
663​
664 // Resolve the session id if/when it is known, bounded by `ms`, so an early
665 // kill still reaches the server-side kill endpoint rather than only dropping
666 // the local socket (which would orphan the remote process).
667 const waitForSessionId = (ms: number): Promise<string | undefined> => {
668 if (sessionId !== undefined || settled) return Promise.resolve(sessionId)
669 return new Promise((resolve) => {
670 let done = false
671 const timer = setTimeout(() => {
672 if (!done) {
673 done = true
674 resolve(sessionId)
675 }
676 }, ms)
677 timer.unref()
678 void sessionReady.then((id) => {
679 if (!done) {
680 done = true
681 clearTimeout(timer)
682 resolve(id)
683 }
684 })
685 })
686 }
687​
688 // Terminate the remote process and close the socket.
689 const terminate = async (): Promise<void> => {
690 const id = await waitForSessionId(5000)
691 if (id !== undefined) await this.killSession(name, id)
692 try {
693 ws.close()
694 } catch {
695 // already closing/closed
696 }
697 }
698​
699 if (options.signal) {
700 onAbort = (): void => {
701 void terminate()
702 }
703 if (options.signal.aborted) onAbort()
704 else options.signal.addEventListener('abort', onAbort)
705 }
706​
707 return {
708 stdout: stdoutQ,
709 stderr: stderrQ,
710 wait: async (): Promise<number> => {
711 await closed
712 // A real exit wins, even if a kill/abort raced in at the same instant.
713 if (exitObserved) return exitCode ?? 0
714 // Caller-initiated abort is a cancellation → reject with the reason.
715 if (options.signal?.aborted) throw signalReason(options.signal)
716 // An explicit kill() is normal teardown → resolve with a conventional
717 // "terminated by signal" code rather than throwing.
718 if (killedByCaller) return 137
719 // Closed without an exit: a dropped/abnormal connection. Surface it
720 // rather than masquerading as a successful exit 0.
721 throw (
722 socketError ??
723 new Error(
724 `Sprites exec connection closed before the process reported an exit code (${safeUrl}).`,
725 )
726 )
727 },
728 kill: async (): Promise<void> => {
729 killedByCaller = true
730 await terminate()
731 },
732 }
733 }
734​
735 private async fail(
736 method: string,
737 url: string,
738 response: Response,
739 ): Promise<never> {
740 const body = await response.text().catch(() => '')
741 throw new Error(
742 `Sprites API ${method} ${url} failed: ${response.status} ${response.statusText}${
743 body ? ` — ${body}` : ''
744 }`,
745 )
746 }
748​
749interface ExecControlMessage {
750 type?: string
751 session_id?: unknown
752 exit_code?: unknown
754​
755/** Abortable delay: resolves after `ms`, or rejects with AbortError if aborted. */
756function delay(ms: number, signal?: AbortSignal): Promise<void> {
757 if (signal?.aborted) return Promise.reject(signalReason(signal))
758 return new Promise<void>((resolve, reject) => {
759 const timer = setTimeout(() => {
760 signal?.removeEventListener('abort', onAbort)
761 resolve()
762 }, ms)
763 const onAbort = (): void => {
764 clearTimeout(timer)
765 reject(signalReason(signal))
766 }
767 signal?.addEventListener('abort', onAbort, { once: true })
768 })
770​
771function signalReason(signal: AbortSignal | undefined): Error {
772 const reason = signal?.reason
773 if (reason instanceof Error) return reason
774 const error = new Error('The operation was aborted')
775 error.name = 'AbortError'
776 return error
778​
779function parseControlMessage(text: string): ExecControlMessage | undefined {
780 try {
781 return JSON.parse(text) as ExecControlMessage
782 } catch {
783 return undefined
784 }
786​
787function parseSprite(text: string): SpriteResource {
788 let value: unknown
789 try {
790 value = JSON.parse(text)
791 } catch {
792 throw new Error(`Sprites API returned a non-JSON response: ${text}`)
793 }
794 const record = value as {
795 id?: unknown
796 name?: unknown
797 status?: unknown
798 url?: unknown
799 url_settings?: { auth?: unknown }
800 }
801 if (
802 typeof record.id !== 'string' ||
803 typeof record.name !== 'string' ||
804 typeof record.url !== 'string'
805 ) {
806 throw new Error(`Sprites API returned an unexpected sprite shape: ${text}`)
807 }
808 const auth = record.url_settings?.auth
809 return {
810 id: record.id,
811 name: record.name,
812 status: typeof record.status === 'string' ? record.status : 'unknown',
813 url: record.url,
814 ...(auth === 'public' || auth === 'sprite' ? { urlAuth: auth } : {}),
815 }