@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
@@ -0,0 +1,1507 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { execFileSync } from 'node:child_process';
6
+ import type { ExecFileSyncOptions, StdioOptions } from 'node:child_process';
7
+ import { parseArgs } from 'node:util';
8
+ import * as p from '@clack/prompts';
9
+ import pc from 'picocolors';
10
+ import * as toml from 'smol-toml';
11
+ import { loadConfig } from '../config.ts';
12
+ import {
13
+ assertValidBranchName,
14
+ containerName,
15
+ containerNameCandidates,
16
+ parsePositiveIntegerOption,
17
+ sandboxBranchLabel,
18
+ sandboxImageConfigLabel,
19
+ sandboxLabel,
20
+ sanitizeBranchName,
21
+ shareBranchDir,
22
+ shareCommonDir,
23
+ worktreeDirCandidates
24
+ } from '../constants.ts';
25
+ import { prepareDockerfile } from '../dockerfile.ts';
26
+ import { detectEngine, ensureDocker } from '../engine.ts';
27
+ import {
28
+ commandForEngine,
29
+ execEngine,
30
+ run,
31
+ runEngine,
32
+ runOk,
33
+ runOkEngine,
34
+ runSafe,
35
+ runSafeEngine,
36
+ runVerboseEngine
37
+ } from '../shell.ts';
38
+ import { resolveTaskBranch } from '../task-resolver.ts';
39
+ import { resolveTools, toolConfigDirCandidates, toolNpmPackagesArg } from '../tools.ts';
40
+ import type { SandboxTool } from '../tools.ts';
41
+ import { hostJoin, toEnginePath, volumeArg } from '../engines/wsl2-paths.ts';
42
+ import { validateSelinuxDisableEnv } from '../engines/selinux.ts';
43
+ import { resolveBuildUid } from '../engines/native.ts';
44
+ import { dotfilesCacheDir, materializeDotfiles } from '../dotfiles.ts';
45
+ import {
46
+ assertClaudeCredentialsAvailable,
47
+ redactCommandError,
48
+ validateClaudeCredentialsEnvOverride
49
+ } from '../credentials.ts';
50
+
51
+ const OPENCODE_YOLO_PERMISSION = '{"*":"allow","read":"allow","bash":"allow","edit":"allow","webfetch":"allow","external_directory":"allow","doom_loop":"allow"}';
52
+ const SANDBOX_ALIAS_BLOCK_BEGIN = '# >>> agent-infra managed aliases >>>';
53
+ const SANDBOX_ALIAS_BLOCK_END = '# <<< agent-infra managed aliases <<<';
54
+ const SANDBOX_ALIAS_NAMES = [
55
+ 'claude-yolo',
56
+ 'opencode-yolo',
57
+ 'codex-yolo',
58
+ 'gemini-yolo',
59
+ 'cy',
60
+ 'oy',
61
+ 'xy',
62
+ 'gy'
63
+ ];
64
+ const DEFAULT_SANDBOX_ALIASES = `alias claude-yolo='claude --dangerously-skip-permissions; tput ed'
65
+ alias opencode-yolo='OPENCODE_PERMISSION='\\''${OPENCODE_YOLO_PERMISSION}'\\'' opencode; tput ed'
66
+ alias codex-yolo='codex --yolo; tput ed'
67
+ alias gemini-yolo='gemini --yolo; tput ed'
68
+
69
+ alias cy='claude --dangerously-skip-permissions; tput ed'
70
+ alias oy='OPENCODE_PERMISSION='\\''${OPENCODE_YOLO_PERMISSION}'\\'' opencode; tput ed'
71
+ alias xy='codex --yolo; tput ed'
72
+ alias gy='gemini --yolo; tput ed'
73
+ `;
74
+ const CONTAINER_HOME = '/home/devuser';
75
+ const CONTAINER_SHELL_CONFIG_MOUNT = `${CONTAINER_HOME}/.host-shell-config`;
76
+ const USAGE = `Usage: ai sandbox create <branch> [base] [--cpu <n>] [--memory <n>]
77
+
78
+ Host aliases:
79
+ ${'~'}/.agent-infra/aliases/sandbox.sh is auto-created on first run and exposed
80
+ as ${CONTAINER_HOME}/.bash_aliases inside the sandbox container (the host
81
+ shell-config directory is bind-mounted at ${CONTAINER_SHELL_CONFIG_MOUNT} and
82
+ symlinked into $HOME).`;
83
+
84
+ type SandboxCreateConfig = ReturnType<typeof loadConfig>;
85
+ type PreparedDockerfile = ReturnType<typeof prepareDockerfile>;
86
+ type ResolvedTool = { tool: SandboxTool; dir: string };
87
+ type RuntimeCheck = { name: string; cmd: string[] };
88
+ type JsonObject = Record<string, unknown>;
89
+ type GpgCache = { pub: Buffer; sec: Buffer } | null;
90
+ type ExecSyncOptions = ExecFileSyncOptions & {
91
+ input?: Buffer | string;
92
+ env?: NodeJS.ProcessEnv;
93
+ stdio?: StdioOptions;
94
+ encoding?: BufferEncoding;
95
+ };
96
+ type ExecSyncFn = (cmd: string, args: string[], options?: ExecSyncOptions) => Buffer | string;
97
+ type EngineExecFn = (engine: string, cmd: string, args: string[], opts?: ExecFileSyncOptions) => Buffer | string;
98
+ type EngineRunFn = (engine: string, cmd: string, args: string[], opts?: { cwd?: string }) => string;
99
+ type EngineRunSafeFn = EngineRunFn;
100
+ type EngineRunVerboseFn = (engine: string, cmd: string, args: string[], opts?: { cwd?: string }) => void;
101
+ type DirectRunFn = (cmd: string, args: string[], opts?: { cwd?: string }) => string;
102
+ type DirectRunSafeFn = DirectRunFn;
103
+ type DirectRunVerboseFn = (cmd: string, args: string[], opts?: { cwd?: string }) => void;
104
+ type HostShellConfig = {
105
+ hostDir: string;
106
+ mounts: Array<{ hostPath: string; containerPath: string }>;
107
+ };
108
+
109
+ function buildSignature(preparedDockerfile: PreparedDockerfile, tools: SandboxTool[]): string {
110
+ return createHash('sha256')
111
+ .update(JSON.stringify({
112
+ dockerfile: preparedDockerfile.signature,
113
+ tools: tools.map((tool) => tool.npmPackage)
114
+ }))
115
+ .digest('hex')
116
+ .slice(0, 12);
117
+ }
118
+
119
+ function resolveToolDirs(config: Pick<SandboxCreateConfig, 'project'>, tools: SandboxTool[], branch: string): ResolvedTool[] {
120
+ return tools.map((tool) => {
121
+ const candidates = toolConfigDirCandidates(tool, config.project, branch);
122
+ return {
123
+ tool,
124
+ dir: candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0] ?? ''
125
+ };
126
+ });
127
+ }
128
+
129
+ export function hostShellConfigDir(home: string, project: string, branch: string): string {
130
+ return hostJoin(home, '.agent-infra', 'config', project, sanitizeBranchName(branch));
131
+ }
132
+
133
+ function runtimeChecks(runtimes: string[]): RuntimeCheck[] {
134
+ const checks: RuntimeCheck[] = [];
135
+ if (runtimes.some((runtime) => runtime.startsWith('node'))) {
136
+ checks.push({ name: 'Node.js', cmd: ['node', '--version'] });
137
+ }
138
+ if (runtimes.some((runtime) => runtime.startsWith('java'))) {
139
+ checks.push({ name: 'Java', cmd: ['java', '-version'] });
140
+ checks.push({ name: 'Maven', cmd: ['mvn', '--version'] });
141
+ }
142
+ if (runtimes.includes('python3')) {
143
+ checks.push({ name: 'Python', cmd: ['python3', '--version'] });
144
+ }
145
+ return checks;
146
+ }
147
+
148
+ export function detectGpgConfig(gitconfig: string): boolean {
149
+ return /\bgpgsign\s*=\s*true\b/i.test(gitconfig) || /^\s*\[gpg(?:\s|"|\])/im.test(gitconfig);
150
+ }
151
+
152
+ function appendSafeDirectories(lines: string[], repoRoot: string): string[] {
153
+ if (!repoRoot) {
154
+ return lines;
155
+ }
156
+
157
+ const requiredDirectories = ['/workspace', repoRoot];
158
+ const existingDirectories = new Set<string>();
159
+ let firstSafeSectionIndex = -1;
160
+ let inSafeSection = false;
161
+
162
+ for (let index = 0; index < lines.length; index += 1) {
163
+ const line = lines[index] ?? '';
164
+ const sectionMatch = line.match(/^\s*\[([^\]]+)\]\s*$/);
165
+ if (sectionMatch) {
166
+ inSafeSection = (sectionMatch[1] ?? '').trim().toLowerCase() === 'safe';
167
+ if (inSafeSection && firstSafeSectionIndex === -1) {
168
+ firstSafeSectionIndex = index;
169
+ }
170
+ continue;
171
+ }
172
+
173
+ if (!inSafeSection) {
174
+ continue;
175
+ }
176
+
177
+ const directoryMatch = line.match(/^\s*directory\s*=\s*(.+?)\s*$/i);
178
+ if (directoryMatch) {
179
+ existingDirectories.add((directoryMatch[1] ?? '').trim());
180
+ }
181
+ }
182
+
183
+ const missingDirectories = requiredDirectories
184
+ .filter((directory) => !existingDirectories.has(directory));
185
+ if (missingDirectories.length === 0) {
186
+ return lines;
187
+ }
188
+
189
+ if (firstSafeSectionIndex === -1) {
190
+ return [
191
+ ...lines,
192
+ '[safe]',
193
+ ...missingDirectories.map((directory) => `\tdirectory = ${directory}`)
194
+ ];
195
+ }
196
+
197
+ const updatedLines = [...lines];
198
+ let insertIndex = updatedLines.length;
199
+ for (let index = firstSafeSectionIndex + 1; index < updatedLines.length; index += 1) {
200
+ if (/^\s*\[([^\]]+)\]\s*$/.test(updatedLines[index] ?? '')) {
201
+ insertIndex = index;
202
+ break;
203
+ }
204
+ }
205
+
206
+ updatedLines.splice(
207
+ insertIndex,
208
+ 0,
209
+ ...missingDirectories.map((directory) => `\tdirectory = ${directory}`)
210
+ );
211
+ return updatedLines;
212
+ }
213
+
214
+ function normalizeContainerHomeSeparators(content: string): string {
215
+ const containerHomePattern = new RegExp(`${escapeRegExp(CONTAINER_HOME)}\\S*`, 'g');
216
+ return content.replace(containerHomePattern, (value) => value.replaceAll('\\', '/'));
217
+ }
218
+
219
+ export function sanitizeGitConfig(
220
+ gitconfig: string,
221
+ home: string,
222
+ { stripGpg = false, repoRoot = '' }: { stripGpg?: boolean; repoRoot?: string } = {}
223
+ ): string {
224
+ const posixHome = home.replaceAll('\\', '/');
225
+ const normalizedGitconfig = gitconfig
226
+ .replaceAll(home, CONTAINER_HOME)
227
+ .replaceAll(posixHome, CONTAINER_HOME);
228
+ const lines = normalizeContainerHomeSeparators(normalizedGitconfig)
229
+ .replace(/\[difftool "sourcetree"\][^\[]*/gs, '')
230
+ .replace(/\[mergetool "sourcetree"\][^\[]*/gs, '')
231
+ .split(/\r?\n/);
232
+
233
+ const sanitized = [];
234
+ let inGpgSection = false;
235
+ let currentSection = '';
236
+
237
+ for (const line of lines) {
238
+ const sectionMatch = line.match(/^\s*\[([^\]]+)\]\s*$/);
239
+ if (sectionMatch) {
240
+ const sectionName = (sectionMatch[1] ?? '').trim();
241
+ currentSection = ((sectionName.match(/^([^\s"]+)/)?.[1]) ?? '').toLowerCase();
242
+ inGpgSection = /^gpg(?:\s+"[^"]+")?$/i.test(sectionName);
243
+ if (stripGpg && inGpgSection) {
244
+ continue;
245
+ }
246
+ sanitized.push(line);
247
+ continue;
248
+ }
249
+
250
+ if (inGpgSection) {
251
+ if (stripGpg) {
252
+ continue;
253
+ }
254
+ if (/^\s*program\s*=.*$/i.test(line)) {
255
+ continue;
256
+ }
257
+ }
258
+
259
+ if (stripGpg && currentSection === 'commit' && /^\s*gpgsign\s*=.*$/i.test(line)) {
260
+ continue;
261
+ }
262
+ if (stripGpg && currentSection === 'tag' && /^\s*gpgsign\s*=.*$/i.test(line)) {
263
+ continue;
264
+ }
265
+ if (stripGpg && currentSection === 'user' && /^\s*signingKey\s*=.*$/i.test(line)) {
266
+ continue;
267
+ }
268
+
269
+ sanitized.push(line);
270
+ }
271
+
272
+ return appendSafeDirectories(sanitized, repoRoot).join('\n');
273
+ }
274
+
275
+ export function hostHasGpgKeys(home: string, execFn: ExecSyncFn = execFileSync): boolean {
276
+ return currentKeyringFingerprint(home, execFn) !== null;
277
+ }
278
+
279
+ export function writeSanitizedGitconfig({
280
+ home,
281
+ hostConfigDir,
282
+ stripGpg,
283
+ repoRoot
284
+ }: {
285
+ home: string;
286
+ hostConfigDir: string;
287
+ stripGpg: boolean;
288
+ repoRoot: string;
289
+ }): string {
290
+ const gitconfigPath = hostJoin(home, '.gitconfig');
291
+ // Always emit a sanitized .gitconfig, even when the host has none. The
292
+ // container ~/.gitconfig is a symlink into the bound shell-config directory;
293
+ // a missing file would leave the symlink dangling and drop the default
294
+ // safe.directory entries the image relies on.
295
+ const sourceContent = fs.existsSync(gitconfigPath)
296
+ ? fs.readFileSync(gitconfigPath, 'utf8')
297
+ : '';
298
+
299
+ fs.mkdirSync(hostConfigDir, { recursive: true });
300
+ const targetPath = path.join(hostConfigDir, '.gitconfig');
301
+ const gitconfig = sanitizeGitConfig(sourceContent, home, { stripGpg, repoRoot });
302
+ fs.writeFileSync(targetPath, gitconfig, 'utf8');
303
+ return targetPath;
304
+ }
305
+
306
+ // Files inside the host shell-config bind that need to be exposed in $HOME.
307
+ // Keep in sync with the symlink block in lib/sandbox/runtimes/ai-tools.dockerfile.
308
+ const SHELL_CONFIG_SYMLINKS = ['.gitconfig', '.gitignore_global', '.stCommitMsg', '.bash_aliases'];
309
+
310
+ export function ensureShellConfigSymlinks(engine: string, container: string, execFn: EngineExecFn = execEngine): void {
311
+ // Idempotent symlink setup. Runs against a started container so it also
312
+ // covers custom Dockerfiles that don't bake the symlinks into the image.
313
+ const script = SHELL_CONFIG_SYMLINKS
314
+ .map((file) => `ln -sf .host-shell-config/${file} ${CONTAINER_HOME}/${file}`)
315
+ .join(' && ');
316
+ execFn(engine, 'docker', ['exec', container, 'bash', '-lc', script], { stdio: 'ignore' });
317
+ }
318
+
319
+ export function prepareHostShellConfig({
320
+ home,
321
+ project,
322
+ branch,
323
+ repoRoot
324
+ }: {
325
+ home: string;
326
+ project: string;
327
+ branch: string;
328
+ repoRoot: string;
329
+ }): HostShellConfig {
330
+ const hostDir = hostShellConfigDir(home, project, branch);
331
+ fs.rmSync(hostDir, { recursive: true, force: true });
332
+ fs.mkdirSync(hostDir, { recursive: true });
333
+
334
+ writeSanitizedGitconfig({
335
+ home,
336
+ hostConfigDir: hostDir,
337
+ stripGpg: true,
338
+ repoRoot
339
+ });
340
+
341
+ for (const file of ['.gitignore_global', '.stCommitMsg']) {
342
+ const hostPath = hostJoin(home, file);
343
+ if (!fs.existsSync(hostPath)) {
344
+ continue;
345
+ }
346
+
347
+ fs.copyFileSync(hostPath, path.join(hostDir, file));
348
+ }
349
+
350
+ const aliasesPath = sandboxAliasesPath(home);
351
+ if (fs.existsSync(aliasesPath)) {
352
+ fs.copyFileSync(aliasesPath, path.join(hostDir, '.bash_aliases'));
353
+ }
354
+
355
+ // Single directory bind keeps virtiofs happy: per-file rewrites inside no
356
+ // longer race the bind layer like individual single-file binds do.
357
+ const mounts = [{ hostPath: hostDir, containerPath: CONTAINER_SHELL_CONFIG_MOUNT }];
358
+
359
+ return { hostDir, mounts };
360
+ }
361
+
362
+ function gpgCacheDir(home: string, project: string): string {
363
+ return hostJoin(home, '.agent-infra', 'gpg-cache', project);
364
+ }
365
+
366
+ function normalizeSigningKey(signingKey: unknown): string | null {
367
+ if (typeof signingKey !== 'string') {
368
+ return null;
369
+ }
370
+
371
+ const trimmed = signingKey.trim();
372
+ return trimmed.length > 0 ? trimmed : null;
373
+ }
374
+
375
+ function normalizeWorktreePath(worktreePath: string): string {
376
+ if (!worktreePath) {
377
+ return '';
378
+ }
379
+
380
+ try {
381
+ return fs.existsSync(worktreePath) ? fs.realpathSync(worktreePath) : path.resolve(worktreePath);
382
+ } catch {
383
+ return path.resolve(worktreePath);
384
+ }
385
+ }
386
+
387
+ export function getGitSigningKey({
388
+ home,
389
+ repoPath = null,
390
+ execFn = execFileSync
391
+ }: {
392
+ home?: string;
393
+ repoPath?: string | null;
394
+ execFn?: ExecSyncFn;
395
+ } = {}): string | null {
396
+ if (!home) {
397
+ return null;
398
+ }
399
+ try {
400
+ const output = execFn('git', [
401
+ ...(repoPath ? ['-C', repoPath] : []),
402
+ 'config',
403
+ ...(repoPath ? [] : ['--global']),
404
+ 'user.signingKey'
405
+ ], {
406
+ encoding: 'utf8',
407
+ env: { ...process.env, HOME: home },
408
+ stdio: ['ignore', 'pipe', 'pipe']
409
+ });
410
+ return normalizeSigningKey(output.toString());
411
+ } catch {
412
+ return null;
413
+ }
414
+ }
415
+
416
+ export function currentKeyringFingerprint(home: string, execFn: ExecSyncFn = execFileSync): string | null {
417
+ const hostEnv = { ...process.env, HOME: home };
418
+ try {
419
+ const keyring = execFn('gpg', ['--list-secret-keys', '--with-colons'], {
420
+ encoding: 'utf8',
421
+ env: hostEnv,
422
+ stdio: ['ignore', 'pipe', 'pipe']
423
+ });
424
+ const keyringText = keyring.toString();
425
+ if (!keyringText || keyringText.trim().length === 0) {
426
+ return null;
427
+ }
428
+ return createHash('sha256').update(keyringText).digest('hex');
429
+ } catch {
430
+ return null;
431
+ }
432
+ }
433
+
434
+ export function readGpgCache(
435
+ home: string,
436
+ project: string,
437
+ execFn: ExecSyncFn = execFileSync,
438
+ signingKey: string | null = null
439
+ ): GpgCache {
440
+ const cacheDir = gpgCacheDir(home, project);
441
+ const pubPath = path.join(cacheDir, 'public.asc');
442
+ const secPath = path.join(cacheDir, 'secret.asc');
443
+ const statePath = path.join(cacheDir, 'state.json');
444
+
445
+ try {
446
+ const state = JSON.parse(fs.readFileSync(statePath, 'utf8')) as { fingerprint?: unknown; signingKey?: unknown };
447
+ if (typeof state?.fingerprint !== 'string' || state.fingerprint.length === 0) {
448
+ return null;
449
+ }
450
+ if (normalizeSigningKey(state?.signingKey) !== normalizeSigningKey(signingKey)) {
451
+ return null;
452
+ }
453
+
454
+ const currentFingerprint = currentKeyringFingerprint(home, execFn);
455
+ if (!currentFingerprint || currentFingerprint !== state.fingerprint) {
456
+ return null;
457
+ }
458
+
459
+ const pub = fs.readFileSync(pubPath);
460
+ const sec = fs.readFileSync(secPath);
461
+ if (pub.length === 0 || sec.length === 0) {
462
+ return null;
463
+ }
464
+
465
+ return { pub, sec };
466
+ } catch {
467
+ return null;
468
+ }
469
+ }
470
+
471
+ export function writeGpgCache(
472
+ home: string,
473
+ project: string,
474
+ pub: Buffer | string,
475
+ sec: Buffer | string,
476
+ fingerprint: string | null,
477
+ signingKey: string | null = null
478
+ ): boolean {
479
+ if (!fingerprint) {
480
+ return false;
481
+ }
482
+
483
+ const cacheDir = gpgCacheDir(home, project);
484
+ const pubPath = path.join(cacheDir, 'public.asc');
485
+ const secPath = path.join(cacheDir, 'secret.asc');
486
+ const statePath = path.join(cacheDir, 'state.json');
487
+
488
+ try {
489
+ const state: { fingerprint: string; signingKey?: string } = { fingerprint };
490
+ const normalizedSigningKey = normalizeSigningKey(signingKey);
491
+ if (normalizedSigningKey) {
492
+ state.signingKey = normalizedSigningKey;
493
+ }
494
+
495
+ fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
496
+ fs.chmodSync(cacheDir, 0o700);
497
+
498
+ fs.writeFileSync(pubPath, pub, { mode: 0o600 });
499
+ fs.chmodSync(pubPath, 0o600);
500
+
501
+ fs.writeFileSync(secPath, sec, { mode: 0o600 });
502
+ fs.chmodSync(secPath, 0o600);
503
+
504
+ fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
505
+ fs.chmodSync(statePath, 0o600);
506
+
507
+ return true;
508
+ } catch {
509
+ return false;
510
+ }
511
+ }
512
+
513
+ export function syncGpgKeys(
514
+ container: string,
515
+ home: string,
516
+ project: string,
517
+ execFn: ExecSyncFn = execFileSync,
518
+ runSafeFn: DirectRunSafeFn = runSafe,
519
+ options: {
520
+ cachedOverride?: GpgCache;
521
+ repoPath?: string | null;
522
+ signingKey?: string | null;
523
+ dockerExecFn?: ExecSyncFn;
524
+ dockerRunSafeFn?: DirectRunSafeFn;
525
+ } = {}
526
+ ): boolean {
527
+ const {
528
+ cachedOverride = null,
529
+ repoPath = null,
530
+ signingKey: signingKeyOverride,
531
+ dockerExecFn = execFn,
532
+ dockerRunSafeFn = runSafeFn
533
+ } = options;
534
+ const hostEnv = { ...process.env, HOME: home };
535
+ let signingKey = normalizeSigningKey(signingKeyOverride);
536
+ let resolvedSigningKey = Object.hasOwn(options, 'signingKey');
537
+ // Allow callers to supply a pre-computed cache read so we don't re-invoke
538
+ // `gpg --list-secret-keys` just to decide the progress message.
539
+ if (cachedOverride === null && !resolvedSigningKey) {
540
+ signingKey = getGitSigningKey({ repoPath, home, execFn });
541
+ resolvedSigningKey = true;
542
+ }
543
+ const cached = cachedOverride ?? readGpgCache(home, project, execFn, signingKey);
544
+ let pubKeys = cached?.pub ?? null;
545
+ let secKeys = cached?.sec ?? null;
546
+
547
+ if (!cached && !resolvedSigningKey) {
548
+ signingKey = getGitSigningKey({ repoPath, home, execFn });
549
+ resolvedSigningKey = true;
550
+ }
551
+
552
+ if (!cached) {
553
+ const exportArgs = signingKey ? ['--export', signingKey] : ['--export'];
554
+ const exportSecretArgs = signingKey
555
+ ? ['--export-secret-keys', signingKey]
556
+ : ['--export-secret-keys'];
557
+
558
+ pubKeys = Buffer.from(execFn('gpg', exportArgs, {
559
+ env: hostEnv,
560
+ stdio: ['ignore', 'pipe', 'pipe']
561
+ }));
562
+ if (!pubKeys || pubKeys.length === 0) {
563
+ return false;
564
+ }
565
+
566
+ secKeys = Buffer.from(execFn('gpg', exportSecretArgs, {
567
+ env: hostEnv,
568
+ stdio: ['ignore', 'pipe', 'pipe']
569
+ }));
570
+ if (!secKeys || secKeys.length === 0) {
571
+ return false;
572
+ }
573
+
574
+ const fingerprint = currentKeyringFingerprint(home, execFn);
575
+ if (fingerprint) {
576
+ const written = writeGpgCache(home, project, pubKeys, secKeys, fingerprint, signingKey);
577
+ if (!written) {
578
+ process.stderr.write(
579
+ 'Warning: failed to cache GPG keys; next sandbox create may prompt again.\n'
580
+ );
581
+ }
582
+ }
583
+ }
584
+
585
+ dockerExecFn('docker', ['exec', '-i', container, 'gpg', '--import'], {
586
+ input: pubKeys ?? undefined,
587
+ stdio: ['pipe', 'pipe', 'pipe']
588
+ });
589
+ dockerExecFn('docker', ['exec', '-i', container, 'gpg', '--batch', '--import'], {
590
+ input: secKeys ?? undefined,
591
+ stdio: ['pipe', 'pipe', 'pipe']
592
+ });
593
+
594
+ dockerRunSafeFn('docker', ['exec', container, 'gpgconf', '--launch', 'gpg-agent']);
595
+ return true;
596
+ }
597
+
598
+ // Docker `--env-file` parsing has no quoting/escaping support and treats
599
+ // leading '#' as a comment. Newlines split entries, so reject them outright.
600
+ // Other shell metacharacters are safe because the values are not expanded.
601
+ function formatEnvFileEntry(key: string, value: string): string {
602
+ if (String(key).includes('\n') || String(value).includes('\n')) {
603
+ throw new Error(`Container environment variable ${key} must not contain newlines`);
604
+ }
605
+ return `${key}=${value}`;
606
+ }
607
+
608
+ export function buildContainerEnvFile(
609
+ resolvedTools: ResolvedTool[],
610
+ engine: string,
611
+ runSafeEngineFn: EngineRunSafeFn = runSafeEngine,
612
+ options: {
613
+ mkdtempFn?: typeof fs.mkdtempSync;
614
+ writeFileFn?: typeof fs.writeFileSync;
615
+ chmodFn?: typeof fs.chmodSync;
616
+ rmFn?: typeof fs.rmSync;
617
+ tmpDir?: string;
618
+ } = {}
619
+ ): { dockerArgs: string[]; cleanup: () => void } {
620
+ const {
621
+ mkdtempFn = fs.mkdtempSync,
622
+ writeFileFn = fs.writeFileSync,
623
+ chmodFn = fs.chmodSync,
624
+ rmFn = fs.rmSync,
625
+ tmpDir = os.tmpdir()
626
+ } = options;
627
+
628
+ const entries: Array<[string, string]> = resolvedTools.flatMap(({ tool }) => Object.entries(tool.envVars ?? {}));
629
+ const ghToken = runSafeEngineFn(engine, 'gh', ['auth', 'token']);
630
+ if (ghToken) {
631
+ entries.push(['GH_TOKEN', ghToken]);
632
+ }
633
+
634
+ if (entries.length === 0) {
635
+ return { dockerArgs: [], cleanup: () => {} };
636
+ }
637
+
638
+ const dir = mkdtempFn(path.join(tmpDir, 'agent-infra-env-'));
639
+ try {
640
+ chmodFn(dir, 0o700);
641
+ const envPath = path.join(dir, 'env');
642
+ const content = `${entries.map(([key, value]) => formatEnvFileEntry(key, value)).join('\n')}\n`;
643
+ writeFileFn(envPath, content, { mode: 0o600 });
644
+ chmodFn(envPath, 0o600);
645
+
646
+ return {
647
+ dockerArgs: ['--env-file', toEnginePath(engine, envPath)],
648
+ cleanup: () => {
649
+ try {
650
+ rmFn(dir, { recursive: true, force: true });
651
+ } catch {
652
+ // Best-effort cleanup only.
653
+ }
654
+ }
655
+ };
656
+ } catch (error) {
657
+ try {
658
+ rmFn(dir, { recursive: true, force: true });
659
+ } catch {
660
+ // Best-effort cleanup only.
661
+ }
662
+ throw error;
663
+ }
664
+ }
665
+
666
+ export function buildDotfilesVolumeArgs(
667
+ engine: string,
668
+ snapshotDir: string | null | undefined,
669
+ existsFn: typeof fs.existsSync = fs.existsSync
670
+ ): string[] {
671
+ if (!snapshotDir || !existsFn(snapshotDir)) {
672
+ return [];
673
+ }
674
+ return ['-v', volumeArg(engine, snapshotDir, '/dotfiles', ':ro')];
675
+ }
676
+
677
+ export function assertBranchAvailable(
678
+ repoRoot: string,
679
+ branch: string,
680
+ { allowedWorktrees = [], runFn = runSafe }: { allowedWorktrees?: string[]; runFn?: DirectRunSafeFn } = {}
681
+ ): void {
682
+ const normalizedAllowedWorktrees = new Set(allowedWorktrees.map((worktree) => normalizeWorktreePath(worktree)));
683
+ const output = runFn('git', ['-C', repoRoot, 'worktree', 'list', '--porcelain']);
684
+ if (!output) {
685
+ return;
686
+ }
687
+
688
+ let currentWorktree = '';
689
+ for (const line of output.split('\n')) {
690
+ if (line.startsWith('worktree ')) {
691
+ currentWorktree = line.slice('worktree '.length).trim();
692
+ continue;
693
+ }
694
+ if (!line.startsWith('branch refs/heads/')) {
695
+ continue;
696
+ }
697
+
698
+ const usedBranch = line.slice('branch refs/heads/'.length).trim();
699
+ if (usedBranch === branch) {
700
+ if (normalizedAllowedWorktrees.has(normalizeWorktreePath(currentWorktree))) {
701
+ continue;
702
+ }
703
+ throw new Error(
704
+ `Branch '${branch}' is already checked out at '${currentWorktree}'.\n`
705
+ + `Use a different branch name, or run 'git switch <other>' in that worktree first.`
706
+ );
707
+ }
708
+ }
709
+ }
710
+
711
+ function readHostJsonSafe(filePath: string): JsonObject | null {
712
+ if (!filePath || !fs.existsSync(filePath)) {
713
+ return null;
714
+ }
715
+
716
+ try {
717
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as unknown;
718
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as JsonObject : null;
719
+ } catch {
720
+ return null;
721
+ }
722
+ }
723
+
724
+ export function ensureClaudeOnboarding(toolDir: string, hostHomeDir?: string): void {
725
+ const claudeJsonPath = path.join(toolDir, '.claude.json');
726
+ let data: JsonObject & {
727
+ hasCompletedOnboarding?: boolean;
728
+ projects?: Record<string, { hasTrustDialogAccepted?: boolean }>;
729
+ model?: string;
730
+ } = {};
731
+ if (fs.existsSync(claudeJsonPath)) {
732
+ try {
733
+ data = JSON.parse(fs.readFileSync(claudeJsonPath, 'utf8')) as typeof data;
734
+ } catch {
735
+ // malformed JSON, start fresh
736
+ }
737
+ }
738
+ let changed = false;
739
+ if (!data.hasCompletedOnboarding) {
740
+ data.hasCompletedOnboarding = true;
741
+ changed = true;
742
+ }
743
+ if (!data.projects) {
744
+ data.projects = {};
745
+ changed = true;
746
+ }
747
+ if (!data.projects['/workspace']) {
748
+ data.projects['/workspace'] = {};
749
+ changed = true;
750
+ }
751
+ if (!data.projects['/workspace'].hasTrustDialogAccepted) {
752
+ data.projects['/workspace'].hasTrustDialogAccepted = true;
753
+ changed = true;
754
+ }
755
+ if (hostHomeDir) {
756
+ const hostClaudeJson = readHostJsonSafe(path.join(hostHomeDir, '.claude.json'));
757
+ if (
758
+ hostClaudeJson
759
+ && typeof hostClaudeJson.model === 'string'
760
+ && hostClaudeJson.model !== ''
761
+ && !Object.hasOwn(data, 'model')
762
+ ) {
763
+ data.model = hostClaudeJson.model;
764
+ changed = true;
765
+ }
766
+ // Claude Code launch-pins a default effort per model generation (for
767
+ // example xhigh for Opus 4.7). The saved effortLevel is honored only after
768
+ // a top-level boolean `unpin*LaunchEffort: true` flag unlocks it, so mirror
769
+ // those flags here with the existing first-write semantics.
770
+ //
771
+ // Pattern matching avoids one patch per future model generation. If
772
+ // Anthropic changes the naming convention, this block will no-op and should
773
+ // be revisited.
774
+ if (hostClaudeJson) {
775
+ for (const key of Object.keys(hostClaudeJson)) {
776
+ if (
777
+ /^unpin.*LaunchEffort$/.test(key)
778
+ && hostClaudeJson[key] === true
779
+ && !Object.hasOwn(data, key)
780
+ ) {
781
+ data[key] = true;
782
+ changed = true;
783
+ }
784
+ }
785
+ }
786
+ }
787
+ if (changed) {
788
+ fs.writeFileSync(claudeJsonPath, JSON.stringify(data, null, 4), 'utf8');
789
+ }
790
+ }
791
+
792
+ export function ensureClaudeSettings(toolDir: string, hostHomeDir?: string): void {
793
+ const settingsPath = path.join(toolDir, 'settings.json');
794
+ let data: JsonObject & { skipDangerousModePermissionPrompt?: boolean; effortLevel?: string } = {};
795
+ if (fs.existsSync(settingsPath)) {
796
+ try {
797
+ data = JSON.parse(fs.readFileSync(settingsPath, 'utf8')) as typeof data;
798
+ } catch {
799
+ // malformed JSON, start fresh
800
+ }
801
+ }
802
+ let changed = false;
803
+ if (data.skipDangerousModePermissionPrompt !== true) {
804
+ data.skipDangerousModePermissionPrompt = true;
805
+ changed = true;
806
+ }
807
+ if (hostHomeDir) {
808
+ const hostSettings = readHostJsonSafe(path.join(hostHomeDir, '.claude', 'settings.json'));
809
+ if (
810
+ hostSettings
811
+ && typeof hostSettings.effortLevel === 'string'
812
+ && hostSettings.effortLevel !== ''
813
+ && !Object.hasOwn(data, 'effortLevel')
814
+ ) {
815
+ data.effortLevel = hostSettings.effortLevel;
816
+ changed = true;
817
+ }
818
+ }
819
+ if (changed) {
820
+ fs.writeFileSync(settingsPath, JSON.stringify(data, null, 4), 'utf8');
821
+ }
822
+ }
823
+
824
+ export function ensureCodexModelInheritance(toolDir: string, hostHomeDir?: string): void {
825
+ if (!hostHomeDir) {
826
+ return;
827
+ }
828
+
829
+ const hostConfigPath = path.join(hostHomeDir, '.codex', 'config.toml');
830
+ if (!fs.existsSync(hostConfigPath)) {
831
+ return;
832
+ }
833
+
834
+ let hostParsed: JsonObject;
835
+ try {
836
+ hostParsed = toml.parse(fs.readFileSync(hostConfigPath, 'utf8')) as JsonObject;
837
+ } catch {
838
+ return;
839
+ }
840
+
841
+ const sandboxConfigPath = path.join(toolDir, 'config.toml');
842
+ // This rewrites sandbox-side TOML and drops comments; the host config stays untouched.
843
+ let sandboxParsed: JsonObject = {};
844
+ if (fs.existsSync(sandboxConfigPath)) {
845
+ try {
846
+ sandboxParsed = toml.parse(fs.readFileSync(sandboxConfigPath, 'utf8')) as JsonObject;
847
+ } catch {
848
+ return;
849
+ }
850
+ }
851
+
852
+ let changed = false;
853
+ for (const key of ['model', 'model_reasoning_effort']) {
854
+ if (Object.hasOwn(sandboxParsed, key)) {
855
+ continue;
856
+ }
857
+ const value = hostParsed[key];
858
+ if (typeof value !== 'string' || value === '') {
859
+ continue;
860
+ }
861
+ sandboxParsed[key] = value;
862
+ changed = true;
863
+ }
864
+
865
+ if (changed) {
866
+ fs.writeFileSync(sandboxConfigPath, `${toml.stringify(sandboxParsed)}\n`, 'utf8');
867
+ }
868
+ }
869
+
870
+ export function ensureCodexWorkspaceTrust(toolDir: string): void {
871
+ const configPath = path.join(toolDir, 'config.toml');
872
+ let content = '';
873
+ if (fs.existsSync(configPath)) {
874
+ content = fs.readFileSync(configPath, 'utf8');
875
+ }
876
+ if (!content.includes('[projects."/workspace"]')) {
877
+ const entry = '\n[projects."/workspace"]\ntrust_level = "trusted"\n';
878
+ fs.writeFileSync(configPath, content + entry, 'utf8');
879
+ }
880
+ }
881
+
882
+ export function ensureOpenCodeModelInheritance(toolDir: string, hostHomeDir?: string): void {
883
+ if (!hostHomeDir) {
884
+ return;
885
+ }
886
+
887
+ const hostConfigPath = path.join(hostHomeDir, '.config', 'opencode', 'opencode.json');
888
+ const hostJson = readHostJsonSafe(hostConfigPath);
889
+ if (!hostJson) {
890
+ return;
891
+ }
892
+
893
+ const sandboxConfigPath = path.join(toolDir, 'opencode.json');
894
+ let sandboxJson: JsonObject = {};
895
+ if (fs.existsSync(sandboxConfigPath)) {
896
+ const existing = readHostJsonSafe(sandboxConfigPath);
897
+ if (!existing) {
898
+ return;
899
+ }
900
+ sandboxJson = existing;
901
+ }
902
+ let changed = false;
903
+ for (const key of ['model', 'small_model']) {
904
+ if (Object.hasOwn(sandboxJson, key)) {
905
+ continue;
906
+ }
907
+ const value = hostJson[key];
908
+ if (typeof value !== 'string' || value === '') {
909
+ continue;
910
+ }
911
+ sandboxJson[key] = value;
912
+ changed = true;
913
+ }
914
+
915
+ if (changed) {
916
+ fs.writeFileSync(sandboxConfigPath, JSON.stringify(sandboxJson, null, 2), 'utf8');
917
+ }
918
+ }
919
+
920
+ export function ensureGeminiWorkspaceTrust(toolDir: string): void {
921
+ const trustPath = path.join(toolDir, 'trustedFolders.json');
922
+ let data: Record<string, string> = {};
923
+ if (fs.existsSync(trustPath)) {
924
+ try {
925
+ data = JSON.parse(fs.readFileSync(trustPath, 'utf8')) as Record<string, string>;
926
+ } catch {
927
+ // malformed JSON, start fresh
928
+ }
929
+ }
930
+ if (data['/workspace'] !== 'TRUST_FOLDER') {
931
+ data['/workspace'] = 'TRUST_FOLDER';
932
+ fs.writeFileSync(trustPath, JSON.stringify(data, null, 2), 'utf8');
933
+ }
934
+ }
935
+
936
+ export function sandboxAliasesPath(home: string): string {
937
+ return hostJoin(home, '.agent-infra', 'aliases', 'sandbox.sh');
938
+ }
939
+
940
+ function escapeRegExp(value: string): string {
941
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
942
+ }
943
+
944
+ function stripManagedSandboxAliasBlocks(content: string): string {
945
+ const blockPattern = new RegExp(
946
+ `${escapeRegExp(SANDBOX_ALIAS_BLOCK_BEGIN)}[\\s\\S]*?${escapeRegExp(SANDBOX_ALIAS_BLOCK_END)}\\n?`,
947
+ 'g'
948
+ );
949
+ return content.replace(blockPattern, '').trimEnd();
950
+ }
951
+
952
+ function isLegacyManagedSandboxAliasFile(content: string): boolean {
953
+ const lines = content
954
+ .split(/\r?\n/)
955
+ .map((line) => line.trim())
956
+ .filter(Boolean);
957
+
958
+ if (lines.length === 0) {
959
+ return false;
960
+ }
961
+
962
+ const aliasPattern = new RegExp(`^alias (${SANDBOX_ALIAS_NAMES.map(escapeRegExp).join('|')})=`);
963
+ return lines.every((line) => aliasPattern.test(line));
964
+ }
965
+
966
+ export function ensureSandboxAliasesFile(home: string): { created: boolean; path: string } {
967
+ const aliasesPath = sandboxAliasesPath(home);
968
+ const managedBlock = `${SANDBOX_ALIAS_BLOCK_BEGIN}\n${DEFAULT_SANDBOX_ALIASES}${SANDBOX_ALIAS_BLOCK_END}\n`;
969
+ fs.mkdirSync(path.dirname(aliasesPath), { recursive: true });
970
+ const created = !fs.existsSync(aliasesPath);
971
+ let existing = '';
972
+
973
+ if (!created) {
974
+ existing = fs.readFileSync(aliasesPath, 'utf8');
975
+ }
976
+
977
+ const userContent = isLegacyManagedSandboxAliasFile(existing)
978
+ ? ''
979
+ : stripManagedSandboxAliasBlocks(existing);
980
+ const nextContent = userContent
981
+ ? `${userContent}\n\n${managedBlock}`
982
+ : managedBlock;
983
+
984
+ if (created || nextContent !== existing) {
985
+ fs.writeFileSync(aliasesPath, nextContent, 'utf8');
986
+ }
987
+
988
+ return { created, path: aliasesPath };
989
+ }
990
+
991
+ export function commandErrorMessage(error: unknown): string {
992
+ const stderr = typeof error === 'object' && error !== null && 'stderr' in error
993
+ ? String(error.stderr).trim()
994
+ : '';
995
+ const message = error instanceof Error
996
+ ? error.message
997
+ : typeof error === 'object' && error !== null && 'message' in error
998
+ ? String(error.message)
999
+ : 'Command failed';
1000
+ return redactCommandError(stderr || message);
1001
+ }
1002
+
1003
+ function runTaskCommand(cmd: string, args: string[], opts: { cwd?: string } = {}): string {
1004
+ try {
1005
+ return run(cmd, args, opts);
1006
+ } catch (error) {
1007
+ throw new Error(commandErrorMessage(error));
1008
+ }
1009
+ }
1010
+
1011
+ function runEngineTaskCommand(engine: string, cmd: string, args: string[], opts: { cwd?: string } = {}): string {
1012
+ const command = commandForEngine(engine, cmd, args);
1013
+ return runTaskCommand(command.cmd, command.args, opts);
1014
+ }
1015
+
1016
+ export function buildImage(
1017
+ config: SandboxCreateConfig,
1018
+ tools: SandboxTool[],
1019
+ dockerfilePath: string,
1020
+ imageSignature: string,
1021
+ {
1022
+ engine,
1023
+ runFn = runEngine,
1024
+ runSafeFn = runSafeEngine,
1025
+ runVerboseFn = runVerboseEngine,
1026
+ env = process.env
1027
+ }: {
1028
+ engine?: string;
1029
+ runFn?: EngineRunFn;
1030
+ runSafeFn?: EngineRunSafeFn;
1031
+ runVerboseFn?: EngineRunVerboseFn;
1032
+ env?: NodeJS.ProcessEnv;
1033
+ } = {}
1034
+ ): void {
1035
+ const selectedEngine = engine ?? detectEngine(config);
1036
+ const { uid: hostUid, gid: hostGid } = resolveBuildUid({
1037
+ engine: selectedEngine,
1038
+ runFn,
1039
+ runSafeFn,
1040
+ env
1041
+ });
1042
+
1043
+ runVerboseFn(selectedEngine, 'docker', [
1044
+ 'build',
1045
+ '-t',
1046
+ config.imageName,
1047
+ '--build-arg',
1048
+ `HOST_UID=${hostUid}`,
1049
+ '--build-arg',
1050
+ `HOST_GID=${hostGid}`,
1051
+ '--build-arg',
1052
+ `AI_TOOL_PACKAGES=${toolNpmPackagesArg(tools)}`,
1053
+ '--label',
1054
+ sandboxLabel(config),
1055
+ '--label',
1056
+ `${sandboxImageConfigLabel(config)}=${imageSignature}`,
1057
+ '-f',
1058
+ toEnginePath(selectedEngine, dockerfilePath),
1059
+ toEnginePath(selectedEngine, config.repoRoot)
1060
+ ], { cwd: config.repoRoot });
1061
+ }
1062
+
1063
+ export async function create(args: string[]): Promise<void> {
1064
+ const { values, positionals } = parseArgs({
1065
+ args,
1066
+ allowPositionals: true,
1067
+ strict: true,
1068
+ options: {
1069
+ cpu: { type: 'string' },
1070
+ memory: { type: 'string' },
1071
+ help: { type: 'boolean', short: 'h' }
1072
+ }
1073
+ });
1074
+
1075
+ if (values.help) {
1076
+ process.stdout.write(`${USAGE}\n`);
1077
+ return;
1078
+ }
1079
+
1080
+ if (positionals.length < 1 || positionals.length > 2) {
1081
+ throw new Error(USAGE);
1082
+ }
1083
+
1084
+ validateSelinuxDisableEnv();
1085
+ validateClaudeCredentialsEnvOverride();
1086
+
1087
+ const config = loadConfig();
1088
+ const [branchOrTaskId = '', base] = positionals;
1089
+ const branch = resolveTaskBranch(branchOrTaskId, config.repoRoot);
1090
+ assertValidBranchName(branch);
1091
+ const effectiveConfig = {
1092
+ ...config,
1093
+ vm: {
1094
+ ...config.vm,
1095
+ cpu: parsePositiveIntegerOption(values.cpu, '--cpu') ?? config.vm.cpu,
1096
+ memory: parsePositiveIntegerOption(values.memory, '--memory') ?? config.vm.memory
1097
+ }
1098
+ };
1099
+ const worktreeCandidates = worktreeDirCandidates(effectiveConfig, branch);
1100
+ assertBranchAvailable(config.repoRoot, branch, { allowedWorktrees: worktreeCandidates });
1101
+ const tools = resolveTools(effectiveConfig);
1102
+ const resolvedTools = resolveToolDirs(effectiveConfig, tools, branch);
1103
+ // Fail fast before any filesystem/docker side effects so a missing
1104
+ // Claude Code credential blob doesn't leave the user with a stale
1105
+ // worktree, docker image, or temporary Dockerfile they need to manually
1106
+ // clean up.
1107
+ assertClaudeCredentialsAvailable(
1108
+ effectiveConfig.home,
1109
+ effectiveConfig.project,
1110
+ resolvedTools
1111
+ );
1112
+ const container = containerName(effectiveConfig, branch);
1113
+ const worktree = worktreeCandidates.find((candidate) => fs.existsSync(candidate)) ?? worktreeCandidates[0] ?? '';
1114
+ const shareCommon = shareCommonDir(effectiveConfig);
1115
+ const shareBranch = shareBranchDir(effectiveConfig, branch);
1116
+ const preparedDockerfile = prepareDockerfile(effectiveConfig);
1117
+ const baseBranch = base ?? runSafe('git', ['-C', effectiveConfig.repoRoot, 'branch', '--show-current']);
1118
+ const expectedImageSignature = buildSignature(preparedDockerfile, tools);
1119
+ const engine = detectEngine(effectiveConfig);
1120
+
1121
+ p.intro(pc.cyan('AI Sandbox'));
1122
+ p.log.info(
1123
+ `Project: ${pc.bold(effectiveConfig.project)} | Branch: ${pc.bold(branch)} | Base: ${pc.bold(baseBranch || 'HEAD')}`
1124
+ );
1125
+
1126
+ try {
1127
+ p.log.step('Checking container engine...');
1128
+ await ensureDocker(effectiveConfig, (detail: string) => {
1129
+ p.log.info(` ${detail}`);
1130
+ });
1131
+ p.log.success('Docker is ready');
1132
+
1133
+ const imageExists = runOkEngine(engine, 'docker', ['image', 'inspect', effectiveConfig.imageName]);
1134
+ const currentImageSignature = imageExists
1135
+ ? runSafeEngine(engine, 'docker', [
1136
+ 'image',
1137
+ 'inspect',
1138
+ '--format',
1139
+ `{{ index .Config.Labels "${sandboxImageConfigLabel(effectiveConfig)}" }}`,
1140
+ effectiveConfig.imageName
1141
+ ])
1142
+ : '';
1143
+ const needsImageBuild = !imageExists || currentImageSignature !== expectedImageSignature;
1144
+
1145
+ if (needsImageBuild) {
1146
+ p.log.step(imageExists ? 'Rebuilding stale image...' : 'Building image for first use...');
1147
+ buildImage(
1148
+ effectiveConfig,
1149
+ tools,
1150
+ preparedDockerfile.path,
1151
+ expectedImageSignature,
1152
+ { engine }
1153
+ );
1154
+ p.log.success(imageExists ? 'Image rebuilt' : 'Image built');
1155
+ } else {
1156
+ p.log.step(`Using existing image ${effectiveConfig.imageName}`);
1157
+ }
1158
+
1159
+ await p.tasks([
1160
+ {
1161
+ title: 'Setting up git worktree',
1162
+ task: async (message: (text: string) => void) => {
1163
+ if (fs.existsSync(worktree)) {
1164
+ if (fs.readdirSync(worktree).length > 0) {
1165
+ return `Worktree exists at ${worktree}`;
1166
+ }
1167
+ fs.rmSync(worktree, { recursive: true, force: true });
1168
+ }
1169
+
1170
+ const branchExists = runOk('git', [
1171
+ '-C',
1172
+ effectiveConfig.repoRoot,
1173
+ 'show-ref',
1174
+ '--verify',
1175
+ '--quiet',
1176
+ `refs/heads/${branch}`
1177
+ ]);
1178
+
1179
+ if (branchExists) {
1180
+ message(`Using existing branch '${branch}'...`);
1181
+ runEngineTaskCommand(engine, 'git', [
1182
+ '-C',
1183
+ toEnginePath(engine, effectiveConfig.repoRoot),
1184
+ 'worktree',
1185
+ 'add',
1186
+ toEnginePath(engine, worktree),
1187
+ branch
1188
+ ]);
1189
+ } else {
1190
+ message(`Creating branch '${branch}' from '${baseBranch}'...`);
1191
+ runEngineTaskCommand(engine, 'git', [
1192
+ '-C',
1193
+ toEnginePath(engine, effectiveConfig.repoRoot),
1194
+ 'worktree',
1195
+ 'add',
1196
+ '-b',
1197
+ branch,
1198
+ toEnginePath(engine, worktree),
1199
+ baseBranch
1200
+ ]);
1201
+ }
1202
+
1203
+ return `Worktree ready at ${worktree}`;
1204
+ }
1205
+ },
1206
+ {
1207
+ title: 'Preparing tool state',
1208
+ task: async () => {
1209
+ for (const { tool, dir } of resolvedTools) {
1210
+ fs.mkdirSync(dir, { recursive: true });
1211
+
1212
+ for (const { hostPath, sandboxName } of tool.hostPreSeedFiles ?? []) {
1213
+ const destination = path.join(dir, sandboxName);
1214
+ if (fs.existsSync(hostPath) && !fs.existsSync(destination)) {
1215
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
1216
+ fs.copyFileSync(hostPath, destination);
1217
+ }
1218
+ }
1219
+
1220
+ for (const { hostDir, sandboxSubdir } of tool.hostPreSeedDirs ?? []) {
1221
+ const destination = path.join(dir, sandboxSubdir);
1222
+ if (fs.existsSync(hostDir) && !fs.existsSync(destination)) {
1223
+ fs.cpSync(hostDir, destination, { recursive: true });
1224
+ }
1225
+ }
1226
+
1227
+ for (const relativePath of tool.pathRewriteFiles ?? []) {
1228
+ const filePath = path.join(dir, relativePath);
1229
+ if (!fs.existsSync(filePath)) {
1230
+ continue;
1231
+ }
1232
+ let content = fs.readFileSync(filePath, 'utf8');
1233
+ const containerHome = path.posix.dirname(tool.containerMount);
1234
+ for (const hostPath of [effectiveConfig.repoRoot, effectiveConfig.home]) {
1235
+ const replacement = hostPath === effectiveConfig.repoRoot ? '/workspace' : containerHome;
1236
+ content = content.replaceAll(hostPath, replacement);
1237
+ const posixHostPath = hostPath.replaceAll('\\', '/');
1238
+ if (posixHostPath !== hostPath) {
1239
+ content = content.replaceAll(posixHostPath, replacement);
1240
+ }
1241
+ }
1242
+ fs.writeFileSync(filePath, content, 'utf8');
1243
+ }
1244
+ }
1245
+
1246
+ return `${resolvedTools.length} tool config directories ready`;
1247
+ }
1248
+ },
1249
+ {
1250
+ title: `Starting container '${container}'`,
1251
+ task: async (message: (text: string) => void) => {
1252
+ const existing = runSafeEngine(engine, 'docker', ['ps', '-a', '--format', '{{.Names}}']).split('\n').filter(Boolean);
1253
+ const matchedContainers = containerNameCandidates(effectiveConfig, branch)
1254
+ .filter((name) => existing.includes(name));
1255
+
1256
+ if (matchedContainers.length > 0) {
1257
+ message('Removing old container instance...');
1258
+ for (const name of matchedContainers) {
1259
+ runSafeEngine(engine, 'docker', ['stop', name]);
1260
+ runSafeEngine(engine, 'docker', ['rm', name]);
1261
+ }
1262
+ }
1263
+
1264
+ const aliasesFile = ensureSandboxAliasesFile(effectiveConfig.home);
1265
+ if (aliasesFile.created) {
1266
+ message(`Created default sandbox aliases at ${aliasesFile.path}`);
1267
+ }
1268
+
1269
+ const gitconfigPath = path.join(effectiveConfig.home, '.gitconfig');
1270
+ const gitconfigContent = fs.existsSync(gitconfigPath)
1271
+ ? fs.readFileSync(gitconfigPath, 'utf8')
1272
+ : '';
1273
+ const needsGpg = detectGpgConfig(gitconfigContent);
1274
+ const hasHostGpgKeys = needsGpg && hostHasGpgKeys(effectiveConfig.home);
1275
+ const signingKey = needsGpg
1276
+ ? getGitSigningKey({ repoPath: worktree, home: effectiveConfig.home })
1277
+ : null;
1278
+ const cachedGpg = needsGpg
1279
+ ? readGpgCache(
1280
+ effectiveConfig.home,
1281
+ effectiveConfig.project,
1282
+ undefined,
1283
+ signingKey
1284
+ )
1285
+ : null;
1286
+ const envFile = buildContainerEnvFile(resolvedTools, engine);
1287
+ let hostShellConfig: HostShellConfig;
1288
+ try {
1289
+ const claudeCodeEntry = resolvedTools.find(({ tool }) => tool.id === 'claude-code');
1290
+ if (claudeCodeEntry) {
1291
+ ensureClaudeOnboarding(claudeCodeEntry.dir, effectiveConfig.home);
1292
+ ensureClaudeSettings(claudeCodeEntry.dir, effectiveConfig.home);
1293
+ // Credential availability is asserted up-front in create() so we
1294
+ // know the shared credentials file already exists at this point.
1295
+ }
1296
+ const codexEntry = resolvedTools.find(({ tool }) => tool.id === 'codex');
1297
+ if (codexEntry) {
1298
+ ensureCodexModelInheritance(codexEntry.dir, effectiveConfig.home);
1299
+ ensureCodexWorkspaceTrust(codexEntry.dir);
1300
+ }
1301
+ const geminiEntry = resolvedTools.find(({ tool }) => tool.id === 'gemini-cli');
1302
+ if (geminiEntry) {
1303
+ ensureGeminiWorkspaceTrust(geminiEntry.dir);
1304
+ }
1305
+ const opencodeEntry = resolvedTools.find(({ tool }) => tool.id === 'opencode');
1306
+ if (opencodeEntry) {
1307
+ // The TUI reads <toolDir>/opencode.json via OPENCODE_CONFIG pinned in tools.js.
1308
+ ensureOpenCodeModelInheritance(opencodeEntry.dir, effectiveConfig.home);
1309
+ }
1310
+ const toolVolumes = resolvedTools.flatMap(({ tool, dir }) => [
1311
+ '-v',
1312
+ volumeArg(engine, dir, tool.containerMount)
1313
+ ]);
1314
+ const workspaceDir = path.join(effectiveConfig.repoRoot, '.agents', 'workspace');
1315
+ hostShellConfig = prepareHostShellConfig({
1316
+ home: effectiveConfig.home,
1317
+ project: effectiveConfig.project,
1318
+ branch,
1319
+ repoRoot: effectiveConfig.repoRoot
1320
+ });
1321
+ const shellConfigVolumes = hostShellConfig.mounts.flatMap(({ hostPath, containerPath }) => [
1322
+ '-v',
1323
+ volumeArg(engine, hostPath, containerPath, ':ro')
1324
+ ]);
1325
+ const liveMountVolumes = resolvedTools.flatMap(({ tool }) =>
1326
+ (tool.hostLiveMounts ?? [])
1327
+ .filter(({ hostPath }) => fs.existsSync(hostPath))
1328
+ .flatMap(({ hostPath, containerSubpath }) => [
1329
+ '-v',
1330
+ volumeArg(engine, hostPath, path.posix.join(tool.containerMount, containerSubpath))
1331
+ ])
1332
+ );
1333
+
1334
+ fs.mkdirSync(workspaceDir, { recursive: true });
1335
+ fs.mkdirSync(shareCommon, { recursive: true });
1336
+ fs.mkdirSync(shareBranch, { recursive: true });
1337
+
1338
+ const dotfilesSnapshot = materializeDotfiles(
1339
+ effectiveConfig.dotfilesDir,
1340
+ dotfilesCacheDir(effectiveConfig.home, effectiveConfig.project)
1341
+ );
1342
+ const dotfilesMount = dotfilesSnapshot
1343
+ ? buildDotfilesVolumeArgs(engine, dotfilesSnapshot.cacheDir)
1344
+ : [];
1345
+
1346
+ runEngineTaskCommand(engine, 'docker', [
1347
+ 'run',
1348
+ '-d',
1349
+ '--name',
1350
+ container,
1351
+ '--hostname',
1352
+ `${effectiveConfig.project}-sandbox`,
1353
+ '--label',
1354
+ sandboxLabel(effectiveConfig),
1355
+ '--label',
1356
+ `${sandboxBranchLabel(effectiveConfig)}=${branch}`,
1357
+ '-v',
1358
+ volumeArg(engine, worktree, '/workspace'),
1359
+ '-v',
1360
+ volumeArg(engine, workspaceDir, '/workspace/.agents/workspace'),
1361
+ '-v',
1362
+ volumeArg(engine, shareCommon, '/share/common'),
1363
+ '-v',
1364
+ volumeArg(engine, shareBranch, '/share/branch'),
1365
+ '-v',
1366
+ volumeArg(
1367
+ engine,
1368
+ path.join(effectiveConfig.repoRoot, '.git'),
1369
+ `${toEnginePath(engine, effectiveConfig.repoRoot)}/.git`
1370
+ ),
1371
+ '-v',
1372
+ volumeArg(engine, hostJoin(effectiveConfig.home, '.ssh'), '/home/devuser/.ssh', ':ro'),
1373
+ ...dotfilesMount,
1374
+ ...toolVolumes,
1375
+ ...liveMountVolumes,
1376
+ ...shellConfigVolumes,
1377
+ ...envFile.dockerArgs,
1378
+ '-w',
1379
+ '/workspace',
1380
+ effectiveConfig.imageName
1381
+ ]);
1382
+ } finally {
1383
+ envFile.cleanup();
1384
+ }
1385
+
1386
+ // Belt-and-suspenders: re-create the four shell-config symlinks at
1387
+ // runtime so users with a custom `sandbox.dockerfile` (which won't
1388
+ // include the ai-tools.dockerfile symlink fragment) still get
1389
+ // ~/.gitconfig and friends pointing into the host bind-mount.
1390
+ // `ln -sf` is idempotent for the default image.
1391
+ ensureShellConfigSymlinks(engine, container);
1392
+
1393
+ if (needsGpg) {
1394
+ message(
1395
+ cachedGpg
1396
+ ? 'Syncing GPG keys from cache...'
1397
+ : hasHostGpgKeys
1398
+ ? 'Syncing GPG keys (you may be prompted for your passphrase)...'
1399
+ : 'Checking GPG cache before falling back to stripped git config...'
1400
+ );
1401
+ try {
1402
+ if (syncGpgKeys(
1403
+ container,
1404
+ effectiveConfig.home,
1405
+ effectiveConfig.project,
1406
+ undefined,
1407
+ undefined,
1408
+ {
1409
+ cachedOverride: cachedGpg,
1410
+ repoPath: worktree,
1411
+ signingKey,
1412
+ dockerExecFn: (cmd: string, args: string[], opts?: ExecSyncOptions) => execEngine(engine, cmd, args, opts),
1413
+ dockerRunSafeFn: (cmd: string, args: string[], opts?: { cwd?: string }) => runSafeEngine(engine, cmd, args, opts)
1414
+ }
1415
+ )) {
1416
+ writeSanitizedGitconfig({
1417
+ home: effectiveConfig.home,
1418
+ hostConfigDir: hostShellConfig.hostDir,
1419
+ stripGpg: false,
1420
+ repoRoot: effectiveConfig.repoRoot
1421
+ });
1422
+ } else {
1423
+ message(
1424
+ hasHostGpgKeys
1425
+ ? 'GPG key sync failed; using stripped git config fallback...'
1426
+ : 'Host GPG keys unavailable; using stripped git config fallback...'
1427
+ );
1428
+ }
1429
+ } catch {
1430
+ message(
1431
+ hasHostGpgKeys
1432
+ ? 'GPG key sync failed; using stripped git config fallback...'
1433
+ : 'Host GPG keys unavailable; using stripped git config fallback...'
1434
+ );
1435
+ }
1436
+ }
1437
+
1438
+ for (const { tool } of resolvedTools) {
1439
+ for (const command of tool.postSetupCmds ?? []) {
1440
+ runSafeEngine(engine, 'docker', ['exec', container, 'bash', '-lc', command]);
1441
+ }
1442
+ }
1443
+
1444
+ return 'Container started';
1445
+ }
1446
+ }
1447
+ ]);
1448
+ } finally {
1449
+ preparedDockerfile.cleanup();
1450
+ }
1451
+
1452
+ p.log.step('Verifying setup...');
1453
+ const runningContainers = runSafeEngine(engine, 'docker', ['ps', '--format', '{{.Names}}']).split('\n');
1454
+ const checks = [
1455
+ { name: 'Container running', ok: runningContainers.includes(container) },
1456
+ ...runtimeChecks(effectiveConfig.runtimes).map((check) => ({
1457
+ name: check.name,
1458
+ ok: runOkEngine(engine, 'docker', ['exec', container, ...check.cmd])
1459
+ })),
1460
+ { name: 'GitHub CLI', ok: runOkEngine(engine, 'docker', ['exec', container, 'gh', '--version']) }
1461
+ ];
1462
+ const toolChecks = tools.map((tool) => ({
1463
+ name: tool.name,
1464
+ ok: runOkEngine(engine, 'docker', ['exec', container, 'bash', '-lc', tool.versionCmd]),
1465
+ hint: tool.setupHint
1466
+ }));
1467
+
1468
+ for (const check of checks) {
1469
+ p.log.info(` ${check.ok ? pc.green('✓') : pc.yellow('?')} ${check.name}`);
1470
+ }
1471
+ for (const check of toolChecks) {
1472
+ p.log.info(` ${check.ok ? pc.green('✓') : pc.yellow('?')} ${check.name}`);
1473
+ if (!check.ok) {
1474
+ p.log.warn(` ${check.hint}`);
1475
+ }
1476
+ }
1477
+
1478
+ p.outro(pc.green('Sandbox ready'));
1479
+
1480
+ const toolHints = resolvedTools.map(({ tool, dir }) => {
1481
+ const hasLiveMount = (tool.hostLiveMounts ?? []).some(({ hostPath }) => fs.existsSync(hostPath));
1482
+ const hint = hasLiveMount
1483
+ ? 'Live-mounted auth/config files stay in sync with the host.'
1484
+ : tool.setupHint;
1485
+ return `${tool.name}: ${hint} Config dir: ${dir}`;
1486
+ }).join('\n');
1487
+
1488
+ process.stdout.write(`
1489
+ Container: ${container}
1490
+ Image: ${effectiveConfig.imageName}
1491
+ Worktree: ${worktree}
1492
+ Host aliases: ${sandboxAliasesPath(effectiveConfig.home)}
1493
+ Share (common): ${shareCommon} -> /share/common
1494
+ Share (branch): ${shareBranch} -> /share/branch
1495
+
1496
+ Management:
1497
+ ai sandbox ls
1498
+ ai sandbox exec ${branch}
1499
+ ai sandbox rm ${branch}
1500
+
1501
+ Sandbox aliases:
1502
+ Edit the host aliases file to customize shortcuts exposed at ${CONTAINER_HOME}/.bash_aliases inside the sandbox container.
1503
+
1504
+ Tool notes:
1505
+ ${toolHints}
1506
+ `);
1507
+ }