@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.
- package/README.md +22 -4
- package/custom-harness.schema.json +243 -0
- package/harnesses.json +244 -6
- package/package.json +3 -2
- package/src/checks/ci-workflow.mjs +105 -0
- package/src/checks/claude-app.mjs +11 -2
- package/src/checks/custom-harness.mjs +157 -0
- package/src/checks/github-app.mjs +214 -0
- package/src/checks/rulesets.mjs +9 -8
- package/src/checks/secrets-and-variables.mjs +27 -8
- package/src/checks/stages.mjs +705 -0
- package/src/cli.mjs +583 -36
- package/src/deep-scan/agent.mjs +88 -21
- package/src/deep-scan/credential.mjs +81 -32
- package/src/deep-scan/docker-driver.mjs +105 -42
- package/src/deep-scan/harness-text.mjs +99 -0
- package/src/deep-scan/lifecycle.mjs +68 -178
- package/src/deep-scan/limits.mjs +13 -7
- package/src/deep-scan/model-proxy.mjs +21 -10
- package/src/deep-scan/preflight.mjs +19 -6
- package/src/deep-scan/recipe.mjs +4 -0
- package/src/deep-scan/runtime.mjs +54 -6
- package/src/deep-scan/sandbox-run.mjs +232 -0
- package/src/deep-scan/sbx-driver.mjs +224 -39
- package/src/deep-scan/tar.mjs +69 -22
- package/src/deep-scan/verify.mjs +6 -1
- package/src/deep-scan.mjs +73 -13
- package/src/doctor.mjs +166 -5
- package/src/exec.mjs +14 -5
- package/src/factory/budget/budget.mjs +259 -0
- package/src/factory/build/command.mjs +321 -0
- package/src/factory/build/factory.mjs +473 -0
- package/src/factory/build/findings.mjs +55 -0
- package/src/factory/build/host.mjs +230 -0
- package/src/factory/build/notes.mjs +191 -0
- package/src/factory/build/pull-request.mjs +74 -0
- package/src/factory/bundle.mjs +146 -0
- package/src/factory/checks/allowed-paths.mjs +50 -0
- package/src/factory/checks/plan-header.mjs +296 -0
- package/src/factory/checks/qa.mjs +85 -0
- package/src/factory/checks/review.mjs +73 -0
- package/src/factory/checks/security.mjs +50 -0
- package/src/factory/checks/stage-check.mjs +89 -0
- package/src/factory/claims/command.mjs +187 -0
- package/src/factory/claims/release.mjs +111 -0
- package/src/factory/decision/answers.mjs +103 -0
- package/src/factory/decision/command.mjs +64 -0
- package/src/factory/decision/plan.mjs +99 -0
- package/src/factory/decision/request.mjs +116 -0
- package/src/factory/doctor/files.mjs +329 -0
- package/src/factory/doctor/index.mjs +56 -0
- package/src/factory/doctor/local.mjs +497 -0
- package/src/factory/doctor/orchestrate.mjs +146 -0
- package/src/factory/engine/lease.mjs +146 -0
- package/src/factory/engine/local-engine.mjs +177 -0
- package/src/factory/engine/lockfile.mjs +64 -0
- package/src/factory/engine/workflow-engine.mjs +124 -0
- package/src/factory/gate/comment.mjs +88 -0
- package/src/factory/gate/config.mjs +57 -0
- package/src/factory/gate/gate-core.mjs +250 -0
- package/src/factory/gate/guarded.mjs +17 -0
- package/src/factory/gate/reads.mjs +105 -0
- package/src/factory/gate/task.mjs +193 -0
- package/src/factory/gate/trip-reads.mjs +82 -0
- package/src/factory/gate/trip.mjs +87 -0
- package/src/factory/init/blueprint.mjs +174 -0
- package/src/factory/init/index.mjs +337 -0
- package/src/factory/labels/evidence.mjs +162 -0
- package/src/factory/labels/moves.mjs +32 -0
- package/src/factory/labels/reconcile.mjs +267 -0
- package/src/factory/labels/revert.mjs +87 -0
- package/src/factory/labels/timeline.mjs +72 -0
- package/src/factory/labels/voided.mjs +59 -0
- package/src/factory/limits/harness.mjs +39 -0
- package/src/factory/limits/limits.mjs +123 -0
- package/src/factory/merge/command.mjs +172 -0
- package/src/factory/outbox/check.mjs +240 -0
- package/src/factory/outbox/rulings.mjs +195 -0
- package/src/factory/plan/command.mjs +66 -0
- package/src/factory/plan/comment.mjs +156 -0
- package/src/factory/plan/publish.mjs +149 -0
- package/src/factory/plan/risk.mjs +153 -0
- package/src/factory/qa/command.mjs +163 -0
- package/src/factory/records/engine-record.mjs +133 -0
- package/src/factory/records/main.mjs +96 -0
- package/src/factory/records/record.mjs +226 -0
- package/src/factory/records/sink.mjs +57 -0
- package/src/factory/report/build.mjs +92 -0
- package/src/factory/report/command.mjs +80 -0
- package/src/factory/report/facts.mjs +226 -0
- package/src/factory/report/gate-section.mjs +122 -0
- package/src/factory/report/metrics.mjs +111 -0
- package/src/factory/report/reads.mjs +246 -0
- package/src/factory/report/render.mjs +121 -0
- package/src/factory/report/rollout.mjs +154 -0
- package/src/factory/review/command.mjs +182 -0
- package/src/factory/run/awake.mjs +70 -0
- package/src/factory/run/collect.mjs +77 -0
- package/src/factory/run/command.mjs +490 -0
- package/src/factory/run/gh.mjs +46 -0
- package/src/factory/run/launch.mjs +47 -0
- package/src/factory/run/pipelines.mjs +261 -0
- package/src/factory/run/raw.mjs +96 -0
- package/src/factory/run/restart.mjs +83 -0
- package/src/factory/run/s3.mjs +193 -0
- package/src/factory/run/secrets.mjs +142 -0
- package/src/factory/run/teardown.mjs +242 -0
- package/src/factory/run/token.mjs +68 -0
- package/src/factory/security/command.mjs +157 -0
- package/src/factory/setup/app.mjs +122 -0
- package/src/factory/setup/command.mjs +409 -0
- package/src/factory/setup/labels.mjs +25 -0
- package/src/factory/setup/reads.mjs +129 -0
- package/src/factory/setup/writes.mjs +126 -0
- package/src/factory/snapshot/write.mjs +176 -0
- package/src/factory/stop/command.mjs +136 -0
- package/src/factory/sweep/actions-main.mjs +117 -0
- package/src/factory/sweep/command.mjs +65 -0
- package/src/factory/sweep/knobs.mjs +78 -0
- package/src/factory/sweep/marker-version.mjs +15 -0
- package/src/factory/sweep/markers.mjs +112 -0
- package/src/factory/sweep/overlap.mjs +24 -0
- package/src/factory/sweep/run.mjs +198 -0
- package/src/factory/sweep/shell.mjs +394 -0
- package/src/factory/sweep/split.mjs +104 -0
- package/src/factory/sweep/states.mjs +87 -0
- package/src/factory/sweep/sweep-core.mjs +1781 -0
- package/src/factory/tracker/github.mjs +674 -0
- package/src/factory/tracker/operations.mjs +153 -0
- package/src/factory/upgrade/index.mjs +83 -0
- package/src/harness/adapters.mjs +30 -0
- package/src/harness/antigravity.mjs +187 -0
- package/src/harness/claude-code.mjs +8 -1
- package/src/harness/codex.mjs +219 -0
- package/src/harness/cursor.mjs +199 -0
- package/src/harness/custom/registry.mjs +21 -0
- package/src/harness/custom/schema.mjs +90 -0
- package/src/harness/custom.mjs +299 -0
- package/src/harness/facts.mjs +44 -7
- package/src/harness/gemini.mjs +164 -0
- package/src/harness/install-layer.mjs +86 -3
- package/src/harness/opencode.mjs +289 -0
- package/src/harness/resolve.mjs +156 -0
- package/src/harness/support-levels.mjs +151 -3
- package/src/harness-live/assess.mjs +29 -6
- package/src/harness-live/cursor-real.mjs +146 -0
- package/src/harness-live/cursor-version.mjs +70 -0
- package/src/harness-live/cursor.mjs +80 -0
- package/src/harness-live/custom.mjs +91 -0
- package/src/harness-live/fixture-harness.mjs +45 -0
- package/src/harness-live/harnesses.mjs +263 -0
- package/src/harness-live/host.mjs +113 -4
- package/src/harness-live/opencode.mjs +289 -0
- package/src/harness-live/probes.mjs +87 -7
- package/src/harness-live/run.mjs +101 -20
- package/src/harness-live/setup.mjs +126 -0
- package/src/harness-live/stage.mjs +25 -15
- package/src/harness-live/suite.mjs +276 -95
- package/src/harness-test.mjs +116 -0
- package/src/init.mjs +374 -36
- package/src/kit-owned-paths.mjs +1 -1
- package/src/model-proxy/core.mjs +128 -20
- package/src/model-proxy/profiles/anthropic.mjs +54 -10
- package/src/model-proxy/profiles/gemini-api.mjs +311 -0
- package/src/model-proxy/profiles/openai.mjs +327 -0
- package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
- package/src/model-proxy/stub-dialects/openai.mjs +173 -0
- package/src/model-proxy/stub.mjs +9 -1
- package/src/stage/audit.mjs +79 -0
- package/src/stage/egress-route.mjs +207 -0
- package/src/stage/implement/carry.mjs +308 -0
- package/src/stage/implement/sandbox.mjs +271 -0
- package/src/stage/implement/verify.mjs +70 -0
- package/src/stage/implement.mjs +218 -0
- package/src/stage/plan.mjs +115 -0
- package/src/stage/review-response.mjs +172 -0
- package/src/stage/review.mjs +185 -0
- package/src/stage/workspace.mjs +274 -0
- package/src/stage.mjs +1087 -0
- package/src/upgrade.mjs +39 -7
|
@@ -0,0 +1,490 @@
|
|
|
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
|
+
|
|
47
|
+
export const DEFAULT_POLL_MS = 60_000;
|
|
48
|
+
export const MIN_POLL_MS = 30_000;
|
|
49
|
+
export const DEFAULT_DRAIN_MS = 10 * 60_000;
|
|
50
|
+
export const PREVIEW = "preview";
|
|
51
|
+
export const TEARDOWN_FETCH_MS = 20_000;
|
|
52
|
+
|
|
53
|
+
const STAGE_SETTING = /^AGENT_KIT_(?:(?:PLAN|REVIEW|QA|SECURITY|BUILD)_)?(?:HARNESS|MODEL|EFFORT)$/;
|
|
54
|
+
const SLUG = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
55
|
+
|
|
56
|
+
/** `90s`, `10m`, `2h` or a bare number of seconds, in milliseconds; null when it is not one. */
|
|
57
|
+
export function parseDuration(text) {
|
|
58
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(String(text ?? "").trim());
|
|
59
|
+
if (!match) return null;
|
|
60
|
+
const unit = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[match[2] ?? "s"];
|
|
61
|
+
return Math.round(Number(match[1]) * unit);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const realSleep = (ms, signal) =>
|
|
65
|
+
new Promise((resolve) => {
|
|
66
|
+
if (signal?.aborted) return resolve();
|
|
67
|
+
const timer = setTimeout(resolve, ms);
|
|
68
|
+
signal?.addEventListener(
|
|
69
|
+
"abort",
|
|
70
|
+
() => {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
resolve();
|
|
73
|
+
},
|
|
74
|
+
{ once: true },
|
|
75
|
+
);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const alivePid = (pid) => {
|
|
79
|
+
try {
|
|
80
|
+
process.kill(pid, 0);
|
|
81
|
+
return true;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return error?.code === "EPERM";
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @param {{
|
|
89
|
+
* runner: Function,
|
|
90
|
+
* env: Record<string, string | undefined>,
|
|
91
|
+
* repo?: string,
|
|
92
|
+
* once?: boolean,
|
|
93
|
+
* uploadRaw?: boolean,
|
|
94
|
+
* fetch?: Function,
|
|
95
|
+
* drainMs?: number,
|
|
96
|
+
* pollMs?: number,
|
|
97
|
+
* cwd?: string,
|
|
98
|
+
* clock?: () => number,
|
|
99
|
+
* sleep?: (ms: number, signal?: AbortSignal) => Promise<void>,
|
|
100
|
+
* signals?: { on: Function, off: Function },
|
|
101
|
+
* host?: string,
|
|
102
|
+
* pid?: number,
|
|
103
|
+
* platform?: string,
|
|
104
|
+
* home?: string,
|
|
105
|
+
* fs?: object,
|
|
106
|
+
* alive?: (pid: number) => boolean,
|
|
107
|
+
* uuid?: () => string,
|
|
108
|
+
* nonce?: (issue: number, attempt: number) => string,
|
|
109
|
+
* launch?: (opts: object) => Promise<number>,
|
|
110
|
+
* out: (line: string) => void,
|
|
111
|
+
* err: (line: string) => void,
|
|
112
|
+
* }} io Everything past `runner`, `env`, the options and `out`/`err` is a seam for tests.
|
|
113
|
+
* @returns {Promise<number>}
|
|
114
|
+
*/
|
|
115
|
+
export async function runFactoryRun(params) {
|
|
116
|
+
// The signal handlers go in first, so a Ctrl-C while the engine starts up is taken as a
|
|
117
|
+
// drain too (the loop never begins, and the lease and lockfile are let go), not as the
|
|
118
|
+
// default kill that would leave them behind.
|
|
119
|
+
const ctl = {
|
|
120
|
+
stops: 0,
|
|
121
|
+
nap: new AbortController(),
|
|
122
|
+
engine: null,
|
|
123
|
+
first: null,
|
|
124
|
+
onFirst: () => {},
|
|
125
|
+
};
|
|
126
|
+
ctl.first = new Promise((resolve) => {
|
|
127
|
+
ctl.onFirst = resolve;
|
|
128
|
+
});
|
|
129
|
+
const signals = params.signals ?? process;
|
|
130
|
+
const onSignal = () => {
|
|
131
|
+
ctl.stops += 1;
|
|
132
|
+
if (ctl.stops === 1) {
|
|
133
|
+
params.out(
|
|
134
|
+
"factory run: draining: no new Claims; running Stages finish up to the drain time (Ctrl-C again stops at once)",
|
|
135
|
+
);
|
|
136
|
+
ctl.onFirst();
|
|
137
|
+
} else params.out("factory run: stopping at once");
|
|
138
|
+
if (ctl.stops >= 2) ctl.engine?.cancelAll();
|
|
139
|
+
ctl.nap.abort();
|
|
140
|
+
};
|
|
141
|
+
signals.on("SIGINT", onSignal);
|
|
142
|
+
signals.on("SIGTERM", onSignal);
|
|
143
|
+
try {
|
|
144
|
+
return await runEngine(params, ctl);
|
|
145
|
+
} finally {
|
|
146
|
+
signals.off("SIGINT", onSignal);
|
|
147
|
+
signals.off("SIGTERM", onSignal);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function runEngine(
|
|
152
|
+
{
|
|
153
|
+
runner,
|
|
154
|
+
env,
|
|
155
|
+
repo,
|
|
156
|
+
once = false,
|
|
157
|
+
uploadRaw = false,
|
|
158
|
+
fetch = globalThis.fetch,
|
|
159
|
+
drainMs = DEFAULT_DRAIN_MS,
|
|
160
|
+
pollMs = DEFAULT_POLL_MS,
|
|
161
|
+
cwd = process.cwd(),
|
|
162
|
+
clock = Date.now,
|
|
163
|
+
sleep = realSleep,
|
|
164
|
+
host = hostname(),
|
|
165
|
+
pid = process.pid,
|
|
166
|
+
platform = process.platform,
|
|
167
|
+
home = homedir(),
|
|
168
|
+
fs = {
|
|
169
|
+
mkdirSync,
|
|
170
|
+
writeFileSync,
|
|
171
|
+
readFileSync,
|
|
172
|
+
rmSync,
|
|
173
|
+
existsSync,
|
|
174
|
+
readdirSync,
|
|
175
|
+
statSync,
|
|
176
|
+
chmodSync,
|
|
177
|
+
},
|
|
178
|
+
alive = alivePid,
|
|
179
|
+
uuid = () => globalThis.crypto.randomUUID(),
|
|
180
|
+
nonce,
|
|
181
|
+
launch,
|
|
182
|
+
pipelines,
|
|
183
|
+
out,
|
|
184
|
+
err,
|
|
185
|
+
},
|
|
186
|
+
ctl,
|
|
187
|
+
) {
|
|
188
|
+
out(
|
|
189
|
+
`Orchestrate engine (${PREVIEW}): not yet proven on a second Consumer; keep the merge gate off until review and security run here (docs/factory/engine.md).`,
|
|
190
|
+
);
|
|
191
|
+
if (!Number.isFinite(pollMs) || pollMs < MIN_POLL_MS) {
|
|
192
|
+
err(`factory run: the poll interval is at least ${MIN_POLL_MS / 1000} seconds`);
|
|
193
|
+
return 2;
|
|
194
|
+
}
|
|
195
|
+
if (!Number.isFinite(drainMs) || drainMs < 0) {
|
|
196
|
+
err("factory run: --drain is a duration such as 90s or 10m");
|
|
197
|
+
return 2;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Secrets: read once, kept in memory, never written anywhere.
|
|
201
|
+
const secrets = readSecrets({ env, runner });
|
|
202
|
+
if (secrets.refused) {
|
|
203
|
+
err(`factory run: refused: ${secrets.refused}`);
|
|
204
|
+
return 2;
|
|
205
|
+
}
|
|
206
|
+
// The Sinks' settings and keys: read once, held in these closures only.
|
|
207
|
+
const sinks = readSinks({ env, runner, uploadRaw });
|
|
208
|
+
if (sinks.refused) {
|
|
209
|
+
err(`factory run: refused: ${sinks.refused}`);
|
|
210
|
+
return 2;
|
|
211
|
+
}
|
|
212
|
+
const gh = createGh({ runner, token: secrets.token });
|
|
213
|
+
let slug = repo ?? env.GITHUB_REPOSITORY;
|
|
214
|
+
if (!slug) {
|
|
215
|
+
const view = gh(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]);
|
|
216
|
+
if (view.status === 0) slug = view.stdout.trim();
|
|
217
|
+
}
|
|
218
|
+
if (!slug || !SLUG.test(slug)) {
|
|
219
|
+
err(
|
|
220
|
+
`factory run: no repository (pass --repo owner/name or run it in a clone), got ${JSON.stringify(slug)}`,
|
|
221
|
+
);
|
|
222
|
+
return 2;
|
|
223
|
+
}
|
|
224
|
+
const token = checkToken({ gh, repo: slug, token: secrets.token });
|
|
225
|
+
if (token.refused) {
|
|
226
|
+
err(`factory run: refused: ${token.refused}`);
|
|
227
|
+
return 1;
|
|
228
|
+
}
|
|
229
|
+
if (token.notice) out(`notice: ${token.notice}`);
|
|
230
|
+
const identity = token.login;
|
|
231
|
+
|
|
232
|
+
// One engine per repository: the local lockfile, then the lease on the tracker.
|
|
233
|
+
const stateDir = stateDirOf(home, slug);
|
|
234
|
+
const lock = acquireLock({ dir: stateDir, fs, pid, host, alive, now: clock });
|
|
235
|
+
if (lock.refused) {
|
|
236
|
+
err(
|
|
237
|
+
`factory run: refused: another engine runs ${slug} on ${lock.refused.host} (process ${lock.refused.pid}); lock ${join(stateDir, "engine.lock")}`,
|
|
238
|
+
);
|
|
239
|
+
return 1;
|
|
240
|
+
}
|
|
241
|
+
const tracker = createGithubTracker({ gh, repo: slug });
|
|
242
|
+
const id = uuid();
|
|
243
|
+
const leaseDeps = { tracker, identity, id, host, now: clock, pollMs };
|
|
244
|
+
let lease;
|
|
245
|
+
try {
|
|
246
|
+
lease = acquireLease(leaseDeps);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
lock.release();
|
|
249
|
+
err(`factory run: the Engine lease could not be taken: ${error.message}`);
|
|
250
|
+
return 1;
|
|
251
|
+
}
|
|
252
|
+
if (lease.missing) {
|
|
253
|
+
lock.release();
|
|
254
|
+
err(`factory run: ${slug} has no Factory control issue: run agent-kit factory setup first`);
|
|
255
|
+
return 1;
|
|
256
|
+
}
|
|
257
|
+
if (lease.refused) {
|
|
258
|
+
lock.release();
|
|
259
|
+
err(
|
|
260
|
+
`factory run: refused: a live Engine lease is held by ${lease.refused.host} until ${lease.refused.expires}; one engine runs a repository`,
|
|
261
|
+
);
|
|
262
|
+
return 1;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const log = (line) => out(line);
|
|
266
|
+
const awake = createKeepAwake({ runner, platform, log });
|
|
267
|
+
// The Launcher's environment: the model keys and the harness settings, nothing else.
|
|
268
|
+
const stageEnv = {
|
|
269
|
+
...secrets.modelEnv,
|
|
270
|
+
...Object.fromEntries(Object.entries(env).filter(([k, v]) => STAGE_SETTING.test(k) && v)),
|
|
271
|
+
...(env.PATH ? { PATH: env.PATH } : {}),
|
|
272
|
+
...(env.HOME ? { HOME: env.HOME } : {}),
|
|
273
|
+
};
|
|
274
|
+
const realLaunch = launch ?? createLauncher({ runner, env: stageEnv, cwd, platform, log });
|
|
275
|
+
const stagePipelines = pipelines ?? createPipelines({}, { factory: realLaunch.factory === true });
|
|
276
|
+
const runsDir = join(stateDir, "runs");
|
|
277
|
+
// A teardown never waits on the network for ever, so a stop at once still ends.
|
|
278
|
+
const boundedFetch = (url, init = {}) =>
|
|
279
|
+
fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(TEARDOWN_FETCH_MS) });
|
|
280
|
+
const s3 = sinks.raw
|
|
281
|
+
? createS3({
|
|
282
|
+
endpoint: sinks.raw.endpoint,
|
|
283
|
+
bucket: sinks.raw.bucket,
|
|
284
|
+
region: sinks.raw.region,
|
|
285
|
+
accessKeyId: sinks.raw.accessKeyId,
|
|
286
|
+
secretAccessKey: sinks.raw.secretAccessKey,
|
|
287
|
+
fetch: boundedFetch,
|
|
288
|
+
now: () => new Date(clock()),
|
|
289
|
+
})
|
|
290
|
+
: null;
|
|
291
|
+
const teardown = createTeardown({
|
|
292
|
+
fs,
|
|
293
|
+
runsDir,
|
|
294
|
+
slug,
|
|
295
|
+
identity,
|
|
296
|
+
sink: sinks.records,
|
|
297
|
+
s3,
|
|
298
|
+
uploadRaw,
|
|
299
|
+
fetch: boundedFetch,
|
|
300
|
+
now: clock,
|
|
301
|
+
log,
|
|
302
|
+
});
|
|
303
|
+
// A cancel is an `expiry` when the run's Claim has run out, else a plain `cancel`.
|
|
304
|
+
const classifyCancel = ({ claim }) => {
|
|
305
|
+
for (const issue of tracker.readState().issues ?? [])
|
|
306
|
+
for (const c of claimsOf(issue, { name: LOCAL_ENGINE_NAME, identity }))
|
|
307
|
+
if (c.claim === claim) return Date.parse(c.expires) <= clock() ? "expiry" : "cancel";
|
|
308
|
+
return "cancel";
|
|
309
|
+
};
|
|
310
|
+
const bundleEnv = { GITHUB_REPOSITORY: slug, AGENT_KIT_FACTORY_IDENTITY: identity };
|
|
311
|
+
const engine = createLocalEngine({
|
|
312
|
+
identity,
|
|
313
|
+
pipelines: stagePipelines,
|
|
314
|
+
context: () => ({
|
|
315
|
+
repo: slug,
|
|
316
|
+
identity,
|
|
317
|
+
gh,
|
|
318
|
+
tracker,
|
|
319
|
+
env: stageEnv,
|
|
320
|
+
launch: realLaunch,
|
|
321
|
+
git: (args, opts = {}) =>
|
|
322
|
+
runner("git", args, { cwd, ...(opts.push ? { env: gitPushEnv(secrets.token) } : {}) }),
|
|
323
|
+
tmpDir: stateDir,
|
|
324
|
+
now: clock,
|
|
325
|
+
sleep,
|
|
326
|
+
runDir: (name) => join(runsDir, String(name).replace(/[^A-Za-z0-9._-]/g, "_")),
|
|
327
|
+
readTrusted: (path) => {
|
|
328
|
+
const shown = runner("git", ["show", `HEAD:${path}`], { cwd });
|
|
329
|
+
if (shown.status !== 0) throw new Error(`${path} is not in the checked-out commit`);
|
|
330
|
+
return shown.stdout;
|
|
331
|
+
},
|
|
332
|
+
writeFile: (path, text) => fs.writeFileSync(path, text, { mode: 0o600 }),
|
|
333
|
+
runId: () => clock(),
|
|
334
|
+
log,
|
|
335
|
+
}),
|
|
336
|
+
merge: ({ issue, pull, head, method }) => {
|
|
337
|
+
const args = [
|
|
338
|
+
"--repo",
|
|
339
|
+
slug,
|
|
340
|
+
"--pull",
|
|
341
|
+
String(pull),
|
|
342
|
+
"--head",
|
|
343
|
+
head,
|
|
344
|
+
"--method",
|
|
345
|
+
method,
|
|
346
|
+
"--issue",
|
|
347
|
+
String(issue),
|
|
348
|
+
];
|
|
349
|
+
const lines = [];
|
|
350
|
+
const io = { gh, env: bundleEnv, args, out: log, err: (l) => lines.push(l) };
|
|
351
|
+
if (runMergeRun(io) !== 0) throw new Error(lines.join(" ").slice(0, 300) || "merge refused");
|
|
352
|
+
// The record needs a merge made by an App; a PAT's merge is a user's, and is not recorded.
|
|
353
|
+
runMergeRecord({ ...io, err: log });
|
|
354
|
+
},
|
|
355
|
+
onRunsChanged: (running) => awake.update(running),
|
|
356
|
+
onTeardown: teardown.teardown,
|
|
357
|
+
classifyCancel,
|
|
358
|
+
log,
|
|
359
|
+
});
|
|
360
|
+
ctl.engine = engine;
|
|
361
|
+
const claimEngine = { name: LOCAL_ENGINE_NAME, identity };
|
|
362
|
+
|
|
363
|
+
// Start-up clean-up: sandboxes a dead run left, and its own open Claims.
|
|
364
|
+
removeSandboxes({ runner, log });
|
|
365
|
+
const left = releaseOwnClaims({ tracker, engine: claimEngine, reason: "engine-restart", log });
|
|
366
|
+
for (const r of left)
|
|
367
|
+
log(`restart: released ${r.stage} Claim ${r.claim} on #${r.issue} (engine-restart)`);
|
|
368
|
+
// Its run folders are collected too, and each Stage's record written as `no-result`.
|
|
369
|
+
await teardown.restart({ left });
|
|
370
|
+
|
|
371
|
+
out(
|
|
372
|
+
`factory run: ${slug} as ${identity} on ${host}; polling every ${pollMs / 1000}s${once ? " (once)" : ""}; raw upload ${uploadRaw ? "on" : "off"}`,
|
|
373
|
+
);
|
|
374
|
+
if (sinks.notice) out(`notice: ${sinks.notice}`);
|
|
375
|
+
|
|
376
|
+
let exit = 0;
|
|
377
|
+
const killSwitch = () => {
|
|
378
|
+
if (env.AGENT_KIT_FACTORY_ENABLED !== undefined) return env.AGENT_KIT_FACTORY_ENABLED;
|
|
379
|
+
const variable = gh([
|
|
380
|
+
"api",
|
|
381
|
+
`repos/${slug}/actions/variables/AGENT_KIT_FACTORY_ENABLED`,
|
|
382
|
+
"--jq",
|
|
383
|
+
".value",
|
|
384
|
+
]);
|
|
385
|
+
return variable.status === 0 ? variable.stdout.replace(/\n$/, "") : undefined;
|
|
386
|
+
};
|
|
387
|
+
try {
|
|
388
|
+
let lastRenewed = clock();
|
|
389
|
+
while (ctl.stops === 0) {
|
|
390
|
+
try {
|
|
391
|
+
let renewed;
|
|
392
|
+
try {
|
|
393
|
+
renewed = renewLease({ ...leaseDeps, commentId: lease.commentId });
|
|
394
|
+
lastRenewed = clock();
|
|
395
|
+
} catch (error) {
|
|
396
|
+
// No claiming without a lease: skip this sweep, and stop before the lease can lapse.
|
|
397
|
+
err(`factory run: the Engine lease could not be renewed: ${error.message}`);
|
|
398
|
+
if (clock() - lastRenewed >= leaseMs(pollMs) - pollMs) {
|
|
399
|
+
err("factory run: the Engine lease is about to lapse: stopping");
|
|
400
|
+
exit = 1;
|
|
401
|
+
break;
|
|
402
|
+
}
|
|
403
|
+
if (once) break;
|
|
404
|
+
ctl.nap = new AbortController();
|
|
405
|
+
await sleep(pollMs, ctl.nap.signal);
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (renewed.lost) {
|
|
409
|
+
err(`factory run: the Engine lease is now held by ${renewed.lost.host}: stopping`);
|
|
410
|
+
exit = 1;
|
|
411
|
+
break;
|
|
412
|
+
}
|
|
413
|
+
runFromEnvironment({
|
|
414
|
+
gh,
|
|
415
|
+
env: {
|
|
416
|
+
AGENT_KIT_FACTORY_ENABLED: killSwitch(),
|
|
417
|
+
AGENT_KIT_FACTORY_IDENTITY: identity,
|
|
418
|
+
},
|
|
419
|
+
repo: slug,
|
|
420
|
+
identity,
|
|
421
|
+
clock,
|
|
422
|
+
...(nonce ? { nonce } : {}),
|
|
423
|
+
tracker,
|
|
424
|
+
engine,
|
|
425
|
+
out,
|
|
426
|
+
err,
|
|
427
|
+
});
|
|
428
|
+
} catch (error) {
|
|
429
|
+
err(`factory run: a sweep failed: ${error instanceof Error ? error.message : error}`);
|
|
430
|
+
}
|
|
431
|
+
if (once) {
|
|
432
|
+
// Wait for the Stages it started; a Ctrl-C meanwhile drains them as it does anywhere.
|
|
433
|
+
await Promise.race([engine.idle(), ctl.first]);
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
ctl.nap = new AbortController();
|
|
437
|
+
await sleep(pollMs, ctl.nap.signal);
|
|
438
|
+
}
|
|
439
|
+
if (ctl.stops >= 1) {
|
|
440
|
+
// Drain: Stages finish up to `--drain`; the second signal cancels them at once.
|
|
441
|
+
if (ctl.stops === 1) {
|
|
442
|
+
// The drain can outlast the lease (10 minutes against 5 sweeps): keep renewing it.
|
|
443
|
+
const keepAlive = new AbortController();
|
|
444
|
+
const keeping = (async () => {
|
|
445
|
+
while (!keepAlive.signal.aborted) {
|
|
446
|
+
await sleep(pollMs, keepAlive.signal);
|
|
447
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
448
|
+
if (keepAlive.signal.aborted) break;
|
|
449
|
+
try {
|
|
450
|
+
renewLease({ ...leaseDeps, commentId: lease.commentId });
|
|
451
|
+
} catch (error) {
|
|
452
|
+
err(`factory run: the Engine lease could not be renewed: ${error.message}`);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
})();
|
|
456
|
+
await engine.drain({ timeoutMs: drainMs, wait: (ms, signal) => sleep(ms, signal) });
|
|
457
|
+
keepAlive.abort();
|
|
458
|
+
await keeping;
|
|
459
|
+
} else {
|
|
460
|
+
await engine.idle();
|
|
461
|
+
}
|
|
462
|
+
if (ctl.stops === 1) {
|
|
463
|
+
// Claims of runs the drain cut short: released `stopped`, no Attempt, tasks moved back.
|
|
464
|
+
const cut = releaseOwnClaims({
|
|
465
|
+
tracker,
|
|
466
|
+
engine: claimEngine,
|
|
467
|
+
reason: "stopped",
|
|
468
|
+
only: (c) => !engine.finished.has(c.claim),
|
|
469
|
+
log,
|
|
470
|
+
});
|
|
471
|
+
moveBack({ tracker, released: cut, log });
|
|
472
|
+
for (const r of cut)
|
|
473
|
+
log(`drain: released ${r.stage} Claim ${r.claim} on #${r.issue} (stopped)`);
|
|
474
|
+
}
|
|
475
|
+
exit = ctl.stops >= 2 ? 130 : exit;
|
|
476
|
+
}
|
|
477
|
+
} finally {
|
|
478
|
+
awake.release();
|
|
479
|
+
try {
|
|
480
|
+
releaseLease({ ...leaseDeps, commentId: lease.commentId });
|
|
481
|
+
} catch (error) {
|
|
482
|
+
err(
|
|
483
|
+
`factory run: the Engine lease could not be let go (it expires in ${(5 * pollMs) / 1000}s): ${error.message}`,
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
lock.release();
|
|
487
|
+
}
|
|
488
|
+
out("factory run: stopped");
|
|
489
|
+
return exit;
|
|
490
|
+
}
|
|
@@ -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,47 @@
|
|
|
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 { runStage } from "../../stage.mjs";
|
|
8
|
+
|
|
9
|
+
/** An object with `on` and `off` that fires its SIGINT/SIGTERM listeners when `signal` aborts. */
|
|
10
|
+
export function signalsOf(signal) {
|
|
11
|
+
const listeners = new Map();
|
|
12
|
+
const fire = () => {
|
|
13
|
+
for (const handler of listeners.values()) handler("SIGTERM");
|
|
14
|
+
};
|
|
15
|
+
signal.addEventListener("abort", fire, { once: true });
|
|
16
|
+
return {
|
|
17
|
+
on(name, handler) {
|
|
18
|
+
listeners.set(`${name}`, handler);
|
|
19
|
+
},
|
|
20
|
+
off(name) {
|
|
21
|
+
listeners.delete(`${name}`);
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {{ runner: Function, env: Record<string, string>, cwd: string, platform?: string, log: (line: string) => void }} deps
|
|
28
|
+
* @returns {(opts: object) => Promise<number>} runs one Stage; resolves to the Launcher's exit code
|
|
29
|
+
*/
|
|
30
|
+
export function createLauncher({ runner, env, cwd, platform = process.platform, log }) {
|
|
31
|
+
const launch = ({ signal, ...opts }) =>
|
|
32
|
+
runStage({
|
|
33
|
+
...opts,
|
|
34
|
+
cwd,
|
|
35
|
+
runner,
|
|
36
|
+
env,
|
|
37
|
+
platform,
|
|
38
|
+
signals: signalsOf(signal),
|
|
39
|
+
out: (line) => log(`launcher: ${line}`),
|
|
40
|
+
err: (line) => log(`launcher: ${line}`),
|
|
41
|
+
});
|
|
42
|
+
// The Launcher has no Stage for a factory-mode Chief of Staff yet (a Snapshot mounted
|
|
43
|
+
// read-only, an Outbox written live): the engine does not offer the build Stage until a
|
|
44
|
+
// launcher sets this (docs/factory/orchestrate.md, "What is not here yet").
|
|
45
|
+
launch.factory = false;
|
|
46
|
+
return launch;
|
|
47
|
+
}
|