@mnaimfaizy/agent-kit 1.0.0-beta.15 → 1.0.0-beta.17

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 (120) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +332 -5
  4. package/src/deep-scan/docker-driver.mjs +70 -3
  5. package/src/deep-scan/lifecycle.mjs +2 -2
  6. package/src/deep-scan/sbx-driver.mjs +34 -47
  7. package/src/doctor.mjs +53 -1
  8. package/src/exec.mjs +18 -5
  9. package/src/factory/budget/budget.mjs +260 -0
  10. package/src/factory/build/command.mjs +321 -0
  11. package/src/factory/build/factory.mjs +473 -0
  12. package/src/factory/build/findings.mjs +55 -0
  13. package/src/factory/build/host.mjs +230 -0
  14. package/src/factory/build/notes.mjs +191 -0
  15. package/src/factory/build/pull-request.mjs +74 -0
  16. package/src/factory/bundle.mjs +146 -0
  17. package/src/factory/checks/allowed-paths.mjs +50 -0
  18. package/src/factory/checks/plan-header.mjs +296 -0
  19. package/src/factory/checks/qa.mjs +85 -0
  20. package/src/factory/checks/review.mjs +73 -0
  21. package/src/factory/checks/security.mjs +50 -0
  22. package/src/factory/checks/stage-check.mjs +89 -0
  23. package/src/factory/claims/command.mjs +187 -0
  24. package/src/factory/claims/release.mjs +111 -0
  25. package/src/factory/decision/answers.mjs +103 -0
  26. package/src/factory/decision/command.mjs +64 -0
  27. package/src/factory/decision/plan.mjs +99 -0
  28. package/src/factory/decision/request.mjs +116 -0
  29. package/src/factory/doctor/files.mjs +349 -0
  30. package/src/factory/doctor/index.mjs +56 -0
  31. package/src/factory/doctor/local.mjs +513 -0
  32. package/src/factory/doctor/orchestrate.mjs +146 -0
  33. package/src/factory/engine/lease.mjs +146 -0
  34. package/src/factory/engine/local-engine.mjs +177 -0
  35. package/src/factory/engine/lockfile.mjs +64 -0
  36. package/src/factory/engine/workflow-engine.mjs +124 -0
  37. package/src/factory/gate/comment.mjs +88 -0
  38. package/src/factory/gate/config.mjs +57 -0
  39. package/src/factory/gate/gate-core.mjs +250 -0
  40. package/src/factory/gate/guarded.mjs +17 -0
  41. package/src/factory/gate/reads.mjs +105 -0
  42. package/src/factory/gate/task.mjs +193 -0
  43. package/src/factory/gate/trip-reads.mjs +82 -0
  44. package/src/factory/gate/trip.mjs +87 -0
  45. package/src/factory/init/blueprint.mjs +181 -0
  46. package/src/factory/init/index.mjs +338 -0
  47. package/src/factory/labels/evidence.mjs +162 -0
  48. package/src/factory/labels/moves.mjs +32 -0
  49. package/src/factory/labels/reconcile.mjs +267 -0
  50. package/src/factory/labels/revert.mjs +87 -0
  51. package/src/factory/labels/timeline.mjs +72 -0
  52. package/src/factory/labels/voided.mjs +59 -0
  53. package/src/factory/limits/harness.mjs +39 -0
  54. package/src/factory/limits/limits.mjs +131 -0
  55. package/src/factory/merge/command.mjs +172 -0
  56. package/src/factory/outbox/check.mjs +240 -0
  57. package/src/factory/outbox/rulings.mjs +195 -0
  58. package/src/factory/plan/command.mjs +66 -0
  59. package/src/factory/plan/comment.mjs +156 -0
  60. package/src/factory/plan/publish.mjs +149 -0
  61. package/src/factory/plan/risk.mjs +153 -0
  62. package/src/factory/qa/command.mjs +301 -0
  63. package/src/factory/qa/decide.mjs +86 -0
  64. package/src/factory/qa/report.mjs +50 -0
  65. package/src/factory/records/engine-record.mjs +133 -0
  66. package/src/factory/records/main.mjs +96 -0
  67. package/src/factory/records/record.mjs +226 -0
  68. package/src/factory/records/sink.mjs +57 -0
  69. package/src/factory/report/build.mjs +92 -0
  70. package/src/factory/report/command.mjs +80 -0
  71. package/src/factory/report/facts.mjs +226 -0
  72. package/src/factory/report/gate-section.mjs +122 -0
  73. package/src/factory/report/metrics.mjs +111 -0
  74. package/src/factory/report/reads.mjs +246 -0
  75. package/src/factory/report/render.mjs +121 -0
  76. package/src/factory/report/rollout.mjs +154 -0
  77. package/src/factory/review/brief.mjs +195 -0
  78. package/src/factory/review/command.mjs +182 -0
  79. package/src/factory/run/awake.mjs +70 -0
  80. package/src/factory/run/collect.mjs +77 -0
  81. package/src/factory/run/command.mjs +556 -0
  82. package/src/factory/run/gh.mjs +46 -0
  83. package/src/factory/run/launch.mjs +66 -0
  84. package/src/factory/run/pipelines.mjs +694 -0
  85. package/src/factory/run/raw.mjs +96 -0
  86. package/src/factory/run/restart.mjs +83 -0
  87. package/src/factory/run/s3.mjs +193 -0
  88. package/src/factory/run/secrets.mjs +142 -0
  89. package/src/factory/run/teardown.mjs +242 -0
  90. package/src/factory/run/token.mjs +70 -0
  91. package/src/factory/run/worktree.mjs +160 -0
  92. package/src/factory/security/audit.mjs +353 -0
  93. package/src/factory/security/command.mjs +157 -0
  94. package/src/factory/setup/app.mjs +122 -0
  95. package/src/factory/setup/command.mjs +472 -0
  96. package/src/factory/setup/labels.mjs +25 -0
  97. package/src/factory/setup/reads.mjs +159 -0
  98. package/src/factory/setup/writes.mjs +138 -0
  99. package/src/factory/snapshot/write.mjs +176 -0
  100. package/src/factory/stop/command.mjs +136 -0
  101. package/src/factory/sweep/actions-main.mjs +119 -0
  102. package/src/factory/sweep/command.mjs +65 -0
  103. package/src/factory/sweep/knobs.mjs +78 -0
  104. package/src/factory/sweep/marker-version.mjs +15 -0
  105. package/src/factory/sweep/markers.mjs +112 -0
  106. package/src/factory/sweep/overlap.mjs +24 -0
  107. package/src/factory/sweep/run.mjs +198 -0
  108. package/src/factory/sweep/shell.mjs +398 -0
  109. package/src/factory/sweep/split.mjs +104 -0
  110. package/src/factory/sweep/states.mjs +87 -0
  111. package/src/factory/sweep/sweep-core.mjs +2009 -0
  112. package/src/factory/tracker/github.mjs +713 -0
  113. package/src/factory/tracker/operations.mjs +153 -0
  114. package/src/factory/upgrade/index.mjs +83 -0
  115. package/src/init.mjs +62 -24
  116. package/src/kit-owned-paths.mjs +1 -1
  117. package/src/stage/build.mjs +100 -0
  118. package/src/stage/factory-live.mjs +288 -0
  119. package/src/stage.mjs +100 -4
  120. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,556 @@
1
+ // `agent-kit factory run [--once] [--drain <dur>]`: the Orchestrate engine host (ADR 0039,
2
+ // docs/factory/engine.md). A foreground process for one repository, on the developer's
3
+ // own machine. It holds the PAT and the model keys in memory only, takes the local
4
+ // lockfile and the Engine lease, cleans up what a crashed run left (labelled sandboxes,
5
+ // its own open Claims released `engine-restart`), then polls: every sweep it renews the
6
+ // lease and runs the shared sweep over a tracker on the PAT and the local engine.
7
+ //
8
+ // Stopping: the first SIGINT/SIGTERM (Ctrl-C, or `factory stop` on this machine) drains:
9
+ // no more sweeps, running Stages finish for up to `--drain`, the rest are cancelled and
10
+ // their Claims released `stopped` (no Attempt), their tasks moved back. The second stops
11
+ // at once: every Stage cancelled and its sandbox torn down, nothing written to the
12
+ // tracker; the Claims expire or are released `engine-restart` by the next start.
13
+ //
14
+ // Exit codes: 0 drained or swept (`--once`), 1 refused (token, lease, lock) or the
15
+ // lease was lost, 2 not runnable (usage, missing secrets), 130 stopped at once.
16
+
17
+ import {
18
+ chmodSync,
19
+ existsSync,
20
+ mkdirSync,
21
+ readdirSync,
22
+ readFileSync,
23
+ rmSync,
24
+ statSync,
25
+ writeFileSync,
26
+ } from "node:fs";
27
+ import { homedir, hostname } from "node:os";
28
+ import { join } from "node:path";
29
+
30
+ import { createLocalEngine, LOCAL_ENGINE_NAME } from "../engine/local-engine.mjs";
31
+ import { acquireLease, leaseMs, releaseLease, renewLease } from "../engine/lease.mjs";
32
+ import { acquireLock, stateDirOf } from "../engine/lockfile.mjs";
33
+ import { createGithubTracker } from "../tracker/github.mjs";
34
+ import { runFromEnvironment } from "../sweep/run.mjs";
35
+ import { claimsOf } from "../sweep/sweep-core.mjs";
36
+ import { createS3 } from "./s3.mjs";
37
+ import { runMergeRecord, runMergeRun } from "../merge/command.mjs";
38
+ import { createKeepAwake } from "./awake.mjs";
39
+ import { createGh, gitPushEnv } from "./gh.mjs";
40
+ import { createLauncher } from "./launch.mjs";
41
+ import { createPipelines } from "./pipelines.mjs";
42
+ import { moveBack, releaseOwnClaims, removeSandboxes } from "./restart.mjs";
43
+ import { readSecrets, readSinks } from "./secrets.mjs";
44
+ import { createTeardown } from "./teardown.mjs";
45
+ import { checkToken } from "./token.mjs";
46
+ import { createCheckouts } from "./worktree.mjs";
47
+
48
+ export const DEFAULT_POLL_MS = 60_000;
49
+ export const MIN_POLL_MS = 30_000;
50
+ export const DEFAULT_DRAIN_MS = 10 * 60_000;
51
+ export const PREVIEW = "preview";
52
+ export const TEARDOWN_FETCH_MS = 20_000;
53
+
54
+ const STAGE_SETTING =
55
+ /^AGENT_KIT_(?:(?:PLAN|REVIEW|QA|SECURITY(?:_AUDIT)?|BUILD)_)?(?:HARNESS|MODEL|EFFORT)$/;
56
+ const SLUG = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
57
+
58
+ /** `90s`, `10m`, `2h` or a bare number of seconds, in milliseconds; null when it is not one. */
59
+ export function parseDuration(text) {
60
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(String(text ?? "").trim());
61
+ if (!match) return null;
62
+ const unit = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[match[2] ?? "s"];
63
+ return Math.round(Number(match[1]) * unit);
64
+ }
65
+
66
+ const realSleep = (ms, signal) =>
67
+ new Promise((resolve) => {
68
+ if (signal?.aborted) return resolve();
69
+ const timer = setTimeout(resolve, ms);
70
+ signal?.addEventListener(
71
+ "abort",
72
+ () => {
73
+ clearTimeout(timer);
74
+ resolve();
75
+ },
76
+ { once: true },
77
+ );
78
+ });
79
+
80
+ const alivePid = (pid) => {
81
+ try {
82
+ process.kill(pid, 0);
83
+ return true;
84
+ } catch (error) {
85
+ return error?.code === "EPERM";
86
+ }
87
+ };
88
+
89
+ /**
90
+ * @param {{
91
+ * runner: Function,
92
+ * env: Record<string, string | undefined>,
93
+ * repo?: string,
94
+ * once?: boolean,
95
+ * uploadRaw?: boolean,
96
+ * fetch?: Function,
97
+ * drainMs?: number,
98
+ * pollMs?: number,
99
+ * cwd?: string,
100
+ * clock?: () => number,
101
+ * sleep?: (ms: number, signal?: AbortSignal) => Promise<void>,
102
+ * signals?: { on: Function, off: Function },
103
+ * host?: string,
104
+ * pid?: number,
105
+ * platform?: string,
106
+ * home?: string,
107
+ * fs?: object,
108
+ * alive?: (pid: number) => boolean,
109
+ * uuid?: () => string,
110
+ * nonce?: (issue: number, attempt: number) => string,
111
+ * launch?: (opts: object) => Promise<number>,
112
+ * out: (line: string) => void,
113
+ * err: (line: string) => void,
114
+ * }} io Everything past `runner`, `env`, the options and `out`/`err` is a seam for tests.
115
+ * @returns {Promise<number>}
116
+ */
117
+ export async function runFactoryRun(params) {
118
+ // The signal handlers go in first, so a Ctrl-C while the engine starts up is taken as a
119
+ // drain too (the loop never begins, and the lease and lockfile are let go), not as the
120
+ // default kill that would leave them behind.
121
+ const ctl = {
122
+ stops: 0,
123
+ nap: new AbortController(),
124
+ engine: null,
125
+ first: null,
126
+ onFirst: () => {},
127
+ };
128
+ ctl.first = new Promise((resolve) => {
129
+ ctl.onFirst = resolve;
130
+ });
131
+ const signals = params.signals ?? process;
132
+ const onSignal = () => {
133
+ ctl.stops += 1;
134
+ if (ctl.stops === 1) {
135
+ params.out(
136
+ "factory run: draining: no new Claims; running Stages finish up to the drain time (Ctrl-C again stops at once)",
137
+ );
138
+ ctl.onFirst();
139
+ } else params.out("factory run: stopping at once");
140
+ if (ctl.stops >= 2) ctl.engine?.cancelAll();
141
+ ctl.nap.abort();
142
+ };
143
+ signals.on("SIGINT", onSignal);
144
+ signals.on("SIGTERM", onSignal);
145
+ try {
146
+ return await runEngine(params, ctl);
147
+ } finally {
148
+ signals.off("SIGINT", onSignal);
149
+ signals.off("SIGTERM", onSignal);
150
+ }
151
+ }
152
+
153
+ async function runEngine(
154
+ {
155
+ runner,
156
+ env,
157
+ repo,
158
+ once = false,
159
+ uploadRaw = false,
160
+ fetch = globalThis.fetch,
161
+ drainMs = DEFAULT_DRAIN_MS,
162
+ pollMs = DEFAULT_POLL_MS,
163
+ cwd = process.cwd(),
164
+ clock = Date.now,
165
+ sleep = realSleep,
166
+ host = hostname(),
167
+ pid = process.pid,
168
+ platform = process.platform,
169
+ home = homedir(),
170
+ fs = {
171
+ mkdirSync,
172
+ writeFileSync,
173
+ readFileSync,
174
+ rmSync,
175
+ existsSync,
176
+ readdirSync,
177
+ statSync,
178
+ chmodSync,
179
+ },
180
+ alive = alivePid,
181
+ uuid = () => globalThis.crypto.randomUUID(),
182
+ nonce,
183
+ launch,
184
+ pipelines,
185
+ out,
186
+ err,
187
+ },
188
+ ctl,
189
+ ) {
190
+ out(
191
+ `Orchestrate engine (${PREVIEW}): not yet proven on a second Consumer (docs/factory/engine.md).`,
192
+ );
193
+ if (!Number.isFinite(pollMs) || pollMs < MIN_POLL_MS) {
194
+ err(`factory run: the poll interval is at least ${MIN_POLL_MS / 1000} seconds`);
195
+ return 2;
196
+ }
197
+ if (!Number.isFinite(drainMs) || drainMs < 0) {
198
+ err("factory run: --drain is a duration such as 90s or 10m");
199
+ return 2;
200
+ }
201
+
202
+ // Secrets: read once, kept in memory, never written anywhere.
203
+ const secrets = readSecrets({ env, runner });
204
+ if (secrets.refused) {
205
+ err(`factory run: refused: ${secrets.refused}`);
206
+ return 2;
207
+ }
208
+ // The Sinks' settings and keys: read once, held in these closures only.
209
+ const sinks = readSinks({ env, runner, uploadRaw });
210
+ if (sinks.refused) {
211
+ err(`factory run: refused: ${sinks.refused}`);
212
+ return 2;
213
+ }
214
+ const gh = createGh({ runner, token: secrets.token });
215
+ let slug = repo ?? env.GITHUB_REPOSITORY;
216
+ if (!slug) {
217
+ const view = gh(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]);
218
+ if (view.status === 0) slug = view.stdout.trim();
219
+ }
220
+ if (!slug || !SLUG.test(slug)) {
221
+ err(
222
+ `factory run: no repository (pass --repo owner/name or run it in a clone), got ${JSON.stringify(slug)}`,
223
+ );
224
+ return 2;
225
+ }
226
+ const token = checkToken({ gh, repo: slug, token: secrets.token });
227
+ if (token.refused) {
228
+ err(`factory run: refused: ${token.refused}`);
229
+ return 1;
230
+ }
231
+ if (token.notice) out(`notice: ${token.notice}`);
232
+ const identity = token.login;
233
+
234
+ // One engine per repository: the local lockfile, then the lease on the tracker.
235
+ const stateDir = stateDirOf(home, slug);
236
+ const lock = acquireLock({ dir: stateDir, fs, pid, host, alive, now: clock });
237
+ if (lock.refused) {
238
+ err(
239
+ `factory run: refused: another engine runs ${slug} on ${lock.refused.host} (process ${lock.refused.pid}); lock ${join(stateDir, "engine.lock")}`,
240
+ );
241
+ return 1;
242
+ }
243
+ const tracker = createGithubTracker({ gh, repo: slug });
244
+ const id = uuid();
245
+ const leaseDeps = { tracker, identity, id, host, now: clock, pollMs };
246
+ let lease;
247
+ try {
248
+ lease = acquireLease(leaseDeps);
249
+ } catch (error) {
250
+ lock.release();
251
+ err(`factory run: the Engine lease could not be taken: ${error.message}`);
252
+ return 1;
253
+ }
254
+ if (lease.missing) {
255
+ lock.release();
256
+ err(`factory run: ${slug} has no Factory control issue: run agent-kit factory setup first`);
257
+ return 1;
258
+ }
259
+ if (lease.refused) {
260
+ lock.release();
261
+ err(
262
+ `factory run: refused: a live Engine lease is held by ${lease.refused.host} until ${lease.refused.expires}; one engine runs a repository`,
263
+ );
264
+ return 1;
265
+ }
266
+
267
+ const log = (line) => out(line);
268
+ const awake = createKeepAwake({ runner, platform, log });
269
+ // The Launcher's environment: the model keys and the harness settings, nothing else.
270
+ const stageEnv = {
271
+ ...secrets.modelEnv,
272
+ ...Object.fromEntries(Object.entries(env).filter(([k, v]) => STAGE_SETTING.test(k) && v)),
273
+ ...(env.PATH ? { PATH: env.PATH } : {}),
274
+ ...(env.HOME ? { HOME: env.HOME } : {}),
275
+ };
276
+ const realLaunch = launch ?? createLauncher({ runner, env: stageEnv, cwd, platform, log });
277
+ const stagePipelines = pipelines ?? createPipelines({}, { factory: realLaunch.factory === true });
278
+ const runsDir = join(stateDir, "runs");
279
+ // A teardown never waits on the network for ever, so a stop at once still ends.
280
+ const boundedFetch = (url, init = {}) =>
281
+ fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(TEARDOWN_FETCH_MS) });
282
+ const s3 = sinks.raw
283
+ ? createS3({
284
+ endpoint: sinks.raw.endpoint,
285
+ bucket: sinks.raw.bucket,
286
+ region: sinks.raw.region,
287
+ accessKeyId: sinks.raw.accessKeyId,
288
+ secretAccessKey: sinks.raw.secretAccessKey,
289
+ fetch: boundedFetch,
290
+ now: () => new Date(clock()),
291
+ })
292
+ : null;
293
+ const teardown = createTeardown({
294
+ fs,
295
+ runsDir,
296
+ slug,
297
+ identity,
298
+ sink: sinks.records,
299
+ s3,
300
+ uploadRaw,
301
+ fetch: boundedFetch,
302
+ now: clock,
303
+ log,
304
+ });
305
+ // A cancel is an `expiry` when the run's Claim has run out, else a plain `cancel`.
306
+ const classifyCancel = ({ claim }) => {
307
+ for (const issue of tracker.readState().issues ?? [])
308
+ for (const c of claimsOf(issue, { name: LOCAL_ENGINE_NAME, identity }))
309
+ if (c.claim === claim) return Date.parse(c.expires) <= clock() ? "expiry" : "cancel";
310
+ return "cancel";
311
+ };
312
+ const bundleEnv = { GITHUB_REPOSITORY: slug, AGENT_KIT_FACTORY_IDENTITY: identity };
313
+ const engine = createLocalEngine({
314
+ identity,
315
+ pipelines: stagePipelines,
316
+ context: () => {
317
+ // One Stage run, one fetched commit: the first trusted read fetches the default branch's
318
+ // remote head, the rest reuse it. A fetch that fails throws before the Launcher is called.
319
+ let trustedCommit;
320
+ const trustedRoot = () => {
321
+ if (trustedCommit) return trustedCommit;
322
+ const branch = tracker.defaultBranch();
323
+ if (!branch) throw new Error("the repository's default branch could not be resolved");
324
+ // The repository is the tracker's, by URL, never the checkout's `origin` (a fork, or none).
325
+ // The token rides in the child's environment (`GIT_CONFIG_*`), never in the repository's
326
+ // config. The fetch adds objects and moves no ref but FETCH_HEAD (`--refmap=` turns off the
327
+ // remote-tracking update), and never touches the checkout, the index or the working tree.
328
+ const fetched = runner(
329
+ "git",
330
+ [
331
+ "fetch",
332
+ "--no-tags",
333
+ "--quiet",
334
+ "--refmap=",
335
+ `https://github.com/${slug}.git`,
336
+ `refs/heads/${branch}`,
337
+ ],
338
+ { cwd, env: gitPushEnv(secrets.token) },
339
+ );
340
+ if (fetched.status !== 0) {
341
+ throw new Error(
342
+ `could not fetch the default branch ${branch}: ${String(fetched.stderr || "git fetch failed").trim()}`,
343
+ );
344
+ }
345
+ const sha = runner("git", ["rev-parse", "--verify", "FETCH_HEAD^{commit}"], { cwd });
346
+ const commit = String(sha.stdout ?? "").trim();
347
+ if (sha.status !== 0 || !commit) {
348
+ throw new Error(`could not resolve the fetched default branch ${branch}`);
349
+ }
350
+ trustedCommit = { branch, commit };
351
+ return trustedCommit;
352
+ };
353
+ return {
354
+ repo: slug,
355
+ identity,
356
+ gh,
357
+ tracker,
358
+ env: stageEnv,
359
+ launch: realLaunch,
360
+ git: (args, opts = {}) =>
361
+ runner("git", args, { cwd, ...(opts.push ? { env: gitPushEnv(secrets.token) } : {}) }),
362
+ // A detached worktree at one commit, for a Stage that judges a pull request's code.
363
+ checkout: createCheckouts({
364
+ runner,
365
+ cwd,
366
+ tmpDir: stateDir,
367
+ fetchUrl: `https://github.com/${slug}.git`,
368
+ fetchEnv: gitPushEnv(secrets.token),
369
+ fs,
370
+ }),
371
+ tmpDir: stateDir,
372
+ now: clock,
373
+ sleep,
374
+ runDir: (name) => join(runsDir, String(name).replace(/[^A-Za-z0-9._-]/g, "_")),
375
+ trustedCommit: () => trustedRoot().commit,
376
+ readTrusted: (path) => {
377
+ const { branch, commit } = trustedRoot();
378
+ const shown = runner("git", ["show", `${commit}:${path}`], { cwd });
379
+ if (shown.status !== 0) {
380
+ throw new Error(
381
+ `${path} is not on the default branch (${branch}): run init --factory --engine orchestrate and merge it`,
382
+ );
383
+ }
384
+ return shown.stdout;
385
+ },
386
+ writeFile: (path, text, { mode = 0o600 } = {}) => {
387
+ fs.rmSync?.(path, { force: true });
388
+ fs.writeFileSync(path, text, { mode });
389
+ },
390
+ // A Kit script from the default branch, run as a child of this process with the engine's
391
+ // token in the child's environment only (never an argument, a file or a log): the review's
392
+ // publish (`review-threads.mjs`), which shares its code with the Workflow engine's.
393
+ runScript: (file, args, extraEnv = {}) =>
394
+ runner(process.execPath, [file, ...args], {
395
+ cwd,
396
+ env: { GH_TOKEN: secrets.token, GH_PROMPT_DISABLED: "1", ...extraEnv },
397
+ }),
398
+ runId: () => clock(),
399
+ log,
400
+ };
401
+ },
402
+ merge: ({ issue, pull, head, method }) => {
403
+ const args = [
404
+ "--repo",
405
+ slug,
406
+ "--pull",
407
+ String(pull),
408
+ "--head",
409
+ head,
410
+ "--method",
411
+ method,
412
+ "--issue",
413
+ String(issue),
414
+ ];
415
+ const lines = [];
416
+ const io = { gh, env: bundleEnv, args, out: log, err: (l) => lines.push(l) };
417
+ if (runMergeRun(io) !== 0) throw new Error(lines.join(" ").slice(0, 300) || "merge refused");
418
+ // The record needs a merge made by an App; a PAT's merge is a user's, and is not recorded.
419
+ runMergeRecord({ ...io, err: log });
420
+ },
421
+ onRunsChanged: (running) => awake.update(running),
422
+ onTeardown: teardown.teardown,
423
+ classifyCancel,
424
+ log,
425
+ });
426
+ ctl.engine = engine;
427
+ const claimEngine = { name: LOCAL_ENGINE_NAME, identity };
428
+
429
+ // Start-up clean-up: sandboxes a dead run left, and its own open Claims.
430
+ removeSandboxes({ runner, log });
431
+ const left = releaseOwnClaims({ tracker, engine: claimEngine, reason: "engine-restart", log });
432
+ for (const r of left)
433
+ log(`restart: released ${r.stage} Claim ${r.claim} on #${r.issue} (engine-restart)`);
434
+ // Its run folders are collected too, and each Stage's record written as `no-result`.
435
+ await teardown.restart({ left });
436
+
437
+ out(
438
+ `factory run: ${slug} as ${identity} on ${host}; polling every ${pollMs / 1000}s${once ? " (once)" : ""}; raw upload ${uploadRaw ? "on" : "off"}`,
439
+ );
440
+ if (sinks.notice) out(`notice: ${sinks.notice}`);
441
+
442
+ let exit = 0;
443
+ const killSwitch = () => {
444
+ if (env.AGENT_KIT_FACTORY_ENABLED !== undefined) return env.AGENT_KIT_FACTORY_ENABLED;
445
+ const variable = gh([
446
+ "api",
447
+ `repos/${slug}/actions/variables/AGENT_KIT_FACTORY_ENABLED`,
448
+ "--jq",
449
+ ".value",
450
+ ]);
451
+ return variable.status === 0 ? variable.stdout.replace(/\n$/, "") : undefined;
452
+ };
453
+ try {
454
+ let lastRenewed = clock();
455
+ while (ctl.stops === 0) {
456
+ try {
457
+ let renewed;
458
+ try {
459
+ renewed = renewLease({ ...leaseDeps, commentId: lease.commentId });
460
+ lastRenewed = clock();
461
+ } catch (error) {
462
+ // No claiming without a lease: skip this sweep, and stop before the lease can lapse.
463
+ err(`factory run: the Engine lease could not be renewed: ${error.message}`);
464
+ if (clock() - lastRenewed >= leaseMs(pollMs) - pollMs) {
465
+ err("factory run: the Engine lease is about to lapse: stopping");
466
+ exit = 1;
467
+ break;
468
+ }
469
+ if (once) break;
470
+ ctl.nap = new AbortController();
471
+ await sleep(pollMs, ctl.nap.signal);
472
+ continue;
473
+ }
474
+ if (renewed.lost) {
475
+ err(`factory run: the Engine lease is now held by ${renewed.lost.host}: stopping`);
476
+ exit = 1;
477
+ break;
478
+ }
479
+ runFromEnvironment({
480
+ gh,
481
+ env: {
482
+ AGENT_KIT_FACTORY_ENABLED: killSwitch(),
483
+ AGENT_KIT_FACTORY_IDENTITY: identity,
484
+ },
485
+ repo: slug,
486
+ identity,
487
+ clock,
488
+ ...(nonce ? { nonce } : {}),
489
+ tracker,
490
+ engine,
491
+ out,
492
+ err,
493
+ });
494
+ } catch (error) {
495
+ err(`factory run: a sweep failed: ${error instanceof Error ? error.message : error}`);
496
+ }
497
+ if (once) {
498
+ // Wait for the Stages it started; a Ctrl-C meanwhile drains them as it does anywhere.
499
+ await Promise.race([engine.idle(), ctl.first]);
500
+ break;
501
+ }
502
+ ctl.nap = new AbortController();
503
+ await sleep(pollMs, ctl.nap.signal);
504
+ }
505
+ if (ctl.stops >= 1) {
506
+ // Drain: Stages finish up to `--drain`; the second signal cancels them at once.
507
+ if (ctl.stops === 1) {
508
+ // The drain can outlast the lease (10 minutes against 5 sweeps): keep renewing it.
509
+ const keepAlive = new AbortController();
510
+ const keeping = (async () => {
511
+ while (!keepAlive.signal.aborted) {
512
+ await sleep(pollMs, keepAlive.signal);
513
+ await new Promise((resolve) => setImmediate(resolve));
514
+ if (keepAlive.signal.aborted) break;
515
+ try {
516
+ renewLease({ ...leaseDeps, commentId: lease.commentId });
517
+ } catch (error) {
518
+ err(`factory run: the Engine lease could not be renewed: ${error.message}`);
519
+ }
520
+ }
521
+ })();
522
+ await engine.drain({ timeoutMs: drainMs, wait: (ms, signal) => sleep(ms, signal) });
523
+ keepAlive.abort();
524
+ await keeping;
525
+ } else {
526
+ await engine.idle();
527
+ }
528
+ if (ctl.stops === 1) {
529
+ // Claims of runs the drain cut short: released `stopped`, no Attempt, tasks moved back.
530
+ const cut = releaseOwnClaims({
531
+ tracker,
532
+ engine: claimEngine,
533
+ reason: "stopped",
534
+ only: (c) => !engine.finished.has(c.claim),
535
+ log,
536
+ });
537
+ moveBack({ tracker, released: cut, log });
538
+ for (const r of cut)
539
+ log(`drain: released ${r.stage} Claim ${r.claim} on #${r.issue} (stopped)`);
540
+ }
541
+ exit = ctl.stops >= 2 ? 130 : exit;
542
+ }
543
+ } finally {
544
+ awake.release();
545
+ try {
546
+ releaseLease({ ...leaseDeps, commentId: lease.commentId });
547
+ } catch (error) {
548
+ err(
549
+ `factory run: the Engine lease could not be let go (it expires in ${(5 * pollMs) / 1000}s): ${error.message}`,
550
+ );
551
+ }
552
+ lock.release();
553
+ }
554
+ out("factory run: stopped");
555
+ return exit;
556
+ }
@@ -0,0 +1,46 @@
1
+ // `gh` as the engine runs it: one function over the allowlisted runner, with the PAT in
2
+ // `GH_TOKEN` of each call's environment and nowhere else (never in an argument, a file or
3
+ // a log). The sync runner has no stdin, so a body given as `input` goes through a
4
+ // user-only temporary file named by `--input`, which is removed at once.
5
+
6
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+
10
+ /**
11
+ * @param {{ runner: Function, token: string, tmp?: string }} deps
12
+ * @returns {(args: string[], input?: string) => { status: number | null, stdout: string, stderr: string }}
13
+ */
14
+ export function createGh({ runner, token, tmp = tmpdir() }) {
15
+ return (args, input) => {
16
+ const env = { GH_TOKEN: token, GH_PROMPT_DISABLED: "1" };
17
+ if (input === undefined) return runner("gh", args, { env });
18
+ const at = args.indexOf("--input");
19
+ if (at === -1 || args[at + 1] !== "-") return runner("gh", args, { env });
20
+ const dir = mkdtempSync(join(tmp, "agent-kit-gh-"));
21
+ const file = join(dir, "body.json");
22
+ try {
23
+ writeFileSync(file, input, { mode: 0o600 });
24
+ const withFile = [...args];
25
+ withFile[at + 1] = file;
26
+ return runner("gh", withFile, { env });
27
+ } finally {
28
+ rmSync(dir, { recursive: true, force: true });
29
+ }
30
+ };
31
+ }
32
+
33
+ /**
34
+ * The environment of the engine's one `git push`: git reads its settings from
35
+ * `GIT_CONFIG_*`, so the token travels in the child's environment and never in an
36
+ * argument (a process list shows arguments), a file or a log.
37
+ */
38
+ export function gitPushEnv(token) {
39
+ const basic = Buffer.from(`x-access-token:${token}`).toString("base64");
40
+ return {
41
+ GIT_TERMINAL_PROMPT: "0",
42
+ GIT_CONFIG_COUNT: "1",
43
+ GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader",
44
+ GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basic}`,
45
+ };
46
+ }
@@ -0,0 +1,66 @@
1
+ // The Launcher as the engine starts it: `agent-kit stage <stage>` in this process
2
+ // (`runStage`), on the engine's runner, with only the model keys and the harness settings
3
+ // in its environment (never the GitHub token). A cancelled run's abort signal arrives
4
+ // where the Launcher listens for an interrupt, so it stops its step and destroys its
5
+ // sandbox as it does for a Ctrl-C.
6
+
7
+ import { selectRuntime } from "../../deep-scan/runtime.mjs";
8
+ import { runStage } from "../../stage.mjs";
9
+
10
+ /** An object with `on` and `off` that fires its SIGINT/SIGTERM listeners when `signal` aborts. */
11
+ export function signalsOf(signal) {
12
+ const listeners = new Map();
13
+ const fire = () => {
14
+ for (const handler of listeners.values()) handler("SIGTERM");
15
+ };
16
+ signal.addEventListener("abort", fire, { once: true });
17
+ return {
18
+ on(name, handler) {
19
+ listeners.set(`${name}`, handler);
20
+ },
21
+ off(name) {
22
+ listeners.delete(`${name}`);
23
+ },
24
+ };
25
+ }
26
+
27
+ /**
28
+ * True when the runtime this host would pick runs the harness as a user that is not root: sbx
29
+ * (a template whose user is `agent`) and the Docker drivers (gVisor, Kata, Firecracker), which
30
+ * run the build Stage's steps as uid 1000 (`runtime.agentUser`, set in stage.mjs for the factory-mode
31
+ * Stage alone). False when no runtime is accepted.
32
+ */
33
+ function canRunNonRootHarness({ runner, platform }) {
34
+ try {
35
+ const choice = selectRuntime({ runner, platform });
36
+ return "runtime" in choice;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * @param {{ runner: Function, env: Record<string, string>, cwd: string, platform?: string, log: (line: string) => void }} deps
44
+ * @returns {(opts: object) => Promise<number>} runs one Stage; resolves to the Launcher's exit code
45
+ */
46
+ export function createLauncher({ runner, env, cwd, platform = process.platform, log }) {
47
+ // `opts.cwd` is the checkout for this one call (a detached worktree at the pull request's head);
48
+ // without it the Launcher runs on the host's checkout.
49
+ const launch = ({ signal, cwd: checkout, ...opts }) =>
50
+ runStage({
51
+ ...opts,
52
+ cwd: checkout ?? cwd,
53
+ runner,
54
+ env,
55
+ platform,
56
+ signals: signalsOf(signal),
57
+ out: (line) => log(`launcher: ${line}`),
58
+ err: (line) => log(`launcher: ${line}`),
59
+ });
60
+ // `agent-kit stage build` runs a factory-mode Chief of Staff (stage/build.mjs: a Snapshot
61
+ // copied in read-only, an Outbox copied out live) and refuses a harness that runs as root.
62
+ // Both drivers run the build Stage's harness as a user that is not root, so the engine offers
63
+ // build on either.
64
+ launch.factory = canRunNonRootHarness({ runner, platform });
65
+ return launch;
66
+ }