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

bootstrap.ts

200 lines6.9 KB

1/**
2 * Workspace bootstrap engine — provider-agnostic because it only uses the
3 * {@link SandboxHandle} contract. Runs once when a sandbox is freshly created
4 * (or restored without its working tree): land the source, inject secrets,
5 * detect the package manager, and run setup commands.
6 *
7 * Harness-specific projection (CLAUDE.md, agent skills, MCP config) is NOT done
8 * here — that's each adapter's `projectWorkspace()` hook, since the format
9 * differs per harness.
10 */
11import { resolveHarnessCwd } from './harness-cwd'
12import { buildSetupPlan } from './setup-plan'
13import { createBootstrapShell } from './shell'
14import {
15 mergeAgentsContent,
16 resolveGitSkillDir,
17 writeAgentsFile,
18} from './agents-file'
19import { resolveAllSecrets, resolveSecret } from './secrets'
20import type { SandboxHandle } from './contracts'
21import type { PackageManager, WorkspaceDefinition } from './workspace'
22​
23const LOCKFILES: Record<Exclude<PackageManager, 'auto'>, string> = {
24 pnpm: 'pnpm-lock.yaml',
25 yarn: 'yarn.lock',
26 bun: 'bun.lockb',
27 npm: 'package-lock.json',
29​
30export const DEFAULT_WORKSPACE_ROOT = '/workspace'
31​
32/** Resolve the package manager, detecting from a lockfile when `'auto'`. */
33export async function detectPackageManager(
34 handle: SandboxHandle,
35 workspace: WorkspaceDefinition,
36 root: string,
37): Promise<Exclude<PackageManager, 'auto'> | undefined> {
38 const pm = workspace.packageManager ?? 'auto'
39 if (pm !== 'auto') return pm
40 for (const [manager, lockfile] of Object.entries(LOCKFILES) as Array<
41 [Exclude<PackageManager, 'auto'>, string]
42 >) {
43 if (await handle.fs.exists(`${root}/${lockfile}`)) return manager
44 }
45 return undefined
47​
48export interface BootstrapResult {
49 packageManager?: Exclude<PackageManager, 'auto'>
50 ranSetup: Array<string>
52​
53/**
54 * Bootstrap a freshly created sandbox's workspace. Idempotent enough to be safe
55 * on restore: a git clone into a populated dir is skipped by checking for the
56 * target dir first.
57 */
58export async function bootstrapWorkspace(
59 handle: SandboxHandle,
60 workspace: WorkspaceDefinition,
61 options: { signal?: AbortSignal } = {},
62): Promise<BootstrapResult> {
63 const root = workspace.root ?? DEFAULT_WORKSPACE_ROOT
64​
65 // Secrets live only in the running sandbox env (never persisted).
66 if (workspace.secrets !== undefined) {
67 const resolved = resolveAllSecrets(workspace.secrets)
68 if (Object.keys(resolved).length > 0) {
69 await handle.env.set(resolved)
70 }
71 }
72​
73 // Land the source. Clone into the handle's own default root (each provider
74 // maps the conventional `/workspace` virtual root to its real backing dir),
75 // rather than passing a virtual `dir` that can't be remapped inside a shell
76 // command string.
77 if (workspace.source.type === 'git') {
78 const alreadyCloned = await handle.fs.exists(`${root}/.git`)
79 if (!alreadyCloned) {
80 await handle.git.clone({
81 url: workspace.source.url,
82 ref: workspace.source.ref,
83 auth: workspace.source.auth,
84 ...(workspace.source.depth !== undefined
85 ? { depth: workspace.source.depth }
86 : {}),
87 })
88 }
89 }
90 // 'local' is provider-pre-populated at create; 'none' starts empty.
91​
92 // Clone git-skill repos so setup steps (and the harness projector) can use
93 // them. gitSkill clones are always shallow (depth 1) unless the skill's own
94 // repo entry carries a depth override — the WorkspaceSkill `git` variant
95 // does not expose one, so depth always defaults to 1 inside git.clone.
96 const skills = workspace.skills ?? []
97 for (const skill of skills) {
98 if (skill.kind === 'git') {
99 const url = skill.repo.startsWith('http')
100 ? skill.repo
101 : `https://github.com/${skill.repo}.git`
102 const dir = resolveHarnessCwd(
103 handle,
104 skill.into ?? resolveGitSkillDir(root, skill),
105 )
106 const auth =
107 skill.secret !== undefined && workspace.secrets !== undefined
108 ? { token: resolveSecret(workspace.secrets, skill.secret) }
109 : undefined
110 await handle.git.clone({
111 url,
112 dir,
113 ...(auth !== undefined ? { auth } : {}),
114 depth: 1,
115 })
116 }
117 }
118​
119 // Write AGENTS.md (and its per-CLI symlinks) when instructions are provided
120 // directly on the workspace, via a fileSkill whose path is `AGENTS.md`, or
121 // when named workspace scripts should be surfaced for the agent.
122 let agentsContent: string | undefined
123 if (
124 workspace.instructions !== undefined &&
125 workspace.instructions.length > 0
126 ) {
127 agentsContent = workspace.instructions
128 } else {
129 const agentsFileSkill = skills.find(
130 (s): s is Extract<typeof s, { kind: 'file' }> =>
131 s.kind === 'file' && s.path === 'AGENTS.md',
132 )
133 if (agentsFileSkill !== undefined) {
134 agentsContent = agentsFileSkill.content
135 }
136 }
137 agentsContent = mergeAgentsContent(agentsContent, workspace.scripts)
138 if (agentsContent !== undefined) {
139 await writeAgentsFile(handle, root, agentsContent)
140 }
141​
142 // Write all other fileSkills directly into the workspace root.
143 for (const skill of skills) {
144 if (skill.kind === 'file' && skill.path !== 'AGENTS.md') {
145 await handle.fs.write(`${root}/${skill.path}`, skill.content)
146 }
147 }
148​
149 const packageManager = await detectPackageManager(handle, workspace, root)
150​
151 // Run setup over a single persistent shell so `cd`/exports persist across
152 // serial steps. Parallel groups fork the shell's current cwd+env into
153 // concurrent one-shot exec calls.
154 const ranSetup: Array<string> = []
155 const plan = buildSetupPlan(workspace.setup)
156 if (plan.length > 0) {
157 const shell = await createBootstrapShell(handle, { cwd: root })
158 try {
159 for (const group of plan) {
160 if (group.kind === 'serial') {
161 const result = await shell.run(group.command)
162 if (result.exitCode !== 0) {
163 const tail = result.stdout.trim().slice(-1500)
164 throw new Error(
165 `setup step failed: ${group.command} (exit ${result.exitCode})${tail ? `\n${tail}` : ''}`,
166 )
167 }
168 ranSetup.push(group.command)
169 } else {
170 const { cwd, env } = await shell.forkState()
171 const results = await Promise.all(
172 group.commands.map((command) =>
173 handle.process
174 .exec(command, {
175 cwd,
176 env,
177 ...(options.signal ? { signal: options.signal } : {}),
178 })
179 .then((res) => ({ command, res })),
180 ),
181 )
182 const failed = results.find((entry) => entry.res.exitCode !== 0)
183 if (failed !== undefined) {
184 const tail = `${failed.res.stdout}\n${failed.res.stderr}`
185 .trim()
186 .slice(-1500)
187 throw new Error(
188 `setup step failed: ${failed.command} (exit ${failed.res.exitCode})${tail ? `\n${tail}` : ''}`,
189 )
190 }
191 ranSetup.push(...group.commands)
192 }
193 }
194 } finally {
195 await shell.dispose()
196 }
197 }
198​
199 return { packageManager, ranSetup }