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,157 @@
|
|
|
1
|
+
import { resultsOf } from "./code-leaderboard.js";
|
|
2
|
+
import { recommendCapacity } from "./capacity.js";
|
|
3
|
+
import { historyFromSamples, summarizeByRung } from "./machine-summary.js";
|
|
4
|
+
import { escapeHtml, formatTime, ladderSection, pageHtml, pressureSection, summaryHtml, summaryLines, table, warningSection } from "./report.js";
|
|
5
|
+
export function renderCodeReportHtml(rows, ledger, events, metric, machine = []) {
|
|
6
|
+
const results = resultsOf(ledger);
|
|
7
|
+
return pageHtml([
|
|
8
|
+
warningSection(events),
|
|
9
|
+
summary(rows, events, results, metric),
|
|
10
|
+
leaderboard(rows, metric),
|
|
11
|
+
bestEntry(rows, results),
|
|
12
|
+
scoreChart(results, events, metric),
|
|
13
|
+
resultList(results, metric),
|
|
14
|
+
reviewSection(events),
|
|
15
|
+
ladderSection(events),
|
|
16
|
+
machineSection(machine),
|
|
17
|
+
pressureSection(events),
|
|
18
|
+
].join("\n"));
|
|
19
|
+
}
|
|
20
|
+
function summary(rows, events, results, metric) {
|
|
21
|
+
const { task, ended } = summaryLines(events);
|
|
22
|
+
const scored = results.filter((entry) => entry.status === "ok" && !entry.selfReported).length;
|
|
23
|
+
const best = rows.find((row) => row.score !== null);
|
|
24
|
+
const leftover = events.findLast((event) => event.type === "leftover_processes");
|
|
25
|
+
const gates = ["cpu", "gpu"].flatMap((kind) => {
|
|
26
|
+
const found = events.findLast((event) => event.type === "slot_summary" && event.kind === kind);
|
|
27
|
+
return found ? [found] : [];
|
|
28
|
+
});
|
|
29
|
+
return summaryHtml([
|
|
30
|
+
task,
|
|
31
|
+
`Agents seen: ${rows.length}; submits: ${results.length} (${scored} scored by the evaluator, ${results.filter((entry) => entry.selfReported).length} self-reported, ${results.filter((entry) => entry.status === "error").length} with an error)`,
|
|
32
|
+
best
|
|
33
|
+
? `Best ${escapeHtml(metric.name)} (${metric.direction === "max" ? "higher" : "lower"} is better): ${best.score}${best.selfReported ? " (self-reported)" : ""} by agent ${best.agent}`
|
|
34
|
+
: "No scored result yet",
|
|
35
|
+
ended,
|
|
36
|
+
...gates.map((gate) => `Slot gate, ${gate.kind.toUpperCase()} (${gate.slots} slots): ${gate.commands} ${gate.kind === "gpu" ? "GPU jobs" : "heavy commands"}, ${gate.waited} waited a second or more, ` +
|
|
37
|
+
`${Math.round(gate.totalWaitMs / 1000)} s waiting in all, longest ${Math.round(gate.maxWaitMs / 1000)} s; slots busy ${Math.round(100 * gate.utilisation)} % of the time`),
|
|
38
|
+
...(leftover ? [`Processes still working in the run directory at the end: ${leftover.found} stopped (${leftover.killedHard} needed SIGKILL)`] : []),
|
|
39
|
+
]);
|
|
40
|
+
}
|
|
41
|
+
function leaderboard(rows, metric) {
|
|
42
|
+
const cells = rows.map((row) => [
|
|
43
|
+
String(row.rank),
|
|
44
|
+
String(row.agent),
|
|
45
|
+
row.score === null ? "-" : `${row.score}${row.selfReported ? " (self-reported)" : ""}`,
|
|
46
|
+
String(row.submits),
|
|
47
|
+
String(row.errors),
|
|
48
|
+
`<code>${escapeHtml(row.commit?.slice(0, 10) ?? "-")}</code>`,
|
|
49
|
+
`<code>${escapeHtml(row.workDir)}</code>`,
|
|
50
|
+
]);
|
|
51
|
+
return `<h2>Leaderboard</h2>${table(["#", "agent", escapeHtml(metric.name), "submits", "errors", "commit", "work"], cells)}`;
|
|
52
|
+
}
|
|
53
|
+
/** What the best scored submit handed in (the files it listed: the code, or the proof). */
|
|
54
|
+
function bestEntry(rows, results) {
|
|
55
|
+
const best = rows.find((row) => row.score !== null && row.commit !== null);
|
|
56
|
+
const entry = best ? results.findLast((result) => result.agent === best.agent && result.commit === best.commit && result.score === best.score) : undefined;
|
|
57
|
+
if (!best || !entry)
|
|
58
|
+
return "";
|
|
59
|
+
return `<h2>Best submit</h2><p>Agent ${best.agent}, score ${best.score}, commit <code>${escapeHtml(best.commit?.slice(0, 10) ?? "-")}</code>, command <code>${escapeHtml(entry.command.slice(0, 200))}</code></p><pre>${escapeHtml(entry.entry.slice(0, 20_000))}</pre>`;
|
|
60
|
+
}
|
|
61
|
+
const WIDTH = 720;
|
|
62
|
+
const HEIGHT = 260;
|
|
63
|
+
const PAD = 36;
|
|
64
|
+
const COLORS = ["#1f77b4", "#d62728", "#2ca02c", "#9467bd", "#ff7f0e", "#17becf", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22"];
|
|
65
|
+
/** Best score so far over time, one line per agent, drawn as inline SVG (no script). */
|
|
66
|
+
function scoreChart(results, events, metric) {
|
|
67
|
+
const points = results.filter((entry) => entry.status === "ok" && entry.score !== null && !entry.selfReported);
|
|
68
|
+
if (points.length === 0)
|
|
69
|
+
return "<h2>Score over time</h2><p><em>no scored result yet</em></p>";
|
|
70
|
+
const t0 = events.find((event) => event.type === "run_start")?.ts ?? points[0]?.ts ?? 0;
|
|
71
|
+
const t1 = Math.max(...points.map((entry) => entry.ts), t0 + 1);
|
|
72
|
+
const scores = points.map((entry) => entry.score);
|
|
73
|
+
const low = Math.min(...scores);
|
|
74
|
+
const high = Math.max(...scores);
|
|
75
|
+
const x = (ts) => PAD + ((ts - t0) / (t1 - t0)) * (WIDTH - 2 * PAD);
|
|
76
|
+
const y = (score) => HEIGHT - PAD - (high === low ? 0.5 : (score - low) / (high - low)) * (HEIGHT - 2 * PAD);
|
|
77
|
+
const byAgent = new Map();
|
|
78
|
+
for (const entry of points)
|
|
79
|
+
byAgent.set(entry.agent, [...(byAgent.get(entry.agent) ?? []), entry]);
|
|
80
|
+
const lines = [...byAgent].map(([agent, entries], index) => {
|
|
81
|
+
let best;
|
|
82
|
+
const path = entries
|
|
83
|
+
.map((entry) => {
|
|
84
|
+
const score = entry.score;
|
|
85
|
+
if (best === undefined || (metric.direction === "max" ? score > best : score < best))
|
|
86
|
+
best = score;
|
|
87
|
+
return `${x(entry.ts).toFixed(1)},${y(best).toFixed(1)}`;
|
|
88
|
+
})
|
|
89
|
+
.join(" ");
|
|
90
|
+
const color = COLORS[index % COLORS.length];
|
|
91
|
+
return `<polyline fill="none" stroke="${color}" stroke-width="1.5" points="${path}"><title>agent ${agent}</title></polyline>`;
|
|
92
|
+
});
|
|
93
|
+
const axis = `<text x="4" y="${PAD}" font-size="11">${high}</text><text x="4" y="${HEIGHT - PAD}" font-size="11">${low}</text><text x="${PAD}" y="${HEIGHT - 8}" font-size="11">${formatTime(t0)}</text><text x="${WIDTH - PAD - 40}" y="${HEIGHT - 8}" font-size="11">${formatTime(t1)}</text>`;
|
|
94
|
+
return `<h2>Score over time</h2><p>Best ${escapeHtml(metric.name)} so far, one line per agent (hover for the agent).</p><svg viewBox="0 0 ${WIDTH} ${HEIGHT}" width="100%" role="img">${axis}${lines.join("")}</svg>`;
|
|
95
|
+
}
|
|
96
|
+
function resultList(results, metric) {
|
|
97
|
+
const latest = results.slice(-40).reverse();
|
|
98
|
+
const cells = latest.map((entry) => [
|
|
99
|
+
formatTime(entry.ts),
|
|
100
|
+
String(entry.agent),
|
|
101
|
+
entry.status === "ok" ? `${entry.score}${entry.selfReported ? " (self-reported)" : ""}` : `<strong>error</strong>`,
|
|
102
|
+
`<code>${escapeHtml(entry.command.slice(0, 120))}</code>`,
|
|
103
|
+
escapeHtml(entry.details.slice(0, 160)),
|
|
104
|
+
]);
|
|
105
|
+
return `<h2>Latest submits</h2>${table(["time", "agent", escapeHtml(metric.name), "command", "details"], cells)}`;
|
|
106
|
+
}
|
|
107
|
+
/** Branch reviews: how many, what came of them, what they cost, and every steer next to the time it happened (docs/10 section 1.3). */
|
|
108
|
+
function reviewSection(events) {
|
|
109
|
+
const reviews = events.filter((event) => event.type === "review");
|
|
110
|
+
const off = events.find((event) => event.type === "review_off");
|
|
111
|
+
const skips = events.findLast((event) => event.type === "review_skips");
|
|
112
|
+
if (reviews.length === 0 && !off && !skips)
|
|
113
|
+
return "";
|
|
114
|
+
const count = (outcome) => reviews.filter((review) => review.outcome === outcome).length;
|
|
115
|
+
const tokens = reviews.reduce((sum, review) => sum + review.tokens, 0);
|
|
116
|
+
const cached = reviews.reduce((sum, review) => sum + (review.cacheRead ?? 0), 0);
|
|
117
|
+
const lines = [
|
|
118
|
+
`Reviews: ${reviews.length} (${count("ok")} nothing to say, ${count("steer")} advice sent, ${count("error")} failed); ${tokens} tokens (also counted in the total), ${tokens > 0 ? Math.round((100 * cached) / tokens) : 0} % of them served from the provider's cache.`,
|
|
119
|
+
skips
|
|
120
|
+
? `Skipped checks: ${Object.entries(skips.skips)
|
|
121
|
+
.map(([reason, n]) => `${escapeHtml(reason)} ${n}`)
|
|
122
|
+
.join(", ") || "none"}.`
|
|
123
|
+
: "",
|
|
124
|
+
off ? `<strong>Switched off at ${formatTime(off.ts)}: ${escapeHtml(off.reason)}</strong>` : "",
|
|
125
|
+
].filter(Boolean);
|
|
126
|
+
const steers = reviews
|
|
127
|
+
.filter((review) => review.outcome === "steer")
|
|
128
|
+
.map((review) => [formatTime(review.ts), String(review.agent), escapeHtml(review.text ?? "")]);
|
|
129
|
+
return `<h2>Reviews</h2><ul>${lines.map((line) => `<li>${line}</li>`).join("")}</ul>${table(["time", "agent", "advice sent to the agent"], steers)}`;
|
|
130
|
+
}
|
|
131
|
+
/** The machine by rung (mean and peak), and the rule-of-thumb agent count. The count is a hint for the next run; nothing applies it. */
|
|
132
|
+
function machineSection(samples) {
|
|
133
|
+
if (samples.length === 0)
|
|
134
|
+
return "";
|
|
135
|
+
const gated = samples.some((sample) => sample.slotsInUse !== null && sample.slotsInUse !== undefined);
|
|
136
|
+
const gpuGated = samples.some((sample) => sample.gpuSlotsInUse !== null && sample.gpuSlotsInUse !== undefined);
|
|
137
|
+
const rows = summarizeByRung(samples).map((row) => [
|
|
138
|
+
String(row.rung),
|
|
139
|
+
String(row.samples),
|
|
140
|
+
`${row.loadMean.toFixed(1)} / ${row.loadPeak.toFixed(1)}`,
|
|
141
|
+
row.cpuMean === null ? "-" : `${Math.round(100 * row.cpuMean)} % / ${Math.round(100 * (row.cpuPeak ?? 0))} %`,
|
|
142
|
+
`${(row.memPeakMb / 1024).toFixed(1)} GB`,
|
|
143
|
+
row.gpuMemPeakMb === null ? "-" : `${(row.gpuMemPeakMb / 1024).toFixed(1)} GB`,
|
|
144
|
+
row.pressureMean === null ? "-" : `${row.pressureMean.toFixed(1)} %`,
|
|
145
|
+
row.runCoresMean === null ? "-" : row.runCoresMean.toFixed(1),
|
|
146
|
+
row.runRssPeakMb === null ? "-" : `${(row.runRssPeakMb / 1024).toFixed(1)} GB`,
|
|
147
|
+
row.jobsMean === null ? "-" : `${row.jobsMean.toFixed(1)} / ${row.jobsPeak}`,
|
|
148
|
+
...(gated ? [row.slotsUseMean === null ? "-" : `${row.slotsUseMean.toFixed(1)} / ${(row.slotsWaitMean ?? 0).toFixed(1)}`] : []),
|
|
149
|
+
...(gpuGated ? [row.gpuSlotsUseMean === null ? "-" : `${row.gpuSlotsUseMean.toFixed(1)} / ${(row.gpuSlotsWaitMean ?? 0).toFixed(1)}`] : []),
|
|
150
|
+
]);
|
|
151
|
+
const first = samples[0];
|
|
152
|
+
const history = historyFromSamples(samples);
|
|
153
|
+
const hint = recommendCapacity({ cores: first.cores, freeMemMb: first.memAvailableMb }, undefined, history);
|
|
154
|
+
const basis = hint.source === "history" ? `measured in this run, limited by ${hint.limitedBy}` : "one per core: this run recorded no per-agent figures";
|
|
155
|
+
const note = `<p>Rule of thumb for the next run (not applied by anything): ${hint.agents} agents (${basis}; more than ${hint.maxUseful} adds little).</p>`;
|
|
156
|
+
return `<h2>Machine by rung</h2>${table(["rung", "samples", "load (mean / peak)", "CPU busy (mean / peak)", "memory peak", "GPU memory peak", "CPU pressure (mean)", "run CPU cores (mean)", "run memory peak", "python jobs (mean / peak)", ...(gated ? ["gate slots in use / waiting (mean)"] : []), ...(gpuGated ? ["GPU slots in use / waiting (mean)"] : [])], rows)}${note}`;
|
|
157
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** Which shell commands are cheap and which are heavy (docs/16 section C, docs/18): the table and the classifier, with nothing else in the file. */
|
|
2
|
+
// Commands that cannot hold a CPU for long. Not "read only" in the strict sense: making a directory or committing is cheap and must not wait behind a training job.
|
|
3
|
+
const LIGHT = new Set([
|
|
4
|
+
...["ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "wc", "pwd", "echo", "printf", "sleep", "true", "false", "test", "[", "cd", "stat", "file"],
|
|
5
|
+
...["du", "df", "which", "type", "date", "env", "printenv", "basename", "dirname", "realpath", "readlink", "sort", "uniq", "cut", "tr", "diff", "cmp", "nl"],
|
|
6
|
+
...["mkdir", "touch", "cp", "mv", "rm", "ln", "chmod", "tee", "export", "set", "unset", "wait", "nproc", "uname", "id", "whoami", "ps", "kill", "tree"],
|
|
7
|
+
]);
|
|
8
|
+
const LIGHT_GIT = new Set([
|
|
9
|
+
"status",
|
|
10
|
+
"log",
|
|
11
|
+
"diff",
|
|
12
|
+
"show",
|
|
13
|
+
"branch",
|
|
14
|
+
"rev-parse",
|
|
15
|
+
"ls-files",
|
|
16
|
+
"add",
|
|
17
|
+
"commit",
|
|
18
|
+
"init",
|
|
19
|
+
"config",
|
|
20
|
+
"checkout",
|
|
21
|
+
"tag",
|
|
22
|
+
"stash",
|
|
23
|
+
"restore",
|
|
24
|
+
"reset",
|
|
25
|
+
]);
|
|
26
|
+
/** True when every part of the command is a cheap one. Anything with a command substitution, an unknown program, a script or an interpreter counts as heavy. */
|
|
27
|
+
export function isLightCommand(command) {
|
|
28
|
+
if (command.includes("$(") || command.includes("`"))
|
|
29
|
+
return false;
|
|
30
|
+
const parts = command.split(/;|&&|\|\||\||\n|&/).map((part) => part.trim().replace(/^[({]+\s*/, ""));
|
|
31
|
+
let any = false;
|
|
32
|
+
for (const part of parts) {
|
|
33
|
+
if (part === "")
|
|
34
|
+
continue;
|
|
35
|
+
const words = part.split(/\s+/).filter((word) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(word));
|
|
36
|
+
const program = (words[0] ?? "").split("/").pop() ?? "";
|
|
37
|
+
if (program === "")
|
|
38
|
+
continue; // only assignments
|
|
39
|
+
any = true;
|
|
40
|
+
if (program === "git") {
|
|
41
|
+
if (!LIGHT_GIT.has(words.find((word, index) => index > 0 && !word.startsWith("-")) ?? ""))
|
|
42
|
+
return false;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (program === "sed" || program === "awk") {
|
|
46
|
+
if (words.some((word) => /^-i/.test(word) || word === "--in-place"))
|
|
47
|
+
return false;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (program === "find") {
|
|
51
|
+
if (words.some((word) => ["-exec", "-execdir", "-delete", "-ok"].includes(word)))
|
|
52
|
+
return false;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!LIGHT.has(program))
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
return any;
|
|
59
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createLocalEnvironment } from "sakura-agent";
|
|
2
|
+
import { cpuOf } from "./capacity.js";
|
|
3
|
+
import { binDirOf } from "./run-layout.js";
|
|
4
|
+
const THREAD_VARIABLES = ["OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS"];
|
|
5
|
+
const DEFAULT_NICE = 10;
|
|
6
|
+
export const limitsOf = (profile) => ({
|
|
7
|
+
threadsPerJob: cpuOf(profile).threadsPerJob,
|
|
8
|
+
...(profile?.kind === "gpu" ? { gpu: true } : {}),
|
|
9
|
+
});
|
|
10
|
+
const quote = (text) => `'${text.replaceAll("'", `'\\''`)}'`;
|
|
11
|
+
/**
|
|
12
|
+
* The text that goes in front of a command: the thread variables, and a lower priority for the shell (niceness set to the level before the command starts; its children inherit it).
|
|
13
|
+
* For a GPU task also: no GPU visible, the run's `gpu` shim on the PATH, and the agent's number for the shim's log. `context` is the run directory and the agent.
|
|
14
|
+
*/
|
|
15
|
+
export function limitPrefix(limits, context) {
|
|
16
|
+
const threads = Math.max(1, Math.floor(limits.threadsPerJob));
|
|
17
|
+
const nice = limits.niceLevel ?? DEFAULT_NICE;
|
|
18
|
+
const exports = [...THREAD_VARIABLES.map((name) => `${name}=${threads}`)];
|
|
19
|
+
if (limits.gpu && context)
|
|
20
|
+
exports.push("CUDA_VISIBLE_DEVICES=-1", `INFINITY_AGENT=${context.agent}`, `PATH=${quote(binDirOf(context.root))}:"$PATH"`);
|
|
21
|
+
const line = `export ${exports.join(" ")}; `;
|
|
22
|
+
// once per shell: in the shell that stays (Sakura's foreground commands) a second renice would add to the first where -n is an increment
|
|
23
|
+
return nice > 0 ? `${line}[ "\${INFINITY_NICED:-}" = 1 ] || { renice -n ${Math.floor(nice)} -p $$ >/dev/null 2>&1; INFINITY_NICED=1; }; ` : line;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The same environment, with the limits in front of every command. Nothing in the framework changes: this is the `createEnvironment` option.
|
|
27
|
+
* The agent's own script can still set a variable again; this is guidance that works for every program that reads the variables, not a lock.
|
|
28
|
+
*/
|
|
29
|
+
export function limitCommands(env, limits, context) {
|
|
30
|
+
const prefix = limitPrefix(limits, context);
|
|
31
|
+
const wrap = (command) => `${prefix}${command}`;
|
|
32
|
+
return {
|
|
33
|
+
...env,
|
|
34
|
+
exec: (command, options) => env.exec(wrap(command), options),
|
|
35
|
+
spawn: (command, options) => env.spawn(wrap(command), options),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** The agent number and the run directory in a work directory of a run (`<run>/agents/NNN/work`); agent 0 when it cannot be told. */
|
|
39
|
+
export function runPlaceOf(workDir) {
|
|
40
|
+
const found = /^(.*)\/agents\/(\d+)\/work/.exec(workDir);
|
|
41
|
+
return { root: found?.[1] ?? workDir, agent: Number(found?.[2] ?? 0) };
|
|
42
|
+
}
|
|
43
|
+
/** The environment factory of a run with these limits; `base` makes the underlying environment (default: this machine). */
|
|
44
|
+
export function limitedEnvironment(limits, base = ({ workDir }) => createLocalEnvironment(workDir)) {
|
|
45
|
+
return (paths) => limitCommands(base(paths), limits, runPlaceOf(paths.workDir));
|
|
46
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { commitAll } from "./work-repo.js";
|
|
2
|
+
/**
|
|
3
|
+
* Commits the work directory after every turn. It observes the `turn_end` event, so it runs from the orchestrator's side and
|
|
4
|
+
* not through the agent's tools. Commits are queued one after another; a failing git is reported and ignored.
|
|
5
|
+
*/
|
|
6
|
+
export function commitPlugin(options) {
|
|
7
|
+
let turn = 0;
|
|
8
|
+
let queue = Promise.resolve();
|
|
9
|
+
const commit = async (message, turnNumber) => {
|
|
10
|
+
try {
|
|
11
|
+
const id = await commitAll(options.dir, message);
|
|
12
|
+
if (id !== undefined)
|
|
13
|
+
options.onCommit?.(id, turnNumber);
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
options.onError?.(error, message);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
name: "infinity-commit",
|
|
21
|
+
setup(api) {
|
|
22
|
+
api.on("event", (event) => {
|
|
23
|
+
if (event.type !== "turn_end")
|
|
24
|
+
return;
|
|
25
|
+
turn += 1;
|
|
26
|
+
const turnNumber = turn;
|
|
27
|
+
queue = queue.then(() => commit(`turn ${turnNumber}`, turnNumber));
|
|
28
|
+
});
|
|
29
|
+
},
|
|
30
|
+
flush: () => queue,
|
|
31
|
+
checkpoint() {
|
|
32
|
+
queue = queue.then(() => commit("checkpoint", turn));
|
|
33
|
+
return queue;
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/src/csv.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A CSV text: the header, then one line per row; a cell with a comma, a quote or a line break is quoted. */
|
|
2
|
+
export function renderCsv(header, rows) {
|
|
3
|
+
const cell = (value) => {
|
|
4
|
+
const text = value === null ? "" : String(value);
|
|
5
|
+
return /[",\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
|
6
|
+
};
|
|
7
|
+
return `${[header.join(","), ...rows.map((row) => row.map(cell).join(","))].join("\n")}\n`;
|
|
8
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { GpuLedger, gpuShim } from "./gpu-shim.js";
|
|
2
|
+
import { leftoverStopper } from "./leftover.js";
|
|
3
|
+
import { NO_GATE, machineSampler } from "./machine-sampler.js";
|
|
4
|
+
import { slotGate } from "./slot-gate.js";
|
|
5
|
+
/** The one place that names the components a run has unless the caller gives its own list. */
|
|
6
|
+
export function defaultComponents(options = {}) {
|
|
7
|
+
const gpuSlots = options.gpuSlotMap?.length ?? 0;
|
|
8
|
+
const ledger = gpuSlots > 0 ? new GpuLedger(gpuSlots) : undefined;
|
|
9
|
+
const gate = {
|
|
10
|
+
...NO_GATE,
|
|
11
|
+
enabled: options.gate !== undefined,
|
|
12
|
+
cpuSlots: options.gate?.capacity ?? null,
|
|
13
|
+
gpuSlots: gpuSlots > 0 ? gpuSlots : null,
|
|
14
|
+
commandTimeoutMinutes: options.commandTimeoutMinutes ?? null,
|
|
15
|
+
};
|
|
16
|
+
const gate0 = options.gate;
|
|
17
|
+
return [
|
|
18
|
+
machineSampler({
|
|
19
|
+
gate,
|
|
20
|
+
...(options.notes ? { notes: options.notes } : {}),
|
|
21
|
+
needsGpu: gpuSlots > 0,
|
|
22
|
+
slots: () => ({
|
|
23
|
+
...(gate0 ? { cpu: { inUse: gate0.inUse, waiting: gate0.waiting } } : {}),
|
|
24
|
+
...(ledger ? { gpu: { inUse: ledger.inUse, waiting: ledger.waiting } } : {}),
|
|
25
|
+
}),
|
|
26
|
+
...(options.pressureBrake ? { brake: options.pressureBrake === true ? {} : options.pressureBrake } : {}),
|
|
27
|
+
...(options.ceiling === undefined ? {} : { ceiling: options.ceiling }),
|
|
28
|
+
...(options.commandLine === undefined ? {} : { commandLine: options.commandLine }),
|
|
29
|
+
...(options.foreignBusyCores === undefined ? {} : { foreignBusyCores: options.foreignBusyCores }),
|
|
30
|
+
}),
|
|
31
|
+
leftoverStopper(),
|
|
32
|
+
...(options.gate ? [slotGate(options.gate)] : []),
|
|
33
|
+
...(ledger ? [gpuShim({ slotMap: options.gpuSlotMap ?? [], ledger })] : []),
|
|
34
|
+
];
|
|
35
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Counts events inside a sliding window. `note` says true when `threshold` events have happened within `windowMs`, and starts counting again.
|
|
3
|
+
* Pure: the caller passes the time.
|
|
4
|
+
*/
|
|
5
|
+
export class ClusterDetector {
|
|
6
|
+
times = [];
|
|
7
|
+
threshold;
|
|
8
|
+
windowMs;
|
|
9
|
+
constructor(threshold, windowMs) {
|
|
10
|
+
this.threshold = threshold;
|
|
11
|
+
this.windowMs = windowMs;
|
|
12
|
+
}
|
|
13
|
+
note(now) {
|
|
14
|
+
this.times = [...this.times.filter((time) => now - time < this.windowMs), now];
|
|
15
|
+
if (this.times.length < this.threshold)
|
|
16
|
+
return false;
|
|
17
|
+
this.times = [];
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
const MAX_CAPTURE = 20_000;
|
|
3
|
+
const DEFAULT_TIMEOUT_MS = 10 * 60_000;
|
|
4
|
+
/**
|
|
5
|
+
* An evaluator that is a program (a Python script, say). It is started with the work directory, the commit and the private paths of the hidden
|
|
6
|
+
* data in the variables INFINITY_WORK_DIR, INFINITY_COMMIT and INFINITY_HIDDEN_0, INFINITY_HIDDEN_1, ..., and must print a JSON object
|
|
7
|
+
* `{"score": 0.93, "metrics": {...}, "details": "..."}` as the last line of its standard output. Any other ending is an error result.
|
|
8
|
+
*/
|
|
9
|
+
export function commandEvaluator(options) {
|
|
10
|
+
return (context) => runProgram(options, context);
|
|
11
|
+
}
|
|
12
|
+
function runProgram(options, context) {
|
|
13
|
+
const env = {
|
|
14
|
+
...(process.env.PATH ? { PATH: process.env.PATH } : {}),
|
|
15
|
+
...(process.env.HOME ? { HOME: process.env.HOME } : {}),
|
|
16
|
+
LANG: process.env.LANG ?? "C.UTF-8",
|
|
17
|
+
INFINITY_WORK_DIR: context.workDir,
|
|
18
|
+
INFINITY_COMMIT: context.commit ?? "",
|
|
19
|
+
...Object.fromEntries(context.hidden.map((path, index) => [`INFINITY_HIDDEN_${index}`, path])),
|
|
20
|
+
...options.env,
|
|
21
|
+
};
|
|
22
|
+
return new Promise((resolve) => {
|
|
23
|
+
const child = spawn(options.file, options.args ?? [], { cwd: options.cwd ?? context.workDir, env, stdio: ["ignore", "pipe", "pipe"], detached: true });
|
|
24
|
+
let out = "";
|
|
25
|
+
let err = "";
|
|
26
|
+
let timedOut = false;
|
|
27
|
+
const killGroup = () => {
|
|
28
|
+
try {
|
|
29
|
+
if (child.pid !== undefined)
|
|
30
|
+
process.kill(-child.pid, "SIGKILL");
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// already gone
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
child.stdout.on("data", (chunk) => {
|
|
37
|
+
out = (out + chunk.toString("utf8")).slice(-MAX_CAPTURE);
|
|
38
|
+
});
|
|
39
|
+
child.stderr.on("data", (chunk) => {
|
|
40
|
+
err = (err + chunk.toString("utf8")).slice(-MAX_CAPTURE);
|
|
41
|
+
});
|
|
42
|
+
const timer = setTimeout(() => {
|
|
43
|
+
timedOut = true;
|
|
44
|
+
killGroup();
|
|
45
|
+
}, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
46
|
+
context.signal.addEventListener("abort", killGroup, { once: true });
|
|
47
|
+
const settle = (result) => {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
context.signal.removeEventListener("abort", killGroup);
|
|
50
|
+
resolve(result);
|
|
51
|
+
};
|
|
52
|
+
child.on("error", (error) => settle(failure(`the evaluator could not be started: ${error.message}`)));
|
|
53
|
+
child.on("close", (code) => {
|
|
54
|
+
if (timedOut)
|
|
55
|
+
return settle(failure(`the evaluator did not finish in time (${Math.round((options.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1000)} s)`));
|
|
56
|
+
if (context.signal.aborted)
|
|
57
|
+
return settle(failure("the evaluation was cancelled"));
|
|
58
|
+
if (code !== 0)
|
|
59
|
+
return settle(failure(`the evaluator failed (exit ${code}): ${tail(err || out)}`));
|
|
60
|
+
settle(parseResult(out));
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
const tail = (text) => text.trim().split("\n").slice(-6).join("\n").slice(-800);
|
|
65
|
+
function failure(details) {
|
|
66
|
+
return { status: "error", score: null, metrics: {}, details };
|
|
67
|
+
}
|
|
68
|
+
/** The last non-empty line of the output must be the JSON object. */
|
|
69
|
+
export function parseResult(output) {
|
|
70
|
+
const line = output
|
|
71
|
+
.trim()
|
|
72
|
+
.split("\n")
|
|
73
|
+
.findLast((candidate) => candidate.trim() !== "");
|
|
74
|
+
try {
|
|
75
|
+
const value = JSON.parse(line ?? "");
|
|
76
|
+
if (typeof value.score !== "number" || !Number.isFinite(value.score))
|
|
77
|
+
return failure("the evaluator's answer has no numeric 'score'");
|
|
78
|
+
const metrics = Object.fromEntries(Object.entries((value.metrics ?? {})).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])));
|
|
79
|
+
return { status: "ok", score: value.score, metrics, details: typeof value.details === "string" ? value.details : "" };
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return failure(`the evaluator's last output line is not JSON: ${tail(output)}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
package/dist/src/form.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { isAbsolute, resolve } from "node:path";
|
|
2
|
+
import { cpuOf, profileProblems } from "./capacity.js";
|
|
3
|
+
import { commandEvaluator } from "./evaluation.js";
|
|
4
|
+
import { defineTask } from "./task.js";
|
|
5
|
+
const KEYS = [
|
|
6
|
+
"preset",
|
|
7
|
+
"name",
|
|
8
|
+
"summary",
|
|
9
|
+
"prompt",
|
|
10
|
+
"statement",
|
|
11
|
+
"data",
|
|
12
|
+
"hidden",
|
|
13
|
+
"evaluate",
|
|
14
|
+
"metric",
|
|
15
|
+
"stop",
|
|
16
|
+
"review",
|
|
17
|
+
"branchReview",
|
|
18
|
+
"tokens",
|
|
19
|
+
"wallMinutes",
|
|
20
|
+
"profile",
|
|
21
|
+
"evalSlots",
|
|
22
|
+
"submitIntervalMinutes",
|
|
23
|
+
"evalTimeoutMinutes",
|
|
24
|
+
"leanPool",
|
|
25
|
+
"sandbox",
|
|
26
|
+
"stuckMinutes",
|
|
27
|
+
"hints",
|
|
28
|
+
"workDirGb",
|
|
29
|
+
];
|
|
30
|
+
const CODE_ONLY = ["workDirGb", "data", "hidden", "evaluate", "metric", "review", "branchReview", "evalSlots", "submitIntervalMinutes", "evalTimeoutMinutes"];
|
|
31
|
+
const MATH_ONLY = ["statement", "leanPool", "sandbox"];
|
|
32
|
+
const isText = (value) => typeof value === "string" && value.trim() !== "";
|
|
33
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
34
|
+
/** What is wrong with something that should be a form, as words (empty when it is fine). Works on parsed JSON as well as on a TypeScript object. */
|
|
35
|
+
export function formProblems(raw) {
|
|
36
|
+
if (!isRecord(raw))
|
|
37
|
+
return ["a form must be an object"];
|
|
38
|
+
const problems = [];
|
|
39
|
+
for (const key of Object.keys(raw))
|
|
40
|
+
if (!KEYS.includes(key))
|
|
41
|
+
problems.push(`unknown field '${key}' (fields: ${KEYS.join(", ")})`);
|
|
42
|
+
if (raw.preset !== "code" && raw.preset !== "math")
|
|
43
|
+
problems.push("preset must be 'code' or 'math'");
|
|
44
|
+
if (!isText(raw.name))
|
|
45
|
+
problems.push("name is required");
|
|
46
|
+
const preset = raw.preset;
|
|
47
|
+
if (preset === "code") {
|
|
48
|
+
if (!isText(raw.prompt))
|
|
49
|
+
problems.push("prompt is required for the code preset: say what the agents are to do");
|
|
50
|
+
for (const key of MATH_ONLY)
|
|
51
|
+
if (raw[key] !== undefined)
|
|
52
|
+
problems.push(`'${key}' belongs to the math preset`);
|
|
53
|
+
if (raw.stop === "first-success")
|
|
54
|
+
problems.push("stop 'first-success' belongs to the math preset");
|
|
55
|
+
}
|
|
56
|
+
if (preset === "math") {
|
|
57
|
+
if (!isText(raw.statement))
|
|
58
|
+
problems.push("statement is required for the math preset");
|
|
59
|
+
for (const key of CODE_ONLY)
|
|
60
|
+
if (raw[key] !== undefined)
|
|
61
|
+
problems.push(`'${key}' belongs to the code preset`);
|
|
62
|
+
if (isRecord(raw.stop))
|
|
63
|
+
problems.push("a target score belongs to the code preset");
|
|
64
|
+
if (raw.stop === "until-stopped")
|
|
65
|
+
problems.push("a math task stops at the first accepted proof: leave out stop");
|
|
66
|
+
}
|
|
67
|
+
const evaluate = raw.evaluate;
|
|
68
|
+
if (evaluate !== undefined && typeof evaluate !== "function") {
|
|
69
|
+
if (!isRecord(evaluate) || !isText(evaluate.program))
|
|
70
|
+
problems.push("evaluate must be a function or { program, run?, args?, timeoutMinutes? }");
|
|
71
|
+
else {
|
|
72
|
+
for (const key of Object.keys(evaluate))
|
|
73
|
+
if (!["program", "run", "args", "timeoutMinutes"].includes(key))
|
|
74
|
+
problems.push(`evaluate: unknown field '${key}'`);
|
|
75
|
+
if (evaluate.run !== undefined && !isText(evaluate.run))
|
|
76
|
+
problems.push("evaluate.run must be a program name such as 'python3'");
|
|
77
|
+
if (evaluate.args !== undefined && !(Array.isArray(evaluate.args) && evaluate.args.every((item) => typeof item === "string")))
|
|
78
|
+
problems.push("evaluate.args must be a list of text");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const metric = raw.metric;
|
|
82
|
+
if (metric !== undefined && !(isRecord(metric) && isText(metric.name) && (metric.direction === "max" || metric.direction === "min")))
|
|
83
|
+
problems.push("metric must be { name, direction: 'max' | 'min' }");
|
|
84
|
+
if (evaluate !== undefined && metric === undefined)
|
|
85
|
+
problems.push("metric is required with evaluate");
|
|
86
|
+
if (metric !== undefined && evaluate === undefined)
|
|
87
|
+
problems.push("metric needs an evaluate");
|
|
88
|
+
const stop = raw.stop;
|
|
89
|
+
if (isRecord(stop) && !(Object.keys(stop).length === 1 && typeof stop.targetScore === "number" && Number.isFinite(stop.targetScore)))
|
|
90
|
+
problems.push("stop must be 'until-stopped', 'first-success' or { targetScore: number }");
|
|
91
|
+
if (isRecord(stop) && metric === undefined)
|
|
92
|
+
problems.push("stop.targetScore needs a metric");
|
|
93
|
+
if (raw.data !== undefined && !(isRecord(raw.data) && Object.values(raw.data).every(isText)))
|
|
94
|
+
problems.push("data must map a name to a path");
|
|
95
|
+
if (raw.hidden !== undefined && !(Array.isArray(raw.hidden) && raw.hidden.every(isText)))
|
|
96
|
+
problems.push("hidden must be a list of paths");
|
|
97
|
+
if (raw.hints !== undefined && !(Array.isArray(raw.hints) && raw.hints.length > 0 && raw.hints.every(isText)))
|
|
98
|
+
problems.push("hints must be a non-empty list of text, one per agent");
|
|
99
|
+
if (isRecord(raw.profile))
|
|
100
|
+
problems.push(...profileProblems(raw.profile));
|
|
101
|
+
for (const key of ["workDirGb", "tokens", "wallMinutes", "evalSlots", "evalTimeoutMinutes", "leanPool", "stuckMinutes"])
|
|
102
|
+
if (raw[key] !== undefined && !(typeof raw[key] === "number" && raw[key] > 0))
|
|
103
|
+
problems.push(`${key} must be a number above 0`);
|
|
104
|
+
if (raw.submitIntervalMinutes !== undefined && !(typeof raw.submitIntervalMinutes === "number" && raw.submitIntervalMinutes >= 0))
|
|
105
|
+
problems.push("submitIntervalMinutes must not be negative");
|
|
106
|
+
return problems;
|
|
107
|
+
}
|
|
108
|
+
/** For TypeScript forms: checks the form at once, with every problem named, and returns it. */
|
|
109
|
+
export function defineForm(form) {
|
|
110
|
+
const problems = formProblems(form);
|
|
111
|
+
if (problems.length > 0)
|
|
112
|
+
throw new Error(`Invalid form '${form.name ?? "?"}': ${problems.join("; ")}`);
|
|
113
|
+
return form;
|
|
114
|
+
}
|
|
115
|
+
/** Is this module export a form (and not already a task package)? */
|
|
116
|
+
export const looksLikeForm = (value) => isRecord(value) && typeof value.preset === "string" && typeof value.build !== "function";
|
|
117
|
+
/** The task package of a form. `baseDir` is the folder of the form file: relative paths in the form are relative to it. */
|
|
118
|
+
export function formPackage(form, baseDir) {
|
|
119
|
+
const problems = formProblems(form);
|
|
120
|
+
if (problems.length > 0)
|
|
121
|
+
throw new Error(`Invalid form '${form.name}': ${problems.join("; ")}`);
|
|
122
|
+
const path = (value) => (isAbsolute(value) ? value : resolve(baseDir, value));
|
|
123
|
+
const summary = form.summary ?? (form.preset === "math" ? `Prove "${form.statement}" in Lean 4` : (form.prompt ?? "").slice(0, 100));
|
|
124
|
+
const defaults = {
|
|
125
|
+
...(form.tokens === undefined ? {} : { tokens: form.tokens }),
|
|
126
|
+
...(form.wallMinutes === undefined ? {} : { wallMinutes: form.wallMinutes }),
|
|
127
|
+
};
|
|
128
|
+
return {
|
|
129
|
+
name: form.name,
|
|
130
|
+
summary,
|
|
131
|
+
...(form.profile ? { profile: form.profile } : {}),
|
|
132
|
+
defaults,
|
|
133
|
+
build({ agents, profile, model, tokens, branchReview, commandMinutes, runsDir }) {
|
|
134
|
+
const common = {
|
|
135
|
+
name: form.name,
|
|
136
|
+
agents,
|
|
137
|
+
model,
|
|
138
|
+
...(tokens === undefined ? {} : { tokens }),
|
|
139
|
+
...(form.stuckMinutes === undefined ? {} : { stuckMinutes: form.stuckMinutes }),
|
|
140
|
+
...(form.hints === undefined ? {} : { hints: form.hints.map((hint) => hint.trim()) }),
|
|
141
|
+
runsDir,
|
|
142
|
+
};
|
|
143
|
+
if (form.preset === "math")
|
|
144
|
+
return defineTask({
|
|
145
|
+
...common,
|
|
146
|
+
tools: {
|
|
147
|
+
kind: "lean",
|
|
148
|
+
statement: form.statement,
|
|
149
|
+
...(form.leanPool === undefined ? {} : { leanPool: form.leanPool }),
|
|
150
|
+
sandbox: form.sandbox ?? false,
|
|
151
|
+
},
|
|
152
|
+
...(form.prompt === undefined ? {} : { prompt: form.prompt }),
|
|
153
|
+
});
|
|
154
|
+
const program = typeof form.evaluate === "object" ? path(form.evaluate.program) : undefined;
|
|
155
|
+
const evaluate = typeof form.evaluate === "function"
|
|
156
|
+
? form.evaluate
|
|
157
|
+
: form.evaluate && program
|
|
158
|
+
? commandEvaluator({
|
|
159
|
+
file: form.evaluate.run ?? program,
|
|
160
|
+
args: form.evaluate.run ? [program, ...(form.evaluate.args ?? [])] : [...(form.evaluate.args ?? [])],
|
|
161
|
+
timeoutMs: (form.evaluate.timeoutMinutes ?? 5) * 60_000,
|
|
162
|
+
})
|
|
163
|
+
: undefined;
|
|
164
|
+
const prompt = withMachineLimits(form.prompt, profile);
|
|
165
|
+
return defineTask({
|
|
166
|
+
...common,
|
|
167
|
+
tools: { kind: "shell" },
|
|
168
|
+
prompt,
|
|
169
|
+
...(form.data ? { files: Object.fromEntries(Object.entries(form.data).map(([name, value]) => [name, path(value)])) } : {}),
|
|
170
|
+
...(form.hidden ? { hidden: form.hidden.map(path) } : {}),
|
|
171
|
+
...(program ? { protect: [program] } : {}),
|
|
172
|
+
...(evaluate ? { evaluate } : {}),
|
|
173
|
+
...(form.metric ? { metric: form.metric } : {}),
|
|
174
|
+
review: form.review ?? {},
|
|
175
|
+
...(branchReview ? { branchReview: { ...branchReview, ...form.branchReview } } : {}),
|
|
176
|
+
profile,
|
|
177
|
+
stop: typeof form.stop === "object" ? form.stop : "until-stopped",
|
|
178
|
+
...(form.evalSlots === undefined ? {} : { evalSlots: form.evalSlots }),
|
|
179
|
+
...(form.workDirGb === undefined ? {} : { workDirGb: form.workDirGb }),
|
|
180
|
+
...(form.submitIntervalMinutes === undefined ? {} : { submitIntervalMinutes: form.submitIntervalMinutes }),
|
|
181
|
+
...(form.evalTimeoutMinutes === undefined ? {} : { evalTimeoutMinutes: form.evalTimeoutMinutes }),
|
|
182
|
+
...(commandMinutes === undefined ? {} : { commandTimeoutMinutes: commandMinutes }),
|
|
183
|
+
});
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/** The machine is shared by many agents: the prompt says how much one command may use (the numbers come from the profile and the machine file). */
|
|
188
|
+
function withMachineLimits(prompt, profile) {
|
|
189
|
+
const cpu = cpuOf(profile);
|
|
190
|
+
return `${prompt}\n\nThe machine is shared by many agents: use at most ${cpu.threadsPerJob} threads per process and about ${cpu.memPerJobGb} GB of memory per process.`;
|
|
191
|
+
}
|