sakura-infinity 0.0.0-stage → 0.1.0

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 (81) 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 +156 -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/hidden-keeper.js +183 -0
  28. package/dist/src/host.js +180 -0
  29. package/dist/src/jsonl.js +30 -0
  30. package/dist/src/ladder.js +118 -0
  31. package/dist/src/launch.js +123 -0
  32. package/dist/src/lean-kit.js +42 -0
  33. package/dist/src/lean-runner.js +84 -0
  34. package/dist/src/lean-setup.js +23 -0
  35. package/dist/src/lean-tool.js +57 -0
  36. package/dist/src/leftover.js +59 -0
  37. package/dist/src/machine-config.js +43 -0
  38. package/dist/src/machine-sampler.js +103 -0
  39. package/dist/src/machine-summary.js +64 -0
  40. package/dist/src/mode-factory.js +25 -0
  41. package/dist/src/mode.js +1 -0
  42. package/dist/src/network.js +12 -0
  43. package/dist/src/orchestrator.js +375 -0
  44. package/dist/src/planner.js +98 -0
  45. package/dist/src/platform.js +21 -0
  46. package/dist/src/pool.js +73 -0
  47. package/dist/src/pressure-brake.js +26 -0
  48. package/dist/src/proc-readings.js +207 -0
  49. package/dist/src/prompts.js +46 -0
  50. package/dist/src/records.js +2 -0
  51. package/dist/src/report.js +81 -0
  52. package/dist/src/review-loop.js +141 -0
  53. package/dist/src/review-rules.js +104 -0
  54. package/dist/src/review-run.js +110 -0
  55. package/dist/src/review-schedule.js +53 -0
  56. package/dist/src/review-snapshot.js +150 -0
  57. package/dist/src/run-layout.js +29 -0
  58. package/dist/src/run-notes.js +61 -0
  59. package/dist/src/run-recorder.js +51 -0
  60. package/dist/src/run-state.js +17 -0
  61. package/dist/src/run-status.js +37 -0
  62. package/dist/src/rung-meter.js +39 -0
  63. package/dist/src/safety-review.js +43 -0
  64. package/dist/src/sakura-tools.js +130 -0
  65. package/dist/src/shell-kit.js +113 -0
  66. package/dist/src/slot-gate.js +136 -0
  67. package/dist/src/slot-leases.js +64 -0
  68. package/dist/src/stuck.js +47 -0
  69. package/dist/src/submit-tool.js +99 -0
  70. package/dist/src/task-mode.js +170 -0
  71. package/dist/src/task.js +85 -0
  72. package/dist/src/verifier.js +115 -0
  73. package/dist/src/work-repo.js +50 -0
  74. package/dist/src/worker-policy.js +16 -0
  75. package/dist/tasks/math-odd-sum/task.js +6 -0
  76. package/dist/tasks/math-parity/task.js +6 -0
  77. package/dist/viewer/index.html +397 -0
  78. package/dist/viewer/run-reader.js +600 -0
  79. package/dist/viewer/server.js +160 -0
  80. package/dist/viewer/view.js +50 -0
  81. package/package.json +52 -4
@@ -0,0 +1,64 @@
1
+ import { JsonlFile } from "./jsonl.js";
2
+ // ----- reading a run's record: the rows of the report and the history the recommendation reads -----
3
+ export const readMachineSamples = (path) => new JsonlFile(path).readAll();
4
+ const present = (group, key) => group.flatMap((sample) => {
5
+ const value = sample[key];
6
+ return typeof value === "number" ? [value] : [];
7
+ });
8
+ const meanOrNull = (values) => (values.length > 0 ? mean(values) : null);
9
+ const maxOrNull = (values) => (values.length > 0 ? Math.max(...values) : null);
10
+ export const optional = (key, value) => value === undefined ? {} : { [key]: value };
11
+ const mean = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
12
+ /** Mean and peak of load, CPU and memory for each rung (the ladder's step at the time of the reading), lowest rung first. */
13
+ export function summarizeByRung(samples) {
14
+ const byRung = new Map();
15
+ for (const sample of samples)
16
+ byRung.set(sample.rung, [...(byRung.get(sample.rung) ?? []), sample]);
17
+ return [...byRung]
18
+ .sort((a, b) => a[0] - b[0])
19
+ .map(([rung, group]) => {
20
+ const cpu = group.flatMap((sample) => (sample.cpuBusy === null ? [] : [sample.cpuBusy]));
21
+ const gpu = group.flatMap((sample) => (sample.gpuMemUsedMb === null ? [] : [sample.gpuMemUsedMb]));
22
+ return {
23
+ rung,
24
+ samples: group.length,
25
+ loadMean: mean(group.map((sample) => sample.load1)),
26
+ loadPeak: Math.max(...group.map((sample) => sample.load1)),
27
+ cpuMean: cpu.length > 0 ? mean(cpu) : null,
28
+ cpuPeak: cpu.length > 0 ? Math.max(...cpu) : null,
29
+ memPeakMb: Math.max(...group.map((sample) => sample.memUsedMb)),
30
+ gpuMemPeakMb: gpu.length > 0 ? Math.max(...gpu) : null,
31
+ pressureMean: meanOrNull(present(group, "cpuPressure10")),
32
+ runCoresMean: meanOrNull(present(group, "runCpuCores")),
33
+ runRssPeakMb: maxOrNull(present(group, "runRssMb")),
34
+ jobsMean: meanOrNull(present(group, "runPythonProcesses")),
35
+ jobsPeak: maxOrNull(present(group, "runPythonProcesses")),
36
+ slotsUseMean: meanOrNull(present(group, "slotsInUse")),
37
+ slotsWaitMean: meanOrNull(present(group, "slotsWaiting")),
38
+ gpuSlotsUseMean: meanOrNull(present(group, "gpuSlotsInUse")),
39
+ gpuSlotsWaitMean: meanOrNull(present(group, "gpuSlotsWaiting")),
40
+ };
41
+ });
42
+ }
43
+ /** What one run's readings say about an agent: the CPU cores and the memory it used, and the share of readings in which the run had a python job going. */
44
+ export function historyFromSamples(samples) {
45
+ const cores = samples.flatMap((sample) => sample.runCpuCores !== null && sample.runCpuCores !== undefined && sample.agents > 0 ? [sample.runCpuCores / sample.agents] : []);
46
+ const memory = peakMemoryPerAgentMb(samples);
47
+ const jobs = samples.filter((sample) => sample.agents > 0 && sample.runPythonProcesses !== null && sample.runPythonProcesses !== undefined);
48
+ const heavy = jobs.reduce((sum, sample) => sum + Math.min(1, (sample.runPythonProcesses ?? 0) / sample.agents), 0);
49
+ return cores.length === 0 && memory === undefined
50
+ ? undefined
51
+ : {
52
+ ...optional("cpuPerAgent", cores.length > 0 ? mean(cores) : undefined),
53
+ ...optional("memPerAgentGb", memory === undefined ? undefined : memory / 1024),
54
+ ...optional("heavyShare", jobs.length > 0 && heavy > 0 ? heavy / jobs.length : undefined),
55
+ };
56
+ }
57
+ /** Peak memory per agent from the readings: how much memory use grew from the first reading to the largest, per agent alive at the largest. */
58
+ export function peakMemoryPerAgentMb(samples) {
59
+ const first = samples[0];
60
+ if (!first)
61
+ return undefined;
62
+ const top = samples.reduce((best, sample) => (sample.memUsedMb > best.memUsedMb ? sample : best), first);
63
+ return top.agents > 0 && top.memUsedMb > first.memUsedMb ? (top.memUsedMb - first.memUsedMb) / top.agents : undefined;
64
+ }
@@ -0,0 +1,25 @@
1
+ import { HiddenKeeper } from "./hidden-keeper.js";
2
+ import { leanKit } from "./lean-kit.js";
3
+ import { Pool } from "./pool.js";
4
+ import { shellKit } from "./shell-kit.js";
5
+ import { TaskMode } from "./task-mode.js";
6
+ import { PROOF_METRIC, targetOf } from "./task.js";
7
+ const DEFAULT_EVAL_SLOTS = 2;
8
+ /** The one place that knows which tools a task can have: it picks the kit and builds the mode around it. */
9
+ export function createMode(context, test = {}) {
10
+ const { task, layout } = context;
11
+ const tools = task.tools ?? { kind: "shell" };
12
+ const keeper = task.hidden && task.hidden.length > 0 ? new HiddenKeeper({ dir: layout.keeperDir, now: () => context.clock.now() }) : undefined;
13
+ const kit = tools.kind === "lean"
14
+ ? leanKit({ tools, prompt: task.prompt, leanDir: layout.leanDir, ...test })
15
+ : shellKit({ task, layout, clock: context.clock, reviewClient: context.clientFor(task.review ? task.review.model : undefined), gate: context.gate });
16
+ return new TaskMode({ task, layout, clock: context.clock, kit, evalPool: new Pool(task.evalSlots ?? DEFAULT_EVAL_SLOTS), keeper, signal: context.signal });
17
+ }
18
+ /** Which number ranks in the report: the task's metric, the proof metric of a proof task, or the agents' claims. */
19
+ export function metricOf(task) {
20
+ return task.metric ?? (task.tools?.kind === "lean" ? PROOF_METRIC : { name: "claimed score", direction: "max" });
21
+ }
22
+ /** True when a resumed run has nothing left to do: it ended on its target. */
23
+ export function isFinishedBefore(task, prior) {
24
+ return prior.finished === "target" && targetOf(task) !== undefined;
25
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import { setDefaultAutoSelectFamilyAttemptTimeout } from "node:net";
2
+ /**
3
+ * Node connects to a host that has both IPv6 and IPv4 addresses with "happy eyeballs": it starts the next address after 250 ms. When one TCP
4
+ * connect takes longer than that (330 ms from the server to the provider), every attempt is abandoned in turn and `fetch` fails with
5
+ * "fetch failed" / ETIMEDOUT within about 500 ms, although the provider is fine and curl works. With 100 agents this looked like a provider limit.
6
+ * Five seconds leaves the fallback between addresses in place but stops it from cutting off a slow but healthy connect.
7
+ * Called by `runTask`, so every entry point gets it; the same can be set from outside with `node --network-family-autoselection-attempt-timeout=5000`.
8
+ */
9
+ export const CONNECT_ATTEMPT_TIMEOUT_MS = 5000;
10
+ export function allowSlowConnects() {
11
+ setDefaultAutoSelectFamilyAttemptTimeout(CONNECT_ATTEMPT_TIMEOUT_MS);
12
+ }
@@ -0,0 +1,375 @@
1
+ import { mkdirSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { createChatClient } from "sakura-agent";
4
+ import { startWorker } from "./agent-worker.js";
5
+ import { Budget, totalTokens } from "./budget.js";
6
+ import { replacementWait } from "./backoff.js";
7
+ import { realClock } from "./clock.js";
8
+ import { defaultComponents } from "./defaults.js";
9
+ import { allowSlowConnects } from "./network.js";
10
+ import { Gate } from "./gate.js";
11
+ import { startLadder, stepLadder } from "./ladder.js";
12
+ import { createMode, isFinishedBefore, metricOf } from "./mode-factory.js";
13
+ import { hintFor, planHints } from "./planner.js";
14
+ import { startBranchReview } from "./review-loop.js";
15
+ import { RungMeter } from "./rung-meter.js";
16
+ import { loadState, saveState } from "./run-state.js";
17
+ import { runLayout } from "./run-layout.js";
18
+ import { RunRecorder } from "./run-recorder.js";
19
+ import { RESCUE_MESSAGE, StuckDetector } from "./stuck.js";
20
+ /** Always plan a full list: a replacement agent needs a new hint even when the ladder is short. */
21
+ const MAX_HINTS_PLANNED = 16;
22
+ const DEFAULT_STUCK_MINUTES = 10;
23
+ const DEFAULT_PAUSE_MS = 5000;
24
+ /** Runs a task to the end (or to the user's stop) and returns why it ended. */
25
+ export async function runTask(task, options = {}) {
26
+ allowSlowConnects();
27
+ const clock = options.clock ?? realClock;
28
+ const layout = runLayout(options.runDir ?? newRunDir(task, clock));
29
+ mkdirSync(layout.root, { recursive: true });
30
+ const prior = options.resume ? loadState(layout.state) : undefined;
31
+ if (options.resume && !prior)
32
+ throw new Error(`Nothing to resume in ${layout.root}`);
33
+ if (prior && isFinishedBefore(task, prior))
34
+ return outcomeOf(layout, prior.finished, prior.tokensUsed, prior.bestScore);
35
+ const run = new Run(task, options, layout, clock, prior);
36
+ return run.execute();
37
+ }
38
+ export function newRunDir(task, clock) {
39
+ const slug = task.name
40
+ .toLowerCase()
41
+ .replace(/[^a-z0-9]+/g, "-")
42
+ .replace(/^-|-$/g, "") || "task";
43
+ return join(task.runsDir ?? "runs", `${slug}-${new Date(clock.now()).toISOString().replace(/[:.]/g, "-")}`);
44
+ }
45
+ const outcomeOf = (layout, reason, tokensUsed, bestScore) => ({
46
+ reason,
47
+ runDir: layout.root,
48
+ tokensUsed,
49
+ ...(bestScore !== undefined ? { bestScore } : {}),
50
+ });
51
+ /** The state of one run and the rules that connect the parts. The parts themselves (ladder, gate, budget, ...) are in their own modules. */
52
+ class Run {
53
+ task;
54
+ options;
55
+ layout;
56
+ clock;
57
+ prior;
58
+ recorder;
59
+ budget;
60
+ gate;
61
+ stuck;
62
+ meter;
63
+ workers = new Map();
64
+ stopWatching = new AbortController();
65
+ allEnded = [];
66
+ branch;
67
+ components;
68
+ ladder;
69
+ /** The ladder as it was when the run was told to stop, so that a resume starts the same agents again. */
70
+ ladderAtStop;
71
+ hints = [];
72
+ mode;
73
+ client;
74
+ failures;
75
+ consecutiveFailures = 0;
76
+ finishing;
77
+ startedAt;
78
+ budgetRefusalLogged = false;
79
+ closed = false;
80
+ resolveOutcome;
81
+ outcome = new Promise((resolve) => {
82
+ this.resolveOutcome = resolve;
83
+ });
84
+ constructor(task, options, layout, clock, prior) {
85
+ this.task = task;
86
+ this.options = options;
87
+ this.layout = layout;
88
+ this.clock = clock;
89
+ this.prior = prior;
90
+ this.components = options.components ?? defaultComponents();
91
+ this.startedAt = prior?.startedAt ?? clock.now();
92
+ this.failures = prior?.failures ?? 0;
93
+ this.recorder = new RunRecorder(layout, clock, metricOf(task));
94
+ this.gate = new Gate({
95
+ now: () => clock.now(),
96
+ sleep: (ms, signal) => clock.sleep(ms, signal),
97
+ defaultPauseMs: DEFAULT_PAUSE_MS,
98
+ refusal: () => this.budget.refusal(),
99
+ onEvent: (event) => this.onGateEvent(event),
100
+ });
101
+ this.budget = new Budget(task.tokens, () => this.gate.inflight);
102
+ if (prior)
103
+ this.budget.restore(prior.tokensUsed, prior.requests);
104
+ this.stuck = new StuckDetector({
105
+ clock,
106
+ stuckAfterMs: (task.stuckMinutes ?? DEFAULT_STUCK_MINUTES) * 60_000,
107
+ isExcused: (agent) => this.workers.get(agent)?.excused() ?? true,
108
+ });
109
+ this.meter = new RungMeter(clock.now());
110
+ }
111
+ async execute() {
112
+ this.recorder.event({
113
+ type: "run_start",
114
+ task: this.task.name,
115
+ ceiling: this.task.agents,
116
+ resumed: this.prior !== undefined,
117
+ metricDirection: metricOf(this.task).direction,
118
+ ...(this.task.tokens === undefined ? {} : { tokenBudget: this.task.tokens }),
119
+ ...(this.options.wallMinutes ? { wallMinutes: this.options.wallMinutes } : {}),
120
+ });
121
+ try {
122
+ for (const agent of Object.keys(this.prior?.ladder.live ?? {})) {
123
+ rmSync(this.layout.finishedMarker(Number(agent)), { force: true });
124
+ }
125
+ await this.prepare();
126
+ }
127
+ catch (error) {
128
+ this.mode?.finish?.([]);
129
+ this.recorder.event({ type: "run_end", reason: `failed to start: ${String(error)}`, tokensUsed: this.budget.tokensUsed });
130
+ this.recorder.report();
131
+ throw error;
132
+ }
133
+ const stop = () => void this.finish(this.options.signal?.reason === "wall" ? "wall" : "stopped");
134
+ this.options.signal?.addEventListener("abort", stop, { once: true });
135
+ const { state, spawn } = this.prior
136
+ ? { state: { ...this.prior.ladder, finished: false }, spawn: Object.keys(this.prior.ladder.live).map(Number) }
137
+ : startLadder(this.task.agents);
138
+ this.ladder = state;
139
+ for (const agent of spawn)
140
+ this.startAgent(agent, this.prior !== undefined);
141
+ this.saveState();
142
+ for (const component of this.components)
143
+ component.start({
144
+ layout: this.layout,
145
+ clock: this.clock,
146
+ view: { rung: () => this.ladder.rungs[this.ladder.rungIndex] ?? this.workers.size, agents: () => this.workers.size },
147
+ note: (message) => this.recorder.event({ type: "warning", message }),
148
+ hold: (on) => {
149
+ if (!this.finishing && this.ladder && Boolean(this.ladder.braked) !== on)
150
+ this.feed({ type: "brake", on });
151
+ },
152
+ });
153
+ if (this.options.signal?.aborted)
154
+ stop();
155
+ void this.watchLoop();
156
+ return this.outcome;
157
+ }
158
+ async prepare() {
159
+ this.client = this.gate.wrap(this.options.createClient ? this.options.createClient(this.gate) : createChatClient({ ...this.task.model, retry: this.gate.retry }));
160
+ const clientFor = (model) => (model ? this.gate.wrap(createChatClient({ ...model, retry: this.gate.retry })) : this.client);
161
+ this.mode = (this.options.mode ?? createMode)({
162
+ task: this.task,
163
+ layout: this.layout,
164
+ clock: this.clock,
165
+ clientFor,
166
+ ...(this.options.signal ? { signal: this.options.signal } : {}),
167
+ ...(this.options.gate ? { gate: this.options.gate } : {}),
168
+ });
169
+ if (this.prior)
170
+ this.mode.restore({ bestScore: this.prior.bestScore ?? null });
171
+ await this.mode.prepare();
172
+ for (const message of this.mode.warnings?.() ?? [])
173
+ this.recorder.event({ type: "warning", message });
174
+ if (this.mode.branchReview) {
175
+ this.branch = startBranchReview({
176
+ settings: this.mode.branchReview,
177
+ ceiling: this.task.agents,
178
+ clock: this.clock,
179
+ layout: this.layout,
180
+ gate: this.gate,
181
+ budget: this.budget,
182
+ workers: this.workers,
183
+ record: (event) => this.recorder.event(event),
184
+ });
185
+ }
186
+ // the task's own hints win over the planner: a person who split the work knows best
187
+ this.hints = this.prior?.hints ?? (this.task.hints && this.task.hints.length > 0 ? [...this.task.hints] : await this.plan());
188
+ }
189
+ async plan() {
190
+ return planHints({ client: this.client, statement: this.mode.plannerSubject, count: MAX_HINTS_PLANNED, kind: this.mode.plannerKind });
191
+ }
192
+ // ----- agents -----
193
+ startAgent(number, resume) {
194
+ this.stuck.register(number);
195
+ this.branch?.agentStarted(number);
196
+ this.recorder.lifecycle(number, "started", resume ? "resumed" : "");
197
+ const worker = startWorker({
198
+ number,
199
+ layout: this.layout,
200
+ client: this.client,
201
+ setup: this.mode.agentSetup(hintFor(this.hints, number), number),
202
+ ...(this.options.createEnvironment ? { createEnvironment: this.options.createEnvironment } : {}),
203
+ resume,
204
+ clock: this.clock,
205
+ gate: this.gate,
206
+ pauseRetryMs: this.options.pauseRetryMs ?? 1000,
207
+ hooks: {
208
+ onActivity: () => this.stuck.touch(number),
209
+ onReply: () => {
210
+ this.consecutiveFailures = 0;
211
+ this.apply(stepLadder(this.ladder, { type: "reply", agent: number }));
212
+ },
213
+ onCommit: (commit, turn) => this.recorder.commit(number, commit, turn),
214
+ onCommitError: (operation) => this.recorder.event({
215
+ type: "warning",
216
+ message: `Agent ${number}: Git ${operation} failed. Check the agent's work directory for uncommitted files.`,
217
+ }),
218
+ onDenied: (denial) => this.recorder.event({ type: "action_denied", agent: number, ...denial }),
219
+ onSubmit: async (submission, info) => this.onSubmit(number, submission, info),
220
+ },
221
+ });
222
+ this.workers.set(number, worker);
223
+ this.allEnded.push(worker.done.then((end) => this.onAgentEnd(number, end)));
224
+ }
225
+ /** The mode takes the submit; the orchestrator only obeys what it says about the run. */
226
+ async onSubmit(agent, submission, info) {
227
+ const effect = this.mode.accept(agent, submission, info, { recorder: this.recorder, layout: this.layout, clock: this.clock });
228
+ if (effect.changed)
229
+ this.saveState();
230
+ if (effect.finish)
231
+ void this.finish(effect.finish);
232
+ }
233
+ async onAgentEnd(number, end) {
234
+ this.workers.delete(number);
235
+ this.stuck.forget(number);
236
+ this.branch?.agentEnded(number);
237
+ const detail = [end.reason, end.cancelled, end.detail].filter(Boolean).join(": ");
238
+ this.recorder.lifecycle(number, end.cancelled === "stuck" ? "stopped" : "ended", detail);
239
+ if (this.finishing || end.cancelled === "retire")
240
+ return;
241
+ if (end.reason !== "done") {
242
+ this.failures += 1;
243
+ this.consecutiveFailures += 1;
244
+ }
245
+ if (this.failures > this.task.agents * 5 + 10)
246
+ return void this.finish("too many agent failures");
247
+ const wait = replacementWait(end.reason !== "done", this.consecutiveFailures, this.options.replacementWaitMs);
248
+ if (wait > 0)
249
+ await this.clock.sleep(wait, this.stopWatching.signal).catch(() => undefined);
250
+ if (this.finishing)
251
+ return;
252
+ this.apply(stepLadder(this.ladder, { type: "agent_ended", agent: number }));
253
+ }
254
+ // ----- the ladder -----
255
+ apply(step) {
256
+ this.ladder = step.state;
257
+ if (step.change) {
258
+ const stats = this.meter.closeRung(this.clock.now());
259
+ this.recorder.event({ type: "rung", from: step.change.from, to: step.change.to, reason: step.change.reason, ...stats });
260
+ this.recorder.report();
261
+ }
262
+ for (const agent of step.retire)
263
+ this.workers.get(agent)?.cancel("retire");
264
+ if (!this.finishing)
265
+ for (const agent of step.spawn)
266
+ this.startAgent(agent, false);
267
+ if (step.change || step.spawn.length > 0 || step.retire.length > 0)
268
+ this.saveState();
269
+ }
270
+ feed(event) {
271
+ this.apply(stepLadder(this.ladder, event));
272
+ }
273
+ // ----- the gate -----
274
+ onGateEvent(event) {
275
+ switch (event.type) {
276
+ case "usage":
277
+ this.budget.record(event.usage);
278
+ this.meter.recordReply(event.latencyMs, totalTokens(event.usage));
279
+ return;
280
+ case "throttle":
281
+ this.recorder.event({ type: "throttle", delayMs: event.delayMs, ...(event.cause ? { cause: event.cause } : {}) });
282
+ this.meter.recordThrottle();
283
+ if (this.ladder)
284
+ this.feed({ type: "throttle" });
285
+ return;
286
+ case "quota":
287
+ this.recorder.event({ type: "quota", message: event.message });
288
+ void this.finish("quota");
289
+ return;
290
+ case "refused":
291
+ if (!this.budgetRefusalLogged)
292
+ this.recorder.event({ type: "budget_refused", reason: event.reason });
293
+ this.budgetRefusalLogged = true;
294
+ void this.finish("budget");
295
+ return;
296
+ }
297
+ }
298
+ // ----- watching -----
299
+ async watchLoop() {
300
+ const every = this.options.checkEveryMs ?? 60_000;
301
+ while (!this.finishing) {
302
+ await this.clock.sleep(every, this.stopWatching.signal).catch(() => { });
303
+ if (this.finishing)
304
+ return;
305
+ for (const action of this.stuck.check()) {
306
+ const worker = this.workers.get(action.agent);
307
+ if (action.type === "rescue") {
308
+ this.recorder.event({ type: "rescue", agent: action.agent, rescue: action.rescue });
309
+ this.recorder.lifecycle(action.agent, "rescued", `rescue ${action.rescue}`);
310
+ worker?.rescue(RESCUE_MESSAGE);
311
+ }
312
+ else {
313
+ worker?.cancel("stuck");
314
+ }
315
+ }
316
+ this.saveState();
317
+ }
318
+ }
319
+ // ----- the end -----
320
+ async finish(reason) {
321
+ if (this.finishing)
322
+ return;
323
+ this.finishing = reason;
324
+ this.ladderAtStop = this.ladder;
325
+ this.stopWatching.abort();
326
+ this.apply(stepLadder(this.ladder, { type: "finish" }));
327
+ this.drainOrCancel(reason);
328
+ await this.branch?.stop();
329
+ if (this.branch)
330
+ this.recorder.event({ type: "review_skips", skips: { ...this.branch.skips } });
331
+ const live = [...this.workers.keys()];
332
+ await Promise.allSettled(this.allEnded);
333
+ await Promise.allSettled(this.components.map((component) => component.stop()));
334
+ this.mode.finish?.(live);
335
+ this.recorder.event({
336
+ type: "run_end",
337
+ reason,
338
+ tokensUsed: this.budget.tokensUsed,
339
+ ...this.mode.endFields(),
340
+ });
341
+ this.saveState(reason);
342
+ this.recorder.report();
343
+ this.closed = true;
344
+ this.resolveOutcome(outcomeOf(this.layout, reason, this.budget.tokensUsed, this.mode.endFields().bestScore));
345
+ }
346
+ /** A budget or quota stop is soft: requests in flight finish and nothing new starts. Any other end cancels the agents at once. */
347
+ drainOrCancel(reason) {
348
+ if (reason === "budget" || reason === "quota") {
349
+ this.gate.stop(`run stopped: ${reason}`, { silent: true });
350
+ return;
351
+ }
352
+ for (const worker of this.workers.values())
353
+ worker.cancel("finish");
354
+ }
355
+ /** What the mode has so far; before the mode exists (a failed start), what the run had when it was resumed. */
356
+ progress() {
357
+ return this.mode?.progress() ?? { bestScore: this.prior?.bestScore ?? null };
358
+ }
359
+ saveState(finished = null) {
360
+ if (this.closed)
361
+ return;
362
+ saveState(this.layout.state, {
363
+ version: 1,
364
+ task: this.task.name,
365
+ startedAt: this.startedAt,
366
+ hints: this.hints,
367
+ ladder: this.ladderAtStop ?? this.ladder,
368
+ bestScore: this.progress().bestScore,
369
+ tokensUsed: this.budget.tokensUsed,
370
+ requests: this.budget.requestCount,
371
+ failures: this.failures,
372
+ finished,
373
+ });
374
+ }
375
+ }
@@ -0,0 +1,98 @@
1
+ /** Used when the planner call fails or answers badly, and to fill up when it gives fewer hints than agents. Lean 4 without Mathlib. */
2
+ export const FALLBACK_HINTS = [
3
+ "Try the simplest automation first: omega, simp, decide, rfl, then combine them.",
4
+ "Prove it by induction on the main variable, with the induction hypothesis written out explicitly.",
5
+ "Split into cases (cases, rcases, by_cases, match) and close each case separately.",
6
+ "Unfold the definitions and rewrite step by step with rw and simp only, reading the goal after every step.",
7
+ "Prove a helper lemma first, then use it in the main theorem.",
8
+ "Work backwards: state the last step you need as a 'have', and then prove the steps before it.",
9
+ "Argue by contradiction (by_contra) and look for a contradiction with omega or simp.",
10
+ "Search the core library for a matching lemma (exact?, apply?, #check on Nat.* names) and use it.",
11
+ "Strengthen the statement for the induction, prove the stronger lemma, and derive the goal.",
12
+ "Use strong induction (Nat.strong_induction_on) when the usual induction step is not enough.",
13
+ "Write the proof as a term (fun n => ...) with Or.inl / Or.inr and Nat lemmas, without tactics.",
14
+ "Use calc blocks so that each equality step is checked on its own.",
15
+ ];
16
+ /** The same for code tasks: no task-specific knowledge, only ways of working that fit most problems with a score. */
17
+ export const CODE_FALLBACK_HINTS = [
18
+ "Build a quick, solid baseline first and submit it early, then improve it step by step.",
19
+ "Look hard at the data first (types, missing values, class balance, leakage), and let what you find choose the method.",
20
+ "Use gradient boosted trees and spend your time on tuning them with a time limit per run.",
21
+ "Try a different model family from the usual one (for example linear, nearest neighbours, neural network) and compare on a validation split.",
22
+ "Work on features: transformations, interactions, encodings; measure each change on a validation split.",
23
+ "Use cross-validation to choose between ideas, and submit only what is clearly better than your best.",
24
+ "Build an ensemble of several different models (averaging or stacking) from your own earlier results.",
25
+ "Search for the best hyper-parameters with a small, time-limited random search before any long training.",
26
+ "Try to make training much faster (sampling, early stopping, fewer features) so that you can test more ideas.",
27
+ "Look at the examples your best model gets wrong and design something for them.",
28
+ "Start from a simple, well-known recipe for this kind of problem and push it as far as it goes before trying anything exotic.",
29
+ "Use a neural network with careful scaling of the inputs and a learning-rate schedule, and compare it with trees.",
30
+ ];
31
+ const PLANNER_SYSTEM = "You plan a team of agents that each try to prove one statement in Lean 4 (core library only, no Mathlib). Answer with a JSON array of strings and nothing else.";
32
+ /**
33
+ * One model call at the start: a different strategy hint for every agent. Any failure (an error, text that is not a list) gives the fixed list,
34
+ * so the run never depends on the planner. A cancelled call is passed on.
35
+ */
36
+ export async function planHints(options) {
37
+ const signal = options.signal ?? new AbortController().signal;
38
+ try {
39
+ const text = await askPlanner(options, signal);
40
+ return completeWithFallback(parseHints(text), options.count, options.kind);
41
+ }
42
+ catch (error) {
43
+ if (signal.aborted)
44
+ throw error;
45
+ return completeWithFallback([], options.count, options.kind);
46
+ }
47
+ }
48
+ async function askPlanner(options, signal) {
49
+ const request = {
50
+ system: options.kind === "code" ? CODE_PLANNER_SYSTEM : PLANNER_SYSTEM,
51
+ messages: [
52
+ {
53
+ role: "user",
54
+ ts: Date.now(),
55
+ content: [
56
+ {
57
+ type: "text",
58
+ text: options.kind === "code"
59
+ ? `Task:\n${options.statement}\n\nWrite ${options.count} different one-sentence strategy hints, one per agent, each pointing to a different way to get a better score.`
60
+ : `Statement:\n${options.statement}\n\nWrite ${options.count} different one-sentence strategy hints, one per agent, each pointing to a different way to prove it.`,
61
+ },
62
+ ],
63
+ },
64
+ ],
65
+ tools: [],
66
+ maxTokens: 1500,
67
+ };
68
+ let text = "";
69
+ for await (const event of options.client.stream(request, signal))
70
+ if (event.type === "text_delta")
71
+ text += event.delta;
72
+ return text;
73
+ }
74
+ function parseHints(text) {
75
+ const start = text.indexOf("[");
76
+ const end = text.lastIndexOf("]");
77
+ if (start < 0 || end <= start)
78
+ return [];
79
+ try {
80
+ const parsed = JSON.parse(text.slice(start, end + 1));
81
+ return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string" && item.trim() !== "").map((item) => item.trim()) : [];
82
+ }
83
+ catch {
84
+ return [];
85
+ }
86
+ }
87
+ const CODE_PLANNER_SYSTEM = "You plan a team of agents that each work on the same task with a score (code, data, machine learning). Answer with a JSON array of strings and nothing else.";
88
+ function completeWithFallback(hints, count, kind = "math") {
89
+ const unique = [...new Set(hints)];
90
+ const filler = (kind === "code" ? CODE_FALLBACK_HINTS : FALLBACK_HINTS).filter((hint) => !unique.includes(hint));
91
+ return [...unique, ...filler].slice(0, Math.max(count, 1));
92
+ }
93
+ /** Agent numbers start at 1 and are never reused, so a replacement agent gets the next hint of the list (and the list repeats when it ends). */
94
+ export function hintFor(hints, agent) {
95
+ if (hints.length === 0)
96
+ return FALLBACK_HINTS[0] ?? "";
97
+ return hints[(agent - 1) % hints.length] ?? "";
98
+ }
@@ -0,0 +1,21 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ const hasProgram = (program) => new Promise((resolve) => execFile("sh", ["-c", `command -v ${program}`], (error) => resolve(!error)));
4
+ export async function unsupportedFeatures(needs = {}) {
5
+ const platform = needs.platform ?? process.platform;
6
+ const has = needs.has ?? hasProgram;
7
+ const missing = [];
8
+ if (platform !== "linux")
9
+ missing.push(`the operating system is ${platform}, not Linux (the machine readings, the limits on commands and the cleanup of processes need Linux)`);
10
+ if (!(needs.hasProc ?? existsSync("/proc/self/stat")))
11
+ missing.push("/proc (machine readings, the run's own processes, the cleanup of leftover processes)");
12
+ if (!(await has("renice")))
13
+ missing.push("renice (lower priority of the agents' commands)");
14
+ if (needs.gpu) {
15
+ if (!(await has("flock")))
16
+ missing.push("flock (the GPU slots: the `gpu` shim needs it, so GPU tasks are disabled)");
17
+ if (!(await has("nvidia-smi")))
18
+ missing.push("nvidia-smi (the GPUs of a GPU task)");
19
+ }
20
+ return missing.map((feature) => `unsupported on this OS: ${feature}`);
21
+ }
@@ -0,0 +1,73 @@
1
+ export class Pool {
2
+ held = 0;
3
+ queue = [];
4
+ capacity;
5
+ constructor(capacity) {
6
+ if (!(capacity >= 1))
7
+ throw new RangeError(`Pool capacity must be at least 1, got ${capacity}`);
8
+ this.capacity = capacity;
9
+ }
10
+ get inUse() {
11
+ return this.held;
12
+ }
13
+ get waiting() {
14
+ return this.queue.length;
15
+ }
16
+ /** Resolves with a release function once a place is free. Rejects, and leaves the line, when the signal aborts. */
17
+ acquire(signal) {
18
+ if (signal?.aborted)
19
+ return Promise.reject(signal.reason);
20
+ if (this.held < this.capacity)
21
+ return Promise.resolve(this.take());
22
+ return new Promise((resolve, reject) => {
23
+ const onAbort = () => {
24
+ this.leaveLine(waiter);
25
+ reject(signal?.reason);
26
+ };
27
+ const waiter = {
28
+ grant: resolve,
29
+ fail: reject,
30
+ detach: () => signal?.removeEventListener("abort", onAbort),
31
+ };
32
+ signal?.addEventListener("abort", onAbort, { once: true });
33
+ this.queue.push(waiter);
34
+ });
35
+ }
36
+ /** Runs `work` while holding a place. The wait for the place is not part of `work`, so a timeout inside `work` does not count it. */
37
+ async run(work, signal) {
38
+ const release = await this.acquire(signal);
39
+ try {
40
+ return await work();
41
+ }
42
+ finally {
43
+ release();
44
+ }
45
+ }
46
+ take() {
47
+ this.held += 1;
48
+ let released = false;
49
+ return () => {
50
+ if (released)
51
+ return;
52
+ released = true;
53
+ this.held -= 1;
54
+ this.serveNext();
55
+ };
56
+ }
57
+ serveNext() {
58
+ const next = this.queue.shift();
59
+ if (!next)
60
+ return;
61
+ next.detach();
62
+ next.grant(this.take());
63
+ }
64
+ leaveLine(waiter) {
65
+ const index = this.queue.indexOf(waiter);
66
+ if (index >= 0)
67
+ this.queue.splice(index, 1);
68
+ }
69
+ }
70
+ /** The pool size to use when a task does not set one: the number of CPU cores. */
71
+ export function defaultLeanPoolSize(cpuCount) {
72
+ return Math.max(1, cpuCount);
73
+ }