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

shell-spawn.ts

67 lines2.0 KB

1/**
2 * A minimal sentinel-driven fake `sh` for driving the persistent bootstrap
3 * shell (see `../shell.ts`). Every command succeeds; `pwd` answers
4 * `/workspace`, `export -p` answers an empty env, so `forkState()` resolves.
5 *
6 * Shipped from the `@tanstack/ai-sandbox/testkit` subpath so provider authors
7 * (local-process, Docker, and third-party providers outside this repo) can
8 * verify their `process.spawn` wiring against the journal contract without
9 * reimplementing this fake themselves.
10 */
11import type { SpawnHandle } from '../contracts'
12​
13export function makeFakeShellSpawn(): SpawnHandle {
14 const queue: Array<string> = []
15 const waiters: Array<(result: IteratorResult<string>) => void> = []
16 let done = false
17​
18 function emit(chunk: string): void {
19 const waiter = waiters.shift()
20 if (waiter !== undefined) {
21 waiter({ value: chunk, done: false })
22 } else {
23 queue.push(chunk)
24 }
25 }
26​
27 const stdout: AsyncIterable<string> = {
28 [Symbol.asyncIterator](): AsyncIterator<string> {
29 return {
30 next(): Promise<IteratorResult<string>> {
31 const queued = queue.shift()
32 if (queued !== undefined) {
33 return Promise.resolve({ value: queued, done: false })
34 }
35 if (done) return Promise.resolve({ value: '', done: true })
36 return new Promise<IteratorResult<string>>((resolve) => {
37 waiters.push(resolve)
38 })
39 },
40 }
41 },
42 }
43​
44 let counter = 0
45 return {
46 pid: 1,
47 stdout,
48 stderr: (async function* empty() {})(),
49 stdin: {
50 write: (data: string) => {
51 const sentinel = `__BSSH_${counter}__`
52 counter += 1
53 if (data.startsWith('pwd;')) emit('/workspace\n')
54 emit(`${sentinel} 0\n`)
55 return Promise.resolve()
56 },
57 end: () => {
58 done = true
59 for (const waiter of waiters) waiter({ value: '', done: true })
60 waiters.length = 0
61 return Promise.resolve()
62 },
63 },
64 wait: () => Promise.resolve(0),
65 kill: () => Promise.resolve(),
66 }