@ygrishajev/jig 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/dist/adapters/find-symlink.js +23 -0
  4. package/dist/adapters/git/git-workspace.js +297 -0
  5. package/dist/adapters/local-store/credentials-file.js +51 -0
  6. package/dist/adapters/local-store/local-run-store.js +45 -0
  7. package/dist/adapters/local-store/local-state.js +12 -0
  8. package/dist/adapters/local-store/metrics-log.js +119 -0
  9. package/dist/adapters/local-store/run-artefacts.js +76 -0
  10. package/dist/adapters/local-store/run-lock.js +51 -0
  11. package/dist/adapters/local-store/run-paths.js +49 -0
  12. package/dist/adapters/logging/create-logger.js +29 -0
  13. package/dist/adapters/run-store/composite-run-store.js +57 -0
  14. package/dist/adapters/run-store/git-remote-run-store.js +239 -0
  15. package/dist/adapters/sandbox-image/docker-images.js +93 -0
  16. package/dist/adapters/sandbox-image/image-recipe.js +96 -0
  17. package/dist/adapters/sandbox-image/latest-agent-versions.js +9 -0
  18. package/dist/adapters/sandcastle/agents.js +100 -0
  19. package/dist/adapters/sandcastle/codex-auth.js +191 -0
  20. package/dist/adapters/sandcastle/git-hooks.js +20 -0
  21. package/dist/adapters/sandcastle/open-session.js +67 -0
  22. package/dist/adapters/sandcastle/private-clone-docker.js +232 -0
  23. package/dist/adapters/sandcastle/sandcastle-env.js +17 -0
  24. package/dist/adapters/sandcastle/sandcastle-session.js +338 -0
  25. package/dist/adapters/sandcastle/structured-output.js +35 -0
  26. package/dist/adapters/sandcastle/usage.js +65 -0
  27. package/dist/adapters/telemetry/open-telemetry.js +29 -0
  28. package/dist/adapters/terminal/ask-for-agents.js +61 -0
  29. package/dist/adapters/terminal/ask-for-credential.js +32 -0
  30. package/dist/adapters/terminal/ask-for-preset.js +15 -0
  31. package/dist/adapters/terminal/standard-input.js +7 -0
  32. package/dist/adapters/terminal/terminal.js +45 -0
  33. package/dist/app/container.js +131 -0
  34. package/dist/app/init-sandbox.js +185 -0
  35. package/dist/app/observed-events.js +10 -0
  36. package/dist/app/report-cleanup.js +10 -0
  37. package/dist/app/run-jig.js +101 -0
  38. package/dist/app/run-status.js +20 -0
  39. package/dist/app/run-stores.js +107 -0
  40. package/dist/app/sandbox-image.js +151 -0
  41. package/dist/app/throwaway-sandbox.js +49 -0
  42. package/dist/cli/app-action.js +18 -0
  43. package/dist/cli/commands/presets.js +32 -0
  44. package/dist/cli/commands/run.js +82 -0
  45. package/dist/cli/commands/sandbox.js +54 -0
  46. package/dist/cli/commands/status.js +41 -0
  47. package/dist/cli/config-option.js +18 -0
  48. package/dist/cli/exit-when-done.js +11 -0
  49. package/dist/cli/log-format-option.js +14 -0
  50. package/dist/cli/main.js +33 -0
  51. package/dist/cli/read-request.js +36 -0
  52. package/dist/cli/with-app.js +73 -0
  53. package/dist/cli/with-error-handling.js +31 -0
  54. package/dist/cli/with-input.js +27 -0
  55. package/dist/config/describe-issues.js +6 -0
  56. package/dist/config/environment.js +53 -0
  57. package/dist/config/load-config.js +122 -0
  58. package/dist/config/presets.js +150 -0
  59. package/dist/config/write-config.js +39 -0
  60. package/dist/domain/agent-role.js +12 -0
  61. package/dist/domain/apply-outcome.js +132 -0
  62. package/dist/domain/completion-reuse.js +176 -0
  63. package/dist/domain/design-docs.js +3 -0
  64. package/dist/domain/design-review-report.js +86 -0
  65. package/dist/domain/design-review.js +193 -0
  66. package/dist/domain/errors.js +139 -0
  67. package/dist/domain/events.js +8 -0
  68. package/dist/domain/final-check.js +133 -0
  69. package/dist/domain/outcome.js +26 -0
  70. package/dist/domain/plan-coverage.js +129 -0
  71. package/dist/domain/protected-paths.js +35 -0
  72. package/dist/domain/retry.js +21 -0
  73. package/dist/domain/run-id.js +42 -0
  74. package/dist/domain/run-state.js +147 -0
  75. package/dist/domain/settings.js +49 -0
  76. package/dist/domain/slice.js +63 -0
  77. package/dist/domain/usage.js +1 -0
  78. package/dist/domain/work-facts.js +22 -0
  79. package/dist/flow/define-flow.js +11 -0
  80. package/dist/flow/engine.js +255 -0
  81. package/dist/flow/run-flow.js +129 -0
  82. package/dist/git/branch.js +26 -0
  83. package/dist/git/merge.js +92 -0
  84. package/dist/git/repository.js +48 -0
  85. package/dist/git/throwaway-branch.js +64 -0
  86. package/dist/observers/logging-observer.js +51 -0
  87. package/dist/observers/metrics.js +109 -0
  88. package/dist/observers/run-events.js +25 -0
  89. package/dist/observers/tracing-observer.js +86 -0
  90. package/dist/ports/agent-session.js +1 -0
  91. package/dist/ports/observability.js +1 -0
  92. package/dist/ports/run-store.js +1 -0
  93. package/dist/ports/sandbox-git.js +1 -0
  94. package/dist/ports/sandbox-images.js +1 -0
  95. package/dist/ports/workspace.js +1 -0
  96. package/dist/prompts/design-review.js +172 -0
  97. package/dist/prompts/final-check.js +58 -0
  98. package/dist/prompts/planning.js +111 -0
  99. package/dist/prompts/pull-request.js +78 -0
  100. package/dist/prompts/slice.js +254 -0
  101. package/dist/prompts/toolchain.js +37 -0
  102. package/dist/steps/completion-reuse.js +32 -0
  103. package/dist/steps/design-review.js +38 -0
  104. package/dist/steps/final-check.js +39 -0
  105. package/dist/steps/finishing.js +72 -0
  106. package/dist/steps/planning.js +77 -0
  107. package/dist/steps/pull-request-description.js +142 -0
  108. package/dist/steps/slice.js +149 -0
  109. package/package.json +95 -4
  110. package/presets/cheap-volume.json +7 -0
  111. package/presets/claude-only.json +7 -0
  112. package/presets/codex-only.json +7 -0
  113. package/presets/codex-reviewed-opencode.json +7 -0
  114. package/presets/full-power-codex.json +7 -0
  115. package/presets/full-power.json +7 -0
  116. package/presets/long-claude.json +7 -0
  117. package/presets/open-weight.json +7 -0
@@ -0,0 +1,232 @@
1
+ import { createBindMountSandboxProvider, } from '@ai-hero/sandcastle';
2
+ import { Result } from 'better-result';
3
+ import { execa, execaSync } from 'execa';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { createWriteStream, existsSync, readFileSync } from 'node:fs';
6
+ import { mkdtemp, rm } from 'node:fs/promises';
7
+ import { homedir, tmpdir } from 'node:os';
8
+ import path from 'node:path';
9
+ import { Transform } from 'node:stream';
10
+ import { pipeline } from 'node:stream/promises';
11
+ import { GitCommandFailed, messageOf } from '../../domain/errors.js';
12
+ import { openRepo } from '../../git/repository.js';
13
+ /**
14
+ * A docker sandbox that shares nothing of the repository with the host. Sandcastle offers the
15
+ * worktree and `.git` as mounts and they are ignored: the container gets its own clone of the run
16
+ * and base branches, so nothing it does can reach git state the host later runs git on. Sandcastle
17
+ * keeps its worktree on the host, where its own git commands stay out of the sandbox's reach. See
18
+ * `docs/superpowers/specs/2026-11-04-private-clone-sandbox-design.md`.
19
+ */
20
+ export function privateCloneDocker(options) {
21
+ const docker = options.docker ?? realDocker;
22
+ const container = `jig-sandbox-${randomUUID()}`;
23
+ const copyLimit = options.copyLimitBytes ?? COPY_LIMIT_BYTES;
24
+ const create = ({ hostRepoPath, env }) => startWithClone({ ...options, docker, container, hostRepoPath, env });
25
+ return {
26
+ provider: createBindMountSandboxProvider({
27
+ name: 'jig-private-clone',
28
+ env: options.env,
29
+ sandboxHomedir: SANDBOX_HOME,
30
+ create,
31
+ }),
32
+ create,
33
+ copyOut: (sandboxPath, hostPath) => copyBytesOut(docker, container, sandboxPath, hostPath, copyLimit),
34
+ };
35
+ }
36
+ const realDocker = {
37
+ run: async (args, { stdin, onLine } = {}) => {
38
+ const { exitCode, stdout, stderr } = await execa('docker', args, {
39
+ reject: false,
40
+ input: stdin,
41
+ maxBuffer: 256 * 1024 ** 2,
42
+ stdout: onLine
43
+ ? function* (line) {
44
+ onLine(String(line));
45
+ yield line;
46
+ }
47
+ : 'pipe',
48
+ });
49
+ return { exitCode: exitCode ?? 1, stdout, stderr };
50
+ },
51
+ copyIn: async (hostPath, target) => {
52
+ await execa('docker', ['cp', hostPath, target]);
53
+ },
54
+ stream: (args) => {
55
+ const subprocess = execa('docker', args, { reject: false, buffer: false, stderr: 'ignore' });
56
+ return {
57
+ stdout: subprocess.stdout,
58
+ finished: subprocess.then(({ exitCode }) => exitCode ?? 1),
59
+ };
60
+ },
61
+ remove: async (container) => {
62
+ await execa('docker', ['rm', '-f', container], { reject: false });
63
+ },
64
+ removeOnExit: (container) => {
65
+ const removeNow = () => {
66
+ execaSync('docker', ['rm', '-f', container], { reject: false, stdio: 'ignore' });
67
+ };
68
+ process.on('exit', removeNow);
69
+ return () => process.off('exit', removeNow);
70
+ },
71
+ };
72
+ /** Far more than a run's commits should ever be; stops a sandbox from filling the host's disk. */
73
+ const COPY_LIMIT_BYTES = 2 * 1024 ** 3;
74
+ async function startWithClone(input) {
75
+ const { docker, container } = input;
76
+ await mustSucceed(docker.run(containerArguments(input)));
77
+ const cancelRemoveOnExit = docker.removeOnExit(container);
78
+ let ready = false;
79
+ try {
80
+ await copyBundleIn(input);
81
+ await mustSucceed(docker.run(inContainer(container, '/', cloneCommand(input))));
82
+ await mustSucceed(docker.run(inContainer(container, SANDBOX_WORKSPACE, 'cat > .git/info/exclude', true), {
83
+ stdin: await hostExcludes(input.hostRepoPath),
84
+ }));
85
+ ready = true;
86
+ }
87
+ finally {
88
+ if (!ready) {
89
+ cancelRemoveOnExit();
90
+ await docker.remove(container);
91
+ }
92
+ }
93
+ return {
94
+ worktreePath: SANDBOX_WORKSPACE,
95
+ exec: (command, { onLine, cwd, sudo, stdin } = {}) => docker.run(inContainer(container, cwd ?? SANDBOX_WORKSPACE, sudo ? `sudo ${command}` : command, stdin !== undefined), { onLine, stdin }),
96
+ copyFileIn: (hostPath, sandboxPath) => docker.copyIn(hostPath, `${container}:${sandboxPath}`),
97
+ copyFileOut: async (sandboxPath, hostPath) => {
98
+ const copied = await copyBytesOut(docker, container, sandboxPath, hostPath, COPY_LIMIT_BYTES);
99
+ if (copied.isErr())
100
+ return Promise.reject(copied.error);
101
+ },
102
+ close: async () => {
103
+ cancelRemoveOnExit();
104
+ await docker.remove(container);
105
+ },
106
+ };
107
+ }
108
+ /** Sandcastle's provider contract reports a failed start by rejecting. */
109
+ async function mustSucceed(running) {
110
+ const { exitCode, stderr } = await running;
111
+ if (exitCode !== 0) {
112
+ return Promise.reject(new Error(`docker failed (exit ${exitCode}): ${stderr.trim()}`));
113
+ }
114
+ }
115
+ function containerArguments(input) {
116
+ const environment = { ...input.env, ...AGENT_IDENTITY, HOME: SANDBOX_HOME };
117
+ return [
118
+ 'run',
119
+ '-d',
120
+ '--name',
121
+ input.container,
122
+ ...(process.getuid && process.getgid
123
+ ? ['--user', `${process.getuid()}:${process.getgid()}`]
124
+ : []),
125
+ ...(input.loginDirectory ? ['-v', `${input.loginDirectory}:${SANDBOX_CODEX_DIRECTORY}:z`] : []),
126
+ ...Object.entries(environment).flatMap(([name, value]) => ['-e', `${name}=${value}`]),
127
+ input.imageName,
128
+ ];
129
+ }
130
+ /** Set in the container so they override the `user.name` sandcastle copies in from the host. */
131
+ const AGENT_IDENTITY = {
132
+ GIT_AUTHOR_NAME: 'jig',
133
+ GIT_AUTHOR_EMAIL: 'jig@users.noreply.invalid',
134
+ GIT_COMMITTER_NAME: 'jig',
135
+ GIT_COMMITTER_EMAIL: 'jig@users.noreply.invalid',
136
+ };
137
+ const SANDBOX_HOME = '/home/agent';
138
+ const SANDBOX_CODEX_DIRECTORY = `${SANDBOX_HOME}/.codex`;
139
+ /** Only the two branches a run needs, so the rest of the repository's history stays on the host. */
140
+ async function copyBundleIn(input) {
141
+ const directory = await mkdtemp(path.join(tmpdir(), 'jig-bundle-'));
142
+ try {
143
+ const bundle = path.join(directory, 'in.bundle');
144
+ await openRepo(input.hostRepoPath).raw([
145
+ 'bundle',
146
+ 'create',
147
+ bundle,
148
+ input.branch,
149
+ input.baseBranch,
150
+ ]);
151
+ await input.docker.copyIn(bundle, `${input.container}:${INCOMING_BUNDLE}`);
152
+ }
153
+ finally {
154
+ await rm(directory, { recursive: true, force: true });
155
+ }
156
+ }
157
+ const INCOMING_BUNDLE = '/tmp/in.bundle';
158
+ function inContainer(container, cwd, command, keepStdin = false) {
159
+ return ['exec', ...(keepStdin ? ['-i'] : []), '-w', cwd, container, 'sh', '-c', command];
160
+ }
161
+ /** Drops the remote afterwards: it names a file that is gone, and agents have nowhere to push. */
162
+ function cloneCommand({ branch, baseBranch }) {
163
+ return [
164
+ `git clone -q -b ${shellQuote(branch)} ${INCOMING_BUNDLE} ${SANDBOX_WORKSPACE}`,
165
+ `git -C ${SANDBOX_WORKSPACE} branch -q ${shellQuote(baseBranch)} ${shellQuote(`origin/${baseBranch}`)}`,
166
+ `git -C ${SANDBOX_WORKSPACE} remote remove origin`,
167
+ `rm -f ${INCOMING_BUNDLE}`,
168
+ ].join(' && ');
169
+ }
170
+ export function shellQuote(argument) {
171
+ return `'${argument.replaceAll("'", `'\\''`)}'`;
172
+ }
173
+ const SANDBOX_WORKSPACE = `${SANDBOX_HOME}/workspace`;
174
+ /** Without these, `git add -A` in the sandbox would commit files the operator's git ignores. */
175
+ async function hostExcludes(repoRoot) {
176
+ const configured = await openRepo(repoRoot)
177
+ .raw(['config', '--path', 'core.excludesFile'])
178
+ .catch(() => '');
179
+ const files = [
180
+ path.join(repoRoot, '.git', 'info', 'exclude'),
181
+ configured.trim() || path.join(homedir(), '.config', 'git', 'ignore'),
182
+ ];
183
+ return files
184
+ .filter((file) => existsSync(file))
185
+ .map((file) => readFileSync(file, 'utf-8'))
186
+ .join('\n');
187
+ }
188
+ /**
189
+ * Bytes through `cat`, never `docker cp`: that could bring a symbolic link across, and whatever
190
+ * the sandbox put at this path, the host ends up with a new regular file of its own.
191
+ */
192
+ async function copyBytesOut(docker, container, sandboxPath, hostPath, limit) {
193
+ const failed = (reason) => new GitCommandFailed({
194
+ message: `Could not copy ${sandboxPath} out of the sandbox: ${reason}`,
195
+ command: `docker exec ${container} cat -- ${sandboxPath}`,
196
+ output: reason,
197
+ });
198
+ const { stdout, finished } = docker.stream([
199
+ 'exec',
200
+ '-w',
201
+ SANDBOX_WORKSPACE,
202
+ container,
203
+ 'cat',
204
+ '--',
205
+ sandboxPath,
206
+ ]);
207
+ const copied = await Result.tryPromise({
208
+ try: () => pipeline(stdout, limitedTo(limit), createWriteStream(hostPath, { flags: 'wx', mode: 0o600 })),
209
+ catch: (cause) => failed(messageOf(cause)),
210
+ });
211
+ const exitCode = await finished;
212
+ if (copied.isOk() && exitCode === 0)
213
+ return Result.ok();
214
+ if (!isAlreadyThere(copied))
215
+ await rm(hostPath, { force: true });
216
+ return Result.err(copied.isErr() ? copied.error : failed(`cat exited with ${exitCode}`));
217
+ }
218
+ function limitedTo(limit) {
219
+ let seen = 0;
220
+ return new Transform({
221
+ transform(chunk, _encoding, done) {
222
+ seen += chunk.length;
223
+ if (seen > limit)
224
+ done(new Error(`it is larger than ${limit} bytes`));
225
+ else
226
+ done(null, chunk);
227
+ },
228
+ });
229
+ }
230
+ function isAlreadyThere(copied) {
231
+ return copied.isErr() && copied.error.output.includes('EEXIST');
232
+ }
@@ -0,0 +1,17 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ /**
4
+ * The variables sandcastle injects into every sandbox from `.sandcastle/.env`, beside the
5
+ * credentials jig passes: each key in the file, valued from the file or else the host's
6
+ * environment. Only the names are read, so they can be reported without the values.
7
+ */
8
+ export async function sandcastleEnvKeys(repoRoot) {
9
+ const content = await readFile(path.join(repoRoot, '.sandcastle', '.env'), 'utf-8').catch(() => '');
10
+ return content.split('\n').flatMap((line) => {
11
+ const trimmed = line.trim();
12
+ const separator = trimmed.indexOf('=');
13
+ if (trimmed.startsWith('#') || separator === -1)
14
+ return [];
15
+ return [trimmed.slice(0, separator).trim()];
16
+ });
17
+ }
@@ -0,0 +1,338 @@
1
+ import { createSandbox, } from '@ai-hero/sandcastle';
2
+ import { Result } from 'better-result';
3
+ import { existsSync } from 'node:fs';
4
+ import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { z } from 'zod';
8
+ import { AgentRunFailed, ConfigInvalid, messageOf, SandboxUnavailable, SetupCommandFailed, } from '../../domain/errors.js';
9
+ import { runBranchFor } from '../../domain/run-state.js';
10
+ import { refuseSymlinks } from '../find-symlink.js';
11
+ import { openCodexAuthCache } from './codex-auth.js';
12
+ import { hookManagerOf } from './git-hooks.js';
13
+ import { privateCloneDocker, shellQuote } from './private-clone-docker.js';
14
+ import { extractOutput, OUTPUT_TAG, outputInstruction } from './structured-output.js';
15
+ import { usageFromStreamLine } from './usage.js';
16
+ /**
17
+ * One sandcastle sandbox for the whole run: every agent call and command runs in the same warm
18
+ * container, over a private clone; sandcastle keeps a worktree of the run branch on the host.
19
+ */
20
+ export class SandcastleSession {
21
+ sandbox;
22
+ options;
23
+ clone;
24
+ codexAuth;
25
+ constructor(sandbox, options, clone, codexAuth) {
26
+ this.sandbox = sandbox;
27
+ this.options = options;
28
+ this.clone = clone;
29
+ this.codexAuth = codexAuth;
30
+ }
31
+ /**
32
+ * The repository path is resolved first: git records a worktree's real path, so a repository
33
+ * opened through a symlink would leave git unusable inside the container.
34
+ */
35
+ static async open(options, start = createSandbox) {
36
+ const repoRoot = await Result.tryPromise({
37
+ try: () => realpath(options.repoRoot),
38
+ catch: (cause) => new ConfigInvalid({
39
+ message: `Cannot resolve the repository path ${options.repoRoot}: ${messageOf(cause)}`,
40
+ }),
41
+ });
42
+ if (repoRoot.isErr())
43
+ return Result.err(repoRoot.error);
44
+ const ignored = await ignoreSandcastleDirectory(repoRoot.value);
45
+ if (ignored.isErr())
46
+ return Result.err(ignored.error);
47
+ const codexAuth = await openCodexAuth(options);
48
+ if (codexAuth.isErr())
49
+ return Result.err(codexAuth.error);
50
+ const cache = codexAuth.value;
51
+ const clone = privateCloneDocker({
52
+ imageName: options.imageName,
53
+ branch: runBranchFor(options.runId),
54
+ baseBranch: options.baseBranch,
55
+ env: options.credentials,
56
+ loginDirectory: cache?.directory,
57
+ });
58
+ const sandbox = await Result.tryPromise({
59
+ try: () => start({
60
+ branch: runBranchFor(options.runId),
61
+ baseBranch: options.baseBranch,
62
+ cwd: repoRoot.value,
63
+ sandbox: clone.provider,
64
+ }),
65
+ catch: sandboxStartFailure,
66
+ });
67
+ if (sandbox.isErr()) {
68
+ await releaseAfterFailedOpen(cache, options.logger);
69
+ return Result.err(sandbox.error);
70
+ }
71
+ const ready = await runSetupSteps(sandbox.value, setupSteps(repoRoot.value, options.setupCommand), options);
72
+ if (ready.isErr()) {
73
+ await releaseAfterFailedOpen(cache, options.logger);
74
+ return Result.err(ready.error);
75
+ }
76
+ return Result.ok(new SandcastleSession(sandbox.value, options, clone, cache));
77
+ }
78
+ get worktreePath() {
79
+ return this.sandbox.worktreePath;
80
+ }
81
+ async run({ role, prompt }) {
82
+ const reply = await this.reply(role, this.options.agents[role], prompt);
83
+ return reply.map(() => undefined);
84
+ }
85
+ reply(role, agent, prompt) {
86
+ return Result.tryPromise({
87
+ try: async () => {
88
+ const result = await this.sandbox.run({
89
+ agent,
90
+ prompt,
91
+ idleTimeoutSeconds: this.options.idleTimeoutSeconds,
92
+ logging: {
93
+ type: 'file',
94
+ path: this.options.agentLogFile,
95
+ onAgentStreamEvent: (event) => this.publishAgentEvent(role, event),
96
+ },
97
+ });
98
+ return result.stdout;
99
+ },
100
+ catch: (error) => new AgentRunFailed({ message: `The ${role} agent failed: ${messageOf(error)}` }),
101
+ });
102
+ }
103
+ publishAgentEvent(role, event) {
104
+ const { runId, events } = this.options;
105
+ if (event.type === 'text')
106
+ events.publish({ type: 'agentMessage', runId, role, text: event.message });
107
+ if (event.type === 'raw') {
108
+ const usage = usageFromStreamLine(event.line);
109
+ if (usage)
110
+ events.publish({ type: 'agentUsage', runId, role, ...usage });
111
+ }
112
+ if (event.type === 'toolCall') {
113
+ events.publish({
114
+ type: 'agentToolCall',
115
+ runId,
116
+ role,
117
+ tool: event.name,
118
+ args: event.formattedArgs,
119
+ });
120
+ }
121
+ }
122
+ async runForOutput({ role, prompt, schema, }) {
123
+ const reply = await this.reply(role, this.options.agents[role], `${prompt}\n\n${outputInstruction()}`);
124
+ if (reply.isErr())
125
+ return Result.err(reply.error);
126
+ return this.parseWithCorrections(role, reply.value, schema);
127
+ }
128
+ async parseWithCorrections(role, firstReply, schema) {
129
+ let reply = firstReply;
130
+ for (let correction = 0;; correction++) {
131
+ const parsed = extractOutput(reply, schema);
132
+ if (parsed.isOk() || correction >= OUTPUT_CORRECTIONS)
133
+ return parsed;
134
+ const corrected = await this.reply(role, continuing(this.options.agents[role]), correctionPrompt(parsed.error.message));
135
+ if (corrected.isErr())
136
+ return Result.err(corrected.error);
137
+ reply = corrected.value;
138
+ }
139
+ }
140
+ async exec(command) {
141
+ const result = await execInSandbox(this.sandbox, command);
142
+ return result.map(({ exitCode, stdout, stderr }) => ({
143
+ exitCode,
144
+ output: `${stdout}${stderr}`.trim(),
145
+ }));
146
+ }
147
+ async execGit(args) {
148
+ const result = await execInSandbox(this.sandbox, ['git', ...args].map(shellQuote).join(' '));
149
+ return result.map(({ exitCode, stdout, stderr }) => ({
150
+ exitCode,
151
+ output: exitCode === 0 ? stdout : `${stdout}${stderr}`.trim(),
152
+ }));
153
+ }
154
+ copyOut(sandboxPath, hostPath) {
155
+ return this.clone.copyOut(sandboxPath, hostPath);
156
+ }
157
+ async close() {
158
+ const stopped = await stopSandbox(this.sandbox);
159
+ const released = (await this.codexAuth?.close()) ?? Result.ok();
160
+ if (stopped.isOk())
161
+ return released;
162
+ if (released.isErr()) {
163
+ this.options.logger.warn({ err: released.error }, 'cleanup failed after the sandbox did not stop');
164
+ }
165
+ return stopped;
166
+ }
167
+ }
168
+ /** Also replaces a catch-all `*`, which would hide the Dockerfile from the repository. */
169
+ export async function ignoreSandcastleDirectory(repoRoot) {
170
+ const directory = path.join(repoRoot, '.sandcastle');
171
+ const gitignore = path.join(directory, '.gitignore');
172
+ const refused = refuseSymlinks([directory, gitignore]);
173
+ if (refused.isErr())
174
+ return refused;
175
+ return Result.tryPromise({
176
+ try: async () => {
177
+ if (existsSync(gitignore) && !ignoresEverything(await readFile(gitignore, 'utf-8')))
178
+ return;
179
+ await mkdir(directory, { recursive: true });
180
+ await writeFile(gitignore, SANDCASTLE_GITIGNORE);
181
+ },
182
+ catch: (cause) => new ConfigInvalid({ message: `Could not write ${gitignore}: ${messageOf(cause)}` }),
183
+ });
184
+ }
185
+ function ignoresEverything(gitignore) {
186
+ return gitignore.split('\n').some((line) => line.trim() === '*');
187
+ }
188
+ /**
189
+ * What sandcastle writes under `.sandcastle/` is scratch; the Dockerfile there is the
190
+ * repository's own and gets committed. Untracked scratch would block the final merge.
191
+ */
192
+ export const SANDCASTLE_GITIGNORE = 'worktrees/\nlogs/\n.env\n';
193
+ async function openCodexAuth(options) {
194
+ return options.codexAuthDirectory
195
+ ? openCodexAuthCache(options.codexAuthDirectory)
196
+ : Result.ok(undefined);
197
+ }
198
+ /**
199
+ * Sandcastle's own `onSandboxReady` hooks ignore a command's exit code and timeout in
200
+ * `createSandbox`, so the setup command is run here, where both are checked.
201
+ */
202
+ function sandboxStartFailure(error) {
203
+ const message = `Could not start the sandbox: ${messageOf(error)}`;
204
+ const tag = sandcastleFailureTag(error);
205
+ return tag && CONFIGURATION_FAILURES.has(tag)
206
+ ? new ConfigInvalid({ message: message })
207
+ : new SandboxUnavailable({ message: message });
208
+ }
209
+ function sandcastleFailureTag(error) {
210
+ if (!(error instanceof Error))
211
+ return undefined;
212
+ const cause = sandcastleFailureSchema.safeParse(Reflect.get(error, FIBER_FAILURE_CAUSE));
213
+ return cause.success ? cause.data.error._tag : undefined;
214
+ }
215
+ const sandcastleFailureSchema = z.object({
216
+ _tag: z.literal('Fail'),
217
+ error: z.object({ _tag: z.string() }),
218
+ });
219
+ /**
220
+ * Sandcastle runs on Effect, whose `runPromise` rejects with a FiberFailure carrying the cause
221
+ * under this symbol; a plain failure's cause names sandcastle's tagged error.
222
+ */
223
+ const FIBER_FAILURE_CAUSE = Symbol.for('effect/Runtime/FiberFailure/Cause');
224
+ /**
225
+ * The sandcastle failures a retry cannot fix. Sandcastle reports a Docker daemon that is down, an
226
+ * image it cannot use and a git worktree it could not create all as `WorktreeError`, so only a
227
+ * repository path it cannot use is told apart; the rest is retried a bounded number of times.
228
+ */
229
+ const CONFIGURATION_FAILURES = new Set(['CwdError']);
230
+ /** The open already failed, so a failure to release the login is logged and the open's failure kept. */
231
+ async function releaseAfterFailedOpen(cache, logger) {
232
+ const released = await cache?.close();
233
+ if (released?.isErr())
234
+ logger.warn({ err: released.error }, 'cleanup failed after the open failed');
235
+ }
236
+ async function runSetupSteps(sandbox, steps, options) {
237
+ for (const step of steps) {
238
+ const ran = await runSetupStep(sandbox, step, options);
239
+ if (ran.isErr())
240
+ return ran;
241
+ }
242
+ return Result.ok();
243
+ }
244
+ async function runSetupStep(sandbox, step, { setupTimeoutSeconds, logger }) {
245
+ const attempt = await Result.tryPromise({
246
+ try: () => setupFailure(sandbox, step, setupTimeoutSeconds),
247
+ catch: (error) => new SandboxUnavailable({ message: `Could not run ${step.name}: ${messageOf(error)}` }),
248
+ });
249
+ const failure = attempt.isErr() ? attempt.error : attempt.value;
250
+ if (!failure)
251
+ return Result.ok();
252
+ const stopped = await stopSandbox(sandbox);
253
+ if (stopped.isErr())
254
+ logger.warn({ err: stopped.error }, 'cleanup failed after the setup failed');
255
+ return Result.err(failure);
256
+ }
257
+ async function setupFailure(sandbox, { name, command }, timeoutSeconds) {
258
+ const timer = new AbortController();
259
+ const finished = await Promise.race([
260
+ sandbox.exec(command),
261
+ delay(timeoutSeconds * 1000, undefined, { signal: timer.signal }),
262
+ ]).finally(() => timer.abort());
263
+ if (!finished) {
264
+ return new SetupCommandFailed({
265
+ message: `${name} did not finish within ${timeoutSeconds}s`,
266
+ output: '',
267
+ });
268
+ }
269
+ if (finished.exitCode === 0)
270
+ return undefined;
271
+ const output = `${finished.stdout}${finished.stderr}`.trim().slice(-SETUP_OUTPUT_TAIL);
272
+ return new SetupCommandFailed({
273
+ message: `${name} exited with ${finished.exitCode}:\n${output}`,
274
+ output,
275
+ });
276
+ }
277
+ /** How much of a failed setup command's output is kept; the end is where the error is. */
278
+ const SETUP_OUTPUT_TAIL = 3000;
279
+ function stopSandbox(sandbox) {
280
+ return Result.tryPromise({
281
+ try: async () => {
282
+ await sandbox.close();
283
+ },
284
+ catch: (cause) => new SandboxUnavailable({ message: `Could not stop the sandbox: ${messageOf(cause)}` }),
285
+ });
286
+ }
287
+ /**
288
+ * The setup command, then the repository's git hooks, so commits made in the sandbox meet the
289
+ * same checks as the operator's. Without a setup command nothing installed the hook manager.
290
+ */
291
+ function setupSteps(repoRoot, setupCommand) {
292
+ if (!setupCommand)
293
+ return [];
294
+ const steps = [{ name: `setupCommand "${setupCommand}"`, command: setupCommand }];
295
+ const hooks = hookManagerOf(repoRoot);
296
+ if (!hooks)
297
+ return steps;
298
+ return [
299
+ ...steps,
300
+ {
301
+ name: `installing ${hooks.name}'s git hooks ("${hooks.installCommand}")`,
302
+ command: hooks.installCommand,
303
+ },
304
+ ];
305
+ }
306
+ /** How many times an agent is asked, in its own session, to correct output that did not parse. */
307
+ const OUTPUT_CORRECTIONS = 1;
308
+ /** The same agent, resuming its last conversation in this sandbox instead of starting a new one. */
309
+ function continuing(agent) {
310
+ return {
311
+ ...agent,
312
+ buildPrintCommand: (options) => {
313
+ const built = agent.buildPrintCommand(options);
314
+ if (agent.name === 'codex') {
315
+ return {
316
+ ...built,
317
+ command: `${built.command.replace(/^codex exec\b/, 'codex exec resume --last')} -`,
318
+ };
319
+ }
320
+ return { ...built, command: `${built.command} --continue` };
321
+ },
322
+ };
323
+ }
324
+ function correctionPrompt(problem) {
325
+ return [
326
+ `Your result could not be used: ${problem}`,
327
+ `Reply again with only the corrected result inside <${OUTPUT_TAG}></${OUTPUT_TAG}> tags.`,
328
+ ].join('\n');
329
+ }
330
+ /** A container that died under a command is Docker's trouble, not the command's answer. */
331
+ function execInSandbox(sandbox, command) {
332
+ return Result.tryPromise({
333
+ try: () => sandbox.exec(command),
334
+ catch: (cause) => new SandboxUnavailable({
335
+ message: `Could not run a command in the sandbox: ${messageOf(cause)}`,
336
+ }),
337
+ });
338
+ }
@@ -0,0 +1,35 @@
1
+ import { Result } from 'better-result';
2
+ import { AgentOutputInvalid, messageOf } from '../../domain/errors.js';
3
+ export function outputInstruction() {
4
+ return [
5
+ `When you are completely done, end your reply with your result as a single JSON object`,
6
+ `inside <${OUTPUT_TAG}></${OUTPUT_TAG}> tags, e.g. <${OUTPUT_TAG}>{"key": "value"}</${OUTPUT_TAG}>.`,
7
+ 'Do not write the result to a file.',
8
+ ].join(' ');
9
+ }
10
+ /** The agent ends its reply with this tag around a JSON object; the last one wins. */
11
+ export const OUTPUT_TAG = 'jig-output';
12
+ /** Reads the last tag in the agent's reply, tolerating a code fence around the JSON and nothing else. */
13
+ export function extractOutput(reply, schema) {
14
+ const tagged = [
15
+ ...reply.matchAll(new RegExp(`<${OUTPUT_TAG}>([\\s\\S]*?)</${OUTPUT_TAG}>`, 'g')),
16
+ ].at(-1)?.[1];
17
+ if (tagged === undefined) {
18
+ return invalid(`The reply has no <${OUTPUT_TAG}> result.`);
19
+ }
20
+ const raw = Result.try(() => JSON.parse(withoutFence(tagged.trim())));
21
+ if (raw.isErr()) {
22
+ return invalid(`The <${OUTPUT_TAG}> result is not valid JSON: ${messageOf(raw.error.cause)}`);
23
+ }
24
+ const parsed = schema.safeParse(raw.value);
25
+ return parsed.success
26
+ ? Result.ok(parsed.data)
27
+ : invalid(`The <${OUTPUT_TAG}> result has the wrong shape: ${parsed.error.message}`);
28
+ }
29
+ function invalid(message) {
30
+ return Result.err(new AgentOutputInvalid({ message }));
31
+ }
32
+ function withoutFence(text) {
33
+ const fenced = text.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);
34
+ return fenced ? fenced[1] : text;
35
+ }
@@ -0,0 +1,65 @@
1
+ import { z } from 'zod';
2
+ /** The usage an agent's raw stream line reports, if it reports any; agents price their own calls. */
3
+ export function usageFromStreamLine(line) {
4
+ let event;
5
+ try {
6
+ event = JSON.parse(line);
7
+ }
8
+ catch {
9
+ return undefined;
10
+ }
11
+ const claude = claudeResultSchema.safeParse(event);
12
+ if (claude.success) {
13
+ const usage = claude.data.usage;
14
+ return {
15
+ costUsd: claude.data.total_cost_usd,
16
+ tokens: {
17
+ input: usage.input_tokens,
18
+ output: usage.output_tokens,
19
+ cacheRead: usage.cache_read_input_tokens,
20
+ cacheWrite: usage.cache_creation_input_tokens,
21
+ reasoning: usage.output_tokens_details?.thinking_tokens ?? 0,
22
+ },
23
+ };
24
+ }
25
+ const opencode = opencodeStepSchema.safeParse(event);
26
+ if (opencode.success) {
27
+ const { cost, tokens } = opencode.data.part;
28
+ return {
29
+ costUsd: cost,
30
+ tokens: {
31
+ input: tokens.input,
32
+ output: tokens.output,
33
+ cacheRead: tokens.cache.read,
34
+ cacheWrite: tokens.cache.write,
35
+ reasoning: tokens.reasoning,
36
+ },
37
+ };
38
+ }
39
+ return undefined;
40
+ }
41
+ /** Claude Code ends every print-mode call with one `result` event carrying the call's totals. */
42
+ const claudeResultSchema = z.object({
43
+ type: z.literal('result'),
44
+ total_cost_usd: z.number().optional(),
45
+ usage: z.object({
46
+ input_tokens: z.number().default(0),
47
+ output_tokens: z.number().default(0),
48
+ cache_read_input_tokens: z.number().default(0),
49
+ cache_creation_input_tokens: z.number().default(0),
50
+ output_tokens_details: z.object({ thinking_tokens: z.number().default(0) }).optional(),
51
+ }),
52
+ });
53
+ /** opencode reports each model step's tokens and cost in a `step_finish` event. */
54
+ const opencodeStepSchema = z.object({
55
+ type: z.literal('step_finish'),
56
+ part: z.object({
57
+ cost: z.number().optional(),
58
+ tokens: z.object({
59
+ input: z.number().default(0),
60
+ output: z.number().default(0),
61
+ reasoning: z.number().default(0),
62
+ cache: z.object({ read: z.number().default(0), write: z.number().default(0) }).default({}),
63
+ }),
64
+ }),
65
+ });