@fitlab-ai/agent-infra 0.5.9 → 0.6.0

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