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.
- package/AGENT-GUIDE.md +104 -0
- package/LICENSE +21 -0
- package/README.md +275 -2
- package/dist/bin/flags.js +110 -0
- package/dist/bin/infinity.js +98 -0
- package/dist/bin/load-task.js +39 -0
- package/dist/bin/model.js +37 -0
- package/dist/bin/scaffold.js +121 -0
- package/dist/src/agent-worker.js +157 -0
- package/dist/src/backoff.js +12 -0
- package/dist/src/budget.js +49 -0
- package/dist/src/capacity.js +103 -0
- package/dist/src/clock.js +16 -0
- package/dist/src/code-leaderboard.js +48 -0
- package/dist/src/code-report.js +157 -0
- package/dist/src/command-class.js +59 -0
- package/dist/src/command-limits.js +46 -0
- package/dist/src/commit-plugin.js +36 -0
- package/dist/src/component.js +1 -0
- package/dist/src/csv.js +8 -0
- package/dist/src/defaults.js +35 -0
- package/dist/src/error-cluster.js +20 -0
- package/dist/src/evaluation.js +84 -0
- package/dist/src/form.js +191 -0
- package/dist/src/gate.js +111 -0
- package/dist/src/gpu-shim.js +165 -0
- package/dist/src/handoff.js +12 -0
- package/dist/src/hidden-keeper.js +183 -0
- package/dist/src/host.js +180 -0
- package/dist/src/jsonl.js +30 -0
- package/dist/src/ladder.js +118 -0
- package/dist/src/launch.js +123 -0
- package/dist/src/lean-kit.js +42 -0
- package/dist/src/lean-runner.js +84 -0
- package/dist/src/lean-setup.js +23 -0
- package/dist/src/lean-tool.js +57 -0
- package/dist/src/leftover.js +59 -0
- package/dist/src/machine-config.js +43 -0
- package/dist/src/machine-sampler.js +103 -0
- package/dist/src/machine-summary.js +64 -0
- package/dist/src/mode-factory.js +25 -0
- package/dist/src/mode.js +1 -0
- package/dist/src/network.js +12 -0
- package/dist/src/orchestrator.js +375 -0
- package/dist/src/planner.js +98 -0
- package/dist/src/platform.js +21 -0
- package/dist/src/pool.js +73 -0
- package/dist/src/pressure-brake.js +26 -0
- package/dist/src/proc-readings.js +207 -0
- package/dist/src/prompts.js +46 -0
- package/dist/src/records.js +2 -0
- package/dist/src/report.js +81 -0
- package/dist/src/review-loop.js +141 -0
- package/dist/src/review-rules.js +104 -0
- package/dist/src/review-run.js +110 -0
- package/dist/src/review-schedule.js +53 -0
- package/dist/src/review-snapshot.js +150 -0
- package/dist/src/run-layout.js +29 -0
- package/dist/src/run-notes.js +61 -0
- package/dist/src/run-recorder.js +51 -0
- package/dist/src/run-state.js +17 -0
- package/dist/src/run-status.js +37 -0
- package/dist/src/rung-meter.js +39 -0
- package/dist/src/safety-review.js +43 -0
- package/dist/src/sakura-tools.js +130 -0
- package/dist/src/shell-kit.js +113 -0
- package/dist/src/slot-gate.js +136 -0
- package/dist/src/slot-leases.js +64 -0
- package/dist/src/stuck.js +47 -0
- package/dist/src/submit-tool.js +99 -0
- package/dist/src/task-mode.js +170 -0
- package/dist/src/task.js +85 -0
- package/dist/src/verifier.js +115 -0
- package/dist/src/work-repo.js +50 -0
- package/dist/src/worker-policy.js +16 -0
- package/dist/tasks/math-odd-sum/task.js +6 -0
- package/dist/tasks/math-parity/task.js +6 -0
- package/dist/viewer/index.html +397 -0
- package/dist/viewer/run-reader.js +600 -0
- package/dist/viewer/server.js +160 -0
- package/dist/viewer/view.js +50 -0
- package/package.json +53 -4
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const DEFAULT_BRAKE = { loadPerCore: 1, pressure10: 40, readings: 3 };
|
|
2
|
+
/** Decides from successive readings when the ladder should be held. Pure state; the component acts on what it answers. */
|
|
3
|
+
export class PressureBrake {
|
|
4
|
+
limits;
|
|
5
|
+
on = false;
|
|
6
|
+
streak = 0;
|
|
7
|
+
constructor(limits = {}) {
|
|
8
|
+
this.limits = { ...DEFAULT_BRAKE, ...limits };
|
|
9
|
+
}
|
|
10
|
+
get active() {
|
|
11
|
+
return this.on;
|
|
12
|
+
}
|
|
13
|
+
/** Is this reading over the limit? */
|
|
14
|
+
over(sample) {
|
|
15
|
+
return sample.load1 / Math.max(1, sample.cores) > this.limits.loadPerCore || (sample.cpuPressure10 ?? 0) > this.limits.pressure10;
|
|
16
|
+
}
|
|
17
|
+
/** Feeds a reading; returns the new state when it changed (on after enough readings over the limit in a row, off after as many under it), else undefined. */
|
|
18
|
+
update(sample) {
|
|
19
|
+
this.streak = this.over(sample) === this.on ? 0 : this.streak + 1;
|
|
20
|
+
if (this.streak < this.limits.readings)
|
|
21
|
+
return undefined;
|
|
22
|
+
this.streak = 0;
|
|
23
|
+
this.on = !this.on;
|
|
24
|
+
return this.on;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { LinuxHost } from "./host.js";
|
|
2
|
+
/** The first line of /proc/stat ("cpu user nice system idle iowait irq softirq steal ...") as busy and total jiffies. */
|
|
3
|
+
export function parseCpuLine(line) {
|
|
4
|
+
const fields = line.trim().split(/\s+/).slice(1).map(Number);
|
|
5
|
+
const idle = (fields[3] ?? 0) + (fields[4] ?? 0);
|
|
6
|
+
const total = fields.reduce((sum, value) => sum + (Number.isFinite(value) ? value : 0), 0);
|
|
7
|
+
return { busy: total - idle, total, iowait: fields[4] ?? 0, steal: fields[7] ?? 0 };
|
|
8
|
+
}
|
|
9
|
+
/** Share (0 to 1) of the time between two readings taken by a field of the CPU line (iowait or steal); null without a gap. */
|
|
10
|
+
export function fieldShare(before, after, field) {
|
|
11
|
+
const total = after.total - before.total;
|
|
12
|
+
return total > 0 ? (after[field] - before[field]) / total : null;
|
|
13
|
+
}
|
|
14
|
+
/** `procs_running` of /proc/stat. */
|
|
15
|
+
export function parseProcsRunning(text) {
|
|
16
|
+
const value = /^procs_running\s+(\d+)/m.exec(text)?.[1];
|
|
17
|
+
return value === undefined ? null : Number(value);
|
|
18
|
+
}
|
|
19
|
+
/** The "some" line of /proc/pressure/cpu ("some avg10=0.12 avg60=0.34 avg300=0.50 total=123"). */
|
|
20
|
+
export function parsePressure(text) {
|
|
21
|
+
const line = text.split("\n").find((candidate) => candidate.startsWith("some "));
|
|
22
|
+
const avg10 = /avg10=([\d.]+)/.exec(line ?? "")?.[1];
|
|
23
|
+
const avg60 = /avg60=([\d.]+)/.exec(line ?? "")?.[1];
|
|
24
|
+
return avg10 === undefined || avg60 === undefined ? undefined : { avg10: Number(avg10), avg60: Number(avg60) };
|
|
25
|
+
}
|
|
26
|
+
/** One /proc/<pid>/stat: the program name sits in parentheses (and may hold spaces), the numbers follow the last closing one. */
|
|
27
|
+
export function parseProcStat(text) {
|
|
28
|
+
const open = text.indexOf("(");
|
|
29
|
+
const close = text.lastIndexOf(")");
|
|
30
|
+
if (open < 0 || close < open)
|
|
31
|
+
return undefined;
|
|
32
|
+
const fields = text
|
|
33
|
+
.slice(close + 2)
|
|
34
|
+
.trim()
|
|
35
|
+
.split(/\s+/);
|
|
36
|
+
const number = (index) => Number(fields[index]);
|
|
37
|
+
const values = [number(11), number(12), number(17), number(21)];
|
|
38
|
+
if (values.some((value) => !Number.isFinite(value)))
|
|
39
|
+
return undefined;
|
|
40
|
+
return {
|
|
41
|
+
comm: text.slice(open + 1, close),
|
|
42
|
+
ticks: values[0] + values[1],
|
|
43
|
+
threads: values[2],
|
|
44
|
+
rssPages: values[3],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** `nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader,nounits`: how many processes hold GPU memory and the largest holding. */
|
|
48
|
+
export function parseComputeApps(text) {
|
|
49
|
+
const used = text
|
|
50
|
+
.split("\n")
|
|
51
|
+
.map((line) => Number(line.split(",")[1]))
|
|
52
|
+
.filter((value) => Number.isFinite(value));
|
|
53
|
+
return { count: used.length, maxMb: used.length > 0 ? Math.max(...used) : 0 };
|
|
54
|
+
}
|
|
55
|
+
/** Share of the time between two readings that the CPUs were busy (0 to 1); null without a gap. */
|
|
56
|
+
export function busyShare(before, after) {
|
|
57
|
+
const total = after.total - before.total;
|
|
58
|
+
return total > 0 ? (after.busy - before.busy) / total : null;
|
|
59
|
+
}
|
|
60
|
+
export function parseMeminfo(text) {
|
|
61
|
+
const kb = (key) => Number(new RegExp(`^${key}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? 0);
|
|
62
|
+
return { totalMb: Math.round(kb("MemTotal") / 1024), availableMb: Math.round(kb("MemAvailable") / 1024) };
|
|
63
|
+
}
|
|
64
|
+
/** `nvidia-smi --query-gpu=utilization.gpu,memory.used`: the first GPU's use in percent and memory in MB. */
|
|
65
|
+
function parseGpuUsage(text) {
|
|
66
|
+
const [util, memMb] = text.trim().split("\n")[0]?.split(",").map(Number) ?? [];
|
|
67
|
+
return Number.isFinite(util) && Number.isFinite(memMb) ? { util: util, memMb: memMb } : undefined;
|
|
68
|
+
}
|
|
69
|
+
export function parseGpuFacts(text) {
|
|
70
|
+
const [name, mem] = text
|
|
71
|
+
.trim()
|
|
72
|
+
.split("\n")[0]
|
|
73
|
+
?.split(",")
|
|
74
|
+
.map((part) => part.trim()) ?? [];
|
|
75
|
+
const memMb = Number(mem);
|
|
76
|
+
return name && Number.isFinite(memMb) ? { name, memMb } : undefined;
|
|
77
|
+
}
|
|
78
|
+
/** `nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits`: one number per GPU, in MB. */
|
|
79
|
+
const parseGpuMemories = (text) => text
|
|
80
|
+
.split("\n")
|
|
81
|
+
.map((line) => Number(line.trim()))
|
|
82
|
+
.filter((value) => Number.isFinite(value) && value > 0);
|
|
83
|
+
/** Memory in MB: from /proc/meminfo, else from the operating system API. */
|
|
84
|
+
function readMemory(host) {
|
|
85
|
+
const info = host.readProc("meminfo");
|
|
86
|
+
return info ? parseMeminfo(info) : { totalMb: Math.round(host.totalMemoryBytes() / 1048576), availableMb: Math.round(host.freeMemoryBytes() / 1048576) };
|
|
87
|
+
}
|
|
88
|
+
// ----- reading -----
|
|
89
|
+
const TICKS_PER_SECOND = 100;
|
|
90
|
+
const PAGE_BYTES = 4096;
|
|
91
|
+
/** One pass over the processes: counts bash processes on the machine and sums the run's processes (working directory under `runRoot`). */
|
|
92
|
+
export function scanProcesses(host, runRoot) {
|
|
93
|
+
const scan = { shells: 0, run: { processes: 0, python: 0, threads: 0, rssMb: 0, ticks: new Map() } };
|
|
94
|
+
const prefix = runRoot === undefined ? undefined : runRoot.endsWith("/") ? runRoot : `${runRoot}/`;
|
|
95
|
+
let rssPages = 0;
|
|
96
|
+
for (const process of host.processes({ cwd: prefix !== undefined })) {
|
|
97
|
+
const stat = parseProcStat(process.stat);
|
|
98
|
+
if (!stat)
|
|
99
|
+
continue;
|
|
100
|
+
if (stat.comm === "bash")
|
|
101
|
+
scan.shells += 1;
|
|
102
|
+
if (prefix === undefined || process.cwd === undefined)
|
|
103
|
+
continue;
|
|
104
|
+
if (process.cwd !== prefix.slice(0, -1) && !process.cwd.startsWith(prefix))
|
|
105
|
+
continue;
|
|
106
|
+
scan.run.processes += 1;
|
|
107
|
+
if (stat.comm.startsWith("python"))
|
|
108
|
+
scan.run.python += 1;
|
|
109
|
+
scan.run.threads += stat.threads;
|
|
110
|
+
rssPages += stat.rssPages;
|
|
111
|
+
scan.run.ticks.set(process.pid, stat.ticks);
|
|
112
|
+
}
|
|
113
|
+
scan.run.rssMb = Math.round((rssPages * PAGE_BYTES) / 1048576);
|
|
114
|
+
return scan;
|
|
115
|
+
}
|
|
116
|
+
/** Reads the machine. Keeps the last CPU reading to compute the busy share; the first call returns null for it. */
|
|
117
|
+
export class MachineReader {
|
|
118
|
+
lastCpu;
|
|
119
|
+
lastTicks;
|
|
120
|
+
lastTs;
|
|
121
|
+
host;
|
|
122
|
+
runRoot;
|
|
123
|
+
slots;
|
|
124
|
+
constructor(options = {}) {
|
|
125
|
+
this.host = options.host ?? new LinuxHost();
|
|
126
|
+
this.slots = options.slots;
|
|
127
|
+
this.runRoot = options.runRoot === undefined ? undefined : this.host.realPath(options.runRoot);
|
|
128
|
+
}
|
|
129
|
+
async read(now, run) {
|
|
130
|
+
const host = this.host;
|
|
131
|
+
const stat = host.readProc("stat");
|
|
132
|
+
const cpu = stat ? parseCpuLine(stat.split("\n")[0] ?? "") : undefined;
|
|
133
|
+
const before = this.lastCpu;
|
|
134
|
+
this.lastCpu = cpu;
|
|
135
|
+
const mem = readMemory(host);
|
|
136
|
+
const [load1, load5, load15] = host.loadAverage();
|
|
137
|
+
const pressureText = host.readProc("pressure/cpu");
|
|
138
|
+
const pressure = pressureText ? parsePressure(pressureText) : undefined;
|
|
139
|
+
const scan = host.hasProc() ? scanProcesses(host, this.runRoot) : undefined;
|
|
140
|
+
const runCpu = scan && this.runRoot !== undefined ? this.runCpuSince(scan.run.ticks, now) : null;
|
|
141
|
+
const slotCounts = this.slots?.();
|
|
142
|
+
const [usageText, appsText] = await Promise.all([
|
|
143
|
+
host.gpuQuery("--query-gpu=utilization.gpu,memory.used"),
|
|
144
|
+
host.gpuQuery("--query-compute-apps=pid,used_memory"),
|
|
145
|
+
]);
|
|
146
|
+
const gpu = usageText === undefined ? undefined : parseGpuUsage(usageText);
|
|
147
|
+
const apps = appsText === undefined ? undefined : parseComputeApps(appsText);
|
|
148
|
+
return {
|
|
149
|
+
ts: now,
|
|
150
|
+
cores: host.cpuCount(),
|
|
151
|
+
load1,
|
|
152
|
+
load5,
|
|
153
|
+
load15,
|
|
154
|
+
cpuBusy: cpu && before ? busyShare(before, cpu) : null,
|
|
155
|
+
memUsedMb: mem.totalMb - mem.availableMb,
|
|
156
|
+
memAvailableMb: mem.availableMb,
|
|
157
|
+
memTotalMb: mem.totalMb,
|
|
158
|
+
shells: scan?.shells ?? null,
|
|
159
|
+
gpuUtilPercent: gpu?.util ?? null,
|
|
160
|
+
gpuMemUsedMb: gpu?.memMb ?? null,
|
|
161
|
+
cpuPressure10: pressure?.avg10 ?? null,
|
|
162
|
+
cpuPressure60: pressure?.avg60 ?? null,
|
|
163
|
+
procsRunning: stat ? parseProcsRunning(stat) : null,
|
|
164
|
+
iowaitShare: cpu && before ? fieldShare(before, cpu, "iowait") : null,
|
|
165
|
+
stealShare: cpu && before ? fieldShare(before, cpu, "steal") : null,
|
|
166
|
+
runProcesses: scan && this.runRoot !== undefined ? scan.run.processes : null,
|
|
167
|
+
runPythonProcesses: scan && this.runRoot !== undefined ? scan.run.python : null,
|
|
168
|
+
runThreads: scan && this.runRoot !== undefined ? scan.run.threads : null,
|
|
169
|
+
runRssMb: scan && this.runRoot !== undefined ? scan.run.rssMb : null,
|
|
170
|
+
runCpuSeconds: runCpu?.seconds ?? null,
|
|
171
|
+
runCpuCores: runCpu?.cores ?? null,
|
|
172
|
+
gpuProcesses: apps?.count ?? null,
|
|
173
|
+
gpuProcMaxMb: apps?.maxMb ?? null,
|
|
174
|
+
slotsInUse: slotCounts?.cpu?.inUse ?? null,
|
|
175
|
+
slotsWaiting: slotCounts?.cpu?.waiting ?? null,
|
|
176
|
+
gpuSlotsInUse: slotCounts?.gpu?.inUse ?? null,
|
|
177
|
+
gpuSlotsWaiting: slotCounts?.gpu?.waiting ?? null,
|
|
178
|
+
rung: run.rung,
|
|
179
|
+
agents: run.agents,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** CPU seconds the run's processes used since the last reading, counted per process (a new process counts from its start). */
|
|
183
|
+
runCpuSince(ticks, now) {
|
|
184
|
+
const previous = this.lastTicks;
|
|
185
|
+
const previousTs = this.lastTs;
|
|
186
|
+
this.lastTicks = ticks;
|
|
187
|
+
this.lastTs = now;
|
|
188
|
+
if (!previous || previousTs === undefined)
|
|
189
|
+
return null;
|
|
190
|
+
let delta = 0;
|
|
191
|
+
for (const [pid, value] of ticks)
|
|
192
|
+
delta += Math.max(0, value - (previous.get(pid) ?? 0));
|
|
193
|
+
const seconds = delta / TICKS_PER_SECOND;
|
|
194
|
+
const wall = (now - previousTs) / 1000;
|
|
195
|
+
return { seconds, cores: wall > 0 ? seconds / wall : null };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** What the machine offers now, for the recommendation printed before a run. */
|
|
199
|
+
export async function readMachineFacts(measureMs = 500, host = new LinuxHost()) {
|
|
200
|
+
const mem = readMemory(host);
|
|
201
|
+
const cores = host.cpuCount();
|
|
202
|
+
const first = host.readProc("stat");
|
|
203
|
+
const [gpuText] = await Promise.all([host.gpuQuery("--query-gpu=memory.total"), new Promise((resolve) => setTimeout(resolve, measureMs))]);
|
|
204
|
+
const second = host.readProc("stat");
|
|
205
|
+
const share = first && second ? busyShare(parseCpuLine(first.split("\n")[0] ?? ""), parseCpuLine(second.split("\n")[0] ?? "")) : null;
|
|
206
|
+
return { cores, busyCores: (share ?? 0) * cores, freeMemMb: mem.availableMb, gpuMemMb: gpuText ? parseGpuMemories(gpuText) : [] };
|
|
207
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** The words given to math agents. Kept apart from the code that runs them. */
|
|
2
|
+
export const GOAL_OBJECTIVE = "Produce a Lean proof of Statement.Goal that the 'submit' action of the lean tool accepts.";
|
|
3
|
+
export const MATH_RULES = [
|
|
4
|
+
"You work alone in your own directory. There is no shell; you have the tools read, write and lean.",
|
|
5
|
+
"The file Statement.lean in your directory shows what you must prove. Do not edit it: the official check uses its own copy.",
|
|
6
|
+
"Write your proof to Proof.lean. It starts with 'import Statement' (no other import) and contains 'theorem main : Statement.Goal := ...' with exactly that type.",
|
|
7
|
+
"Only the Lean 4 core library is available, no Mathlib. Do not use #eval, macros, elab, syntax, initialize or axioms.",
|
|
8
|
+
"Use the lean tool with action 'check' as often as you like while you work; read its messages and fix the errors one by one.",
|
|
9
|
+
"When the check shows no errors, call the lean tool with action 'submit'. Only an accepted submit counts. A proof with sorry is rejected.",
|
|
10
|
+
"If a submit is rejected, read the reason, fix the proof and submit again.",
|
|
11
|
+
];
|
|
12
|
+
export function taskPrompt(statement, userPrompt) {
|
|
13
|
+
const extra = userPrompt ? `\n\nNotes from the task author:\n${userPrompt}` : "";
|
|
14
|
+
return `Prove this statement in Lean 4:\n\n${statement}\n\nIt is already available as Statement.Goal (see Statement.lean). Work until the lean tool accepts your submit.${extra}`;
|
|
15
|
+
}
|
|
16
|
+
export function strategyRule(hint) {
|
|
17
|
+
return `Your strategy hint: ${hint} It is a suggestion for where to start; change your approach if it does not work.`;
|
|
18
|
+
}
|
|
19
|
+
export const CODE_GOAL_OBJECTIVE = "Improve the score of your solution and keep going until you are told to stop. A result counts only when you send it with the 'submit' tool.";
|
|
20
|
+
export function codeRules(options) {
|
|
21
|
+
const rules = [
|
|
22
|
+
"You work alone in your own directory with the tools read, write, edit, bash and submit. Your directory is yours; the rest of the machine is not.",
|
|
23
|
+
options.hasEvaluator
|
|
24
|
+
? `A result counts only through the 'submit' tool: give the shell command that produced it and the files that hold it. The answer shows the score (${options.metricName ?? "score"}). The score is computed on data you cannot see.`
|
|
25
|
+
: "A result counts only through the 'submit' tool: give the shell command that produced it, the files that hold it, and your own numbers in 'claim'. They are recorded as self-reported.",
|
|
26
|
+
"Nobody tells you when you are finished. After a good result, try to make it better (another method, better features, tuning, more data use) and submit again. Keep every submitted result reproducible from your directory.",
|
|
27
|
+
"Run every long command with a time limit (for example `timeout 600 python train.py`) and print little: a short summary, not whole tables. Commands run in the foreground and end by themselves; there is no background mode.",
|
|
28
|
+
"Keep large intermediate files (pickles, checkpoints, caches) in cache/ in your directory and delete the ones you no longer need as you go: the disk is shared, and every request tells you how much of it you hold.",
|
|
29
|
+
"You may install packages and download public models or data. Do not upload your directory or any data anywhere.",
|
|
30
|
+
"Never look for, read, guess or rebuild the data the score is computed on, and do not touch other agents' directories or the evaluator. Such actions are refused and counted against you.",
|
|
31
|
+
];
|
|
32
|
+
if (options.dataNames.length > 0)
|
|
33
|
+
rules.push(`Read-only data is linked in your directory: ${options.dataNames.join(", ")}. Do not try to modify it.`);
|
|
34
|
+
if (options.submitIntervalMinutes > 0)
|
|
35
|
+
rules.push(`You may submit at most once every ${options.submitIntervalMinutes} minutes; use the time to improve before the next submit.`);
|
|
36
|
+
return rules;
|
|
37
|
+
}
|
|
38
|
+
export function codePrompt(userPrompt) {
|
|
39
|
+
return `${userPrompt}\n\nWork until you are told to stop. Submit with the 'submit' tool every time you have a result that should count.`;
|
|
40
|
+
}
|
|
41
|
+
/** How advice from a branch review reaches the agent: clearly not from the user, and how old the picture was. */
|
|
42
|
+
export function adviceMessage(advice, repliesAgo, secondsAgo) {
|
|
43
|
+
const age = `${repliesAgo} replies and about ${Math.max(1, Math.round(secondsAgo / 60))} minutes ago`;
|
|
44
|
+
return (`[Outside review. This note is not from the user. A reviewer looked at a copy of your work as it was ${age}; things may have changed since. ` +
|
|
45
|
+
`Use it if it still applies, ignore it if not.]\n${advice}`);
|
|
46
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { renderCodeCsv, rankCodeAgents } from "./code-leaderboard.js";
|
|
3
|
+
import { renderCodeReportHtml } from "./code-report.js";
|
|
4
|
+
import { JsonlFile } from "./jsonl.js";
|
|
5
|
+
import { readMachineSamples } from "./machine-summary.js";
|
|
6
|
+
/** Generates `leaderboard.csv` and `report.html` from the two logs. Safe to call at any time, also during a run. */
|
|
7
|
+
export function writeReport(layout, metric) {
|
|
8
|
+
const ledger = new JsonlFile(layout.ledger).readAll();
|
|
9
|
+
const events = new JsonlFile(layout.events).readAll();
|
|
10
|
+
mkdirSync(layout.reportDir, { recursive: true });
|
|
11
|
+
const rows = rankCodeAgents(ledger, metric.direction);
|
|
12
|
+
writeFileSync(layout.leaderboardCsv, renderCodeCsv(rows));
|
|
13
|
+
writeFileSync(layout.reportHtml, renderCodeReportHtml(rows, ledger, events, metric, readMachineSamples(layout.machine)));
|
|
14
|
+
}
|
|
15
|
+
export const escapeHtml = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
16
|
+
export const formatTime = (ts) => new Date(ts).toISOString().slice(11, 19);
|
|
17
|
+
export function table(headers, rows) {
|
|
18
|
+
if (rows.length === 0)
|
|
19
|
+
return "<p><em>none</em></p>";
|
|
20
|
+
const head = headers.map((header) => `<th>${header}</th>`).join("");
|
|
21
|
+
const body = rows.map((cells) => `<tr>${cells.map((cell) => `<td>${cell}</td>`).join("")}</tr>`).join("");
|
|
22
|
+
return `<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`;
|
|
23
|
+
}
|
|
24
|
+
/** The first and last lines of every summary: the task, and how the run ended (or that it has not). */
|
|
25
|
+
export function summaryLines(events) {
|
|
26
|
+
const end = events.findLast((event) => event.type === "run_start" || event.type === "run_end");
|
|
27
|
+
const start = events.find((event) => event.type === "run_start");
|
|
28
|
+
return {
|
|
29
|
+
task: `Task: ${escapeHtml(start?.task ?? "unknown")}`,
|
|
30
|
+
ended: end?.type === "run_end"
|
|
31
|
+
? `Ended: ${escapeHtml(end.reason)} at ${formatTime(end.ts)}, ${end.tokensUsed} tokens used`
|
|
32
|
+
: "Still running (no end recorded yet)",
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export const summaryHtml = (lines) => `<h2>Summary</h2><ul>${lines.map((line) => `<li>${line}</li>`).join("")}</ul>`;
|
|
36
|
+
export function ladderSection(events) {
|
|
37
|
+
const rungs = events.filter((event) => event.type === "rung");
|
|
38
|
+
const cells = rungs.map((rung) => [
|
|
39
|
+
formatTime(rung.ts),
|
|
40
|
+
`${rung.from} → ${rung.to}`,
|
|
41
|
+
rung.reason === "throttle" ? "<strong>throttled (provider limit)</strong>" : "advance",
|
|
42
|
+
String(rung.replies),
|
|
43
|
+
String(rung.throttles),
|
|
44
|
+
`${rung.latencyP50Ms} / ${rung.latencyP95Ms} ms`,
|
|
45
|
+
String(Math.round(rung.tokensPerMinute)),
|
|
46
|
+
]);
|
|
47
|
+
return `<h2>Ladder</h2>${table(["time", "agents", "why", "replies", "throttles", "latency p50 / p95", "tokens per minute"], cells)}`;
|
|
48
|
+
}
|
|
49
|
+
export function pressureSection(events) {
|
|
50
|
+
const rows = [];
|
|
51
|
+
for (const event of events) {
|
|
52
|
+
if (event.type === "throttle")
|
|
53
|
+
rows.push([formatTime(event.ts), "pause for everybody", `${event.delayMs} ms`]);
|
|
54
|
+
if (event.type === "quota")
|
|
55
|
+
rows.push([formatTime(event.ts), "stop", escapeHtml(event.message)]);
|
|
56
|
+
if (event.type === "budget_refused")
|
|
57
|
+
rows.push([formatTime(event.ts), "budget stop", escapeHtml(event.reason)]);
|
|
58
|
+
if (event.type === "pressure_hold")
|
|
59
|
+
rows.push([
|
|
60
|
+
formatTime(event.ts),
|
|
61
|
+
event.on ? "pressure brake ON (no climb, no replacements)" : "pressure brake off",
|
|
62
|
+
`rung ${event.rung}, load per core ${event.loadPerCore.toFixed(2)}, CPU pressure ${event.cpuPressure10 ?? "-"} %`,
|
|
63
|
+
]);
|
|
64
|
+
if (event.type === "rescue")
|
|
65
|
+
rows.push([formatTime(event.ts), `rescue ${event.rescue} of agent ${event.agent}`, "stuck"]);
|
|
66
|
+
}
|
|
67
|
+
return `<h2>Throttles, stops and rescues</h2>${table(["time", "what", "detail"], rows)}`;
|
|
68
|
+
}
|
|
69
|
+
/** Warnings of the start (no review, hidden data not protected, ...), shown first so they cannot be missed. */
|
|
70
|
+
export function warningSection(events) {
|
|
71
|
+
const warnings = events.filter((event) => event.type === "warning");
|
|
72
|
+
if (warnings.length === 0)
|
|
73
|
+
return "";
|
|
74
|
+
return `<h2>Warnings</h2><ul>${warnings.map((event) => `<li><strong>${escapeHtml(event.message)}</strong></li>`).join("")}</ul>`;
|
|
75
|
+
}
|
|
76
|
+
export const pageHtml = (body) => `<!doctype html>
|
|
77
|
+
<html lang="en"><head><meta charset="utf-8"><title>Infinity Agent report</title>
|
|
78
|
+
<style>body{font:14px system-ui,sans-serif;margin:2rem auto;max-width:60rem;padding:0 1rem}table{border-collapse:collapse;width:100%;margin:.5rem 0}
|
|
79
|
+
th,td{border:1px solid #ccc;padding:.25rem .5rem;text-align:left}pre{background:#f4f4f4;padding:.75rem;overflow:auto}code{font-family:ui-monospace,monospace}</style></head>
|
|
80
|
+
<body><h1>Infinity Agent report</h1>${body}</body></html>
|
|
81
|
+
`;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { mkdirSync, rmSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { runReview } from "./review-run.js";
|
|
4
|
+
import { ReviewScheduler } from "./review-schedule.js";
|
|
5
|
+
const MAX_ERRORS_IN_A_ROW = 5;
|
|
6
|
+
/** Runs the reviews of all agents on their schedule. Failure isolation: an error is reported and ignored; five in a row switch the feature off. */
|
|
7
|
+
export class BranchReviewer {
|
|
8
|
+
options;
|
|
9
|
+
scheduler;
|
|
10
|
+
running = new Map();
|
|
11
|
+
reviewedAt = new Map();
|
|
12
|
+
stopSignal = new AbortController();
|
|
13
|
+
skipCounts = {};
|
|
14
|
+
errorsInARow = 0;
|
|
15
|
+
off = false;
|
|
16
|
+
counter = 0;
|
|
17
|
+
loop;
|
|
18
|
+
constructor(options) {
|
|
19
|
+
this.options = options;
|
|
20
|
+
this.scheduler = new ReviewScheduler(options.everyMs, options.ceiling);
|
|
21
|
+
}
|
|
22
|
+
agentStarted(agent) {
|
|
23
|
+
this.scheduler.register(agent, this.options.clock.now());
|
|
24
|
+
this.reviewedAt.delete(agent);
|
|
25
|
+
}
|
|
26
|
+
agentEnded(agent) {
|
|
27
|
+
this.scheduler.forget(agent);
|
|
28
|
+
}
|
|
29
|
+
get skips() {
|
|
30
|
+
return this.skipCounts;
|
|
31
|
+
}
|
|
32
|
+
get switchedOff() {
|
|
33
|
+
return this.off;
|
|
34
|
+
}
|
|
35
|
+
start() {
|
|
36
|
+
const tick = Math.min(10_000, Math.max(250, this.options.everyMs / this.options.ceiling / 2));
|
|
37
|
+
this.loop = (async () => {
|
|
38
|
+
while (!this.stopSignal.signal.aborted && !this.off) {
|
|
39
|
+
await this.options.clock.sleep(tick, this.stopSignal.signal).catch(() => undefined);
|
|
40
|
+
if (this.stopSignal.signal.aborted)
|
|
41
|
+
return;
|
|
42
|
+
this.check();
|
|
43
|
+
}
|
|
44
|
+
})();
|
|
45
|
+
}
|
|
46
|
+
/** One look at the schedule: starts the reviews that are due and allowed. Exposed so that tests can drive it with a fake clock. */
|
|
47
|
+
check() {
|
|
48
|
+
if (this.off)
|
|
49
|
+
return;
|
|
50
|
+
const now = this.options.clock.now();
|
|
51
|
+
for (const agent of this.scheduler.dueAgents(now)) {
|
|
52
|
+
const reason = this.skipReason(agent);
|
|
53
|
+
if (reason !== undefined) {
|
|
54
|
+
this.skipCounts[reason] = (this.skipCounts[reason] ?? 0) + 1;
|
|
55
|
+
if (reason === "limit")
|
|
56
|
+
break; // the rest would be skipped for the same reason
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
this.scheduler.begun(agent, now);
|
|
60
|
+
this.launch(agent);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
skipReason(agent) {
|
|
64
|
+
const target = this.options.target(agent);
|
|
65
|
+
if (!target)
|
|
66
|
+
return "not running";
|
|
67
|
+
if (this.running.has(agent))
|
|
68
|
+
return "already running";
|
|
69
|
+
if (this.running.size >= this.options.maxConcurrent)
|
|
70
|
+
return "limit";
|
|
71
|
+
const hold = this.options.holdReason();
|
|
72
|
+
if (hold !== undefined)
|
|
73
|
+
return "held";
|
|
74
|
+
const replies = target.replies();
|
|
75
|
+
if (replies === 0 || replies <= (this.reviewedAt.get(agent) ?? 0))
|
|
76
|
+
return "no new turn";
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
launch(agent) {
|
|
80
|
+
const target = this.options.target(agent);
|
|
81
|
+
this.reviewedAt.set(agent, target.replies());
|
|
82
|
+
const run = (this.options.review ?? runReview)({
|
|
83
|
+
target,
|
|
84
|
+
forkPath: join(this.options.dir, `${String(agent).padStart(3, "0")}-${++this.counter}.jsonl`),
|
|
85
|
+
workDir: target.workDir,
|
|
86
|
+
maxTurns: this.options.maxTurns,
|
|
87
|
+
signal: this.stopSignal.signal,
|
|
88
|
+
now: () => this.options.clock.now(),
|
|
89
|
+
...(this.options.output ? { output: this.options.output } : {}),
|
|
90
|
+
}).then((outcome) => {
|
|
91
|
+
this.running.delete(agent);
|
|
92
|
+
if (this.stopSignal.signal.aborted)
|
|
93
|
+
return;
|
|
94
|
+
this.options.onResult(agent, outcome);
|
|
95
|
+
this.errorsInARow = outcome.outcome === "error" ? this.errorsInARow + 1 : 0;
|
|
96
|
+
if (this.errorsInARow >= MAX_ERRORS_IN_A_ROW && !this.off) {
|
|
97
|
+
this.off = true;
|
|
98
|
+
this.options.onOff(`${MAX_ERRORS_IN_A_ROW} reviews failed in a row (last: ${outcome.error ?? "unknown"})`);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
this.running.set(agent, run);
|
|
102
|
+
}
|
|
103
|
+
/** Ends the loop and the reviews that are running (their fork files are deleted) and waits for them. */
|
|
104
|
+
async stop() {
|
|
105
|
+
this.stopSignal.abort();
|
|
106
|
+
await Promise.allSettled([...this.running.values(), this.loop]);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The orchestrator's whole knowledge of the branch review lives here: the defaults, where it listens (Gate pause, budget refusal, live workers) and
|
|
111
|
+
* what it writes down. `Run` only calls this once and then tells the result about agents starting and ending. A fork file left by a killed run is swept first.
|
|
112
|
+
*/
|
|
113
|
+
export function startBranchReview(deps) {
|
|
114
|
+
const { settings, layout, gate, budget, workers, record } = deps;
|
|
115
|
+
rmSync(layout.reviewDir, { recursive: true, force: true });
|
|
116
|
+
mkdirSync(layout.reviewDir, { recursive: true });
|
|
117
|
+
const reviewer = new BranchReviewer({
|
|
118
|
+
everyMs: (settings.everyMinutes ?? 7) * 60_000,
|
|
119
|
+
ceiling: deps.ceiling,
|
|
120
|
+
maxTurns: settings.maxTurns ?? 6,
|
|
121
|
+
maxConcurrent: settings.maxConcurrent ?? 3,
|
|
122
|
+
...(settings.output ? { output: settings.output } : {}),
|
|
123
|
+
clock: deps.clock,
|
|
124
|
+
dir: layout.reviewDir,
|
|
125
|
+
target: (agent) => workers.get(agent)?.reviewTarget(),
|
|
126
|
+
holdReason: () => (gate.paused ? "the Gate is paused" : budget.refusal()),
|
|
127
|
+
onResult: (agent, outcome) => record({
|
|
128
|
+
type: "review",
|
|
129
|
+
agent,
|
|
130
|
+
outcome: outcome.outcome,
|
|
131
|
+
ms: outcome.ms,
|
|
132
|
+
tokens: outcome.tokens,
|
|
133
|
+
...(outcome.cacheRead !== undefined ? { cacheRead: outcome.cacheRead } : {}),
|
|
134
|
+
...(outcome.snapshot ? { snapshot: outcome.snapshot } : {}),
|
|
135
|
+
...(outcome.text ? { text: outcome.text } : outcome.error ? { text: `error: ${outcome.error}` } : {}),
|
|
136
|
+
}),
|
|
137
|
+
onOff: (reason) => record({ type: "review_off", reason }),
|
|
138
|
+
});
|
|
139
|
+
reviewer.start();
|
|
140
|
+
return reviewer;
|
|
141
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
2
|
+
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
3
|
+
const real = (path) => {
|
|
4
|
+
let probe = resolve(path);
|
|
5
|
+
const tail = [];
|
|
6
|
+
while (!existsSync(probe) && dirname(probe) !== probe) {
|
|
7
|
+
tail.unshift(probe.slice(dirname(probe).length + 1));
|
|
8
|
+
probe = dirname(probe);
|
|
9
|
+
}
|
|
10
|
+
return join(existsSync(probe) ? realpathSync(probe) : probe, ...tail);
|
|
11
|
+
};
|
|
12
|
+
const inside = (path, directory) => path === directory || path.startsWith(directory + sep);
|
|
13
|
+
// What no agent may run, whatever the reviewer model thinks (docs/05 section 6). Deliberately plain text patterns: a miss goes on to the reviewer model.
|
|
14
|
+
const FORBIDDEN_COMMANDS = [
|
|
15
|
+
[/\bgit\b[^|;&]*\bpush\b/, "pushing code to a remote"],
|
|
16
|
+
[/\b(ssh|scp|sftp|ssh-add|ssh-keygen)\b/, "using ssh or scp"],
|
|
17
|
+
[/\brsync\b[^|;&]*\S+:\S/, "copying files to or from another machine"],
|
|
18
|
+
[/\b(pkill|killall)\b/, "killing processes by name (they may belong to others)"],
|
|
19
|
+
[/\bkill\s+(-\w+\s+)*-1\b/, "killing every process"],
|
|
20
|
+
[/\b(curl|wget)\b[^|;&]*(\s-T\b|\s-F\b|--upload-file|--form\b|--data-binary\s+@|--data-raw\s+@|\s-d\s+@|--data\s+@)/, "uploading a file"],
|
|
21
|
+
[/\b(nc|ncat|netcat|socat)\b/, "opening a raw network connection"],
|
|
22
|
+
[/(\.ssh\b|\.aws\b|\.netrc\b|\.gnupg\b|id_rsa|id_ed25519|\.git-credentials|\.config\/gcloud|\.docker\/config)/, "touching credential files"],
|
|
23
|
+
[/\b(sudo|su)\s/, "gaining other rights"],
|
|
24
|
+
];
|
|
25
|
+
/**
|
|
26
|
+
* A command that puts a job outside the framework's care: `setsid`, `nohup`, `disown`, or a lone `&` (a job in the background of the shell). In this run commands always
|
|
27
|
+
* run in the foreground (the shell tool's `background: true` is refused too), so a job that puts itself away would escape the gate, the wall limit and the cleanup. Text patterns, like the rules above.
|
|
28
|
+
*/
|
|
29
|
+
export function detachedLaunch(command) {
|
|
30
|
+
if (/(^|[\s;&|(])(setsid|nohup|disown)(\s|$|;)/.test(command))
|
|
31
|
+
return "starting a job detached from the run (setsid, nohup or disown)";
|
|
32
|
+
if (/(^|\s)&(\s|$)/.test(command))
|
|
33
|
+
return "putting a job in the background of the shell with &";
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The hard rules of code mode as an authorizer (asked after the framework's own hard rules and before the reviewer model). It only denies or passes on:
|
|
38
|
+
* the keeper, the other agents' directories, the run's own files and the evaluator are off limits for every tool, and a few kinds of command never run.
|
|
39
|
+
* It works on the text of the command and on the real path of a file tool's path (links followed); a shell can still build a path the text does not show,
|
|
40
|
+
* and then the reviewer model is the next check. It is a guard against mistakes and plain attempts, not a lock (docs/06).
|
|
41
|
+
*/
|
|
42
|
+
export function createGuardRules(options) {
|
|
43
|
+
const own = real(options.agentDir);
|
|
44
|
+
const root = real(options.runRoot);
|
|
45
|
+
const shared = real(options.sharedDir);
|
|
46
|
+
const keeper = real(options.keeperDir);
|
|
47
|
+
const forbiddenPlaces = [keeper, ...options.hiddenOriginals.map(real), ...options.protectedPaths.map(real)];
|
|
48
|
+
const otherAgent = /\bagents\/\d{3}\b/g;
|
|
49
|
+
const ownName = own.slice(own.lastIndexOf("/") + 1);
|
|
50
|
+
const placeOf = (path) => {
|
|
51
|
+
const actual = real(path);
|
|
52
|
+
if (forbiddenPlaces.some((place) => inside(actual, place)))
|
|
53
|
+
return "data or files that are hidden from the agents";
|
|
54
|
+
if (inside(actual, root) && !inside(actual, own) && !inside(actual, shared))
|
|
55
|
+
return "a place of the run that is not yours (other agents, the ledger, the state)";
|
|
56
|
+
return undefined;
|
|
57
|
+
};
|
|
58
|
+
return {
|
|
59
|
+
name: "infinity-rules",
|
|
60
|
+
async review(call, { cwd }) {
|
|
61
|
+
const args = (typeof call.args === "object" && call.args !== null ? call.args : {});
|
|
62
|
+
// our own tool: the command is only written down (and scored from the committed files); nothing is run
|
|
63
|
+
if (call.name === "submit")
|
|
64
|
+
return { kind: "allow", reason: "the submit tool of this run" };
|
|
65
|
+
if (call.name === "bash") {
|
|
66
|
+
const command = typeof args.command === "string" ? args.command : "";
|
|
67
|
+
for (const [pattern, what] of FORBIDDEN_COMMANDS)
|
|
68
|
+
if (pattern.test(command))
|
|
69
|
+
return { kind: "deny", reason: `This command looks like ${what}. It is not allowed in this run.` };
|
|
70
|
+
const detached = detachedLaunch(command);
|
|
71
|
+
if (detached)
|
|
72
|
+
return {
|
|
73
|
+
kind: "deny",
|
|
74
|
+
reason: `This command is ${detached}. Run it in the foreground: commands end by themselves here, and a job that is detached would escape the run's limits and its cleanup.`,
|
|
75
|
+
};
|
|
76
|
+
if (forbiddenPlaces.some((place) => command.includes(place)))
|
|
77
|
+
return { kind: "deny", reason: "The command names data that is hidden from the agents. It is not allowed." };
|
|
78
|
+
if (command.includes(root) && [...command.matchAll(otherAgent)].some((match) => !match[0].endsWith(ownName)))
|
|
79
|
+
return { kind: "deny", reason: "The command names another agent's directory. It is not allowed." };
|
|
80
|
+
for (const word of command.split(/[\s'"=:;|&<>()]+/)) {
|
|
81
|
+
if (word === "" || !(isAbsolute(word) || word.startsWith("../") || word === ".."))
|
|
82
|
+
continue;
|
|
83
|
+
const place = placeOf(isAbsolute(word) ? word : resolve(cwd ?? options.agentDir, word));
|
|
84
|
+
if (place)
|
|
85
|
+
return { kind: "deny", reason: `The command reaches ${place}. It is not allowed.` };
|
|
86
|
+
}
|
|
87
|
+
return { kind: "pass" };
|
|
88
|
+
}
|
|
89
|
+
const path = typeof args.path === "string" ? args.path : undefined;
|
|
90
|
+
if (path === undefined)
|
|
91
|
+
return { kind: "pass" };
|
|
92
|
+
const target = isAbsolute(path) ? path : resolve(cwd ?? options.agentDir, path);
|
|
93
|
+
const place = placeOf(target);
|
|
94
|
+
if (place)
|
|
95
|
+
return { kind: "deny", reason: `That path is ${place}. It is not allowed.` };
|
|
96
|
+
if (call.name !== "read" && inside(real(target), shared))
|
|
97
|
+
return { kind: "deny", reason: "The shared data is read-only." };
|
|
98
|
+
// writing and editing inside the agent's own directory is what it is there for (the framework's allow list says the same)
|
|
99
|
+
if ((call.name === "write" || call.name === "edit") && inside(real(target), own))
|
|
100
|
+
return { kind: "allow", reason: "inside the agent's own directory" };
|
|
101
|
+
return { kind: "pass" };
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|