Open History to see the last commit
1/**
2 * Adapt a sandbox {@link SpawnHandle} into byte streams for ACP stdio
3 * (newline-delimited JSON-RPC).
4 */
5import type { SpawnHandle } from '@tanstack/ai-sandbox'
6import type { AcpByteTransport } from './types'
7
8export function spawnHandleToAcpTransport(
9 handle: SpawnHandle,
10): AcpByteTransport {
11 const encoder = new TextEncoder()
12 const decoder = new TextDecoder()
13
14 const readable = new ReadableStream<Uint8Array>({
15 async start(controller) {
16 try {
17 for await (const chunk of handle.stdout) {
18 controller.enqueue(encoder.encode(chunk))
19 }
20 controller.close()
21 } catch (error) {
22 controller.error(error)
23 }
24 },
25 })
26
27 const writable = new WritableStream<Uint8Array>({
28 write(chunk) {
29 return handle.stdin.write(decoder.decode(chunk))
30 },
31 close() {
32 return handle.stdin.end()
33 },
34 })
35
36 let tail = ''
37 void (async () => {
38 try {
39 for await (const chunk of handle.stderr) {
40 tail = (tail + chunk).slice(-4096)
41 }
42 } catch {
43 // stderr closed
44 }
45 })()
46
47 const exited: Promise<never> = handle.wait().then((code) => {
48 throw new Error(
49 `ACP harness process exited unexpectedly (code ${code}).${
50 tail.trim() !== '' ? `\nstderr: ${tail.trim()}` : ''
51 }`,
52 )
53 })
54 void exited.catch(() => undefined)
55
56 return {
57 writable,
58 readable,
59 exited,
60 stderrTail: () => tail,
61 kill: () => handle.kill(),
62 }
63}