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