sakura-infinity 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/AGENT-GUIDE.md +104 -0
  2. package/LICENSE +21 -0
  3. package/README.md +275 -2
  4. package/dist/bin/flags.js +110 -0
  5. package/dist/bin/infinity.js +98 -0
  6. package/dist/bin/load-task.js +39 -0
  7. package/dist/bin/model.js +37 -0
  8. package/dist/bin/scaffold.js +121 -0
  9. package/dist/src/agent-worker.js +157 -0
  10. package/dist/src/backoff.js +12 -0
  11. package/dist/src/budget.js +49 -0
  12. package/dist/src/capacity.js +103 -0
  13. package/dist/src/clock.js +16 -0
  14. package/dist/src/code-leaderboard.js +48 -0
  15. package/dist/src/code-report.js +157 -0
  16. package/dist/src/command-class.js +59 -0
  17. package/dist/src/command-limits.js +46 -0
  18. package/dist/src/commit-plugin.js +36 -0
  19. package/dist/src/component.js +1 -0
  20. package/dist/src/csv.js +8 -0
  21. package/dist/src/defaults.js +35 -0
  22. package/dist/src/error-cluster.js +20 -0
  23. package/dist/src/evaluation.js +84 -0
  24. package/dist/src/form.js +191 -0
  25. package/dist/src/gate.js +111 -0
  26. package/dist/src/gpu-shim.js +165 -0
  27. package/dist/src/handoff.js +12 -0
  28. package/dist/src/hidden-keeper.js +183 -0
  29. package/dist/src/host.js +180 -0
  30. package/dist/src/jsonl.js +30 -0
  31. package/dist/src/ladder.js +118 -0
  32. package/dist/src/launch.js +123 -0
  33. package/dist/src/lean-kit.js +42 -0
  34. package/dist/src/lean-runner.js +84 -0
  35. package/dist/src/lean-setup.js +23 -0
  36. package/dist/src/lean-tool.js +57 -0
  37. package/dist/src/leftover.js +59 -0
  38. package/dist/src/machine-config.js +43 -0
  39. package/dist/src/machine-sampler.js +103 -0
  40. package/dist/src/machine-summary.js +64 -0
  41. package/dist/src/mode-factory.js +25 -0
  42. package/dist/src/mode.js +1 -0
  43. package/dist/src/network.js +12 -0
  44. package/dist/src/orchestrator.js +375 -0
  45. package/dist/src/planner.js +98 -0
  46. package/dist/src/platform.js +21 -0
  47. package/dist/src/pool.js +73 -0
  48. package/dist/src/pressure-brake.js +26 -0
  49. package/dist/src/proc-readings.js +207 -0
  50. package/dist/src/prompts.js +46 -0
  51. package/dist/src/records.js +2 -0
  52. package/dist/src/report.js +81 -0
  53. package/dist/src/review-loop.js +141 -0
  54. package/dist/src/review-rules.js +104 -0
  55. package/dist/src/review-run.js +110 -0
  56. package/dist/src/review-schedule.js +53 -0
  57. package/dist/src/review-snapshot.js +150 -0
  58. package/dist/src/run-layout.js +29 -0
  59. package/dist/src/run-notes.js +61 -0
  60. package/dist/src/run-recorder.js +51 -0
  61. package/dist/src/run-state.js +17 -0
  62. package/dist/src/run-status.js +37 -0
  63. package/dist/src/rung-meter.js +39 -0
  64. package/dist/src/safety-review.js +43 -0
  65. package/dist/src/sakura-tools.js +130 -0
  66. package/dist/src/shell-kit.js +113 -0
  67. package/dist/src/slot-gate.js +136 -0
  68. package/dist/src/slot-leases.js +64 -0
  69. package/dist/src/stuck.js +47 -0
  70. package/dist/src/submit-tool.js +99 -0
  71. package/dist/src/task-mode.js +170 -0
  72. package/dist/src/task.js +85 -0
  73. package/dist/src/verifier.js +115 -0
  74. package/dist/src/work-repo.js +50 -0
  75. package/dist/src/worker-policy.js +16 -0
  76. package/dist/tasks/math-odd-sum/task.js +6 -0
  77. package/dist/tasks/math-parity/task.js +6 -0
  78. package/dist/viewer/index.html +397 -0
  79. package/dist/viewer/run-reader.js +600 -0
  80. package/dist/viewer/server.js +160 -0
  81. package/dist/viewer/view.js +50 -0
  82. package/package.json +53 -4
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The ladder: how many agents are alive. A pure function over events; it holds no timers and starts nothing itself.
3
+ * The caller feeds events in and obeys the answer (spawn these agent numbers, retire those).
4
+ *
5
+ * Rules (docs/02 section 3, confirmed):
6
+ * - Rungs 1, 2, 4, 8, 16, 32, 64, 100, cut at the ceiling.
7
+ * - Advance when the rung is full and every live agent has made at least `repliesToAdvance` replies since the last change, with no throttling answer.
8
+ * - On a throttling answer: record that rung as the provider's limit, drop one rung, and hold (never climb again).
9
+ * A burst of throttles counts once: another drop needs a successful reply after the last change.
10
+ * - A finished or stopped agent is replaced to stay at the rung's number.
11
+ * - While braked (a component says the machine is under pressure, docs/16 section D) the ladder does not climb and no replacement is started; when the brake
12
+ * comes off, the missing agents are started. Unlike a throttle, a brake is not remembered.
13
+ */
14
+ const DEFAULT_RUNGS = [1, 2, 4, 8, 16, 32, 64, 100];
15
+ export const REPLIES_TO_ADVANCE = 3;
16
+ export function rungsFor(ceiling) {
17
+ const below = DEFAULT_RUNGS.filter((rung) => rung < ceiling);
18
+ return [...below, ceiling];
19
+ }
20
+ const target = (state) => (state.finished ? 0 : (state.rungs[state.rungIndex] ?? 0));
21
+ export function startLadder(ceiling) {
22
+ const empty = {
23
+ rungs: rungsFor(ceiling),
24
+ rungIndex: 0,
25
+ held: false,
26
+ finished: false,
27
+ live: {},
28
+ nextAgent: 1,
29
+ dropArmed: true,
30
+ limitRung: undefined,
31
+ };
32
+ return fillToTarget(empty);
33
+ }
34
+ export function stepLadder(state, event) {
35
+ switch (event.type) {
36
+ case "finish":
37
+ return retireAll({ ...state, finished: true });
38
+ case "agent_ended":
39
+ return fillToTarget(withoutAgent(state, event.agent));
40
+ case "throttle":
41
+ return onThrottle(state);
42
+ case "brake":
43
+ return onBrake(state, event.on);
44
+ case "reply":
45
+ return onReply(state, event.agent);
46
+ }
47
+ }
48
+ function onReply(state, agent) {
49
+ if (!(agent in state.live))
50
+ return { state, spawn: [], retire: [] };
51
+ const counted = { ...state, live: { ...state.live, [agent]: (state.live[agent] ?? 0) + 1 }, dropArmed: true };
52
+ return canAdvance(counted) ? advance(counted) : { state: counted, spawn: [], retire: [] };
53
+ }
54
+ function onBrake(state, on) {
55
+ const next = { ...state, braked: on };
56
+ return on || state.finished ? { state: next, spawn: [], retire: [] } : fillToTarget(next);
57
+ }
58
+ function canAdvance(state) {
59
+ if (state.held || state.braked || state.finished)
60
+ return false;
61
+ if (state.rungIndex >= state.rungs.length - 1)
62
+ return false;
63
+ const counts = Object.values(state.live);
64
+ return counts.length === target(state) && counts.every((replies) => replies >= REPLIES_TO_ADVANCE);
65
+ }
66
+ function advance(state) {
67
+ const from = target(state);
68
+ const next = resetCounters({ ...state, rungIndex: state.rungIndex + 1 });
69
+ const step = fillToTarget(next);
70
+ return { ...step, change: { from, to: target(next), reason: "advance" } };
71
+ }
72
+ function onThrottle(state) {
73
+ if (state.finished)
74
+ return { state, spawn: [], retire: [] };
75
+ if (!state.dropArmed)
76
+ return { state, spawn: [], retire: [] };
77
+ const from = target(state);
78
+ const lowered = resetCounters({
79
+ ...state,
80
+ rungIndex: Math.max(0, state.rungIndex - 1),
81
+ held: true,
82
+ limitRung: state.limitRung ?? from,
83
+ dropArmed: false,
84
+ });
85
+ const step = trimToTarget(lowered);
86
+ return { ...step, change: { from, to: target(lowered), reason: "throttle" } };
87
+ }
88
+ function resetCounters(state) {
89
+ const live = Object.fromEntries(Object.keys(state.live).map((agent) => [agent, 0]));
90
+ return { ...state, live };
91
+ }
92
+ function withoutAgent(state, agent) {
93
+ const { [agent]: _gone, ...live } = state.live;
94
+ return { ...state, live };
95
+ }
96
+ function fillToTarget(state) {
97
+ if (state.braked)
98
+ return { state, spawn: [], retire: [] };
99
+ const missing = target(state) - Object.keys(state.live).length;
100
+ if (missing <= 0)
101
+ return { state, spawn: [], retire: [] };
102
+ const spawn = Array.from({ length: missing }, (_, index) => state.nextAgent + index);
103
+ const live = { ...state.live, ...Object.fromEntries(spawn.map((agent) => [agent, 0])) };
104
+ return { state: { ...state, live, nextAgent: state.nextAgent + missing }, spawn, retire: [] };
105
+ }
106
+ function trimToTarget(state) {
107
+ const agents = Object.keys(state.live).map(Number);
108
+ const surplus = agents.length - target(state);
109
+ if (surplus <= 0)
110
+ return { state, spawn: [], retire: [] };
111
+ const retire = agents.sort((a, b) => b - a).slice(0, surplus);
112
+ const live = Object.fromEntries(Object.entries(state.live).filter(([agent]) => !retire.includes(Number(agent))));
113
+ return { state: { ...state, live }, spawn: [], retire };
114
+ }
115
+ function retireAll(state) {
116
+ const retire = Object.keys(state.live).map(Number);
117
+ return { state: { ...state, live: {} }, spawn: [], retire };
118
+ }
@@ -0,0 +1,123 @@
1
+ import { realClock } from "./clock.js";
2
+ import { cpuOf, describeCapacity, recommendCapacity } from "./capacity.js";
3
+ import { limitedEnvironment, limitsOf } from "./command-limits.js";
4
+ import { DEFAULT_COMMAND_TIMEOUT_MINUTES } from "./shell-kit.js";
5
+ import { defaultComponents } from "./defaults.js";
6
+ import { newRunDir, runTask } from "./orchestrator.js";
7
+ import { readMachineFacts } from "./proc-readings.js";
8
+ import { readRunEvents, readRunStatus } from "./run-status.js";
9
+ import { SlotGate } from "./slot-gate.js";
10
+ import { claimSlots } from "./slot-leases.js";
11
+ import { MAX_AGENTS } from "./task.js";
12
+ /** What this machine can carry for this profile, and the number of agents to use: the caller's own number always wins. Reads the machine for half a second. */
13
+ export async function recommendRun(profile, requested) {
14
+ const facts = await readMachineFacts();
15
+ const capacity = recommendCapacity(facts, profile);
16
+ const lines = [describeCapacity(capacity, requested)];
17
+ const busy = facts.busyCores ?? 0;
18
+ if (busy >= 0.5)
19
+ lines.push(`Foreign load: about ${busy.toFixed(1)} cores are busy with other work; they are left out of the slots and only measured.`);
20
+ return { agents: Math.min(MAX_AGENTS, requested ?? capacity.agents), capacity, foreignBusyCores: busy, lines };
21
+ }
22
+ const DEFAULT_REVIEW_MINUTES = 3;
23
+ /** The reasons these options cannot be used together, as words; empty when they can. */
24
+ export function launchProblems(options) {
25
+ const problems = [];
26
+ const positive = (name, value) => {
27
+ if (value !== undefined && !(Number.isFinite(value) && value > 0))
28
+ problems.push(`${name} must be a number above 0`);
29
+ };
30
+ if (options.agents !== undefined && !(Number.isInteger(options.agents) && options.agents >= 1 && options.agents <= MAX_AGENTS))
31
+ problems.push(`agents must be a whole number from 1 to ${MAX_AGENTS}`);
32
+ for (const [name, value] of [
33
+ ["tokens", options.tokens ?? undefined],
34
+ ["wallMinutes", options.wallMinutes],
35
+ ["threads", options.threads],
36
+ ["memGb", options.memGb],
37
+ ["heavyShare", options.heavyShare],
38
+ ["commandMinutes", options.commandMinutes],
39
+ ])
40
+ positive(name, value);
41
+ if (options.heavyShare !== undefined && options.heavyShare > 1)
42
+ problems.push("heavyShare is a share: 1 at most");
43
+ if (typeof options.gate === "number" && !(Number.isInteger(options.gate) && options.gate >= 1))
44
+ problems.push("gate slots must be a whole number of 1 or more");
45
+ return problems;
46
+ }
47
+ export { readRunEvents, readRunStatus };
48
+ /** Starts a run of a task package and returns at once. Refuses conflicting or impossible options before anything starts. */
49
+ export async function startRun(pack, options) {
50
+ const problems = launchProblems(options);
51
+ if (problems.length > 0)
52
+ throw new Error(problems.join("; "));
53
+ const base = pack.profile ?? {};
54
+ const profile = {
55
+ ...base,
56
+ cpu: {
57
+ ...cpuOf(base),
58
+ ...(options.threads === undefined ? {} : { threadsPerJob: options.threads }),
59
+ ...(options.memGb === undefined ? {} : { memPerJobGb: options.memGb }),
60
+ ...(options.heavyShare === undefined ? {} : { heavyShare: options.heavyShare }),
61
+ },
62
+ };
63
+ const recommendation = await recommendRun(profile, options.agents);
64
+ const agents = recommendation.agents;
65
+ const gateSlots = options.gate === false ? undefined : typeof options.gate === "number" ? options.gate : recommendation.capacity.cpuSlots;
66
+ const notes = options.review === false ? ["Branch review: off. No outside reviewer looks at the agents' work."] : [];
67
+ const commandMinutes = options.commandMinutes;
68
+ const task = pack.build({
69
+ agents,
70
+ profile,
71
+ model: options.model,
72
+ tokens: options.tokens === null ? undefined : (options.tokens ?? pack.defaults?.tokens),
73
+ branchReview: options.review === false ? undefined : { everyMinutes: options.review?.everyMinutes ?? DEFAULT_REVIEW_MINUTES, maxTurns: 6, maxConcurrent: 2 },
74
+ commandMinutes,
75
+ runsDir: options.runsDir ?? "runs",
76
+ });
77
+ const runDir = options.resume ?? newRunDir(task, realClock);
78
+ // the slots are shared with the other live runs of this machine
79
+ const claim = gateSlots === undefined ? undefined : claimSlots(gateSlots, runDir, options.slotLeaseDir ? { dir: options.slotLeaseDir } : {});
80
+ if (claim?.note)
81
+ recommendation.lines.push(claim.note);
82
+ const gate = claim === undefined ? undefined : new SlotGate(claim.slots);
83
+ const stopping = new AbortController();
84
+ if (options.signal?.aborted)
85
+ stopping.abort();
86
+ options.signal?.addEventListener("abort", () => stopping.abort(), { once: true });
87
+ const wallMinutes = options.wallMinutes ?? pack.defaults?.wallMinutes ?? 0;
88
+ const timer = wallMinutes > 0 ? setTimeout(() => stopping.abort("wall"), wallMinutes * 60_000) : undefined;
89
+ timer?.unref();
90
+ const done = runTask(task, {
91
+ ...options.testing,
92
+ runDir,
93
+ signal: stopping.signal,
94
+ ...(wallMinutes > 0 ? { wallMinutes } : {}),
95
+ createEnvironment: limitedEnvironment(limitsOf(profile), options.createEnvironment),
96
+ ...(gate ? { gate } : {}),
97
+ ...(options.resume ? { resume: true } : {}),
98
+ components: defaultComponents({
99
+ ceiling: agents,
100
+ ...(options.commandLine ? { commandLine: options.commandLine } : {}),
101
+ foreignBusyCores: recommendation.foreignBusyCores,
102
+ notes,
103
+ pressureBrake: options.pressureBrake === true,
104
+ commandTimeoutMinutes: commandMinutes ?? DEFAULT_COMMAND_TIMEOUT_MINUTES,
105
+ ...(gate ? { gate } : {}),
106
+ }),
107
+ }).finally(() => {
108
+ clearTimeout(timer);
109
+ claim?.release();
110
+ });
111
+ return {
112
+ runDir,
113
+ agents,
114
+ recommendation,
115
+ done,
116
+ stop: () => {
117
+ stopping.abort();
118
+ return done;
119
+ },
120
+ status: () => readRunStatus(runDir),
121
+ events: (from) => readRunEvents(runDir, from),
122
+ };
123
+ }
@@ -0,0 +1,42 @@
1
+ import { cpus } from "node:os";
2
+ import { createLeanRunner } from "./lean-runner.js";
3
+ import { findLean } from "./lean-setup.js";
4
+ import { createLeanTool } from "./lean-tool.js";
5
+ import { Pool, defaultLeanPoolSize } from "./pool.js";
6
+ import { GOAL_OBJECTIVE, MATH_RULES, strategyRule, taskPrompt } from "./prompts.js";
7
+ import { createVerifier, statementSource } from "./verifier.js";
8
+ /** Agents with file tools only (confined to their directory) and the `lean` tool: `check` is free, `submit` is judged by the verifier (docs/02 section 8). The score is 1 for an accepted proof. */
9
+ export function leanKit(options) {
10
+ const { tools } = options;
11
+ let verifier = options.verifier;
12
+ return {
13
+ plannerKind: "math",
14
+ plannerSubject: tools.statement,
15
+ async prepare() {
16
+ if (verifier)
17
+ return;
18
+ const runner = options.leanRunner ??
19
+ createLeanRunner({
20
+ leanBin: (await findLean()).leanBin,
21
+ pool: new Pool(tools.leanPool ?? defaultLeanPoolSize(cpus().length)),
22
+ sandbox: tools.sandbox ?? false,
23
+ });
24
+ verifier = await createVerifier({ runner, leanDir: options.leanDir, statement: tools.statement });
25
+ },
26
+ warnings: () => [],
27
+ agentSetup({ hint }) {
28
+ const ready = verifier;
29
+ if (!ready)
30
+ throw new Error("The Lean kit must be prepared before agents are set up");
31
+ return {
32
+ prompt: taskPrompt(tools.statement, options.prompt),
33
+ rules: [...MATH_RULES, strategyRule(hint)],
34
+ goalObjective: GOAL_OBJECTIVE,
35
+ files: { "Statement.lean": statementSource(tools.statement) },
36
+ builtinTools: ["read", "write"],
37
+ confine: true,
38
+ tools: (submit) => [createLeanTool({ verifier: ready, onSubmit: submit })],
39
+ };
40
+ },
41
+ };
42
+ }
@@ -0,0 +1,84 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname } from "node:path";
5
+ const MAX_OUTPUT = 20_000;
6
+ const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
7
+ /**
8
+ * Lean files can run any code at compile time (`#eval`, macros), so a proof file is untrusted code.
9
+ * The environment is always cleaned: no keys reach the process. Without the sandbox (the default) the process runs with the user's rights.
10
+ * With `sandbox: true`, on macOS, the run is confined with the same mechanism Codex CLI uses (`sandbox-exec`): writes only to the given directories,
11
+ * no network, no reading of the user's home directory except the Lean toolchain and the given directories.
12
+ */
13
+ export function createLeanRunner(options) {
14
+ const sandboxed = (options.sandbox ?? false) && process.platform === "darwin" && existsSync(SANDBOX_EXEC);
15
+ const toolchainRoot = real(dirname(dirname(options.leanBin)));
16
+ return {
17
+ sandboxed,
18
+ run: (request) => options.pool.run(() => runProcess(options.leanBin, toolchainRoot, sandboxed, request), request.signal),
19
+ };
20
+ }
21
+ function runProcess(leanBin, toolchainRoot, sandboxed, request) {
22
+ const command = sandboxed ? SANDBOX_EXEC : leanBin;
23
+ const args = sandboxed ? ["-p", sandboxProfile(toolchainRoot, request), leanBin, ...request.args] : request.args;
24
+ const env = { PATH: "/usr/bin:/bin", HOME: request.cwd, LEAN_PATH: request.leanPath.join(":") };
25
+ return new Promise((resolve, reject) => {
26
+ if (request.signal?.aborted)
27
+ return reject(request.signal.reason);
28
+ const child = spawn(command, args, { cwd: request.cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true });
29
+ const killGroup = () => killProcessGroup(child.pid);
30
+ let output = "";
31
+ let timedOut = false;
32
+ const collect = (chunk) => {
33
+ output = (output + chunk.toString("utf8")).slice(-MAX_OUTPUT);
34
+ };
35
+ child.stdout.on("data", collect);
36
+ child.stderr.on("data", collect);
37
+ const timer = setTimeout(() => {
38
+ timedOut = true;
39
+ killGroup();
40
+ }, request.timeoutMs);
41
+ const onAbort = killGroup;
42
+ request.signal?.addEventListener("abort", onAbort, { once: true });
43
+ const finish = () => {
44
+ clearTimeout(timer);
45
+ request.signal?.removeEventListener("abort", onAbort);
46
+ };
47
+ child.on("error", (error) => {
48
+ finish();
49
+ reject(error);
50
+ });
51
+ child.on("close", (exitCode) => {
52
+ finish();
53
+ if (request.signal?.aborted)
54
+ return reject(request.signal.reason);
55
+ resolve({ exitCode, output, timedOut });
56
+ });
57
+ });
58
+ }
59
+ /** Kills the process and everything it started (a shell script, the sandbox wrapper), so that no one keeps the output open. */
60
+ function killProcessGroup(pid) {
61
+ if (pid === undefined)
62
+ return;
63
+ try {
64
+ process.kill(-pid, "SIGKILL");
65
+ }
66
+ catch {
67
+ // already gone
68
+ }
69
+ }
70
+ const real = (path) => realpathSync(path);
71
+ function sandboxProfile(toolchainRoot, request) {
72
+ const writable = request.writableDirs.map(real);
73
+ const readable = [toolchainRoot, real(request.cwd), ...request.leanPath.map(real), ...writable];
74
+ const quoted = (path) => `(subpath ${JSON.stringify(path)})`;
75
+ return [
76
+ "(version 1)",
77
+ "(allow default)",
78
+ "(deny file-write*)",
79
+ `(allow file-write* ${writable.map(quoted).join(" ")} (literal "/dev/null"))`,
80
+ `(deny file-read-data ${quoted(real(homedir()))})`,
81
+ `(allow file-read-data ${readable.map(quoted).join(" ")})`,
82
+ "(deny network*)",
83
+ ].join("\n");
84
+ }
@@ -0,0 +1,23 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const execFileAsync = promisify(execFile);
4
+ export const LEAN_INSTALL_COMMAND = "curl https://elan.lean-lang.org/elan-init.sh -sSf | sh";
5
+ async function output(command, args) {
6
+ const { stdout } = await execFileAsync(command, args, { timeout: 120_000 });
7
+ return stdout.trim();
8
+ }
9
+ /**
10
+ * Start-up check of math mode: `lean --version` and `lake --version` must work. Stops with the install command when they do not.
11
+ * Mathlib is not checked here; only a task that asks for it needs it.
12
+ */
13
+ export async function findLean() {
14
+ try {
15
+ const leanVersion = await output("lean", ["--version"]);
16
+ const lakeVersion = await output("lake", ["--version"]);
17
+ const leanBin = await output("elan", ["which", "lean"]);
18
+ return { leanBin, leanVersion, lakeVersion };
19
+ }
20
+ catch (error) {
21
+ throw new Error(`Math mode needs a local Lean 4 (lean and lake on the PATH, installed with elan). Install it with:\n ${LEAN_INSTALL_COMMAND}\n(${String(error)})`);
22
+ }
23
+ }
@@ -0,0 +1,57 @@
1
+ const DEFAULT_FILE = "Proof.lean";
2
+ const text = (message, isError = false) => ({ content: [{ type: "text", text: message }], ...(isError ? { isError } : {}) });
3
+ /**
4
+ * The agent's one way to run Lean. `check` compiles a file and shows Lean's messages (free to use, as often as wanted).
5
+ * `submit` is the official call: the verifier decides whether the file proves `Statement.Goal`.
6
+ */
7
+ export function createLeanTool(options) {
8
+ return {
9
+ name: "lean",
10
+ description: "Runs Lean 4 on a proof file in your working directory. action 'check': compile the file and show Lean's messages (use it freely while you work). " +
11
+ "action 'submit': the official submission; answers 'proved' only when the file compiles, has no sorry, uses only the standard axioms and " +
12
+ "'theorem main : Statement.Goal' has exactly that type. The file starts with 'import Statement'.",
13
+ parameters: {
14
+ type: "object",
15
+ properties: {
16
+ action: { type: "string", enum: ["check", "submit"] },
17
+ file: { type: "string", description: `Path of the proof file, default ${DEFAULT_FILE}` },
18
+ },
19
+ required: ["action"],
20
+ additionalProperties: false,
21
+ },
22
+ effect: "exec",
23
+ executionMode: "serial",
24
+ async execute(args, context) {
25
+ const { action, file } = parseArgs(args);
26
+ if (action === undefined)
27
+ return text("The 'action' must be 'check' or 'submit'.", true);
28
+ const source = await readSource(file, context);
29
+ if (source === undefined)
30
+ return text(`Cannot read '${file}'. Write the proof file first.`, true);
31
+ if (action === "check")
32
+ return text(await options.verifier.check(source, context.signal));
33
+ const verdict = await options.verifier.verify(source, context.signal);
34
+ await options.onSubmit({
35
+ command: `lean submit ${file}`,
36
+ files: [file],
37
+ entry: source,
38
+ result: { status: "ok", score: verdict.proved ? 1 : 0, metrics: {}, details: verdict.reason },
39
+ selfReported: false,
40
+ });
41
+ return text(verdict.proved ? "proved: the proof is accepted." : `Not accepted: ${verdict.reason}`);
42
+ },
43
+ };
44
+ }
45
+ function parseArgs(args) {
46
+ const value = (args ?? {});
47
+ const action = value.action === "check" || value.action === "submit" ? value.action : undefined;
48
+ return { action, file: typeof value.file === "string" && value.file !== "" ? value.file : DEFAULT_FILE };
49
+ }
50
+ async function readSource(file, context) {
51
+ try {
52
+ return new TextDecoder().decode(await context.env.readFile(file));
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
@@ -0,0 +1,59 @@
1
+ import { LinuxHost } from "./host.js";
2
+ import { JsonlFile } from "./jsonl.js";
3
+ /** Process ids whose working directory is the run directory or below it, found through /proc/<pid>/cwd (never by name). */
4
+ export function processesUnder(root, host = new LinuxHost()) {
5
+ if (!host.hasProc())
6
+ return [];
7
+ const base = host.realPath(root);
8
+ return host
9
+ .processes({ cwd: true })
10
+ .filter((process) => process.cwd !== undefined && (process.cwd === base || process.cwd.startsWith(`${base}/`)))
11
+ .map((process) => process.pid);
12
+ }
13
+ /**
14
+ * At the end of the run, stops every process that still has the run directory as its working directory: agents' background jobs and anything they left behind.
15
+ * By process id, SIGTERM first and SIGKILL after a few seconds; never by name, never its own process. The count goes to the events and the report.
16
+ * Where there is no /proc (macOS) it finds nothing.
17
+ */
18
+ export function leftoverStopper(options = {}) {
19
+ const host = options.host ?? new LinuxHost();
20
+ const kill = options.kill ?? ((pid, signal) => host.signal(pid, signal));
21
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
22
+ const graceMs = options.graceMs ?? 5000;
23
+ let context;
24
+ let done = false;
25
+ const send = (pid, signal) => {
26
+ try {
27
+ kill(pid, signal);
28
+ }
29
+ catch {
30
+ // gone already, or not ours
31
+ }
32
+ };
33
+ return {
34
+ name: "leftover-stopper",
35
+ start(started) {
36
+ context = started;
37
+ },
38
+ async stop() {
39
+ if (done || !context)
40
+ return;
41
+ done = true;
42
+ const found = processesUnder(context.layout.root, host).filter((pid) => pid !== process.pid);
43
+ if (!host.hasProc())
44
+ return;
45
+ for (const pid of found)
46
+ send(pid, "SIGTERM");
47
+ let remaining = found;
48
+ const step = Math.max(1, Math.min(200, graceMs));
49
+ for (let waited = 0; remaining.length > 0 && waited < graceMs; waited += step) {
50
+ await sleep(step);
51
+ remaining = remaining.filter((pid) => host.isAlive(pid));
52
+ }
53
+ for (const pid of remaining)
54
+ send(pid, "SIGKILL");
55
+ const event = { type: "leftover_processes", ts: context.clock.now(), found: found.length, killedHard: remaining.length };
56
+ new JsonlFile(context.layout.events).append(event);
57
+ },
58
+ };
59
+ }
@@ -0,0 +1,43 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ const KEYS = ["agents", "slots", "threads", "memGb", "heavyShare", "commandMinutes"];
3
+ /** The file's content, checked: unknown fields and numbers that are not above 0 are refused with words. */
4
+ export function parseMachineConfig(text) {
5
+ let raw;
6
+ try {
7
+ raw = JSON.parse(text);
8
+ }
9
+ catch {
10
+ throw new Error("the machine file is not valid JSON");
11
+ }
12
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
13
+ throw new Error("the machine file must be a JSON object");
14
+ const problems = [];
15
+ for (const [key, value] of Object.entries(raw)) {
16
+ if (key === "note")
17
+ continue;
18
+ if (!KEYS.includes(key))
19
+ problems.push(`unknown field '${key}' (fields: ${KEYS.join(", ")})`);
20
+ else if (!(typeof value === "number" && value > 0))
21
+ problems.push(`${key} must be a number above 0`);
22
+ }
23
+ if (problems.length > 0)
24
+ throw new Error(`the machine file: ${problems.join("; ")}`);
25
+ return raw;
26
+ }
27
+ export const readMachineConfig = (path) => parseMachineConfig(readFileSync(path, "utf8"));
28
+ /** The launch options the file stands for (`gate: number` is the slot count). */
29
+ export function machineOptions(config) {
30
+ return {
31
+ ...(config.agents === undefined ? {} : { agents: config.agents }),
32
+ ...(config.slots === undefined ? {} : { gate: config.slots }),
33
+ ...(config.threads === undefined ? {} : { threads: config.threads }),
34
+ ...(config.memGb === undefined ? {} : { memGb: config.memGb }),
35
+ ...(config.heavyShare === undefined ? {} : { heavyShare: config.heavyShare }),
36
+ ...(config.commandMinutes === undefined ? {} : { commandMinutes: config.commandMinutes }),
37
+ };
38
+ }
39
+ /** The file for this machine from a recommendation: what the capacity logic concluded, with the per-command limits it was computed from. */
40
+ export function machineConfigFrom(capacity, profile) {
41
+ return { agents: capacity.agents, slots: capacity.cpuSlots, threads: profile.threadsPerJob, memGb: profile.memPerJobGb, heavyShare: profile.heavyShare };
42
+ }
43
+ export const writeMachineConfig = (path, config, note) => writeFileSync(path, `${JSON.stringify({ note, ...config }, null, 2)}\n`);
@@ -0,0 +1,103 @@
1
+ import { appendFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { LinuxHost } from "./host.js";
4
+ import { JsonlFile } from "./jsonl.js";
5
+ import { optional } from "./machine-summary.js";
6
+ import { unsupportedFeatures } from "./platform.js";
7
+ import { PressureBrake } from "./pressure-brake.js";
8
+ import { MachineReader, parseGpuFacts, parseMeminfo } from "./proc-readings.js";
9
+ /** The machine sampler as a run component (docs/18): schedules the readings, writes `machine.jsonl` and `run-facts.json`, and asks the ladder to hold when the brake says so. */
10
+ const SAMPLE_EVERY_MS = 5000;
11
+ export const NO_GATE = { enabled: false, cpuSlots: null, gpuSlots: null, commandTimeoutMinutes: null };
12
+ export async function readRunFacts(now, extra = {}) {
13
+ const host = extra.host ?? new LinuxHost();
14
+ const [gpuText, commit, unsupported] = await Promise.all([
15
+ host.gpuQuery("--query-gpu=name,memory.total"),
16
+ host.gitCommit(),
17
+ unsupportedFeatures({ gpu: extra.needsGpu === true }),
18
+ ]);
19
+ const gpu = gpuText ? parseGpuFacts(gpuText) : undefined;
20
+ const info = host.readProc("meminfo");
21
+ return {
22
+ ts: now,
23
+ cores: host.cpuCount(),
24
+ memTotalMb: info ? parseMeminfo(info).totalMb : Math.round(host.totalMemoryBytes() / 1048576),
25
+ gpuName: gpu?.name ?? null,
26
+ gpuMemTotalMb: gpu?.memMb ?? null,
27
+ kernel: host.readProc("sys/kernel/osrelease")?.trim() ?? host.release(),
28
+ node: process.version,
29
+ commit: commit?.trim() || null,
30
+ ceiling: extra.ceiling ?? null,
31
+ commandLine: extra.commandLine ?? process.argv.slice(2),
32
+ gate: extra.gate ?? NO_GATE,
33
+ foreignBusyCores: extra.foreignBusyCores ?? null,
34
+ unsupported,
35
+ };
36
+ }
37
+ /** Writes `machine.jsonl` in the run directory every few seconds from the start of the agents to the end of the run. */
38
+ export function machineSampler(options = {}) {
39
+ const stopping = new AbortController();
40
+ let loop;
41
+ return {
42
+ name: "machine-sampler",
43
+ start(context) {
44
+ for (const line of options.notes ?? [])
45
+ context.note(line);
46
+ const reader = options.reader ?? new MachineReader({ runRoot: context.layout.root, ...optional("slots", options.slots), ...optional("host", options.host) });
47
+ const every = options.everyMs ?? SAMPLE_EVERY_MS;
48
+ const factsOf = options.facts ??
49
+ (() => readRunFacts(context.clock.now(), {
50
+ ...optional("ceiling", options.ceiling),
51
+ ...optional("commandLine", options.commandLine),
52
+ ...optional("gate", options.gate),
53
+ ...optional("foreignBusyCores", options.foreignBusyCores),
54
+ ...optional("needsGpu", options.needsGpu),
55
+ ...optional("host", options.host),
56
+ }));
57
+ factsOf()
58
+ .then((facts) => {
59
+ writeFileSync(join(context.layout.root, "run-facts.json"), `${JSON.stringify(facts, null, 2)}\n`);
60
+ for (const line of facts.unsupported ?? [])
61
+ context.note(line);
62
+ })
63
+ .catch((error) => context.note(`run facts: ${error instanceof Error ? error.message : String(error)}`));
64
+ const brake = options.brake ? new PressureBrake(options.brake) : undefined;
65
+ const sample = async () => {
66
+ try {
67
+ const line = await reader.read(context.clock.now(), { rung: context.view.rung(), agents: context.view.agents() });
68
+ appendFileSync(context.layout.machine, `${JSON.stringify(line)}\n`);
69
+ const changed = brake?.update(line);
70
+ if (changed !== undefined) {
71
+ context.hold(changed);
72
+ new JsonlFile(context.layout.events).append({
73
+ type: "pressure_hold",
74
+ ts: line.ts,
75
+ on: changed,
76
+ rung: line.rung,
77
+ loadPerCore: line.load1 / Math.max(1, line.cores),
78
+ cpuPressure10: line.cpuPressure10,
79
+ });
80
+ }
81
+ }
82
+ catch (error) {
83
+ context.note(`machine sampler: ${error instanceof Error ? error.message : String(error)}`);
84
+ stopping.abort();
85
+ }
86
+ };
87
+ loop = (async () => {
88
+ await sample();
89
+ while (!stopping.signal.aborted) {
90
+ await sleepOf(context.clock, every, stopping.signal);
91
+ if (stopping.signal.aborted)
92
+ return;
93
+ await sample();
94
+ }
95
+ })();
96
+ },
97
+ async stop() {
98
+ stopping.abort();
99
+ await loop;
100
+ },
101
+ };
102
+ }
103
+ const sleepOf = (clock, ms, signal) => clock.sleep(ms, signal).catch(() => undefined);