@fitlab-ai/agent-infra 0.4.5 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +18 -2
  2. package/README.zh-CN.md +18 -2
  3. package/bin/cli.js +19 -0
  4. package/lib/defaults.json +17 -0
  5. package/lib/init.js +1 -0
  6. package/lib/log.js +5 -10
  7. package/lib/merge.js +885 -0
  8. package/lib/sandbox/commands/create.js +1170 -0
  9. package/lib/sandbox/commands/enter.js +64 -0
  10. package/lib/sandbox/commands/ls.js +71 -0
  11. package/lib/sandbox/commands/rebuild.js +102 -0
  12. package/lib/sandbox/commands/rm.js +211 -0
  13. package/lib/sandbox/commands/vm.js +101 -0
  14. package/lib/sandbox/config.js +79 -0
  15. package/lib/sandbox/constants.js +113 -0
  16. package/lib/sandbox/dockerfile.js +95 -0
  17. package/lib/sandbox/engine.js +93 -0
  18. package/lib/sandbox/index.js +64 -0
  19. package/lib/sandbox/runtimes/ai-tools.dockerfile +26 -0
  20. package/lib/sandbox/runtimes/base.dockerfile +30 -0
  21. package/lib/sandbox/runtimes/java17.dockerfile +3 -0
  22. package/lib/sandbox/runtimes/java21.dockerfile +3 -0
  23. package/lib/sandbox/runtimes/node20.dockerfile +3 -0
  24. package/lib/sandbox/runtimes/node22.dockerfile +3 -0
  25. package/lib/sandbox/runtimes/python3.dockerfile +3 -0
  26. package/lib/sandbox/shell.js +48 -0
  27. package/lib/sandbox/task-resolver.js +35 -0
  28. package/lib/sandbox/tools.js +135 -0
  29. package/lib/update.js +16 -2
  30. package/package.json +5 -1
  31. package/templates/.agents/rules/pr-sync.md +110 -0
  32. package/templates/.agents/rules/pr-sync.zh-CN.md +110 -0
  33. package/templates/.agents/scripts/validate-artifact.js +117 -1
  34. package/templates/.agents/skills/archive-tasks/SKILL.md +6 -3
  35. package/templates/.agents/skills/archive-tasks/SKILL.zh-CN.md +6 -3
  36. package/templates/.agents/skills/archive-tasks/scripts/archive-tasks.sh +91 -8
  37. package/templates/.agents/skills/commit/SKILL.md +9 -1
  38. package/templates/.agents/skills/commit/SKILL.zh-CN.md +9 -1
  39. package/templates/.agents/skills/commit/config/verify.json +5 -1
  40. package/templates/.agents/skills/commit/reference/pr-summary-sync.md +21 -0
  41. package/templates/.agents/skills/commit/reference/pr-summary-sync.zh-CN.md +21 -0
  42. package/templates/.agents/skills/commit/reference/task-status-update.md +2 -0
  43. package/templates/.agents/skills/commit/reference/task-status-update.zh-CN.md +2 -0
  44. package/templates/.agents/skills/create-pr/SKILL.md +2 -1
  45. package/templates/.agents/skills/create-pr/SKILL.zh-CN.md +2 -1
  46. package/templates/.agents/skills/create-pr/reference/comment-publish.md +7 -74
  47. package/templates/.agents/skills/create-pr/reference/comment-publish.zh-CN.md +6 -73
  48. package/templates/.agents/skills/create-task/SKILL.md +6 -0
  49. package/templates/.agents/skills/create-task/SKILL.zh-CN.md +6 -0
  50. package/templates/.agents/skills/create-task/config/verify.json +1 -0
  51. package/templates/.agents/skills/import-issue/SKILL.md +2 -0
  52. package/templates/.agents/skills/import-issue/SKILL.zh-CN.md +2 -0
  53. package/templates/.agents/skills/import-issue/config/verify.json +1 -0
  54. package/templates/.agents/skills/update-agent-infra/scripts/sync-templates.js +18 -1
  55. package/templates/.agents/templates/task.md +5 -4
  56. package/templates/.agents/templates/task.zh-CN.md +5 -4
@@ -0,0 +1,1170 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { parseArgs } from 'node:util';
6
+ import * as p from '@clack/prompts';
7
+ import pc from 'picocolors';
8
+ import { loadConfig } from '../config.js';
9
+ import {
10
+ assertValidBranchName,
11
+ containerName,
12
+ containerNameCandidates,
13
+ parsePositiveIntegerOption,
14
+ sandboxBranchLabel,
15
+ sandboxImageConfigLabel,
16
+ sandboxLabel,
17
+ sanitizeBranchName,
18
+ worktreeDirCandidates
19
+ } from '../constants.js';
20
+ import { prepareDockerfile } from '../dockerfile.js';
21
+ import { ensureDocker } from '../engine.js';
22
+ import { run, runOk, runSafe, runVerbose } from '../shell.js';
23
+ import { resolveTaskBranch } from '../task-resolver.js';
24
+ import { resolveTools, toolConfigDirCandidates, toolNpmPackagesArg } from '../tools.js';
25
+
26
+ const OPENCODE_YOLO_PERMISSION = '{"*":"allow","read":"allow","bash":"allow","edit":"allow","webfetch":"allow","external_directory":"allow","doom_loop":"allow"}';
27
+ const SANDBOX_ALIAS_BLOCK_BEGIN = '# >>> agent-infra managed aliases >>>';
28
+ const SANDBOX_ALIAS_BLOCK_END = '# <<< agent-infra managed aliases <<<';
29
+ const SANDBOX_ALIAS_NAMES = [
30
+ 'claude-yolo',
31
+ 'opencode-yolo',
32
+ 'codex-yolo',
33
+ 'gemini-yolo',
34
+ 'cy',
35
+ 'oy',
36
+ 'xy',
37
+ 'gy'
38
+ ];
39
+ const DEFAULT_SANDBOX_ALIASES = `alias claude-yolo='claude --dangerously-skip-permissions; tput ed'
40
+ alias opencode-yolo='OPENCODE_PERMISSION='\\''${OPENCODE_YOLO_PERMISSION}'\\'' opencode; tput ed'
41
+ alias codex-yolo='codex --yolo; tput ed'
42
+ alias gemini-yolo='gemini --yolo; tput ed'
43
+
44
+ alias cy='claude --dangerously-skip-permissions; tput ed'
45
+ alias oy='OPENCODE_PERMISSION='\\''${OPENCODE_YOLO_PERMISSION}'\\'' opencode; tput ed'
46
+ alias xy='codex --yolo; tput ed'
47
+ alias gy='gemini --yolo; tput ed'
48
+ `;
49
+ const CONTAINER_HOME = '/home/devuser';
50
+ const USAGE = `Usage: ai sandbox create <branch> [base] [--cpu <n>] [--memory <n>]
51
+
52
+ Host aliases:
53
+ ${'~'}/.agent-infra/aliases/sandbox.sh is auto-created on first run and mounted at
54
+ ${CONTAINER_HOME}/.bash_aliases inside the sandbox container.`;
55
+
56
+ function buildSignature(preparedDockerfile, tools) {
57
+ return createHash('sha256')
58
+ .update(JSON.stringify({
59
+ dockerfile: preparedDockerfile.signature,
60
+ tools: tools.map((tool) => tool.npmPackage)
61
+ }))
62
+ .digest('hex')
63
+ .slice(0, 12);
64
+ }
65
+
66
+ function resolveToolDirs(config, tools, branch) {
67
+ return tools.map((tool) => {
68
+ const candidates = toolConfigDirCandidates(tool, config.project, branch);
69
+ return {
70
+ tool,
71
+ dir: candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
72
+ };
73
+ });
74
+ }
75
+
76
+ export function hostShellConfigDir(home, project, branch) {
77
+ return path.join(home, '.agent-infra', 'config', project, sanitizeBranchName(branch));
78
+ }
79
+
80
+ function runtimeChecks(runtimes) {
81
+ const checks = [];
82
+ if (runtimes.some((runtime) => runtime.startsWith('node'))) {
83
+ checks.push({ name: 'Node.js', cmd: ['node', '--version'] });
84
+ }
85
+ if (runtimes.some((runtime) => runtime.startsWith('java'))) {
86
+ checks.push({ name: 'Java', cmd: ['java', '-version'] });
87
+ checks.push({ name: 'Maven', cmd: ['mvn', '--version'] });
88
+ }
89
+ if (runtimes.includes('python3')) {
90
+ checks.push({ name: 'Python', cmd: ['python3', '--version'] });
91
+ }
92
+ return checks;
93
+ }
94
+
95
+ export function detectGpgConfig(gitconfig) {
96
+ return /\bgpgsign\s*=\s*true\b/i.test(gitconfig) || /^\s*\[gpg(?:\s|"|\])/im.test(gitconfig);
97
+ }
98
+
99
+ function appendSafeDirectories(lines, repoRoot) {
100
+ if (!repoRoot) {
101
+ return lines;
102
+ }
103
+
104
+ const requiredDirectories = ['/workspace', repoRoot];
105
+ const existingDirectories = new Set();
106
+ let firstSafeSectionIndex = -1;
107
+ let inSafeSection = false;
108
+
109
+ for (let index = 0; index < lines.length; index += 1) {
110
+ const line = lines[index];
111
+ const sectionMatch = line.match(/^\s*\[([^\]]+)\]\s*$/);
112
+ if (sectionMatch) {
113
+ inSafeSection = sectionMatch[1].trim().toLowerCase() === 'safe';
114
+ if (inSafeSection && firstSafeSectionIndex === -1) {
115
+ firstSafeSectionIndex = index;
116
+ }
117
+ continue;
118
+ }
119
+
120
+ if (!inSafeSection) {
121
+ continue;
122
+ }
123
+
124
+ const directoryMatch = line.match(/^\s*directory\s*=\s*(.+?)\s*$/i);
125
+ if (directoryMatch) {
126
+ existingDirectories.add(directoryMatch[1].trim());
127
+ }
128
+ }
129
+
130
+ const missingDirectories = requiredDirectories
131
+ .filter((directory) => !existingDirectories.has(directory));
132
+ if (missingDirectories.length === 0) {
133
+ return lines;
134
+ }
135
+
136
+ if (firstSafeSectionIndex === -1) {
137
+ return [
138
+ ...lines,
139
+ '[safe]',
140
+ ...missingDirectories.map((directory) => `\tdirectory = ${directory}`)
141
+ ];
142
+ }
143
+
144
+ const updatedLines = [...lines];
145
+ let insertIndex = updatedLines.length;
146
+ for (let index = firstSafeSectionIndex + 1; index < updatedLines.length; index += 1) {
147
+ if (/^\s*\[([^\]]+)\]\s*$/.test(updatedLines[index])) {
148
+ insertIndex = index;
149
+ break;
150
+ }
151
+ }
152
+
153
+ updatedLines.splice(
154
+ insertIndex,
155
+ 0,
156
+ ...missingDirectories.map((directory) => `\tdirectory = ${directory}`)
157
+ );
158
+ return updatedLines;
159
+ }
160
+
161
+ export function sanitizeGitConfig(gitconfig, home, { stripGpg = false, repoRoot = '' } = {}) {
162
+ const lines = gitconfig
163
+ .replaceAll(home, CONTAINER_HOME)
164
+ .replace(/\[difftool "sourcetree"\][^\[]*/gs, '')
165
+ .replace(/\[mergetool "sourcetree"\][^\[]*/gs, '')
166
+ .split(/\r?\n/);
167
+
168
+ const sanitized = [];
169
+ let inGpgSection = false;
170
+ let currentSection = '';
171
+
172
+ for (const line of lines) {
173
+ const sectionMatch = line.match(/^\s*\[([^\]]+)\]\s*$/);
174
+ if (sectionMatch) {
175
+ const sectionName = sectionMatch[1].trim();
176
+ currentSection = (sectionName.match(/^([^\s"]+)/)?.[1] ?? '').toLowerCase();
177
+ inGpgSection = /^gpg(?:\s+"[^"]+")?$/i.test(sectionName);
178
+ if (stripGpg && inGpgSection) {
179
+ continue;
180
+ }
181
+ sanitized.push(line);
182
+ continue;
183
+ }
184
+
185
+ if (inGpgSection) {
186
+ if (stripGpg) {
187
+ continue;
188
+ }
189
+ if (/^\s*program\s*=.*$/i.test(line)) {
190
+ continue;
191
+ }
192
+ }
193
+
194
+ if (stripGpg && currentSection === 'commit' && /^\s*gpgsign\s*=.*$/i.test(line)) {
195
+ continue;
196
+ }
197
+ if (stripGpg && currentSection === 'tag' && /^\s*gpgsign\s*=.*$/i.test(line)) {
198
+ continue;
199
+ }
200
+ if (stripGpg && currentSection === 'user' && /^\s*signingKey\s*=.*$/i.test(line)) {
201
+ continue;
202
+ }
203
+
204
+ sanitized.push(line);
205
+ }
206
+
207
+ return appendSafeDirectories(sanitized, repoRoot).join('\n');
208
+ }
209
+
210
+ export function hostHasGpgKeys(home, execFn = execFileSync) {
211
+ return currentKeyringFingerprint(home, execFn) !== null;
212
+ }
213
+
214
+ export function writeSanitizedGitconfig({ home, hostConfigDir, stripGpg, repoRoot }) {
215
+ const gitconfigPath = path.join(home, '.gitconfig');
216
+ if (!fs.existsSync(gitconfigPath)) {
217
+ return null;
218
+ }
219
+
220
+ fs.mkdirSync(hostConfigDir, { recursive: true });
221
+ const targetPath = path.join(hostConfigDir, '.gitconfig');
222
+ const gitconfig = sanitizeGitConfig(fs.readFileSync(gitconfigPath, 'utf8'), home, {
223
+ stripGpg,
224
+ repoRoot
225
+ });
226
+ fs.writeFileSync(targetPath, gitconfig, 'utf8');
227
+ return targetPath;
228
+ }
229
+
230
+ export function prepareHostShellConfig({ home, project, branch, repoRoot }) {
231
+ const hostDir = hostShellConfigDir(home, project, branch);
232
+ fs.rmSync(hostDir, { recursive: true, force: true });
233
+ fs.mkdirSync(hostDir, { recursive: true });
234
+
235
+ /** @type {Array<{ hostPath: string, containerPath: string }>} */
236
+ const mounts = [];
237
+ const gitconfigPath = writeSanitizedGitconfig({
238
+ home,
239
+ hostConfigDir: hostDir,
240
+ stripGpg: true,
241
+ repoRoot
242
+ });
243
+ if (gitconfigPath) {
244
+ mounts.push({ hostPath: gitconfigPath, containerPath: `${CONTAINER_HOME}/.gitconfig` });
245
+ }
246
+
247
+ for (const file of ['.gitignore_global', '.stCommitMsg']) {
248
+ const hostPath = path.join(home, file);
249
+ if (!fs.existsSync(hostPath)) {
250
+ continue;
251
+ }
252
+
253
+ const targetPath = path.join(hostDir, file);
254
+ fs.copyFileSync(hostPath, targetPath);
255
+ mounts.push({ hostPath: targetPath, containerPath: `${CONTAINER_HOME}/${file}` });
256
+ }
257
+
258
+ const aliasesPath = sandboxAliasesPath(home);
259
+ if (fs.existsSync(aliasesPath)) {
260
+ const targetPath = path.join(hostDir, '.bash_aliases');
261
+ fs.copyFileSync(aliasesPath, targetPath);
262
+ mounts.push({ hostPath: targetPath, containerPath: `${CONTAINER_HOME}/.bash_aliases` });
263
+ }
264
+
265
+ return { hostDir, mounts };
266
+ }
267
+
268
+ function gpgCacheDir(home, project) {
269
+ return path.join(home, '.agent-infra', 'gpg-cache', project);
270
+ }
271
+
272
+ function normalizeSigningKey(signingKey) {
273
+ if (typeof signingKey !== 'string') {
274
+ return null;
275
+ }
276
+
277
+ const trimmed = signingKey.trim();
278
+ return trimmed.length > 0 ? trimmed : null;
279
+ }
280
+
281
+ function normalizeWorktreePath(worktreePath) {
282
+ if (!worktreePath) {
283
+ return '';
284
+ }
285
+
286
+ try {
287
+ return fs.existsSync(worktreePath) ? fs.realpathSync(worktreePath) : path.resolve(worktreePath);
288
+ } catch {
289
+ return path.resolve(worktreePath);
290
+ }
291
+ }
292
+
293
+ export function getGitSigningKey({ home, repoPath = null, execFn = execFileSync } = {}) {
294
+ if (!home) {
295
+ return null;
296
+ }
297
+ try {
298
+ const output = execFn('git', [
299
+ ...(repoPath ? ['-C', repoPath] : []),
300
+ 'config',
301
+ ...(repoPath ? [] : ['--global']),
302
+ 'user.signingKey'
303
+ ], {
304
+ encoding: 'utf8',
305
+ env: { ...process.env, HOME: home },
306
+ stdio: ['ignore', 'pipe', 'pipe']
307
+ });
308
+ return normalizeSigningKey(output);
309
+ } catch {
310
+ return null;
311
+ }
312
+ }
313
+
314
+ export function currentKeyringFingerprint(home, execFn = execFileSync) {
315
+ const hostEnv = { ...process.env, HOME: home };
316
+ try {
317
+ const keyring = execFn('gpg', ['--list-secret-keys', '--with-colons'], {
318
+ encoding: 'utf8',
319
+ env: hostEnv,
320
+ stdio: ['ignore', 'pipe', 'pipe']
321
+ });
322
+ if (!keyring || keyring.trim().length === 0) {
323
+ return null;
324
+ }
325
+ return createHash('sha256').update(keyring).digest('hex');
326
+ } catch {
327
+ return null;
328
+ }
329
+ }
330
+
331
+ export function readGpgCache(home, project, execFn = execFileSync, signingKey = null) {
332
+ const cacheDir = gpgCacheDir(home, project);
333
+ const pubPath = path.join(cacheDir, 'public.asc');
334
+ const secPath = path.join(cacheDir, 'secret.asc');
335
+ const statePath = path.join(cacheDir, 'state.json');
336
+
337
+ try {
338
+ const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
339
+ if (typeof state?.fingerprint !== 'string' || state.fingerprint.length === 0) {
340
+ return null;
341
+ }
342
+ if (normalizeSigningKey(state?.signingKey) !== normalizeSigningKey(signingKey)) {
343
+ return null;
344
+ }
345
+
346
+ const currentFingerprint = currentKeyringFingerprint(home, execFn);
347
+ if (!currentFingerprint || currentFingerprint !== state.fingerprint) {
348
+ return null;
349
+ }
350
+
351
+ const pub = fs.readFileSync(pubPath);
352
+ const sec = fs.readFileSync(secPath);
353
+ if (pub.length === 0 || sec.length === 0) {
354
+ return null;
355
+ }
356
+
357
+ return { pub, sec };
358
+ } catch {
359
+ return null;
360
+ }
361
+ }
362
+
363
+ export function writeGpgCache(home, project, pub, sec, fingerprint, signingKey = null) {
364
+ if (!fingerprint) {
365
+ return false;
366
+ }
367
+
368
+ const cacheDir = gpgCacheDir(home, project);
369
+ const pubPath = path.join(cacheDir, 'public.asc');
370
+ const secPath = path.join(cacheDir, 'secret.asc');
371
+ const statePath = path.join(cacheDir, 'state.json');
372
+
373
+ try {
374
+ const state = { fingerprint };
375
+ const normalizedSigningKey = normalizeSigningKey(signingKey);
376
+ if (normalizedSigningKey) {
377
+ state.signingKey = normalizedSigningKey;
378
+ }
379
+
380
+ fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
381
+ fs.chmodSync(cacheDir, 0o700);
382
+
383
+ fs.writeFileSync(pubPath, pub, { mode: 0o600 });
384
+ fs.chmodSync(pubPath, 0o600);
385
+
386
+ fs.writeFileSync(secPath, sec, { mode: 0o600 });
387
+ fs.chmodSync(secPath, 0o600);
388
+
389
+ fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
390
+ fs.chmodSync(statePath, 0o600);
391
+
392
+ return true;
393
+ } catch {
394
+ return false;
395
+ }
396
+ }
397
+
398
+ export function syncGpgKeys(
399
+ container,
400
+ home,
401
+ project,
402
+ execFn = execFileSync,
403
+ runSafeFn = runSafe,
404
+ options = {}
405
+ ) {
406
+ const {
407
+ cachedOverride = null,
408
+ repoPath = null,
409
+ signingKey: signingKeyOverride
410
+ } = options;
411
+ const hostEnv = { ...process.env, HOME: home };
412
+ let signingKey = normalizeSigningKey(signingKeyOverride);
413
+ let resolvedSigningKey = Object.hasOwn(options, 'signingKey');
414
+ // Allow callers to supply a pre-computed cache read so we don't re-invoke
415
+ // `gpg --list-secret-keys` just to decide the progress message.
416
+ if (cachedOverride === null && !resolvedSigningKey) {
417
+ signingKey = getGitSigningKey({ repoPath, home, execFn });
418
+ resolvedSigningKey = true;
419
+ }
420
+ const cached = cachedOverride ?? readGpgCache(home, project, execFn, signingKey);
421
+ let pubKeys = cached?.pub ?? null;
422
+ let secKeys = cached?.sec ?? null;
423
+
424
+ if (!cached && !resolvedSigningKey) {
425
+ signingKey = getGitSigningKey({ repoPath, home, execFn });
426
+ resolvedSigningKey = true;
427
+ }
428
+
429
+ if (!cached) {
430
+ const exportArgs = signingKey ? ['--export', signingKey] : ['--export'];
431
+ const exportSecretArgs = signingKey
432
+ ? ['--export-secret-keys', signingKey]
433
+ : ['--export-secret-keys'];
434
+
435
+ pubKeys = execFn('gpg', exportArgs, {
436
+ env: hostEnv,
437
+ stdio: ['ignore', 'pipe', 'pipe']
438
+ });
439
+ if (!pubKeys || pubKeys.length === 0) {
440
+ return false;
441
+ }
442
+
443
+ secKeys = execFn('gpg', exportSecretArgs, {
444
+ env: hostEnv,
445
+ stdio: ['ignore', 'pipe', 'pipe']
446
+ });
447
+ if (!secKeys || secKeys.length === 0) {
448
+ return false;
449
+ }
450
+
451
+ const fingerprint = currentKeyringFingerprint(home, execFn);
452
+ if (fingerprint) {
453
+ const written = writeGpgCache(home, project, pubKeys, secKeys, fingerprint, signingKey);
454
+ if (!written) {
455
+ process.stderr.write(
456
+ 'Warning: failed to cache GPG keys; next sandbox create may prompt again.\n'
457
+ );
458
+ }
459
+ }
460
+ }
461
+
462
+ execFn('docker', ['exec', '-i', container, 'gpg', '--import'], {
463
+ input: pubKeys,
464
+ stdio: ['pipe', 'pipe', 'pipe']
465
+ });
466
+ execFn('docker', ['exec', '-i', container, 'gpg', '--batch', '--import'], {
467
+ input: secKeys,
468
+ stdio: ['pipe', 'pipe', 'pipe']
469
+ });
470
+
471
+ runSafeFn('docker', ['exec', container, 'gpgconf', '--launch', 'gpg-agent']);
472
+ return true;
473
+ }
474
+
475
+ export function buildContainerEnvArgs(resolvedTools, runSafeCommand = runSafe) {
476
+ const envArgs = resolvedTools.flatMap(({ tool }) =>
477
+ Object.entries(tool.envVars ?? {}).flatMap(([key, value]) => ['-e', `${key}=${value}`])
478
+ );
479
+ const ghToken = runSafeCommand('gh', ['auth', 'token']);
480
+ if (ghToken) {
481
+ envArgs.push('-e', `GH_TOKEN=${ghToken}`);
482
+ }
483
+ return envArgs;
484
+ }
485
+
486
+ export function assertBranchAvailable(
487
+ repoRoot,
488
+ branch,
489
+ { allowedWorktrees = [], runFn = runSafe } = {}
490
+ ) {
491
+ const normalizedAllowedWorktrees = new Set(allowedWorktrees.map((worktree) => normalizeWorktreePath(worktree)));
492
+ const output = runFn('git', ['-C', repoRoot, 'worktree', 'list', '--porcelain']);
493
+ if (!output) {
494
+ return;
495
+ }
496
+
497
+ let currentWorktree = '';
498
+ for (const line of output.split('\n')) {
499
+ if (line.startsWith('worktree ')) {
500
+ currentWorktree = line.slice('worktree '.length).trim();
501
+ continue;
502
+ }
503
+ if (!line.startsWith('branch refs/heads/')) {
504
+ continue;
505
+ }
506
+
507
+ const usedBranch = line.slice('branch refs/heads/'.length).trim();
508
+ if (usedBranch === branch) {
509
+ if (normalizedAllowedWorktrees.has(normalizeWorktreePath(currentWorktree))) {
510
+ continue;
511
+ }
512
+ throw new Error(
513
+ `Branch '${branch}' is already checked out at '${currentWorktree}'.\n`
514
+ + `Use a different branch name, or run 'git switch <other>' in that worktree first.`
515
+ );
516
+ }
517
+ }
518
+ }
519
+
520
+ export function ensureClaudeOnboarding(toolDir) {
521
+ const claudeJsonPath = path.join(toolDir, '.claude.json');
522
+ let data = {};
523
+ if (fs.existsSync(claudeJsonPath)) {
524
+ try {
525
+ data = JSON.parse(fs.readFileSync(claudeJsonPath, 'utf8'));
526
+ } catch {
527
+ // malformed JSON, start fresh
528
+ }
529
+ }
530
+ let changed = false;
531
+ if (!data.hasCompletedOnboarding) {
532
+ data.hasCompletedOnboarding = true;
533
+ changed = true;
534
+ }
535
+ if (!data.projects) {
536
+ data.projects = {};
537
+ changed = true;
538
+ }
539
+ if (!data.projects['/workspace']) {
540
+ data.projects['/workspace'] = {};
541
+ changed = true;
542
+ }
543
+ if (!data.projects['/workspace'].hasTrustDialogAccepted) {
544
+ data.projects['/workspace'].hasTrustDialogAccepted = true;
545
+ changed = true;
546
+ }
547
+ if (changed) {
548
+ fs.writeFileSync(claudeJsonPath, JSON.stringify(data, null, 4), 'utf8');
549
+ }
550
+ }
551
+
552
+ export function ensureClaudeSettings(toolDir) {
553
+ const settingsPath = path.join(toolDir, 'settings.json');
554
+ let data = {};
555
+ if (fs.existsSync(settingsPath)) {
556
+ try {
557
+ data = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
558
+ } catch {
559
+ // malformed JSON, start fresh
560
+ }
561
+ }
562
+ if (data.skipDangerousModePermissionPrompt !== true) {
563
+ data.skipDangerousModePermissionPrompt = true;
564
+ fs.writeFileSync(settingsPath, JSON.stringify(data, null, 4), 'utf8');
565
+ }
566
+ }
567
+
568
+ export function ensureCodexWorkspaceTrust(toolDir) {
569
+ const configPath = path.join(toolDir, 'config.toml');
570
+ let content = '';
571
+ if (fs.existsSync(configPath)) {
572
+ content = fs.readFileSync(configPath, 'utf8');
573
+ }
574
+ if (!content.includes('[projects."/workspace"]')) {
575
+ const entry = '\n[projects."/workspace"]\ntrust_level = "trusted"\n';
576
+ fs.writeFileSync(configPath, content + entry, 'utf8');
577
+ }
578
+ }
579
+
580
+ export function ensureGeminiWorkspaceTrust(toolDir) {
581
+ const trustPath = path.join(toolDir, 'trustedFolders.json');
582
+ let data = {};
583
+ if (fs.existsSync(trustPath)) {
584
+ try {
585
+ data = JSON.parse(fs.readFileSync(trustPath, 'utf8'));
586
+ } catch {
587
+ // malformed JSON, start fresh
588
+ }
589
+ }
590
+ if (data['/workspace'] !== 'TRUST_FOLDER') {
591
+ data['/workspace'] = 'TRUST_FOLDER';
592
+ fs.writeFileSync(trustPath, JSON.stringify(data, null, 2), 'utf8');
593
+ }
594
+ }
595
+
596
+ export function extractClaudeCredentialsBlob(home, execFn = execFileSync) {
597
+ if (process.platform === 'darwin') {
598
+ try {
599
+ const keychainAccount = path.basename(home);
600
+ const credentials = execFn('security', [
601
+ 'find-generic-password',
602
+ '-a',
603
+ keychainAccount,
604
+ '-s',
605
+ 'Claude Code-credentials',
606
+ '-w'
607
+ ], {
608
+ encoding: 'utf8',
609
+ stdio: ['ignore', 'pipe', 'pipe']
610
+ });
611
+ const trimmed = typeof credentials === 'string' ? credentials.trim() : '';
612
+ if (!trimmed) {
613
+ return null;
614
+ }
615
+
616
+ const parsed = JSON.parse(trimmed);
617
+ const payload = parsed?.claudeAiOauth ?? parsed;
618
+ const scopes = Array.isArray(payload?.scopes) ? payload.scopes : [];
619
+ const hasRequiredScopes = scopes.includes('user:profile')
620
+ && scopes.includes('user:sessions:claude_code');
621
+ if (!payload?.accessToken || !payload?.refreshToken || !hasRequiredScopes) {
622
+ return null;
623
+ }
624
+ return trimmed;
625
+ } catch {
626
+ return null;
627
+ }
628
+ }
629
+
630
+ const credentialsPath = path.join(home, '.claude', '.credentials.json');
631
+ if (!fs.existsSync(credentialsPath)) {
632
+ return null;
633
+ }
634
+
635
+ try {
636
+ const raw = fs.readFileSync(credentialsPath, 'utf8');
637
+ const parsed = JSON.parse(raw);
638
+ const payload = parsed?.claudeAiOauth ?? parsed;
639
+ const scopes = Array.isArray(payload?.scopes) ? payload.scopes : [];
640
+ const hasRequiredScopes = scopes.includes('user:profile')
641
+ && scopes.includes('user:sessions:claude_code');
642
+ if (!payload?.accessToken || !payload?.refreshToken || !hasRequiredScopes) {
643
+ return null;
644
+ }
645
+ return raw;
646
+ } catch {
647
+ return null;
648
+ }
649
+ }
650
+
651
+ export function claudeCredentialsDir(home, project) {
652
+ return path.join(home, '.agent-infra', 'credentials', project, 'claude-code');
653
+ }
654
+
655
+ export function claudeCredentialsPath(home, project) {
656
+ return path.join(claudeCredentialsDir(home, project), '.credentials.json');
657
+ }
658
+
659
+ export function writeClaudeCredentialsFile(home, project, blob) {
660
+ const dir = claudeCredentialsDir(home, project);
661
+ const filePath = claudeCredentialsPath(home, project);
662
+
663
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
664
+ fs.chmodSync(dir, 0o700);
665
+ fs.writeFileSync(filePath, blob, { mode: 0o600 });
666
+ fs.chmodSync(filePath, 0o600);
667
+ }
668
+
669
+ export function assertClaudeCredentialsAvailable(
670
+ home,
671
+ project,
672
+ resolvedTools,
673
+ extractFn = extractClaudeCredentialsBlob,
674
+ writeFn = writeClaudeCredentialsFile
675
+ ) {
676
+ const claudeCodeEntry = resolvedTools.find(({ tool }) => tool.id === 'claude-code');
677
+ if (!claudeCodeEntry) {
678
+ return;
679
+ }
680
+
681
+ const blob = extractFn(home);
682
+ if (!blob) {
683
+ throw new Error([
684
+ 'Claude Code credentials not found on host.',
685
+ '',
686
+ 'The sandbox needs your Claude Code OAuth credentials so the container can use Claude Code.',
687
+ '',
688
+ 'To fix:',
689
+ ' 1. On the host, run "claude" once and complete the OAuth login flow.',
690
+ ' 2. Verify with "claude /status" that you see your subscription.',
691
+ ' 3. Re-run "ai sandbox create".',
692
+ '',
693
+ 'Alternatively, if you do not need Claude Code in this sandbox,',
694
+ 'remove "claude-code" from the "sandbox.tools" array in .agents/.airc.json.'
695
+ ].join('\n'));
696
+ }
697
+
698
+ writeFn(home, project, blob);
699
+ }
700
+
701
+ export function sandboxAliasesPath(home) {
702
+ return path.join(home, '.agent-infra', 'aliases', 'sandbox.sh');
703
+ }
704
+
705
+ function escapeRegExp(value) {
706
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
707
+ }
708
+
709
+ function stripManagedSandboxAliasBlocks(content) {
710
+ const blockPattern = new RegExp(
711
+ `${escapeRegExp(SANDBOX_ALIAS_BLOCK_BEGIN)}[\\s\\S]*?${escapeRegExp(SANDBOX_ALIAS_BLOCK_END)}\\n?`,
712
+ 'g'
713
+ );
714
+ return content.replace(blockPattern, '').trimEnd();
715
+ }
716
+
717
+ function isLegacyManagedSandboxAliasFile(content) {
718
+ const lines = content
719
+ .split(/\r?\n/)
720
+ .map((line) => line.trim())
721
+ .filter(Boolean);
722
+
723
+ if (lines.length === 0) {
724
+ return false;
725
+ }
726
+
727
+ const aliasPattern = new RegExp(`^alias (${SANDBOX_ALIAS_NAMES.map(escapeRegExp).join('|')})=`);
728
+ return lines.every((line) => aliasPattern.test(line));
729
+ }
730
+
731
+ export function ensureSandboxAliasesFile(home) {
732
+ const aliasesPath = sandboxAliasesPath(home);
733
+ const managedBlock = `${SANDBOX_ALIAS_BLOCK_BEGIN}\n${DEFAULT_SANDBOX_ALIASES}${SANDBOX_ALIAS_BLOCK_END}\n`;
734
+ fs.mkdirSync(path.dirname(aliasesPath), { recursive: true });
735
+ const created = !fs.existsSync(aliasesPath);
736
+ let existing = '';
737
+
738
+ if (!created) {
739
+ existing = fs.readFileSync(aliasesPath, 'utf8');
740
+ }
741
+
742
+ const userContent = isLegacyManagedSandboxAliasFile(existing)
743
+ ? ''
744
+ : stripManagedSandboxAliasBlocks(existing);
745
+ const nextContent = userContent
746
+ ? `${userContent}\n\n${managedBlock}`
747
+ : managedBlock;
748
+
749
+ if (created || nextContent !== existing) {
750
+ fs.writeFileSync(aliasesPath, nextContent, 'utf8');
751
+ }
752
+
753
+ return { created, path: aliasesPath };
754
+ }
755
+
756
+ export function commandErrorMessage(error) {
757
+ const stderr = error?.stderr?.toString().trim();
758
+ return stderr || error?.message || 'Command failed';
759
+ }
760
+
761
+ function runTaskCommand(cmd, args, opts = {}) {
762
+ try {
763
+ return run(cmd, args, opts);
764
+ } catch (error) {
765
+ throw new Error(commandErrorMessage(error));
766
+ }
767
+ }
768
+
769
+ export function buildImage(
770
+ config,
771
+ tools,
772
+ dockerfilePath,
773
+ imageSignature,
774
+ { runFn = run, runVerboseFn = runVerbose } = {}
775
+ ) {
776
+ const hostUid = runFn('id', ['-u']);
777
+ const hostGid = runFn('id', ['-g']);
778
+
779
+ runVerboseFn('docker', [
780
+ 'build',
781
+ '-t',
782
+ config.imageName,
783
+ '--build-arg',
784
+ `HOST_UID=${hostUid}`,
785
+ '--build-arg',
786
+ `HOST_GID=${hostGid}`,
787
+ '--build-arg',
788
+ `AI_TOOL_PACKAGES=${toolNpmPackagesArg(tools)}`,
789
+ '--label',
790
+ sandboxLabel(config),
791
+ '--label',
792
+ `${sandboxImageConfigLabel(config)}=${imageSignature}`,
793
+ '-f',
794
+ dockerfilePath,
795
+ config.repoRoot
796
+ ], { cwd: config.repoRoot });
797
+ }
798
+
799
+ export async function create(args) {
800
+ const { values, positionals } = parseArgs({
801
+ args,
802
+ allowPositionals: true,
803
+ strict: true,
804
+ options: {
805
+ cpu: { type: 'string' },
806
+ memory: { type: 'string' },
807
+ help: { type: 'boolean', short: 'h' }
808
+ }
809
+ });
810
+
811
+ if (values.help) {
812
+ process.stdout.write(`${USAGE}\n`);
813
+ return;
814
+ }
815
+
816
+ if (positionals.length < 1 || positionals.length > 2) {
817
+ throw new Error(USAGE);
818
+ }
819
+
820
+ const config = loadConfig();
821
+ const [branchOrTaskId, base] = positionals;
822
+ const branch = resolveTaskBranch(branchOrTaskId, config.repoRoot);
823
+ assertValidBranchName(branch);
824
+ const effectiveConfig = {
825
+ ...config,
826
+ vm: {
827
+ ...config.vm,
828
+ cpu: parsePositiveIntegerOption(values.cpu, '--cpu') ?? config.vm.cpu,
829
+ memory: parsePositiveIntegerOption(values.memory, '--memory') ?? config.vm.memory
830
+ }
831
+ };
832
+ const worktreeCandidates = worktreeDirCandidates(effectiveConfig, branch);
833
+ assertBranchAvailable(config.repoRoot, branch, { allowedWorktrees: worktreeCandidates });
834
+ const tools = resolveTools(effectiveConfig);
835
+ const resolvedTools = resolveToolDirs(effectiveConfig, tools, branch);
836
+ // Fail fast before any filesystem/docker side effects so a missing
837
+ // Claude Code credential blob doesn't leave the user with a stale
838
+ // worktree, docker image, or temporary Dockerfile they need to manually
839
+ // clean up.
840
+ assertClaudeCredentialsAvailable(
841
+ effectiveConfig.home,
842
+ effectiveConfig.project,
843
+ resolvedTools
844
+ );
845
+ const container = containerName(effectiveConfig, branch);
846
+ const worktree = worktreeCandidates.find((candidate) => fs.existsSync(candidate)) ?? worktreeCandidates[0];
847
+ const preparedDockerfile = prepareDockerfile(effectiveConfig);
848
+ const baseBranch = base ?? runSafe('git', ['-C', effectiveConfig.repoRoot, 'branch', '--show-current']);
849
+ const expectedImageSignature = buildSignature(preparedDockerfile, tools);
850
+
851
+ p.intro(pc.cyan('AI Sandbox'));
852
+ p.log.info(
853
+ `Project: ${pc.bold(effectiveConfig.project)} | Branch: ${pc.bold(branch)} | Base: ${pc.bold(baseBranch || 'HEAD')}`
854
+ );
855
+
856
+ try {
857
+ p.log.step('Checking container engine...');
858
+ await ensureDocker(effectiveConfig, (detail) => {
859
+ p.log.info(` ${detail}`);
860
+ });
861
+ p.log.success('Docker is ready');
862
+
863
+ const imageExists = runOk('docker', ['image', 'inspect', effectiveConfig.imageName]);
864
+ const currentImageSignature = imageExists
865
+ ? runSafe('docker', [
866
+ 'image',
867
+ 'inspect',
868
+ '--format',
869
+ `{{ index .Config.Labels "${sandboxImageConfigLabel(effectiveConfig)}" }}`,
870
+ effectiveConfig.imageName
871
+ ])
872
+ : '';
873
+ const needsImageBuild = !imageExists || currentImageSignature !== expectedImageSignature;
874
+
875
+ if (needsImageBuild) {
876
+ p.log.step(imageExists ? 'Rebuilding stale image...' : 'Building image for first use...');
877
+ buildImage(
878
+ effectiveConfig,
879
+ tools,
880
+ preparedDockerfile.path,
881
+ expectedImageSignature
882
+ );
883
+ p.log.success(imageExists ? 'Image rebuilt' : 'Image built');
884
+ } else {
885
+ p.log.step(`Using existing image ${effectiveConfig.imageName}`);
886
+ }
887
+
888
+ await p.tasks([
889
+ {
890
+ title: 'Setting up git worktree',
891
+ task: async (message) => {
892
+ if (fs.existsSync(worktree)) {
893
+ if (fs.readdirSync(worktree).length > 0) {
894
+ return `Worktree exists at ${worktree}`;
895
+ }
896
+ fs.rmSync(worktree, { recursive: true, force: true });
897
+ }
898
+
899
+ const branchExists = runOk('git', [
900
+ '-C',
901
+ effectiveConfig.repoRoot,
902
+ 'show-ref',
903
+ '--verify',
904
+ '--quiet',
905
+ `refs/heads/${branch}`
906
+ ]);
907
+
908
+ if (branchExists) {
909
+ message(`Using existing branch '${branch}'...`);
910
+ runTaskCommand('git', ['-C', effectiveConfig.repoRoot, 'worktree', 'add', worktree, branch]);
911
+ } else {
912
+ message(`Creating branch '${branch}' from '${baseBranch}'...`);
913
+ runTaskCommand('git', ['-C', effectiveConfig.repoRoot, 'worktree', 'add', '-b', branch, worktree, baseBranch]);
914
+ }
915
+
916
+ return `Worktree ready at ${worktree}`;
917
+ }
918
+ },
919
+ {
920
+ title: 'Preparing tool state',
921
+ task: async () => {
922
+ for (const { tool, dir } of resolvedTools) {
923
+ fs.mkdirSync(dir, { recursive: true });
924
+
925
+ for (const { hostPath, sandboxName } of tool.hostPreSeedFiles ?? []) {
926
+ const destination = path.join(dir, sandboxName);
927
+ if (fs.existsSync(hostPath) && !fs.existsSync(destination)) {
928
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
929
+ fs.copyFileSync(hostPath, destination);
930
+ }
931
+ }
932
+
933
+ for (const { hostDir, sandboxSubdir } of tool.hostPreSeedDirs ?? []) {
934
+ const destination = path.join(dir, sandboxSubdir);
935
+ if (fs.existsSync(hostDir) && !fs.existsSync(destination)) {
936
+ fs.cpSync(hostDir, destination, { recursive: true });
937
+ }
938
+ }
939
+
940
+ for (const relativePath of tool.pathRewriteFiles ?? []) {
941
+ const filePath = path.join(dir, relativePath);
942
+ if (!fs.existsSync(filePath)) {
943
+ continue;
944
+ }
945
+ let content = fs.readFileSync(filePath, 'utf8');
946
+ content = content.replaceAll(effectiveConfig.repoRoot, '/workspace');
947
+ content = content.replaceAll(effectiveConfig.home, path.dirname(tool.containerMount));
948
+ fs.writeFileSync(filePath, content, 'utf8');
949
+ }
950
+ }
951
+
952
+ return `${resolvedTools.length} tool config directories ready`;
953
+ }
954
+ },
955
+ {
956
+ title: `Starting container '${container}'`,
957
+ task: async (message) => {
958
+ const existing = runSafe('docker', ['ps', '-a', '--format', '{{.Names}}']).split('\n').filter(Boolean);
959
+ const matchedContainers = containerNameCandidates(effectiveConfig, branch)
960
+ .filter((name) => existing.includes(name));
961
+
962
+ if (matchedContainers.length > 0) {
963
+ message('Removing old container instance...');
964
+ for (const name of matchedContainers) {
965
+ runSafe('docker', ['stop', name]);
966
+ runSafe('docker', ['rm', name]);
967
+ }
968
+ }
969
+
970
+ const aliasesFile = ensureSandboxAliasesFile(effectiveConfig.home);
971
+ if (aliasesFile.created) {
972
+ message(`Created default sandbox aliases at ${aliasesFile.path}`);
973
+ }
974
+
975
+ const gitconfigPath = path.join(effectiveConfig.home, '.gitconfig');
976
+ const gitconfigContent = fs.existsSync(gitconfigPath)
977
+ ? fs.readFileSync(gitconfigPath, 'utf8')
978
+ : '';
979
+ const needsGpg = detectGpgConfig(gitconfigContent);
980
+ const hasHostGpgKeys = needsGpg && hostHasGpgKeys(effectiveConfig.home);
981
+ const signingKey = needsGpg
982
+ ? getGitSigningKey({ repoPath: worktree, home: effectiveConfig.home })
983
+ : null;
984
+ const cachedGpg = needsGpg
985
+ ? readGpgCache(
986
+ effectiveConfig.home,
987
+ effectiveConfig.project,
988
+ undefined,
989
+ signingKey
990
+ )
991
+ : null;
992
+ const envArgs = buildContainerEnvArgs(resolvedTools);
993
+ const claudeCodeEntry = resolvedTools.find(({ tool }) => tool.id === 'claude-code');
994
+ if (claudeCodeEntry) {
995
+ ensureClaudeOnboarding(claudeCodeEntry.dir);
996
+ ensureClaudeSettings(claudeCodeEntry.dir);
997
+ // Credential availability is asserted up-front in create() so we
998
+ // know the shared credentials file already exists at this point.
999
+ }
1000
+ const codexEntry = resolvedTools.find(({ tool }) => tool.id === 'codex');
1001
+ if (codexEntry) {
1002
+ ensureCodexWorkspaceTrust(codexEntry.dir);
1003
+ }
1004
+ const geminiEntry = resolvedTools.find(({ tool }) => tool.id === 'gemini-cli');
1005
+ if (geminiEntry) {
1006
+ ensureGeminiWorkspaceTrust(geminiEntry.dir);
1007
+ }
1008
+ // OpenCode has no workspace trust mechanism, so no preseed step is needed.
1009
+ const toolVolumes = resolvedTools.flatMap(({ tool, dir }) => ['-v', `${dir}:${tool.containerMount}`]);
1010
+ const workspaceDir = path.join(effectiveConfig.repoRoot, '.agents', 'workspace');
1011
+ const hostShellConfig = prepareHostShellConfig({
1012
+ home: effectiveConfig.home,
1013
+ project: effectiveConfig.project,
1014
+ branch,
1015
+ repoRoot: effectiveConfig.repoRoot
1016
+ });
1017
+ const shellConfigVolumes = hostShellConfig.mounts.flatMap(({ hostPath, containerPath }) => [
1018
+ '-v',
1019
+ `${hostPath}:${containerPath}:ro`
1020
+ ]);
1021
+ const liveMountVolumes = resolvedTools.flatMap(({ tool }) =>
1022
+ (tool.hostLiveMounts ?? [])
1023
+ .filter(({ hostPath }) => fs.existsSync(hostPath))
1024
+ .flatMap(({ hostPath, containerSubpath }) => [
1025
+ '-v',
1026
+ `${hostPath}:${path.join(tool.containerMount, containerSubpath)}`
1027
+ ])
1028
+ );
1029
+
1030
+ fs.mkdirSync(workspaceDir, { recursive: true });
1031
+
1032
+ runTaskCommand('docker', [
1033
+ 'run',
1034
+ '-d',
1035
+ '--name',
1036
+ container,
1037
+ '--hostname',
1038
+ `${effectiveConfig.project}-sandbox`,
1039
+ '--label',
1040
+ sandboxLabel(effectiveConfig),
1041
+ '--label',
1042
+ `${sandboxBranchLabel(effectiveConfig)}=${branch}`,
1043
+ '-v',
1044
+ `${worktree}:/workspace`,
1045
+ '-v',
1046
+ `${workspaceDir}:/workspace/.agents/workspace`,
1047
+ '-v',
1048
+ `${effectiveConfig.repoRoot}/.git:${effectiveConfig.repoRoot}/.git`,
1049
+ '-v',
1050
+ `${path.join(effectiveConfig.home, '.ssh')}:/home/devuser/.ssh:ro`,
1051
+ ...toolVolumes,
1052
+ ...liveMountVolumes,
1053
+ ...shellConfigVolumes,
1054
+ ...envArgs,
1055
+ '-w',
1056
+ '/workspace',
1057
+ effectiveConfig.imageName
1058
+ ]);
1059
+
1060
+ if (needsGpg) {
1061
+ message(
1062
+ cachedGpg
1063
+ ? 'Syncing GPG keys from cache...'
1064
+ : hasHostGpgKeys
1065
+ ? 'Syncing GPG keys (you may be prompted for your passphrase)...'
1066
+ : 'Checking GPG cache before falling back to stripped git config...'
1067
+ );
1068
+ try {
1069
+ if (syncGpgKeys(
1070
+ container,
1071
+ effectiveConfig.home,
1072
+ effectiveConfig.project,
1073
+ undefined,
1074
+ undefined,
1075
+ {
1076
+ cachedOverride: cachedGpg,
1077
+ repoPath: worktree,
1078
+ signingKey
1079
+ }
1080
+ )) {
1081
+ writeSanitizedGitconfig({
1082
+ home: effectiveConfig.home,
1083
+ hostConfigDir: hostShellConfig.hostDir,
1084
+ stripGpg: false,
1085
+ repoRoot: effectiveConfig.repoRoot
1086
+ });
1087
+ } else {
1088
+ message(
1089
+ hasHostGpgKeys
1090
+ ? 'GPG key sync failed; using stripped git config fallback...'
1091
+ : 'Host GPG keys unavailable; using stripped git config fallback...'
1092
+ );
1093
+ }
1094
+ } catch {
1095
+ message(
1096
+ hasHostGpgKeys
1097
+ ? 'GPG key sync failed; using stripped git config fallback...'
1098
+ : 'Host GPG keys unavailable; using stripped git config fallback...'
1099
+ );
1100
+ }
1101
+ }
1102
+
1103
+ for (const { tool } of resolvedTools) {
1104
+ for (const command of tool.postSetupCmds ?? []) {
1105
+ runSafe('docker', ['exec', container, 'bash', '-lc', command]);
1106
+ }
1107
+ }
1108
+
1109
+ return 'Container started';
1110
+ }
1111
+ }
1112
+ ]);
1113
+ } finally {
1114
+ preparedDockerfile.cleanup();
1115
+ }
1116
+
1117
+ p.log.step('Verifying setup...');
1118
+ const runningContainers = runSafe('docker', ['ps', '--format', '{{.Names}}']).split('\n');
1119
+ const checks = [
1120
+ { name: 'Container running', ok: runningContainers.includes(container) },
1121
+ ...runtimeChecks(effectiveConfig.runtimes).map((check) => ({
1122
+ name: check.name,
1123
+ ok: runOk('docker', ['exec', container, ...check.cmd])
1124
+ })),
1125
+ { name: 'GitHub CLI', ok: runOk('docker', ['exec', container, 'gh', '--version']) }
1126
+ ];
1127
+ const toolChecks = tools.map((tool) => ({
1128
+ name: tool.name,
1129
+ ok: runOk('docker', ['exec', container, 'bash', '-lc', tool.versionCmd]),
1130
+ hint: tool.setupHint
1131
+ }));
1132
+
1133
+ for (const check of checks) {
1134
+ p.log.info(` ${check.ok ? pc.green('✓') : pc.yellow('?')} ${check.name}`);
1135
+ }
1136
+ for (const check of toolChecks) {
1137
+ p.log.info(` ${check.ok ? pc.green('✓') : pc.yellow('?')} ${check.name}`);
1138
+ if (!check.ok) {
1139
+ p.log.warn(` ${check.hint}`);
1140
+ }
1141
+ }
1142
+
1143
+ p.outro(pc.green('Sandbox ready'));
1144
+
1145
+ const toolHints = resolvedTools.map(({ tool, dir }) => {
1146
+ const hasLiveMount = (tool.hostLiveMounts ?? []).some(({ hostPath }) => fs.existsSync(hostPath));
1147
+ const hint = hasLiveMount
1148
+ ? 'Live-mounted auth/config files stay in sync with the host.'
1149
+ : tool.setupHint;
1150
+ return `${tool.name}: ${hint} Config dir: ${dir}`;
1151
+ }).join('\n');
1152
+
1153
+ process.stdout.write(`
1154
+ Container: ${container}
1155
+ Image: ${effectiveConfig.imageName}
1156
+ Worktree: ${worktree}
1157
+ Host aliases: ${sandboxAliasesPath(effectiveConfig.home)}
1158
+
1159
+ Management:
1160
+ ai sandbox ls
1161
+ ai sandbox exec ${branch}
1162
+ ai sandbox rm ${branch}
1163
+
1164
+ Sandbox aliases:
1165
+ Edit the host aliases file to customize shortcuts mounted at ${CONTAINER_HOME}/.bash_aliases.
1166
+
1167
+ Tool notes:
1168
+ ${toolHints}
1169
+ `);
1170
+ }