@mnaimfaizy/agent-kit 1.0.0-beta.14 → 1.0.0-beta.16

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 (180) hide show
  1. package/README.md +22 -4
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +244 -6
  4. package/package.json +3 -2
  5. package/src/checks/ci-workflow.mjs +105 -0
  6. package/src/checks/claude-app.mjs +11 -2
  7. package/src/checks/custom-harness.mjs +157 -0
  8. package/src/checks/github-app.mjs +214 -0
  9. package/src/checks/rulesets.mjs +9 -8
  10. package/src/checks/secrets-and-variables.mjs +27 -8
  11. package/src/checks/stages.mjs +705 -0
  12. package/src/cli.mjs +583 -36
  13. package/src/deep-scan/agent.mjs +88 -21
  14. package/src/deep-scan/credential.mjs +81 -32
  15. package/src/deep-scan/docker-driver.mjs +105 -42
  16. package/src/deep-scan/harness-text.mjs +99 -0
  17. package/src/deep-scan/lifecycle.mjs +68 -178
  18. package/src/deep-scan/limits.mjs +13 -7
  19. package/src/deep-scan/model-proxy.mjs +21 -10
  20. package/src/deep-scan/preflight.mjs +19 -6
  21. package/src/deep-scan/recipe.mjs +4 -0
  22. package/src/deep-scan/runtime.mjs +54 -6
  23. package/src/deep-scan/sandbox-run.mjs +232 -0
  24. package/src/deep-scan/sbx-driver.mjs +224 -39
  25. package/src/deep-scan/tar.mjs +69 -22
  26. package/src/deep-scan/verify.mjs +6 -1
  27. package/src/deep-scan.mjs +73 -13
  28. package/src/doctor.mjs +166 -5
  29. package/src/exec.mjs +14 -5
  30. package/src/factory/budget/budget.mjs +259 -0
  31. package/src/factory/build/command.mjs +321 -0
  32. package/src/factory/build/factory.mjs +473 -0
  33. package/src/factory/build/findings.mjs +55 -0
  34. package/src/factory/build/host.mjs +230 -0
  35. package/src/factory/build/notes.mjs +191 -0
  36. package/src/factory/build/pull-request.mjs +74 -0
  37. package/src/factory/bundle.mjs +146 -0
  38. package/src/factory/checks/allowed-paths.mjs +50 -0
  39. package/src/factory/checks/plan-header.mjs +296 -0
  40. package/src/factory/checks/qa.mjs +85 -0
  41. package/src/factory/checks/review.mjs +73 -0
  42. package/src/factory/checks/security.mjs +50 -0
  43. package/src/factory/checks/stage-check.mjs +89 -0
  44. package/src/factory/claims/command.mjs +187 -0
  45. package/src/factory/claims/release.mjs +111 -0
  46. package/src/factory/decision/answers.mjs +103 -0
  47. package/src/factory/decision/command.mjs +64 -0
  48. package/src/factory/decision/plan.mjs +99 -0
  49. package/src/factory/decision/request.mjs +116 -0
  50. package/src/factory/doctor/files.mjs +329 -0
  51. package/src/factory/doctor/index.mjs +56 -0
  52. package/src/factory/doctor/local.mjs +497 -0
  53. package/src/factory/doctor/orchestrate.mjs +146 -0
  54. package/src/factory/engine/lease.mjs +146 -0
  55. package/src/factory/engine/local-engine.mjs +177 -0
  56. package/src/factory/engine/lockfile.mjs +64 -0
  57. package/src/factory/engine/workflow-engine.mjs +124 -0
  58. package/src/factory/gate/comment.mjs +88 -0
  59. package/src/factory/gate/config.mjs +57 -0
  60. package/src/factory/gate/gate-core.mjs +250 -0
  61. package/src/factory/gate/guarded.mjs +17 -0
  62. package/src/factory/gate/reads.mjs +105 -0
  63. package/src/factory/gate/task.mjs +193 -0
  64. package/src/factory/gate/trip-reads.mjs +82 -0
  65. package/src/factory/gate/trip.mjs +87 -0
  66. package/src/factory/init/blueprint.mjs +174 -0
  67. package/src/factory/init/index.mjs +337 -0
  68. package/src/factory/labels/evidence.mjs +162 -0
  69. package/src/factory/labels/moves.mjs +32 -0
  70. package/src/factory/labels/reconcile.mjs +267 -0
  71. package/src/factory/labels/revert.mjs +87 -0
  72. package/src/factory/labels/timeline.mjs +72 -0
  73. package/src/factory/labels/voided.mjs +59 -0
  74. package/src/factory/limits/harness.mjs +39 -0
  75. package/src/factory/limits/limits.mjs +123 -0
  76. package/src/factory/merge/command.mjs +172 -0
  77. package/src/factory/outbox/check.mjs +240 -0
  78. package/src/factory/outbox/rulings.mjs +195 -0
  79. package/src/factory/plan/command.mjs +66 -0
  80. package/src/factory/plan/comment.mjs +156 -0
  81. package/src/factory/plan/publish.mjs +149 -0
  82. package/src/factory/plan/risk.mjs +153 -0
  83. package/src/factory/qa/command.mjs +163 -0
  84. package/src/factory/records/engine-record.mjs +133 -0
  85. package/src/factory/records/main.mjs +96 -0
  86. package/src/factory/records/record.mjs +226 -0
  87. package/src/factory/records/sink.mjs +57 -0
  88. package/src/factory/report/build.mjs +92 -0
  89. package/src/factory/report/command.mjs +80 -0
  90. package/src/factory/report/facts.mjs +226 -0
  91. package/src/factory/report/gate-section.mjs +122 -0
  92. package/src/factory/report/metrics.mjs +111 -0
  93. package/src/factory/report/reads.mjs +246 -0
  94. package/src/factory/report/render.mjs +121 -0
  95. package/src/factory/report/rollout.mjs +154 -0
  96. package/src/factory/review/command.mjs +182 -0
  97. package/src/factory/run/awake.mjs +70 -0
  98. package/src/factory/run/collect.mjs +77 -0
  99. package/src/factory/run/command.mjs +490 -0
  100. package/src/factory/run/gh.mjs +46 -0
  101. package/src/factory/run/launch.mjs +47 -0
  102. package/src/factory/run/pipelines.mjs +261 -0
  103. package/src/factory/run/raw.mjs +96 -0
  104. package/src/factory/run/restart.mjs +83 -0
  105. package/src/factory/run/s3.mjs +193 -0
  106. package/src/factory/run/secrets.mjs +142 -0
  107. package/src/factory/run/teardown.mjs +242 -0
  108. package/src/factory/run/token.mjs +68 -0
  109. package/src/factory/security/command.mjs +157 -0
  110. package/src/factory/setup/app.mjs +122 -0
  111. package/src/factory/setup/command.mjs +409 -0
  112. package/src/factory/setup/labels.mjs +25 -0
  113. package/src/factory/setup/reads.mjs +129 -0
  114. package/src/factory/setup/writes.mjs +126 -0
  115. package/src/factory/snapshot/write.mjs +176 -0
  116. package/src/factory/stop/command.mjs +136 -0
  117. package/src/factory/sweep/actions-main.mjs +117 -0
  118. package/src/factory/sweep/command.mjs +65 -0
  119. package/src/factory/sweep/knobs.mjs +78 -0
  120. package/src/factory/sweep/marker-version.mjs +15 -0
  121. package/src/factory/sweep/markers.mjs +112 -0
  122. package/src/factory/sweep/overlap.mjs +24 -0
  123. package/src/factory/sweep/run.mjs +198 -0
  124. package/src/factory/sweep/shell.mjs +394 -0
  125. package/src/factory/sweep/split.mjs +104 -0
  126. package/src/factory/sweep/states.mjs +87 -0
  127. package/src/factory/sweep/sweep-core.mjs +1781 -0
  128. package/src/factory/tracker/github.mjs +674 -0
  129. package/src/factory/tracker/operations.mjs +153 -0
  130. package/src/factory/upgrade/index.mjs +83 -0
  131. package/src/harness/adapters.mjs +30 -0
  132. package/src/harness/antigravity.mjs +187 -0
  133. package/src/harness/claude-code.mjs +8 -1
  134. package/src/harness/codex.mjs +219 -0
  135. package/src/harness/cursor.mjs +199 -0
  136. package/src/harness/custom/registry.mjs +21 -0
  137. package/src/harness/custom/schema.mjs +90 -0
  138. package/src/harness/custom.mjs +299 -0
  139. package/src/harness/facts.mjs +44 -7
  140. package/src/harness/gemini.mjs +164 -0
  141. package/src/harness/install-layer.mjs +86 -3
  142. package/src/harness/opencode.mjs +289 -0
  143. package/src/harness/resolve.mjs +156 -0
  144. package/src/harness/support-levels.mjs +151 -3
  145. package/src/harness-live/assess.mjs +29 -6
  146. package/src/harness-live/cursor-real.mjs +146 -0
  147. package/src/harness-live/cursor-version.mjs +70 -0
  148. package/src/harness-live/cursor.mjs +80 -0
  149. package/src/harness-live/custom.mjs +91 -0
  150. package/src/harness-live/fixture-harness.mjs +45 -0
  151. package/src/harness-live/harnesses.mjs +263 -0
  152. package/src/harness-live/host.mjs +113 -4
  153. package/src/harness-live/opencode.mjs +289 -0
  154. package/src/harness-live/probes.mjs +87 -7
  155. package/src/harness-live/run.mjs +101 -20
  156. package/src/harness-live/setup.mjs +126 -0
  157. package/src/harness-live/stage.mjs +25 -15
  158. package/src/harness-live/suite.mjs +276 -95
  159. package/src/harness-test.mjs +116 -0
  160. package/src/init.mjs +374 -36
  161. package/src/kit-owned-paths.mjs +1 -1
  162. package/src/model-proxy/core.mjs +128 -20
  163. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  164. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  165. package/src/model-proxy/profiles/openai.mjs +327 -0
  166. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  167. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  168. package/src/model-proxy/stub.mjs +9 -1
  169. package/src/stage/audit.mjs +79 -0
  170. package/src/stage/egress-route.mjs +207 -0
  171. package/src/stage/implement/carry.mjs +308 -0
  172. package/src/stage/implement/sandbox.mjs +271 -0
  173. package/src/stage/implement/verify.mjs +70 -0
  174. package/src/stage/implement.mjs +218 -0
  175. package/src/stage/plan.mjs +115 -0
  176. package/src/stage/review-response.mjs +172 -0
  177. package/src/stage/review.mjs +185 -0
  178. package/src/stage/workspace.mjs +274 -0
  179. package/src/stage.mjs +1087 -0
  180. package/src/upgrade.mjs +39 -7
package/src/stage.mjs ADDED
@@ -0,0 +1,1087 @@
1
+ // `agent-kit stage <stage>`: the Launcher's path for a CI Stage (ADR 0024),
2
+ // which the reusable workflows call. It runs the static security audit,
3
+ // `stage audit`, the plan, `stage plan`, and the review, `stage review`.
4
+ //
5
+ // Its harness is `--harness`'s, else the Stage setting's
6
+ // (harness/resolve.mjs). Before anything runs it refuses a pair below `tried`
7
+ // unless the run is a Proving run (`--proving-run`, ADR 0028), a GitHub token
8
+ // in its environment (ADR 0026), and a missing credential for the harness.
9
+ // Then the checkout is copied into the Deep scan's sandbox (stage/workspace.mjs:
10
+ // no harness config of the checkout's, instruction files from the trusted
11
+ // commit), the network is cut and checked from the host, the model proxy is
12
+ // opened as the only route out, and the harness runs the brief the trusted
13
+ // step built, holding a placeholder key. A wall clock and the proxy's token
14
+ // cap bound the run, and the harness's turn limit where its adapter declares
15
+ // one.
16
+ //
17
+ // A Stage that takes them (`--input`) has the trusted step's own files copied
18
+ // in beside the brief. A Stage that takes a Sandbox image (implement, the
19
+ // Review response) runs the Caller's setup in a setup container of its own,
20
+ // then the agent in a fresh one that takes only the workspace, `.git/` from
21
+ // the trusted commit and the declared `setup_paths` (ADR 0047).
22
+ //
23
+ // The run is complete when the harness exited cleanly and left a valid Stage
24
+ // result, and by nothing else: its raw event stream is copied to a private
25
+ // file and never read. Nothing is written to GitHub.
26
+
27
+ import {
28
+ existsSync,
29
+ lstatSync,
30
+ mkdtempSync,
31
+ readFileSync,
32
+ realpathSync,
33
+ statSync,
34
+ writeFileSync,
35
+ } from "node:fs";
36
+ import { tmpdir } from "node:os";
37
+ import { basename, dirname, join, posix, resolve } from "node:path";
38
+ import { agentScript, turnsMarker } from "./deep-scan/agent.mjs";
39
+ import {
40
+ acceptedBy,
41
+ credentialKind,
42
+ credentialSource,
43
+ readCredential,
44
+ SUBSCRIPTION,
45
+ withoutCredentials,
46
+ } from "./deep-scan/credential.mjs";
47
+ import { textFor } from "./deep-scan/harness-text.mjs";
48
+ import {
49
+ describeLimits,
50
+ parseLimits,
51
+ STOPPED_EXIT,
52
+ stoppedStatus,
53
+ TOKENS,
54
+ TURNS,
55
+ WALL_CLOCK,
56
+ LimitReached,
57
+ } from "./deep-scan/limits.mjs";
58
+ import { MODEL_ID } from "./deep-scan/model-proxy.mjs";
59
+ import { stageSupport, strayTokens, writeRunSummary } from "./deep-scan/preflight.mjs";
60
+ import { RUNTIMES_DOCS_URL, selectRuntime } from "./deep-scan/runtime.mjs";
61
+ import { cutNetwork, openModelRoute, runInSandbox } from "./deep-scan/sandbox-run.mjs";
62
+ import { indent, StepFailed } from "./deep-scan/steps.mjs";
63
+ import { tarOf } from "./deep-scan/tar.mjs";
64
+ import { firstLine } from "./exec.mjs";
65
+ import { adapterFor } from "./harness/adapters.mjs";
66
+ import { effortFor, harnessFacts } from "./harness/facts.mjs";
67
+ import { loadHarness, resolveHarness } from "./harness/resolve.mjs";
68
+ import * as audit from "./stage/audit.mjs";
69
+ import { egressHosts, openEgressRoute, refuseHeldKey } from "./stage/egress-route.mjs";
70
+ import * as implement from "./stage/implement.mjs";
71
+ import * as reviewResponse from "./stage/review-response.mjs";
72
+ import {
73
+ carryOut,
74
+ commandsError,
75
+ readCommands,
76
+ resolveImage,
77
+ restoreCheckout,
78
+ runCommands,
79
+ sandboxFlags,
80
+ withResolvedImages,
81
+ } from "./stage/implement/sandbox.mjs";
82
+ import {
83
+ AGENT_FLAGS,
84
+ cutForVerify,
85
+ VERIFY_LIMITS,
86
+ verifyInSandbox,
87
+ } from "./stage/implement/verify.mjs";
88
+ import * as plan from "./stage/plan.mjs";
89
+ import * as review from "./stage/review.mjs";
90
+ import { seedPack, WorkspaceError, workspaceTar } from "./stage/workspace.mjs";
91
+ import { CLI_VERSION } from "./tags.mjs";
92
+
93
+ /** Each Stage the command runs, by the name it takes. */
94
+ export const STAGE_COMMANDS = Object.freeze({
95
+ audit,
96
+ plan,
97
+ review,
98
+ implement,
99
+ "review-response": reviewResponse,
100
+ });
101
+
102
+ const DOCS = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs`;
103
+ const HARNESS_DOCS_URL = `${DOCS}/harnesses.md`;
104
+ const PROVING_DOCS_URL = `${DOCS}/harnesses.md#proving-runs`;
105
+
106
+ /** The sandbox's folder for the Launcher, outside the workspace. */
107
+ const KIT_DIR = "/agent-kit";
108
+ const MAX_BRIEF_BYTES = 8 * 1024 * 1024;
109
+ /** The most the trusted step's files may hold together. */
110
+ const MAX_INPUT_BYTES = 64 * 1024 * 1024;
111
+ const INPUT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
112
+ /** The most of a stream that comes out: past it, its start and its end. */
113
+ const MAX_STREAM_BYTES = 20 * 1024 * 1024;
114
+ const STREAM_HEAD_BYTES = 2 * 1024 * 1024;
115
+ /** How many lines of the harness's error output a failed agent step shows. */
116
+ const AGENT_ERROR_LINES = 20;
117
+
118
+ /** Why a line is withheld from a world-readable log. */
119
+ const PUBLIC_LOG = "the Public-log rule: this log is world-readable in GitHub Actions";
120
+
121
+ /** `a, b or c`. */
122
+ const either = (words) => `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
123
+
124
+ /**
125
+ * @param {{
126
+ * cwd: string,
127
+ * runner: import("./exec.mjs").Runner,
128
+ * stage: string,
129
+ * harness?: string,
130
+ * model?: string,
131
+ * effort?: string,
132
+ * credential?: string,
133
+ * credentialFrom?: string,
134
+ * briefPath?: string,
135
+ * resultPath?: string,
136
+ * bundlePath?: string,
137
+ * transcriptPath?: string,
138
+ * errorLogPath?: string,
139
+ * usagePath?: string,
140
+ * trustedRef?: string,
141
+ * untracked?: boolean,
142
+ * inputPaths?: string[],
143
+ * provingRun?: boolean,
144
+ * limitFlags?: Record<string, string | undefined>,
145
+ * sandboxImage?: string,
146
+ * setupRegistries?: string,
147
+ * setupPath?: string,
148
+ * setupPaths?: string,
149
+ * verifyPath?: string,
150
+ * platform?: string,
151
+ * env?: Record<string, string | undefined>,
152
+ * signals?: { on: Function, off: Function },
153
+ * modelApi?: string,
154
+ * timers?: { setTimeout: Function, clearTimeout: Function },
155
+ * out: (s: string) => void,
156
+ * err: (s: string) => void,
157
+ * }} opts `stage` is a name in STAGE_COMMANDS. `trustedRef` is the commit the
158
+ * instruction files come from (default: the checked-out one). `untracked`
159
+ * copies untracked files in too. `inputPaths` are files to copy in beside
160
+ * the brief, on a Stage that takes them. `bundlePath` is where a writing
161
+ * Stage's git bundle goes. `sandboxImage`, `setupRegistries` and
162
+ * `setupPath` (a file of commands) shape the sandbox of a Stage that takes
163
+ * them, with `setupPaths` the paths outside the workspace that cross from
164
+ * setup's container to the agent's, and `verifyPath` (a file of commands) makes the run the verify run,
165
+ * with no agent. `platform`, `env`, `signals`, `timers` are
166
+ * the host's and `modelApi` the real model API; only tests pass others.
167
+ * @returns {Promise<number>} exit code: 0 the Stage completed with a valid
168
+ * result, 1 refused or failed, 2 usage error, 3 a limit stopped the run,
169
+ * 130 or 143 interrupted
170
+ */
171
+ export async function runStage({
172
+ cwd,
173
+ runner: hostRunner,
174
+ stage,
175
+ harness: harnessFlag,
176
+ model,
177
+ effort,
178
+ credential,
179
+ credentialFrom,
180
+ briefPath,
181
+ resultPath,
182
+ bundlePath,
183
+ transcriptPath,
184
+ errorLogPath,
185
+ usagePath,
186
+ trustedRef,
187
+ untracked = false,
188
+ inputPaths = [],
189
+ provingRun = false,
190
+ limitFlags = {},
191
+ sandboxImage,
192
+ setupRegistries,
193
+ setupPath,
194
+ setupPaths,
195
+ verifyPath,
196
+ platform = process.platform,
197
+ env = process.env,
198
+ signals = process,
199
+ modelApi,
200
+ timers = globalThis,
201
+ out,
202
+ err,
203
+ }) {
204
+ let stageDocs = HARNESS_DOCS_URL;
205
+ const refuse = (lines, docs = stageDocs) => {
206
+ err([`REFUSED ${lines[0]}`, ...lines.slice(1), `See ${docs}`].join("\n"));
207
+ return 1;
208
+ };
209
+ const usage = (line) => {
210
+ err(line);
211
+ return 2;
212
+ };
213
+
214
+ if (!Object.hasOwn(STAGE_COMMANDS, stage)) {
215
+ return usage(
216
+ `stage runs only ${Object.keys(STAGE_COMMANDS).join(", ")} so far, got: ${JSON.stringify(stage)}`,
217
+ );
218
+ }
219
+ const definition = STAGE_COMMANDS[stage];
220
+ stageDocs = `${DOCS}/${definition.DOCS_PAGE}`;
221
+ const sandboxGiven = [
222
+ ["--sandbox-image", sandboxImage],
223
+ ["--setup-registries", setupRegistries],
224
+ ["--setup-commands", setupPath],
225
+ ["--setup-paths", setupPaths],
226
+ ["--verify-commands", verifyPath],
227
+ ].find(([, value]) => value !== undefined);
228
+ if (sandboxGiven && !definition.TAKES_SANDBOX) {
229
+ return usage(`stage ${stage} takes no ${sandboxGiven[0]}.`);
230
+ }
231
+ if (verifyPath !== undefined) {
232
+ // In AGENT_FLAGS' order.
233
+ const given = [
234
+ briefPath,
235
+ resultPath,
236
+ bundlePath,
237
+ transcriptPath,
238
+ errorLogPath,
239
+ inputPaths.length || undefined,
240
+ untracked || undefined,
241
+ model,
242
+ effort,
243
+ credential,
244
+ credentialFrom,
245
+ limitFlags["max-turns"],
246
+ limitFlags["max-tokens"],
247
+ provingRun || undefined,
248
+ trustedRef,
249
+ ];
250
+ const foreign = AGENT_FLAGS.find((_, i) => given[i] !== undefined);
251
+ if (foreign) return usage(`The verify run starts no agent, so it takes no ${foreign}.`);
252
+ if (usagePath !== undefined)
253
+ return usage("The verify run starts no agent, so it takes no --usage.");
254
+ } else if (briefPath === undefined || resultPath === undefined) {
255
+ return usage(`stage ${stage} needs --brief <file> and --result <file>.`);
256
+ }
257
+ if (model !== undefined && !MODEL_ID.test(model)) {
258
+ return usage(
259
+ `--model must be a plain model id (letters, digits and . _ : @ / [ ] -), got: ${JSON.stringify(model)}`,
260
+ );
261
+ }
262
+
263
+ const resolved = resolveHarness({ stage: definition.STAGE, flag: harnessFlag, env });
264
+ if ("refused" in resolved) {
265
+ if (resolved.unknown && harnessFlag !== undefined) return usage(resolved.refused);
266
+ return refuse([resolved.refused], HARNESS_DOCS_URL);
267
+ }
268
+ const { harness } = resolved;
269
+ // A Custom harness is its file at the trusted commit (ADR 0027).
270
+ const custom = loadHarness({
271
+ harness,
272
+ runner: withoutCredentials(hostRunner, [env, process.env]),
273
+ cwd,
274
+ trustedRef,
275
+ flags: ["--trusted-ref"],
276
+ });
277
+ if (custom.refused !== undefined) return refuse(custom.refused, HARNESS_DOCS_URL);
278
+ const facts = harnessFacts(harness);
279
+ if (effort !== undefined && (effort === "" || "refused" in effortFor(facts, { effort }))) {
280
+ return usage(
281
+ facts.noEffort
282
+ ? `${facts.displayName} has no effort setting: leave --effort out.`
283
+ : `--effort must be one of ${either(facts.effortValues)}, got: ${JSON.stringify(effort)}`,
284
+ );
285
+ }
286
+ const bounds = parseLimits(
287
+ limitFlags,
288
+ verifyPath === undefined ? definition.LIMITS : VERIFY_LIMITS,
289
+ );
290
+ if ("error" in bounds) return usage(bounds.error);
291
+ const { limits } = bounds;
292
+ const sandbox = sandboxFlags({
293
+ image: sandboxImage,
294
+ registries: setupRegistries,
295
+ setupPath: setupPath === undefined ? undefined : resolve(cwd, setupPath),
296
+ paths: setupPaths,
297
+ });
298
+ if ("error" in sandbox) return usage(sandbox.error);
299
+ if (verifyPath !== undefined) {
300
+ const commands = readCommands(resolve(cwd, verifyPath));
301
+ if (commands === null) return usage(commandsError("--verify-commands", verifyPath));
302
+ return runVerify({
303
+ cwd,
304
+ runner: withoutCredentials(hostRunner, [env, process.env]),
305
+ env,
306
+ definition,
307
+ harness,
308
+ limits,
309
+ sandbox,
310
+ commands,
311
+ platform,
312
+ signals,
313
+ timers,
314
+ out,
315
+ err,
316
+ refuse,
317
+ });
318
+ }
319
+
320
+ const brief = readBrief(resolve(cwd, briefPath));
321
+ if (brief === null) {
322
+ return usage(
323
+ `--brief ${briefPath}: it must be a file with the Stage's brief, of at most ${MAX_BRIEF_BYTES / 1024 / 1024} MiB.`,
324
+ );
325
+ }
326
+ if (inputPaths.length && !definition.TAKES_INPUTS) {
327
+ return usage(`stage ${stage} takes no --input.`);
328
+ }
329
+ if (untracked && !definition.TAKES_UNTRACKED) {
330
+ return usage(`stage ${stage} takes no --untracked.`);
331
+ }
332
+ if (definition.WRITES_BUNDLE && bundlePath === undefined) {
333
+ return usage(`stage ${stage} needs --bundle <file>, where its git bundle goes.`);
334
+ }
335
+ if (!definition.WRITES_BUNDLE && bundlePath !== undefined) {
336
+ return usage(`stage ${stage} takes no --bundle.`);
337
+ }
338
+ const inputs = readInputs(cwd, inputPaths);
339
+ if ("error" in inputs) return usage(inputs.error);
340
+ /** The files the run writes: each new, its own, in a folder that exists. */
341
+ const files = {};
342
+ /** The flag that named each file, by the file's identity. */
343
+ const named = new Map();
344
+ let privateDir = null;
345
+ for (const [flag, given, name] of [
346
+ ["--result", resultPath, definition.RESULT_NAME],
347
+ ...(definition.WRITES_BUNDLE ? [["--bundle", bundlePath, "branch.bundle"]] : []),
348
+ ["--transcript", transcriptPath, "transcript.log"],
349
+ ["--error-log", errorLogPath, "errors.log"],
350
+ // Only when asked for: the Factory's trusted step reads it (#515).
351
+ ...(usagePath === undefined ? [] : [["--usage", usagePath, "usage.json"]]),
352
+ ]) {
353
+ if (given === undefined) {
354
+ privateDir ??= mkdtempSync(join(tmpdir(), "agent-kit-stage-"));
355
+ files[flag] = join(privateDir, name);
356
+ continue;
357
+ }
358
+ const file = resolve(cwd, given);
359
+ const folder = dirname(file);
360
+ if (!existsSync(folder) || !statSync(folder).isDirectory()) {
361
+ return usage(`${flag} ${file}: its folder ${folder} does not exist.`);
362
+ }
363
+ // lstat, so a link counts as taken even when what it names is missing.
364
+ if (lstatSync(file, { throwIfNoEntry: false })) {
365
+ return usage(`${flag} ${file} already exists; name a new file.`);
366
+ }
367
+ // Two flags on one file would lose the report to the stream, after the run.
368
+ const identity = fileIdentity(file);
369
+ if (named.has(identity)) {
370
+ return usage(
371
+ `${named.get(identity)} and ${flag} name the same file, ${file}; give each its own.`,
372
+ );
373
+ }
374
+ named.set(identity, flag);
375
+ files[flag] = file;
376
+ }
377
+
378
+ // The credential's kind: the one named; else, on Claude Code, the
379
+ // subscription token when one is set (as the audit workflow prefers it).
380
+ const accepted = acceptedBy(harness);
381
+ const token = accepted[SUBSCRIPTION];
382
+ const chosen = credentialKind(
383
+ credential ??
384
+ (token && credentialFrom === undefined && env[token.env] ? SUBSCRIPTION : undefined),
385
+ );
386
+ if ("error" in chosen) return usage(chosen.error);
387
+ if (!Object.hasOwn(accepted, chosen.kind)) {
388
+ return usage(
389
+ `--credential ${chosen.kind} is not one ${facts.displayName} takes: leave it out for its API key.`,
390
+ );
391
+ }
392
+ const source = credentialSource(credentialFrom, chosen.kind, harness);
393
+ if ("error" in source) return usage(source.error);
394
+
395
+ // The Support Level (ADR 0028), before anything is read or run.
396
+ const support = stageSupport({ harness, stage: definition.STAGE, provingRun });
397
+ out(support.line);
398
+ const unwritten = writeRunSummary(env, support.summary);
399
+ if (unwritten !== null) err(`Could not write the run summary: ${unwritten}`);
400
+ if (support.refused !== undefined) return refuse([support.refused], PROVING_DOCS_URL);
401
+ if (support.warning !== undefined) err(`Warning: ${support.warning}`);
402
+
403
+ const stray = strayTokenRefusal(env);
404
+ if (stray) return refuse(stray);
405
+
406
+ // A missing credential fails the run before the agent starts.
407
+ if (source.kind === "env" && !env[source.name]) {
408
+ const secrets = facts.secrets
409
+ .map((s) => `the ${s.name} secret (${s.name.toUpperCase()})`)
410
+ .join(" or ");
411
+ return refuse([
412
+ `No model credential: the ${harness} harness needs ${secrets}, and ${source.name} is not set.`,
413
+ ]);
414
+ }
415
+ const runner = withoutCredentials(
416
+ hostRunner,
417
+ [env, process.env],
418
+ source.kind === "env" ? [source.name] : [],
419
+ );
420
+ const key = readCredential({
421
+ source,
422
+ env,
423
+ runner,
424
+ kind: chosen.kind,
425
+ harness,
426
+ command: `stage ${stage}`,
427
+ });
428
+ if ("refused" in key) return refuse(key.refused);
429
+
430
+ const repository = openRepository({ runner, cwd });
431
+ if ("refused" in repository) return refuse(repository.refused);
432
+ const { root, commit, commitOf } = repository;
433
+ const trusted = trustedRef === undefined ? commit : commitOf(trustedRef);
434
+ if (trusted === null) {
435
+ return refuse([
436
+ `The trusted ref ${trustedRef} is not a commit this checkout has: fetch it, or leave --trusted-ref out.`,
437
+ ]);
438
+ }
439
+
440
+ const request = { stage: definition.STAGE, credentialKind: chosen.kind };
441
+ const shape = adapterFor(harness)(request);
442
+ const copy = {
443
+ runner,
444
+ root,
445
+ commit,
446
+ trusted,
447
+ checkoutConfig: shape.checkoutConfig,
448
+ instructionFiles: shape.instructionFiles,
449
+ };
450
+ let workspace;
451
+ let seed = null;
452
+ try {
453
+ workspace = await workspaceTar({ ...copy, untracked });
454
+ // A writing Stage's agent commits, so its copy is made a git repository.
455
+ if (definition.WRITES_BUNDLE) seed = await seedPack(copy);
456
+ } catch (e) {
457
+ if (!(e instanceof WorkspaceError)) throw e;
458
+ return refuse([`Cannot copy the checkout: ${e.message}.`]);
459
+ }
460
+
461
+ const choice = selectRuntime({ runner, platform });
462
+ if ("refused" in choice) return refuse(choice.refused, RUNTIMES_DOCS_URL);
463
+ out(`Sandbox runtime: ${choice.runtime.name}.`);
464
+ const turnLimit = shape.stops.turnCap !== null;
465
+ out(describeLimits(limits, { turnLimit }));
466
+ if (!turnLimit && limitFlags["max-turns"] !== undefined) {
467
+ out(`${facts.displayName} has no turn limit, so --max-turns is ignored.`);
468
+ }
469
+ out(
470
+ egressHosts(shape) !== null
471
+ ? `Model credential: an API key from ${key.from}; ${facts.displayName} cannot be fronted by the model proxy, so the key sits in the sandbox (the weaker form, ADR 0025), and a Stage result or bundle holding it is refused.`
472
+ : `Model credential: ${chosen.kind === SUBSCRIPTION ? "a Claude subscription token" : "an API key"} from ${key.from}; it stays in the model proxy, outside the sandbox.`,
473
+ );
474
+
475
+ const publicLog = env.GITHUB_ACTIONS === "true";
476
+ /** The images the Launcher has pulled, which the driver need not pull. */
477
+ const resolvedImages = new Set();
478
+ return runInSandbox(
479
+ {
480
+ runner: withResolvedImages(runner, resolvedImages),
481
+ runtime: choice.runtime,
482
+ plan: shape,
483
+ signals,
484
+ timers,
485
+ out,
486
+ err,
487
+ },
488
+ ({ driver, clocks }) =>
489
+ launch({
490
+ driver,
491
+ clocks,
492
+ runner,
493
+ sandbox,
494
+ resolvedImages,
495
+ definition,
496
+ harness,
497
+ facts,
498
+ limits,
499
+ turnLimit,
500
+ model,
501
+ effort,
502
+ credential: key.credential,
503
+ credentialKind: chosen.kind,
504
+ credentialFrom: key.from,
505
+ modelApi,
506
+ commit,
507
+ root,
508
+ brief,
509
+ inputs: inputs.files,
510
+ shape,
511
+ workspace,
512
+ seed,
513
+ files,
514
+ publicLog,
515
+ out,
516
+ err,
517
+ }),
518
+ );
519
+ }
520
+
521
+ /** Why a run with a GitHub token in `env` is refused, or null. */
522
+ function strayTokenRefusal(env) {
523
+ const tokens = strayTokens(env);
524
+ return tokens.length
525
+ ? [
526
+ `${tokens.join(" and ")} ${tokens.length > 1 ? "are" : "is"} set in stage's environment, and a GitHub token must never reach the sandbox.`,
527
+ "Run it in a step whose environment holds no GitHub token.",
528
+ ]
529
+ : null;
530
+ }
531
+
532
+ /** The repository at `cwd` and its checked-out commit, or why there is none. */
533
+ function openRepository({ runner, cwd }) {
534
+ const top = runner("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
535
+ if (top.status !== 0) {
536
+ return { refused: [`${cwd} is not a git repository; stage copies the checked-out commit.`] };
537
+ }
538
+ const root = top.stdout.trim();
539
+ const commitOf = (ref) => {
540
+ const r = runner("git", [
541
+ "-C",
542
+ root,
543
+ "rev-parse",
544
+ "--verify",
545
+ "--quiet",
546
+ "--end-of-options",
547
+ `${ref}^{commit}`,
548
+ ]);
549
+ return r.status === 0 ? r.stdout.trim() : null;
550
+ };
551
+ const commit = commitOf("HEAD");
552
+ if (commit === null) return { refused: [`${root} has no commit checked out.`] };
553
+ return { root, commit, commitOf };
554
+ }
555
+
556
+ /**
557
+ * The verify run (ADR 0029): the whole checked-out commit in the same sandbox,
558
+ * with the setup's registries and the same cut, and no agent.
559
+ */
560
+ async function runVerify({
561
+ cwd,
562
+ runner,
563
+ env,
564
+ definition,
565
+ harness,
566
+ limits,
567
+ sandbox,
568
+ commands,
569
+ platform,
570
+ signals,
571
+ timers,
572
+ out,
573
+ err,
574
+ refuse,
575
+ }) {
576
+ const stray = strayTokenRefusal(env);
577
+ if (stray) return refuse(stray);
578
+ const repository = openRepository({ runner, cwd });
579
+ if ("refused" in repository) return refuse(repository.refused);
580
+ const { root, commit } = repository;
581
+ // The image alone is taken from the plan: nothing of the harness runs.
582
+ const shape = adapterFor(harness)({ stage: definition.STAGE, credentialKind: "api-key" });
583
+ // No agent reads this copy, so it leaves nothing of the commit out.
584
+ const copy = { runner, root, commit, trusted: commit, checkoutConfig: [], instructionFiles: [] };
585
+ let workspace;
586
+ let seed;
587
+ try {
588
+ workspace = await workspaceTar(copy);
589
+ seed = await seedPack(copy);
590
+ } catch (e) {
591
+ if (!(e instanceof WorkspaceError)) throw e;
592
+ return refuse([`Cannot copy the checkout: ${e.message}.`]);
593
+ }
594
+ const choice = selectRuntime({ runner, platform });
595
+ if ("refused" in choice) return refuse(choice.refused, RUNTIMES_DOCS_URL);
596
+ out(`Sandbox runtime: ${choice.runtime.name}.`);
597
+ out(
598
+ `Verify: no agent runs. Limits: setup ${limits.setupMinutes} min, verify ${limits.scanMinutes} min.`,
599
+ );
600
+ const resolvedImages = new Set();
601
+ return runInSandbox(
602
+ {
603
+ runner: withResolvedImages(runner, resolvedImages),
604
+ runtime: choice.runtime,
605
+ plan: shape,
606
+ signals,
607
+ timers,
608
+ out,
609
+ err,
610
+ },
611
+ async ({ driver, clocks }) => {
612
+ clocks.begin("setup", limits.setupMinutes);
613
+ await buildSandbox({
614
+ driver,
615
+ clocks,
616
+ runner,
617
+ definition,
618
+ commit,
619
+ workspace,
620
+ seed,
621
+ sandbox,
622
+ resolvedImages,
623
+ installAgent: false,
624
+ // The copy left nothing out, so nothing is cleared but the checkout put back.
625
+ shape: { checkoutConfig: [], instructionFiles: [] },
626
+ cut: () => cutForVerify(driver, out),
627
+ out,
628
+ });
629
+ return verifyInSandbox({
630
+ driver,
631
+ clocks,
632
+ commands,
633
+ minutes: limits.scanMinutes,
634
+ out,
635
+ });
636
+ },
637
+ );
638
+ }
639
+
640
+ /**
641
+ * The sandbox of a run, from its image to the network cut. Where the Caller's
642
+ * setup runs, it runs in a setup container of its own (ADR 0047): what crosses
643
+ * is taken out and checked, the network is cut, that container is removed with
644
+ * every process setup left, and a fresh one from the same image takes the
645
+ * workspace and the declared paths, the checkout put back and `.git/` made
646
+ * again from the trusted commit. The harness is the image's, so setup never
647
+ * touched the copy the agent runs.
648
+ */
649
+ async function buildSandbox({
650
+ driver,
651
+ clocks,
652
+ runner,
653
+ definition,
654
+ commit,
655
+ workspace,
656
+ seed,
657
+ sandbox,
658
+ resolvedImages,
659
+ installAgent = true,
660
+ shape,
661
+ cut,
662
+ out,
663
+ }) {
664
+ const short = commit.slice(0, 12);
665
+ // A registry is opened only for setup commands that can use it.
666
+ const registries = sandbox.setup === null ? [] : sandbox.registries;
667
+ const steps = { setup: [], start: [], ready: [], seed: [], registries, grounding: [] };
668
+ if (sandbox.image !== null) {
669
+ steps.image = await resolveImage({
670
+ docker: async (args) => {
671
+ const signal = clocks.signal();
672
+ if (signal.aborted) throw clocks.reason();
673
+ const r = await runner.start("docker", args, { signal });
674
+ if (r.aborted || signal.aborted) throw clocks.reason();
675
+ return r;
676
+ },
677
+ image: sandbox.image,
678
+ out,
679
+ });
680
+ resolvedImages.add(steps.image);
681
+ }
682
+ try {
683
+ await driver.prepare(steps, {
684
+ out,
685
+ branch: "HEAD",
686
+ short,
687
+ why: definition.TAKES_SANDBOX ? "no sandbox_image is named" : "a CI Stage names no image",
688
+ });
689
+ } catch (e) {
690
+ if (!(e instanceof StepFailed)) throw e;
691
+ // The driver's words are the Scan recipe's; here a Caller named the image.
692
+ throw new StepFailed(
693
+ e.lines.map((line) =>
694
+ line
695
+ .replace("The recipe's image", "The sandbox_image")
696
+ .replace("leave image and dockerfile out", "leave sandbox_image empty"),
697
+ ),
698
+ );
699
+ }
700
+ out(`Sandbox: starting ${driver.container}.`);
701
+ const started = await driver.start(steps);
702
+ if (started?.isolation) out(started.isolation);
703
+ await driver.copyIn(workspace.tar, "copying the repository in");
704
+ out(
705
+ `Copied in: ${workspace.files} files of ${short} to ${definition.WORKSPACE}; ${workspace.left} left out as the checkout's harness config or untrusted instructions${workspace.skipped ? `, ${workspace.skipped} untracked entries skipped` : ""}.`,
706
+ );
707
+ if (seed) await seedRepository({ driver, definition, commit, seed, sandbox, out });
708
+ if (sandbox.setup === null) {
709
+ if (installAgent) await driver.installAgent(out);
710
+ await cut();
711
+ return;
712
+ }
713
+ const egress = await driver.openSetupEgress(steps.registries);
714
+ out(`Setup: running setup_commands in a setup container of their own; ${egress.note}.`);
715
+ await runCommands({
716
+ driver,
717
+ name: "setup",
718
+ commands: sandbox.setup,
719
+ env: [...egress.env, "CI=true"],
720
+ out,
721
+ });
722
+ const carried = await carryOut({ driver, paths: sandbox.paths, out });
723
+ await cut();
724
+ await driver.renew();
725
+ out(
726
+ `Sandbox: the setup container is removed, with every process setup left; ${installAgent ? "the agent runs" : "verify_commands run"} in a fresh ${driver.container} from the same image.`,
727
+ );
728
+ await driver.copyIn(carried, "carrying setup's files over");
729
+ await restoreCheckout({ driver, shape, workspace, root: definition.WORKSPACE });
730
+ const leftOut = shape.checkoutConfig.length + shape.instructionFiles.length > 0;
731
+ out(
732
+ `Restored: the checkout from ${short}${leftOut ? ", its harness config and untrusted instructions left out" : ""}; .git/ is made again from it.`,
733
+ );
734
+ if (seed) await seedRepository({ driver, definition, commit, seed, sandbox, out });
735
+ if (installAgent) await driver.installAgent(out);
736
+ }
737
+
738
+ /** The Stage in the sandbox, from the image to what comes out. */
739
+ async function launch({
740
+ driver,
741
+ clocks,
742
+ runner,
743
+ sandbox,
744
+ resolvedImages,
745
+ definition,
746
+ harness,
747
+ facts,
748
+ limits,
749
+ turnLimit,
750
+ model,
751
+ effort,
752
+ credential,
753
+ credentialKind: kind,
754
+ credentialFrom,
755
+ modelApi,
756
+ commit,
757
+ root,
758
+ brief,
759
+ inputs,
760
+ shape,
761
+ workspace,
762
+ seed,
763
+ files,
764
+ publicLog,
765
+ out,
766
+ err,
767
+ }) {
768
+ clocks.begin("setup", limits.setupMinutes);
769
+ await buildSandbox({
770
+ driver,
771
+ clocks,
772
+ runner,
773
+ definition,
774
+ commit,
775
+ workspace,
776
+ seed,
777
+ sandbox,
778
+ resolvedImages,
779
+ shape,
780
+ cut: () => cutNetwork(driver, out),
781
+ out,
782
+ });
783
+ const hosts = egressHosts(shape);
784
+ // Cursor CLI: no model proxy; the key itself is what the sandbox holds.
785
+ const { callerKey, route, proxy } =
786
+ hosts === null
787
+ ? await openModelRoute({
788
+ driver,
789
+ clocks,
790
+ harness,
791
+ credential,
792
+ credentialKind: kind,
793
+ maxTokens: limits.tokens,
794
+ modelApi,
795
+ })
796
+ : { callerKey: credential, ...(await openEgressRoute({ driver, hosts })) };
797
+ if (route.isolation) out(route.isolation);
798
+ out(
799
+ hosts === null
800
+ ? `Model route: only the model proxy (${route.note}), which forwards to the model API alone.`
801
+ : `Egress route: only the Launcher's allowlist proxy (${route.note}), which forwards to ${hosts.join(", ")} on port 443 alone.`,
802
+ );
803
+
804
+ const names = inputs.map((input) => input.name);
805
+ const preamble = definition.briefPreamble(shape, names, { setup: sandbox.setup !== null });
806
+ const text = `${preamble}${brief}`;
807
+ await driver.copyIn(
808
+ tarOf([
809
+ { path: "agent-kit", dir: true },
810
+ { path: definition.IN_DIR.slice(1), dir: true },
811
+ { path: definition.BRIEF_PATH.slice(1), data: Buffer.from(text, "utf8") },
812
+ { path: definition.PROMPT_PATH.slice(1), data: Buffer.from(definition.PROMPT, "utf8") },
813
+ ...inputs.map(({ name, data }) => ({ path: `${definition.IN_DIR.slice(1)}/${name}`, data })),
814
+ ]),
815
+ "copying the brief in",
816
+ );
817
+ const plan = adapterFor(harness)({
818
+ stage: definition.STAGE,
819
+ proxyUrl: route.url,
820
+ briefPath: definition.PROMPT_PATH,
821
+ kitDir: KIT_DIR,
822
+ workspace: definition.WORKSPACE,
823
+ maxTurns: turnLimit ? limits.turns : undefined,
824
+ model,
825
+ effort,
826
+ credentialKind: kind,
827
+ callerKey,
828
+ });
829
+ const { displayName, version } = plan.identity;
830
+ const unasked = `${displayName}'s default`;
831
+ out(
832
+ `Agent step: ${displayName} ${version} (${textFor(harness, model).agentStep(kind)}, ${turnLimit ? `at most ${limits.turns} turns` : "no turn limit"}; requested model: ${model ?? unasked}, effort: ${effort ?? unasked}).`,
833
+ );
834
+ clocks.end();
835
+ clocks.begin("scan", limits.scanMinutes);
836
+ /** @type {import("./exec.mjs").StartResult | null} null when a limit stopped it */
837
+ let agent = null;
838
+ try {
839
+ agent = await driver.exec(
840
+ agentScript({ plan, report: definition.RESULT_PATH, workspace: definition.WORKSPACE }),
841
+ { env: plan.launch.env },
842
+ );
843
+ } catch (e) {
844
+ if (!(e instanceof LimitReached)) throw e;
845
+ }
846
+ clocks.end();
847
+ if (agent && agent.stdout.toString("utf8").split(/\r?\n/).includes(turnsMarker(plan))) {
848
+ clocks.stop(TURNS, `${displayName}'s ${limits.turns}-turn limit`);
849
+ }
850
+ // The Stage is over: no route out is left open while anything comes out.
851
+ await driver.close();
852
+ out(
853
+ publicLog
854
+ ? `Model proxy: ${proxy ? "closed" : "not started"} (${PUBLIC_LOG}).`
855
+ : `Model proxy: ${proxy?.summary() ?? "not started"}.`,
856
+ );
857
+ if (!publicLog && proxy?.credentialRefused()) {
858
+ err(
859
+ `The model API refused the credential from ${credentialFrom}: every answer was ${textFor(harness, model).refusedAs ?? "401 or 403"}. ${textFor(harness, model).keyRefused}.`,
860
+ );
861
+ }
862
+
863
+ // The raw stream and the error output, to their private files, never read.
864
+ await copyStream(driver, plan.transcript.path, files["--transcript"], "transcript", {
865
+ publicLog,
866
+ out,
867
+ err,
868
+ });
869
+ await copyStream(driver, `${KIT_DIR}/logs/agent.err`, files["--error-log"], "error output", {
870
+ publicLog,
871
+ out,
872
+ err,
873
+ });
874
+
875
+ const stopped = clocks.stopped();
876
+ // The run's usage, for the Factory's trusted step: two numbers from the kit's
877
+ // own proxy and clocks, written before anything that can fail below. A
878
+ // harness the proxy cannot front has no count, so it writes none.
879
+ if (files["--usage"] !== undefined && hosts === null && proxy) {
880
+ const named = { [TURNS]: "turns", [TOKENS]: "tokens", [WALL_CLOCK]: "minutes" };
881
+ writeFileSync(
882
+ files["--usage"],
883
+ `${JSON.stringify({ tokens: proxy.tokens(), stopped: stopped ? (named[stopped.limit] ?? null) : null })}\n`,
884
+ { mode: 0o600, flag: "wx" },
885
+ );
886
+ }
887
+ const failed = agent !== null && agent.status !== 0;
888
+ if (stopped) {
889
+ out(`${stoppedStatus(stopped)} Copying out what result the agent left.`);
890
+ } else if (failed) {
891
+ const lines = agent.stderr
892
+ .trimEnd()
893
+ .split(/\r\n|\r|\n/)
894
+ .filter(Boolean);
895
+ err(
896
+ publicLog
897
+ ? `The agent step exited ${agent.status ?? "abnormally"}. ${displayName}'s error output stays out of the log (${PUBLIC_LOG}).`
898
+ : [
899
+ `The agent step exited ${agent.status ?? "abnormally"}.`,
900
+ ...indent(lines.slice(-AGENT_ERROR_LINES).join("\n")),
901
+ ].join("\n"),
902
+ );
903
+ }
904
+
905
+ const file = await driver.copyOut(definition.RESULT_PATH, {
906
+ maxBytes: definition.MAX_COPY_BYTES ?? definition.MAX_RESULT_BYTES,
907
+ });
908
+ const why =
909
+ "missing" in file
910
+ ? `no file at ${definition.RESULT_PATH}`
911
+ : "error" in file
912
+ ? publicLog
913
+ ? `it was not copied out (why stays out of the log: ${PUBLIC_LOG})`
914
+ : `it was not copied out: ${file.error}`
915
+ : definition.invalid(file.data);
916
+ // A stopped writing Stage may have left half its work: nothing is taken.
917
+ if (stopped && definition.WRITES_BUNDLE) {
918
+ out(`${stoppedStatus(stopped)} Nothing is taken from a stopped ${definition.STAGE} run.`);
919
+ return STOPPED_EXIT;
920
+ }
921
+ if (why !== null) {
922
+ if (stopped) {
923
+ out(`${stoppedStatus(stopped)} No Stage result came out.`);
924
+ return STOPPED_EXIT;
925
+ }
926
+ throw new StepFailed([`FAILED no valid Stage result: ${why}.`]);
927
+ }
928
+ const bundle = definition.WRITES_BUNDLE
929
+ ? await copyBundle({ driver, definition, commit, publicLog })
930
+ : null;
931
+ if (hosts !== null) {
932
+ // On the host, from the bytes that came out: the sandbox's git is not trusted.
933
+ await refuseHeldKey({
934
+ runner,
935
+ definition,
936
+ root,
937
+ commit,
938
+ credential,
939
+ result: file.data,
940
+ bundle,
941
+ });
942
+ }
943
+ if (bundle) writeFileSync(files["--bundle"], bundle, { mode: 0o600, flag: "wx" });
944
+ writeFileSync(files["--result"], definition.markStopped(file.data, stopped?.limit ?? null), {
945
+ mode: 0o600,
946
+ flag: "wx",
947
+ });
948
+ out(
949
+ `Stage result: ${files["--result"]}${stopped ? `, ${definition.stoppedNote(stopped.limit)}` : ""}. Nothing was filed or posted.`,
950
+ );
951
+ if (bundle) out(`Git bundle: ${files["--bundle"]}. Nothing was pushed.`);
952
+ else if (definition.WRITES_BUNDLE) out("The agent made no commit, so there is no bundle.");
953
+ if (stopped) return STOPPED_EXIT;
954
+ return failed ? 1 : 0;
955
+ }
956
+
957
+ /** Make the copy in the sandbox a git repository holding `commit` alone. */
958
+ async function seedRepository({ driver, definition, commit, seed, sandbox, out }) {
959
+ await driver.copyIn(
960
+ tarOf([
961
+ { path: "agent-kit", dir: true },
962
+ { path: posix.dirname(definition.PACK_PATH).slice(1), dir: true },
963
+ ...definition.seedFiles(seed),
964
+ ]),
965
+ "copying the base commit in",
966
+ );
967
+ const made = await driver.exec(definition.seedScript(commit), { workdir: null });
968
+ if (made.status !== 0) {
969
+ throw new StepFailed([
970
+ "FAILED the sandbox's git repository could not be made.",
971
+ ...(sandbox.image === null
972
+ ? []
973
+ : [
974
+ "A sandbox_image needs git and bash, and its user must be able to write the workspace.",
975
+ ]),
976
+ ]);
977
+ }
978
+ out(`The copy is a git repository holding ${commit.slice(0, 12)} alone.`);
979
+ }
980
+
981
+ /**
982
+ * The git bundle of the agent's commits, made in the sandbox. It is data: the
983
+ * trusted step that pushes it validates those commits.
984
+ */
985
+ async function copyBundle({ driver, definition, commit, publicLog }) {
986
+ const fail = (why) => new StepFailed([`FAILED no git bundle: ${why}.`]);
987
+ const made = await driver.exec(definition.bundleScript(commit), { workdir: null });
988
+ if (made.status === 4) {
989
+ // A Stage whose work may be replies alone (the Review response) takes a
990
+ // run with no commit; every other writing Stage fails it.
991
+ if (definition.BUNDLE_OPTIONAL) return null;
992
+ throw fail("the agent made no commit");
993
+ }
994
+ if (made.status !== 0) throw fail("git could not bundle the agent's commits");
995
+ const file = await driver.copyOut(definition.BUNDLE_PATH, {
996
+ maxBytes: definition.MAX_BUNDLE_BYTES,
997
+ });
998
+ if ("missing" in file) throw fail(`no bundle at ${definition.BUNDLE_PATH}`);
999
+ if ("error" in file) {
1000
+ throw fail(
1001
+ publicLog
1002
+ ? `it was not copied out (why stays out of the log: ${PUBLIC_LOG})`
1003
+ : `it was not copied out: ${file.error}`,
1004
+ );
1005
+ }
1006
+ const why = definition.invalidBundle(file.data);
1007
+ if (why !== null) throw fail(why);
1008
+ return file.data;
1009
+ }
1010
+
1011
+ /**
1012
+ * Copy the stream at `path` in the sandbox to `file`, byte for byte (its start
1013
+ * and end alone past the cap). Nothing here reads it, and a stream that cannot
1014
+ * come out only says so.
1015
+ */
1016
+ async function copyStream(driver, path, file, what, { publicLog, out, err }) {
1017
+ // Cut in the sandbox, so a long stream is not lost whole.
1018
+ await driver.exec(
1019
+ `p=${path}; if [ -f "$p" ] && [ ! -L "$p" ] && [ "$(wc -c < "$p")" -gt ${MAX_STREAM_BYTES} ]; then { head -c ${STREAM_HEAD_BYTES} "$p"; tail -c ${MAX_STREAM_BYTES - STREAM_HEAD_BYTES} "$p"; } > "$p.cut" && mv -f "$p.cut" "$p"; fi`,
1020
+ { workdir: null },
1021
+ );
1022
+ const found = await driver.copyOut(path, { maxBytes: MAX_STREAM_BYTES });
1023
+ if ("data" in found) {
1024
+ writeFileSync(file, found.data, { mode: 0o600, flag: "wx" });
1025
+ out(`The ${what}: ${file}.`);
1026
+ return;
1027
+ }
1028
+ const why = publicLog
1029
+ ? PUBLIC_LOG
1030
+ : "error" in found
1031
+ ? found.error
1032
+ : firstLine(found.missing.stderr) || "there is none";
1033
+ err(`The ${what} did not come out (${why}).`);
1034
+ }
1035
+
1036
+ /**
1037
+ * What tells whether two new files are one: the folder's real path and the
1038
+ * name, in any letter case where the host's filesystem usually ignores it.
1039
+ */
1040
+ function fileIdentity(file) {
1041
+ const path = join(realpathSync(dirname(file)), basename(file));
1042
+ return process.platform === "linux" ? path : path.toLowerCase();
1043
+ }
1044
+
1045
+ /**
1046
+ * The files to copy in beside the brief, each a regular file of a plain name
1047
+ * of its own, or why one cannot be.
1048
+ * @returns {{ files: Array<{ name: string, data: Buffer }> } | { error: string }}
1049
+ */
1050
+ function readInputs(cwd, paths) {
1051
+ const files = [];
1052
+ let size = 0;
1053
+ for (const given of paths) {
1054
+ const file = resolve(cwd, given);
1055
+ const name = basename(file);
1056
+ // The brief and the prompt are the Launcher's own.
1057
+ if (!INPUT_NAME.test(name) || ["brief.md", "prompt.md"].includes(name)) {
1058
+ return {
1059
+ error: `--input ${given}: its name must be letters, digits and . _ -, and neither brief.md nor prompt.md.`,
1060
+ };
1061
+ }
1062
+ if (files.some((f) => f.name === name)) {
1063
+ return { error: `--input ${given}: another input is already named ${name}.` };
1064
+ }
1065
+ const stat = statSync(file, { throwIfNoEntry: false });
1066
+ size += stat?.size ?? 0;
1067
+ if (!stat?.isFile() || size > MAX_INPUT_BYTES) {
1068
+ return {
1069
+ error: `--input ${given}: it must be a file, and the inputs hold at most ${MAX_INPUT_BYTES / 1024 / 1024} MiB together.`,
1070
+ };
1071
+ }
1072
+ files.push({ name, data: readFileSync(file) });
1073
+ }
1074
+ return { files };
1075
+ }
1076
+
1077
+ /** The brief's text, or null when `file` is not a brief that can be handed in. */
1078
+ function readBrief(file) {
1079
+ try {
1080
+ const stat = statSync(file);
1081
+ if (!stat.isFile() || stat.size > MAX_BRIEF_BYTES) return null;
1082
+ const text = readFileSync(file, "utf8");
1083
+ return text.trim() ? text : null;
1084
+ } catch {
1085
+ return null;
1086
+ }
1087
+ }