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

provider.ts

131 lines4.3 KB

1import { randomUUID } from 'node:crypto'
2import * as fsp from 'node:fs/promises'
3import * as os from 'node:os'
4import * as path from 'node:path'
5import {
6 LOCAL_PROCESS_CAPS,
7 LocalProcessHandle,
8 removeDirWithRetry,
9} from './handle'
10import type { LocalProcessLogger } from './handle'
11import type {
12 SandboxCapabilities,
13 SandboxCreateInput,
14 SandboxDestroyInput,
15 SandboxHandle,
16 SandboxProvider,
17 SandboxResumeInput,
18} from '@tanstack/ai-sandbox'
19​
20export interface LocalProcessSandboxConfig {
21 /**
22 * Fixed host directory to use as the workspace (e.g. an existing local repo
23 * checkout). When set, every create/resume uses this exact dir and it is NOT
24 * removed on destroy unless `removeOnDestroy` is explicitly true. When
25 * omitted, each create allocates a fresh temp dir that IS removed on destroy.
26 */
27 dir?: string
28 /** Override the default temp base dir for generated sandboxes. */
29 baseDir?: string
30 /** Remove the backing dir on destroy. Defaults: true (generated), false (fixed `dir`). */
31 removeOnDestroy?: boolean
32 /**
33 * Env vars to remove from the inherited `process.env` before spawning. Use to
34 * let a host CLI fall back to its own stored auth — e.g. scrub
35 * `ANTHROPIC_API_KEY` so Claude Code uses your logged-in subscription instead
36 * of billing the API.
37 */
38 scrubEnv?: Array<string>
39 /**
40 * Sink for non-fatal teardown diagnostics — a `killTree` that could not
41 * confirm the spawned process tree is gone. Teardown is total by construction
42 * (it never throws), so without a logger such a failure is silent.
43 * `@tanstack/ai`'s `InternalLogger` satisfies this shape as-is.
44 */
45 logger?: LocalProcessLogger
47​
48class LocalProcessProvider implements SandboxProvider {
49 readonly name = 'local-process'
50​
51 constructor(private readonly config: LocalProcessSandboxConfig) {}
52​
53 capabilities(): SandboxCapabilities {
54 return LOCAL_PROCESS_CAPS
55 }
56​
57 private removeDefault(): boolean {
58 return this.config.removeOnDestroy ?? this.config.dir === undefined
59 }
60​
61 private makeHandle(root: string): SandboxHandle {
62 return new LocalProcessHandle({
63 root,
64 removeOnDestroy: this.removeDefault(),
65 scrubEnv: this.config.scrubEnv,
66 logger: this.config.logger,
67 forkFactory: async (sourceRoot) => {
68 const dest = path.join(this.baseDir(), `fork-${randomUUID()}`)
69 await fsp.mkdir(dest, { recursive: true })
70 await fsp.cp(sourceRoot, dest, { recursive: true })
71 return new LocalProcessHandle({
72 root: dest,
73 removeOnDestroy: true,
74 logger: this.config.logger,
75 forkFactory: () =>
76 Promise.reject(new Error('nested fork unsupported')),
77 })
78 },
79 })
80 }
81​
82 private baseDir(): string {
83 return (
84 this.config.baseDir ?? path.join(os.tmpdir(), 'tanstack-ai-sandboxes')
85 )
86 }
87​
88 async create(_input: SandboxCreateInput): Promise<SandboxHandle> {
89 const root =
90 this.config.dir !== undefined
91 ? path.resolve(this.config.dir)
92 : path.join(this.baseDir(), randomUUID())
93 await fsp.mkdir(root, { recursive: true })
94 return this.makeHandle(root)
95 }
96​
97 async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {
98 // The id is the backing dir path; resume only if it still exists.
99 try {
100 const stat = await fsp.stat(input.id)
101 if (!stat.isDirectory()) return null
102 } catch {
103 return null
104 }
105 return this.makeHandle(input.id)
106 }
107​
108 /**
109 * Destroy by id (a dir path). Unlike `LocalProcessHandle.destroy` there is no
110 * handle here, so no children can be killed first — a process spawned through
111 * a handle we no longer hold may still own the dir as its CWD. The bounded
112 * retry is all that is available, and a dir that never releases is reported
113 * through the logger rather than silently left behind.
114 */
115 async destroy(input: SandboxDestroyInput): Promise<void> {
116 if (this.removeDefault()) {
117 await removeDirWithRetry(input.id, this.config.logger)
118 }
119 }
121​
122/**
123 * Local-process sandbox provider — runs the agent directly on the host with no
124 * isolation. The fast no-Docker dev loop. See the trust-boundary note in
125 * `handle.ts`.
126 */
127export function localProcessSandbox(
128 config: LocalProcessSandboxConfig = {},
129): SandboxProvider {
130 return new LocalProcessProvider(config)