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,130 @@
1
+ import { formPackage, formProblems } from "./form.js";
2
+ import { readRunEvents, readRunStatus, recommendRun, startRun } from "./launch.js";
3
+ const text = (message, isError = false) => ({ content: [{ type: "text", text: message }], ...(isError ? { isError } : {}) });
4
+ const inputOf = (raw) => (typeof raw === "object" && raw !== null ? raw : {});
5
+ const asNumber = (value) => (typeof value === "number" ? value : undefined);
6
+ export function createInfinityTools(options) {
7
+ const handles = new Map();
8
+ let lastRun;
9
+ const pick = (runDir) => (typeof runDir === "string" && runDir !== "" ? runDir : lastRun);
10
+ const run = {
11
+ name: "infinity_run",
12
+ description: "Starts a run of many agents on one task and returns at once; the run goes on in the background. Give the name of a known task, or a task form of your own (see the form parameter). The number of agents is yours to choose; " +
13
+ "without it the machine's recommendation is used. Watch the run with infinity_status; end it with infinity_stop.",
14
+ parameters: {
15
+ type: "object",
16
+ properties: {
17
+ task: {
18
+ type: "string",
19
+ description: `A known task, one of: ${options.packs.map((pack) => `${pack.name} (${pack.summary})`).join("; ") || "(none)"}. Leave out when you give a form.`,
20
+ },
21
+ form: {
22
+ type: "object",
23
+ description: "A task form of your own instead of a known task: { preset: 'code' | 'math', name, prompt (code) or statement (math), data?, hidden?, evaluate?: { program, run?, args? }, metric?: { name, direction }, stop?, tokens?, ... }. " +
24
+ "Paths are relative to formDir. The evaluator program must exist already (write it first).",
25
+ },
26
+ formDir: { type: "string", description: "The folder that the form's relative paths refer to (default: the current directory)." },
27
+ agents: { type: "number", description: "Number of agents (always wins over the recommendation)." },
28
+ tokens: { type: "number", description: "Token budget." },
29
+ wallMinutes: { type: "number", description: "End the run in order after this many minutes." },
30
+ review: { type: "boolean", description: "false leaves the branch review out (default true)." },
31
+ },
32
+ additionalProperties: false,
33
+ },
34
+ effect: "exec",
35
+ executionMode: "serial",
36
+ async execute(rawArgs) {
37
+ const args = inputOf(rawArgs);
38
+ let pack;
39
+ if (args.form !== undefined) {
40
+ const problems = formProblems(args.form);
41
+ if (problems.length > 0)
42
+ return text(`The form is not valid: ${problems.join("; ")}`, true);
43
+ pack = formPackage(args.form, typeof args.formDir === "string" ? args.formDir : process.cwd());
44
+ }
45
+ else
46
+ pack = options.packs.find((candidate) => candidate.name === args.task);
47
+ if (!pack)
48
+ return text(`Unknown task. Choose one of: ${options.packs.map((candidate) => candidate.name).join(", ") || "(none)"}, or give a form.`, true);
49
+ const agents = asNumber(args.agents);
50
+ const tokens = asNumber(args.tokens);
51
+ const wallMinutes = asNumber(args.wallMinutes);
52
+ try {
53
+ const handle = await startRun(pack, {
54
+ ...options.defaults,
55
+ model: options.model,
56
+ ...(agents === undefined ? {} : { agents }),
57
+ ...(tokens === undefined ? {} : { tokens }),
58
+ ...(wallMinutes === undefined ? {} : { wallMinutes }),
59
+ ...(args.review === false ? { review: false } : {}),
60
+ });
61
+ handles.set(handle.runDir, handle);
62
+ lastRun = handle.runDir;
63
+ handle.done.catch(() => { }); // the outcome is read through infinity_status
64
+ return text(`${handle.recommendation.lines.join("\n")}\nStarted with ${handle.agents} agents. Run directory: ${handle.runDir}`);
65
+ }
66
+ catch (error) {
67
+ return text(error instanceof Error ? error.message : String(error), true);
68
+ }
69
+ },
70
+ };
71
+ const status = {
72
+ name: "infinity_status",
73
+ description: "Reads the state of a run from its files: running, stopped or finished, why, agents alive, tokens, best score, results, warnings and the newest events.",
74
+ parameters: {
75
+ type: "object",
76
+ properties: {
77
+ runDir: { type: "string", description: "The run directory (default: the run started last by infinity_run)." },
78
+ recentEvents: { type: "number", description: "How many of the newest events to include (default 5)." },
79
+ },
80
+ additionalProperties: false,
81
+ },
82
+ effect: "read",
83
+ executionMode: "parallel",
84
+ async execute(rawArgs) {
85
+ const args = inputOf(rawArgs);
86
+ const runDir = pick(args.runDir);
87
+ if (!runDir)
88
+ return text("No run yet: start one with infinity_run, or give runDir.", true);
89
+ const { events } = readRunEvents(runDir);
90
+ const recent = events.slice(-Math.max(0, asNumber(args.recentEvents) ?? 5));
91
+ return text(JSON.stringify({ ...readRunStatus(runDir), recentEvents: recent }, null, 2));
92
+ },
93
+ };
94
+ const stop = {
95
+ name: "infinity_stop",
96
+ description: "Ends a run that infinity_run started, in order (agents stopped, report written), and waits for it. Returns why it ended and the best score.",
97
+ parameters: {
98
+ type: "object",
99
+ properties: { runDir: { type: "string", description: "The run directory (default: the run started last)." } },
100
+ additionalProperties: false,
101
+ },
102
+ effect: "exec",
103
+ executionMode: "serial",
104
+ async execute(rawArgs) {
105
+ const args = inputOf(rawArgs);
106
+ const runDir = pick(args.runDir);
107
+ const handle = runDir ? handles.get(runDir) : undefined;
108
+ if (!handle)
109
+ return text("No such run started by this tool.", true);
110
+ try {
111
+ return text(JSON.stringify(await handle.stop()));
112
+ }
113
+ catch (error) {
114
+ return text(error instanceof Error ? error.message : String(error), true);
115
+ }
116
+ },
117
+ };
118
+ const recommend = {
119
+ name: "infinity_recommend",
120
+ description: "Says what this computer can carry for a task: how many agents, how many heavy commands at once, how many threads and how much memory one command may use. Use it before infinity_run when you choose the number of agents.",
121
+ parameters: { type: "object", properties: {}, additionalProperties: false },
122
+ effect: "read",
123
+ executionMode: "parallel",
124
+ async execute() {
125
+ const recommendation = await recommendRun({});
126
+ return text(`${recommendation.lines.join("\n")}\n${JSON.stringify({ agents: recommendation.agents, slots: recommendation.capacity.cpuSlots })}`);
127
+ },
128
+ };
129
+ return [run, status, stop, recommend];
130
+ }
@@ -0,0 +1,113 @@
1
+ import { resolve } from "node:path";
2
+ import { CODE_GOAL_OBJECTIVE, codePrompt, codeRules, strategyRule } from "./prompts.js";
3
+ import { safetyReview } from "./safety-review.js";
4
+ import { commandLimits } from "./slot-gate.js";
5
+ import { JsonlFile } from "./jsonl.js";
6
+ import { runNotesPlugin } from "./run-notes.js";
7
+ import { createSubmitTool } from "./submit-tool.js";
8
+ /** Large binary results are not worth keeping in every agent's Git history. */
9
+ const GITIGNORE = [
10
+ "cache/",
11
+ "__pycache__/",
12
+ "*.pyc",
13
+ "*.pt",
14
+ "*.pth",
15
+ "*.ckpt",
16
+ "*.npy",
17
+ "*.npz",
18
+ "*.pkl",
19
+ "*.joblib",
20
+ "*.safetensors",
21
+ "*.onnx",
22
+ ".venv/",
23
+ "wandb/",
24
+ ];
25
+ export const DEFAULT_COMMAND_TIMEOUT_MINUTES = 120;
26
+ /** The shell tool's own interrupt, set beyond reach: the command limits (commandTimeoutMinutes) stop a command instead. The largest value a timer takes, less room for a `sleep N`. */
27
+ const NEVER_BACKGROUND_MS = 2_000_000_000;
28
+ /** Agents with a shell (`read`, `write`, `edit`, `bash`) and the `submit` tool, behind the safety review and the limits on commands (docs/05). */
29
+ export function shellKit(options) {
30
+ const { task, clock } = options;
31
+ const intervalMinutes = task.submitIntervalMinutes ?? 0;
32
+ return {
33
+ plannerKind: "code",
34
+ plannerSubject: task.prompt ?? "",
35
+ async prepare() { },
36
+ warnings() {
37
+ const warnings = [];
38
+ if (task.review === false)
39
+ warnings.push("The safety review is OFF: the agents' shell commands run unchecked, with your rights.");
40
+ if (!task.evaluate)
41
+ warnings.push("There is no evaluator: the ranking uses the agents' own claims (self-reported).");
42
+ return warnings;
43
+ },
44
+ agentSetup({ hint, agent, links, score }) {
45
+ // a resumed agent keeps the submits it made before
46
+ const submitsBefore = new JsonlFile(options.layout.ledger)
47
+ .readAll()
48
+ .filter((entry) => entry.type === "result" && entry.agent === agent).length;
49
+ const notes = runNotesPlugin({
50
+ workDir: options.layout.workDir(agent),
51
+ submitsBefore,
52
+ ...(task.workDirGb === undefined ? {} : { workDirGb: task.workDirGb }),
53
+ now: () => clock.now(),
54
+ });
55
+ return {
56
+ prompt: codePrompt(task.prompt ?? ""),
57
+ rules: [
58
+ ...codeRules({
59
+ hasEvaluator: task.evaluate !== undefined,
60
+ metricName: task.metric?.name,
61
+ dataNames: Object.keys(links),
62
+ submitIntervalMinutes: intervalMinutes,
63
+ }),
64
+ strategyRule(hint),
65
+ ],
66
+ goalObjective: CODE_GOAL_OBJECTIVE,
67
+ files: {},
68
+ gitignore: GITIGNORE,
69
+ builtinTools: ["read", "write", "edit", "bash"],
70
+ confine: false,
71
+ bashSoftTimeoutMs: NEVER_BACKGROUND_MS,
72
+ plugins: [
73
+ notes,
74
+ commandLimits({ gate: options.gate, wallMinutes: task.commandTimeoutMinutes ?? DEFAULT_COMMAND_TIMEOUT_MINUTES, agent }),
75
+ ...reviewPlugins(options, agent),
76
+ ],
77
+ tools: (submit, helpers) => [
78
+ createSubmitTool({
79
+ helpers,
80
+ onSubmit: async (...args) => {
81
+ const outcome = await submit(...args);
82
+ notes.submitted();
83
+ return outcome;
84
+ },
85
+ metricName: task.metric?.name,
86
+ direction: task.metric?.direction ?? "max",
87
+ minIntervalMs: intervalMinutes * 60_000,
88
+ now: () => clock.now(),
89
+ evaluate: score,
90
+ }),
91
+ ],
92
+ };
93
+ },
94
+ };
95
+ }
96
+ /** One safety-review plugin per agent: its rules know which directory is the agent's own. The reviewer model is shared and goes through the Gate. */
97
+ function reviewPlugins(options, agent) {
98
+ const { task, layout } = options;
99
+ if (task.review === false || task.review === undefined)
100
+ return [];
101
+ return [
102
+ safetyReview({
103
+ settings: task.review,
104
+ client: options.reviewClient,
105
+ agentDir: layout.agentDir(agent),
106
+ runRoot: layout.root,
107
+ sharedDir: layout.sharedDir,
108
+ keeperDir: layout.keeperDir,
109
+ hiddenOriginals: (task.hidden ?? []).map((path) => resolve(path)),
110
+ protectedPaths: task.protect ?? [],
111
+ }),
112
+ ];
113
+ }
@@ -0,0 +1,136 @@
1
+ import { isLightCommand } from "./command-class.js";
2
+ import { JsonlFile } from "./jsonl.js";
3
+ import { Pool } from "./pool.js";
4
+ /**
5
+ * The CPU slot gate (docs/16 section C): a counted semaphore. A heavy command of any agent holds one slot for its whole life, because the commands of a run never
6
+ * go to the background (see `commandLimits`). Nothing observes processes: the slot is taken before the command starts and given back when it has ended.
7
+ */
8
+ export class SlotGate {
9
+ pool;
10
+ capacity;
11
+ stats = { commands: 0, waited: 0, totalWaitMs: 0, maxWaitMs: 0 };
12
+ /** Called after every heavy command got its slot, with the agent and the time it waited (the component writes the events). */
13
+ onWait;
14
+ now;
15
+ startedAt;
16
+ busyMs = 0;
17
+ open = new Set();
18
+ constructor(capacity, now = Date.now) {
19
+ this.pool = new Pool(capacity);
20
+ this.capacity = capacity;
21
+ this.now = now;
22
+ this.startedAt = now();
23
+ }
24
+ get inUse() {
25
+ return this.pool.inUse;
26
+ }
27
+ get waiting() {
28
+ return this.pool.waiting;
29
+ }
30
+ /** Busy slot time over all slot time since the gate was made (0 to 1). */
31
+ utilisation() {
32
+ const now = this.now();
33
+ const elapsed = now - this.startedAt;
34
+ let busy = this.busyMs;
35
+ for (const hold of this.open)
36
+ busy += now - hold.since;
37
+ return elapsed > 0 ? busy / (this.capacity * elapsed) : 0;
38
+ }
39
+ /** Runs `work` while holding a slot; the wait is measured and recorded. */
40
+ async run(agent, work) {
41
+ const asked = this.now();
42
+ const release = await this.pool.acquire();
43
+ const hold = { since: this.now() };
44
+ this.open.add(hold);
45
+ const waitMs = this.now() - asked;
46
+ this.stats.commands += 1;
47
+ this.stats.totalWaitMs += waitMs;
48
+ this.stats.maxWaitMs = Math.max(this.stats.maxWaitMs, waitMs);
49
+ if (waitMs >= 1)
50
+ this.stats.waited += 1;
51
+ try {
52
+ this.onWait?.(agent, waitMs);
53
+ }
54
+ catch {
55
+ // recording must never keep a command from running
56
+ }
57
+ try {
58
+ return await work();
59
+ }
60
+ finally {
61
+ this.busyMs += this.now() - hold.since;
62
+ this.open.delete(hold);
63
+ release();
64
+ }
65
+ }
66
+ }
67
+ const textOf = (result) => result.content.map((part) => (part.type === "text" ? part.text : "")).join("");
68
+ /**
69
+ * A plugin on one agent's shell tool. Commands always run in the foreground: `background: true` is refused (and the prompt does not offer it), and the bash tool's
70
+ * own move to the background after a while is switched off by the setup, so a command is a call that ends when the process ends. Every command gets a hard wall
71
+ * limit (the bash tool's `timeout`, which stops the whole process group), so a hung command cannot hold a slot for ever. A heavy command waits for a slot of the gate.
72
+ */
73
+ export function commandLimits(options) {
74
+ const wallSeconds = Math.round(options.wallMinutes * 60);
75
+ const argsOf = (call) => typeof call.args === "object" && call.args !== null ? call.args : {};
76
+ return {
77
+ name: "command-limits",
78
+ setup(api) {
79
+ api.on("tool.before", (call) => {
80
+ if (call.name !== "bash")
81
+ return;
82
+ const args = argsOf(call);
83
+ if (args.background === true)
84
+ return {
85
+ kind: "deny",
86
+ reason: `Run it in the foreground: commands may run up to ${options.wallMinutes} minutes here, and there is no background mode in this run.`,
87
+ };
88
+ const asked = typeof args.timeout === "number" && args.timeout > 0 ? args.timeout : Number.POSITIVE_INFINITY;
89
+ if (asked <= wallSeconds)
90
+ return;
91
+ return { kind: "rewrite", args: { ...args, timeout: wallSeconds } };
92
+ });
93
+ api.on("tool.run", (call, next) => {
94
+ const command = argsOf(call).command;
95
+ if (call.name !== "bash" || !options.gate || typeof command !== "string" || isLightCommand(command))
96
+ return next();
97
+ return options.gate.run(options.agent, next);
98
+ });
99
+ api.on("tool.after", (call, result) => {
100
+ if (call.name !== "bash" || !result.isError || !/Command timed out after/.test(textOf(result)))
101
+ return;
102
+ return {
103
+ ...result,
104
+ content: [...result.content, { type: "text", text: `(This run stops every command after ${options.wallMinutes} minutes at most.)` }],
105
+ };
106
+ });
107
+ },
108
+ };
109
+ }
110
+ /**
111
+ * The run's side of the gate: turns the waits into events (`slot_wait` for a wait of a second or more) and, at the end, writes `slot_summary` with the
112
+ * utilisation. The waiting itself is done by the commands in `commandLimits`; the sampler reads `inUse` and `waiting` from the gate.
113
+ */
114
+ export function slotGate(gate) {
115
+ let write;
116
+ let now;
117
+ return {
118
+ name: "slot-gate",
119
+ start(context) {
120
+ const events = new JsonlFile(context.layout.events);
121
+ write = (event) => events.append(event);
122
+ now = () => context.clock.now();
123
+ gate.onWait = (agent, waitMs) => {
124
+ if (waitMs >= 1000)
125
+ events.append({ type: "slot_wait", ts: context.clock.now(), kind: "cpu", agent, waitMs });
126
+ };
127
+ },
128
+ async stop() {
129
+ gate.onWait = undefined;
130
+ if (!write || !now)
131
+ return;
132
+ write({ type: "slot_summary", ts: now(), kind: "cpu", slots: gate.capacity, ...gate.stats, utilisation: gate.utilisation() });
133
+ write = undefined;
134
+ },
135
+ };
136
+ }
@@ -0,0 +1,64 @@
1
+ // CPU slots are a resource of the machine, not of one run. Every run that has a slot gate writes down how many slots it holds; a run that starts while
2
+ // others are live takes only what the cores leave over, so two runs on one machine cannot starve each other by both counting all the cores.
3
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { availableParallelism, tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ /** One folder per machine (INFINITY_SLOT_LEASE_DIR moves it, for tests). */
7
+ const defaultLeaseDir = () => process.env.INFINITY_SLOT_LEASE_DIR || join(tmpdir(), "infinity-slot-leases");
8
+ const alive = (pid) => {
9
+ try {
10
+ process.kill(pid, 0);
11
+ return true;
12
+ }
13
+ catch (error) {
14
+ return error.code === "EPERM";
15
+ }
16
+ };
17
+ /** The leases of other live runs on this machine (a lease whose process is gone is removed). */
18
+ function liveLeases(dir, self) {
19
+ let names = [];
20
+ try {
21
+ names = readdirSync(dir);
22
+ }
23
+ catch {
24
+ return [];
25
+ }
26
+ const leases = [];
27
+ for (const name of names) {
28
+ const path = join(dir, name);
29
+ try {
30
+ const lease = JSON.parse(readFileSync(path, "utf8"));
31
+ if (name === self)
32
+ continue;
33
+ if (alive(lease.pid))
34
+ leases.push(lease);
35
+ else
36
+ rmSync(path, { force: true });
37
+ }
38
+ catch {
39
+ // half written or foreign: not a lease
40
+ }
41
+ }
42
+ return leases;
43
+ }
44
+ /** Takes up to `wanted` slots, leaving room for the slots of the other live runs on this machine (at least one slot is always given). */
45
+ export function claimSlots(wanted, runDir, options = {}) {
46
+ const dir = options.dir ?? defaultLeaseDir();
47
+ const pid = options.pid ?? process.pid;
48
+ const cores = options.cores ?? availableParallelism();
49
+ const name = `${pid}-${runDir.replace(/[^A-Za-z0-9_.-]/g, "_").slice(-80)}.json`;
50
+ const others = liveLeases(dir, name);
51
+ const held = others.reduce((sum, lease) => sum + lease.slots, 0);
52
+ const slots = Math.max(1, Math.min(wanted, cores - held));
53
+ try {
54
+ mkdirSync(dir, { recursive: true });
55
+ writeFileSync(join(dir, name), JSON.stringify({ pid, runDir, slots }));
56
+ }
57
+ catch {
58
+ // without a lease the other runs simply do not see this one
59
+ }
60
+ const note = slots < wanted
61
+ ? `CPU slots: ${slots} instead of ${wanted}, because ${others.length} other run${others.length === 1 ? "" : "s"} on this machine hold${others.length === 1 ? "s" : ""} ${held} of the ${cores} cores (${others.map((lease) => lease.runDir).join(", ")}).`
62
+ : undefined;
63
+ return { slots, note, release: () => rmSync(join(dir, name), { force: true }) };
64
+ }
@@ -0,0 +1,47 @@
1
+ export const MAX_RESCUES = 3;
2
+ export const RESCUE_MESSAGE = "You seem stuck: nothing has happened for a long time. Say in one sentence where you are, then choose a different approach and continue.";
3
+ /**
4
+ * Finds stuck agents. Stuck = running, silent for `stuckAfterMs`, and not excused.
5
+ * Each stuck is answered with a rescue (cancel and start again with a message), at most MAX_RESCUES times per agent;
6
+ * the next time it is stuck the answer is stop, and the ladder starts a new agent in its place.
7
+ */
8
+ export class StuckDetector {
9
+ tracked = new Map();
10
+ options;
11
+ constructor(options) {
12
+ this.options = options;
13
+ }
14
+ register(agent) {
15
+ this.tracked.set(agent, { lastEventAt: this.options.clock.now(), rescues: 0 });
16
+ }
17
+ forget(agent) {
18
+ this.tracked.delete(agent);
19
+ }
20
+ /** Call for every event of the agent (any sign of life). */
21
+ touch(agent) {
22
+ const entry = this.tracked.get(agent);
23
+ if (entry)
24
+ entry.lastEventAt = this.options.clock.now();
25
+ }
26
+ /** The actions to take now. Rescued agents count as touched, so they get a full silence period to react. */
27
+ check() {
28
+ const now = this.options.clock.now();
29
+ const actions = [];
30
+ for (const [agent, entry] of this.tracked) {
31
+ if (now - entry.lastEventAt < this.options.stuckAfterMs || this.options.isExcused(agent))
32
+ continue;
33
+ if (entry.rescues >= MAX_RESCUES) {
34
+ this.tracked.delete(agent);
35
+ actions.push({ type: "stop", agent });
36
+ continue;
37
+ }
38
+ entry.rescues += 1;
39
+ entry.lastEventAt = now;
40
+ actions.push({ type: "rescue", agent, rescue: entry.rescues, message: RESCUE_MESSAGE });
41
+ }
42
+ return actions;
43
+ }
44
+ rescuesOf(agent) {
45
+ return this.tracked.get(agent)?.rescues ?? 0;
46
+ }
47
+ }
@@ -0,0 +1,99 @@
1
+ import { better } from "./task.js";
2
+ export const MAX_ENTRY_CHARS_PER_FILE = 20_000;
3
+ const MAX_ENTRY_CHARS = 60_000;
4
+ const text = (message, isError = false) => ({ content: [{ type: "text", text: message }], ...(isError ? { isError } : {}) });
5
+ /** The agent's one official way to have a result counted (docs/05 section 3.1). One tool per agent: it remembers that agent's last submit and best score. */
6
+ export function createSubmitTool(options) {
7
+ let lastSubmitAt;
8
+ let best;
9
+ return {
10
+ name: "submit",
11
+ description: "Sends a result to be counted and scored. Give the shell command that produced it (for example 'python train.py') and the files that hold the result " +
12
+ "(for example predictions.csv). Your directory is committed first, so the result can always be traced to these files. The answer says how it scored.",
13
+ parameters: {
14
+ type: "object",
15
+ properties: {
16
+ command: { type: "string", description: "The shell command that produced the result." },
17
+ files: {
18
+ type: "array",
19
+ items: { type: "string" },
20
+ description: "Files (relative to your directory) that hold the result, such as predictions.csv or the script.",
21
+ },
22
+ claim: {
23
+ type: "object",
24
+ description: 'Only when the task has no scorer: your own numbers, for example {"accuracy": 0.9}.',
25
+ additionalProperties: { type: "number" },
26
+ },
27
+ note: { type: "string", description: "A short remark for the record." },
28
+ },
29
+ required: ["command"],
30
+ additionalProperties: false,
31
+ },
32
+ effect: "exec",
33
+ executionMode: "serial",
34
+ async execute(args, context) {
35
+ const input = parseArgs(args);
36
+ if (typeof input === "string")
37
+ return text(input, true);
38
+ const waitMs = lastSubmitAt === undefined ? 0 : lastSubmitAt + options.minIntervalMs - options.now();
39
+ if (waitMs > 0)
40
+ return text(`You submitted a moment ago. Submit again in ${Math.ceil(waitMs / 1000)} seconds; use the time to improve the result.`, true);
41
+ lastSubmitAt = options.now();
42
+ const commit = await options.helpers.commitNow();
43
+ const entry = await readEntry(input.files, context);
44
+ const { result, selfReported } = await options.evaluate({
45
+ command: input.command,
46
+ files: input.files,
47
+ commit,
48
+ claim: input.claim,
49
+ signal: context.signal,
50
+ workDir: options.helpers.workDir,
51
+ });
52
+ await options.onSubmit({ command: input.command, files: input.files, entry, result, selfReported });
53
+ if (!selfReported && result.status === "ok" && result.score !== null && (best === undefined || better(result.score, best, options.direction)))
54
+ best = result.score;
55
+ const answer = describe(result, selfReported, options.metricName);
56
+ return text(best !== undefined && !selfReported && result.status === "ok" ? `${answer}\nYour best so far: ${best}.` : answer, result.status === "error");
57
+ },
58
+ };
59
+ }
60
+ function parseArgs(args) {
61
+ const value = (args ?? {});
62
+ if (typeof value.command !== "string" || value.command.trim() === "")
63
+ return "The 'command' that produced the result is required.";
64
+ const files = Array.isArray(value.files) ? value.files.filter((file) => typeof file === "string" && file !== "") : [];
65
+ const claim = Object.fromEntries(Object.entries((value.claim ?? {})).filter((pair) => typeof pair[1] === "number"));
66
+ return { command: value.command.trim(), files, claim };
67
+ }
68
+ async function readEntry(files, context) {
69
+ let total = 0;
70
+ const parts = [];
71
+ for (const file of files) {
72
+ let body;
73
+ try {
74
+ body = new TextDecoder().decode(await context.env.readFile(file));
75
+ }
76
+ catch {
77
+ parts.push(`=== ${file} (not readable) ===`);
78
+ continue;
79
+ }
80
+ const room = Math.max(0, Math.min(MAX_ENTRY_CHARS_PER_FILE, MAX_ENTRY_CHARS - total));
81
+ const cut = body.length > room;
82
+ parts.push(`=== ${file}${cut ? ` (first ${room} of ${body.length} characters)` : ""} ===\n${body.slice(0, room)}`);
83
+ total += Math.min(body.length, room);
84
+ }
85
+ return parts.join("\n");
86
+ }
87
+ function describe(result, selfReported, metricName) {
88
+ if (result.status === "error")
89
+ return `The result could not be scored: ${result.details}`;
90
+ const name = metricName ?? "score";
91
+ const extras = Object.entries(result.metrics)
92
+ .filter(([key]) => key !== name)
93
+ .map(([key, value]) => `${key} ${value}`)
94
+ .join(", ");
95
+ const head = selfReported
96
+ ? `Recorded as self-reported (${name} ${result.score ?? "none"}); nothing was verified.`
97
+ : `Scored: ${name} ${result.score}${extras ? ` (${extras})` : ""}.`;
98
+ return result.details ? `${head}\n${result.details}` : head;
99
+ }