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,39 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { existsSync, readFileSync, statSync } from "node:fs";
10
+ import { dirname, join, resolve } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { formPackage, looksLikeForm } from "../src/form.js";
13
+ const ROOT = resolve(import.meta.dirname, "..");
14
+ /** The file a name stands for: a folder of tasks/ (bare name), a folder with a task.ts, task.mts, task.js or task.json, or a form or module file. */
15
+ function taskFile(name) {
16
+ const bare = !name.includes("/") && !/\.(m?ts|m?js)$/.test(name) && !name.endsWith(".json");
17
+ const path = bare ? resolve(ROOT, "tasks", name) : resolve(name);
18
+ if (existsSync(path) && statSync(path).isDirectory()) {
19
+ // task.js: the bundled tasks of the published package are compiled (Node does not run TypeScript inside node_modules)
20
+ for (const file of ["task.ts", "task.mts", "task.js", "task.json"])
21
+ if (existsSync(join(path, file)))
22
+ return join(path, file);
23
+ throw new Error(`${path} has no task.ts, task.mts, task.js or task.json`);
24
+ }
25
+ if (!existsSync(path))
26
+ throw new Error(`no task "${name}" (looked for ${path}); give a task of tasks/, a folder or file of a form (.json or .ts), or a module that exports a task package`);
27
+ return path;
28
+ }
29
+ /** A task package by name or path. A form (preset, name, ...) becomes a package; a module's default export may also be a package itself. */
30
+ export async function loadTaskPackage(name) {
31
+ const path = taskFile(name);
32
+ const exported = path.endsWith(".json") ? JSON.parse(readFileSync(path, "utf8")) : (await import(__rewriteRelativeImportExtension(pathToFileURL(path).href))).default;
33
+ if (looksLikeForm(exported))
34
+ return formPackage(exported, dirname(path));
35
+ const pack = exported;
36
+ if (!pack || typeof pack.build !== "function")
37
+ throw new Error(`${path} must export a form (preset, name, ...) or a task package as its default export`);
38
+ return pack;
39
+ }
@@ -0,0 +1,37 @@
1
+ import { compatPresets } from "sakura-agent";
2
+ /**
3
+ * The providers a run can use: the official APIs of DeepSeek (the default), OpenAI and Anthropic (its OpenAI-compatible endpoint), the same built-ins as
4
+ * sakuracode. INFINITY_PROVIDER picks one, INFINITY_MODEL replaces its default model. The key comes from the environment once and goes nowhere else.
5
+ */
6
+ const PROVIDERS = {
7
+ deepseek: {
8
+ keyEnv: "DEEPSEEK_API_KEY",
9
+ baseUrl: "https://api.deepseek.com",
10
+ model: "deepseek-flash",
11
+ contextWindow: 128_000,
12
+ compat: compatPresets["deepseek-flash"],
13
+ },
14
+ openai: { keyEnv: "OPENAI_API_KEY", baseUrl: "https://api.openai.com/v1", model: "gpt-5", contextWindow: 400_000, compat: compatPresets.openai },
15
+ anthropic: {
16
+ keyEnv: "ANTHROPIC_API_KEY",
17
+ baseUrl: "https://api.anthropic.com/v1/",
18
+ model: "claude-sonnet-5-5",
19
+ contextWindow: 200_000,
20
+ compat: compatPresets.anthropic,
21
+ },
22
+ };
23
+ export const PROVIDER_NAMES = Object.keys(PROVIDERS);
24
+ const KEY_VARIABLES = PROVIDER_NAMES.map((name) => PROVIDERS[name].keyEnv);
25
+ /** Picks the provider, keeps its key in the model configuration and removes every provider key from the environment the agents' commands inherit. */
26
+ export function modelFromEnv(env = process.env) {
27
+ const name = (env.INFINITY_PROVIDER || "deepseek");
28
+ const provider = PROVIDERS[name];
29
+ if (!provider)
30
+ throw new Error(`INFINITY_PROVIDER must be one of ${PROVIDER_NAMES.join(", ")} (it is "${env.INFINITY_PROVIDER}")`);
31
+ const apiKey = env[provider.keyEnv];
32
+ if (!apiKey)
33
+ throw new Error(`${provider.keyEnv} is not set (the key of the ${name} provider; INFINITY_PROVIDER chooses another: ${PROVIDER_NAMES.join(", ")})`);
34
+ for (const variable of KEY_VARIABLES)
35
+ delete env[variable];
36
+ return { baseUrl: provider.baseUrl, apiKey, model: env.INFINITY_MODEL || provider.model, contextWindow: provider.contextWindow, compat: provider.compat };
37
+ }
@@ -0,0 +1,121 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { cpuOf } from "../src/capacity.js";
4
+ import { machineConfigFrom, writeMachineConfig } from "../src/machine-config.js";
5
+ import { recommendRun } from "../src/launch.js";
6
+ import { loadTaskPackage } from "./load-task.js";
7
+ export const NEW_HELP = `usage: infinity new <code|math> <folder>
8
+ writes a task form (task.mts) into <folder>, with an example evaluator for the code preset; edit them, then: infinity run <folder>`;
9
+ export const RECOMMEND_HELP = `usage: infinity recommend [--task <task>] [--write machine.json]
10
+ looks at this computer (cores, memory, GPU, other load) and says how many agents, how many heavy commands at once and how many threads
11
+ and how much memory one command may use; with --task it uses that task's profile; with --write it saves the answer as a machine file
12
+ (edit it by hand if you like; use it with: infinity run <task> --machine machine.json). Flags of a run always win over the file.`;
13
+ const CODE_FORM = `// A task form: what to do and how it is scored. What the machine can carry is a separate file (infinity recommend --write machine.json).
14
+ // Paths are relative to this folder. Run it with: infinity run . --machine machine.json --view (task.mts: always an ES module, whatever package.json is above)
15
+ export default {
16
+ preset: "code",
17
+ name: "my-task",
18
+ summary: "One line about the task",
19
+
20
+ // The problem, in words: the goal, what the agents see, what to hand in (the "submit" tool: a command, the files it made, and the result), what is forbidden.
21
+ prompt:
22
+ "Find the whole number from 0 to 100 that is the best you can justify and write it alone into answer.txt in your directory (this is only an example task: replace this text with your own problem). Submit with the command that made it and the file answer.txt.",
23
+
24
+ // Folders or files the agents may read (a read-only copy appears as data/<name> in every agent's directory).
25
+ data: {},
26
+
27
+ // Things only the evaluator may read (test labels, secret inputs); they are moved away while the agents run and put back at the end.
28
+ // The evaluator finds their private paths in INFINITY_HIDDEN_0, INFINITY_HIDDEN_1, ...
29
+ hidden: [],
30
+
31
+ // How a submit is scored: a program (run with "python3" here) that prints one JSON line {"score": 12, "details": "words for the agent"}.
32
+ // It finds the agent's directory in INFINITY_WORK_DIR. Never put hidden data into "details": the agent reads it.
33
+ evaluate: { program: "evaluate.py", run: "python3" },
34
+ metric: { name: "score", direction: "max" }, // "max": larger is better; "min": smaller is better (time, loss)
35
+
36
+ // When the run ends by itself: "until-stopped" (Ctrl-C, token budget, wall limit) or { targetScore: 100 }.
37
+ stop: "until-stopped",
38
+ tokens: 2_000_000,
39
+ wallMinutes: 30,
40
+ };
41
+ `;
42
+ const MATH_FORM = `// A math task: agents prove one statement in Lean 4 (core library, no Mathlib). The run ends at the first proof the local Lean accepts.
43
+ // Run it with: infinity run . --agents 3 --view
44
+ export default {
45
+ preset: "math",
46
+ name: "my-statement",
47
+ // The Lean source of a proposition. The proof must be "theorem main : Statement.Goal".
48
+ statement: "∀ n : Nat, n % 2 = 0 ∨ n % 2 = 1",
49
+ // prompt: "Extra words for the agents (optional).",
50
+ tokens: 1_000_000,
51
+ wallMinutes: 20,
52
+ };
53
+ `;
54
+ const EVALUATE_PY = `"""Example evaluator: replace it with your own scoring.
55
+
56
+ It is started by Infinity outside the agents' shell, for every submit. Environment:
57
+ INFINITY_WORK_DIR the agent's directory (read the files it handed in)
58
+ INFINITY_HIDDEN_0 private path of the first "hidden" entry of the form (INFINITY_HIDDEN_1, ... for more)
59
+ It must print one JSON line last: {"score": <number or null>, "metrics": {...}, "details": "<words for the agent>"}.
60
+ Print {"score": null, "details": "why"} when the submit is unusable. Do not put hidden data into "details".
61
+ """
62
+ import json
63
+ import os
64
+ import sys
65
+
66
+ path = os.path.join(os.environ["INFINITY_WORK_DIR"], "answer.txt")
67
+ try:
68
+ value = float(open(path).read().strip())
69
+ except (OSError, ValueError):
70
+ print(json.dumps({"score": None, "details": "answer.txt must exist and hold one number."}))
71
+ sys.exit(1)
72
+ # A real evaluator must also refuse results that are out of range or that exploit the scoring: agents will try.
73
+ if not 0 <= value <= 100:
74
+ print(json.dumps({"score": None, "details": "the number must be between 0 and 100."}))
75
+ sys.exit(1)
76
+ print(json.dumps({"score": value, "details": f"read {value}"}))
77
+ `;
78
+ /** `infinity new <preset> <folder>`: writes the form (and, for code, the example evaluator); never overwrites. */
79
+ export function scaffold(argv) {
80
+ const [preset, folder, ...rest] = argv;
81
+ if ((preset !== "code" && preset !== "math") || !folder || rest.length > 0)
82
+ throw new Error(NEW_HELP);
83
+ const dir = resolve(folder);
84
+ const files = [[join(dir, "task.mts"), preset === "code" ? CODE_FORM : MATH_FORM]];
85
+ if (preset === "code")
86
+ files.push([join(dir, "evaluate.py"), EVALUATE_PY]);
87
+ for (const [path] of files)
88
+ if (existsSync(path))
89
+ throw new Error(`${path} exists already; nothing was written`);
90
+ mkdirSync(dir, { recursive: true });
91
+ for (const [path, content] of files)
92
+ writeFileSync(path, content);
93
+ return files.map(([path]) => path);
94
+ }
95
+ /** `infinity recommend`: prints the recommendation and optionally writes the machine file. */
96
+ export async function recommend(argv) {
97
+ const args = [...argv];
98
+ const take = (name) => {
99
+ const at = args.indexOf(`--${name}`);
100
+ if (at < 0)
101
+ return undefined;
102
+ const value = args.splice(at, 2)[1];
103
+ if (!value || value.startsWith("--"))
104
+ throw new Error(`--${name} needs a value\n${RECOMMEND_HELP}`);
105
+ return value;
106
+ };
107
+ const task = take("task");
108
+ const write = take("write");
109
+ if (args.length > 0)
110
+ throw new Error(`not understood: ${args.join(" ")}\n${RECOMMEND_HELP}`);
111
+ const profile = task ? ((await loadTaskPackage(task)).profile ?? {}) : {};
112
+ const recommendation = await recommendRun(profile);
113
+ const lines = [...recommendation.lines];
114
+ const cpu = cpuOf(profile);
115
+ if (write) {
116
+ const config = machineConfigFrom(recommendation.capacity, cpu);
117
+ writeMachineConfig(write, config, "Made by infinity recommend; edit freely. Flags of a run win over this file.");
118
+ lines.push(`Wrote ${write}: ${JSON.stringify(config)}`);
119
+ }
120
+ return lines;
121
+ }
@@ -0,0 +1,156 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { corePlugins, createAgent } from "sakura-agent";
3
+ import { commitPlugin } from "./commit-plugin.js";
4
+ import { afterRun } from "./worker-policy.js";
5
+ import { commitAll, createWorkDir, headCommit } from "./work-repo.js";
6
+ /** Advice for an agent: handed to the active run at once, or kept until the next run starts (a run that is not active drops what is steered into it). */
7
+ export class AdviceBox {
8
+ waiting = [];
9
+ run;
10
+ deliver(text) {
11
+ if (this.run)
12
+ this.run.steer(text);
13
+ else
14
+ this.waiting.push(text);
15
+ }
16
+ attach(run) {
17
+ this.run = run;
18
+ for (const text of this.waiting.splice(0))
19
+ run.steer(text);
20
+ }
21
+ detach() {
22
+ this.run = undefined;
23
+ }
24
+ }
25
+ /** Starts one agent: its work directory (a Git repository), its session, its tools, and the loop that keeps it running until it ends. */
26
+ export function startWorker(deps) {
27
+ const { layout, number, hooks } = deps;
28
+ const workDir = layout.workDir(number);
29
+ const startedAt = deps.clock.now();
30
+ let agent;
31
+ let cancelReason;
32
+ let rescueMessage;
33
+ let inTool = false;
34
+ let pausesWithoutReply = 0;
35
+ let replies = 0;
36
+ const advice = new AdviceBox();
37
+ let configure;
38
+ const noteReview = (data) => {
39
+ const review = data;
40
+ if (review.kind === "review" && review.outcome === "deny")
41
+ hooks.onDenied({ tool: review.tool ?? "?", decidedBy: review.decidedBy ?? "?", reason: String(review.reason ?? "").slice(0, 300) });
42
+ };
43
+ const watch = async (events) => {
44
+ for await (const event of events) {
45
+ hooks.onActivity();
46
+ if (event.type === "tool_start")
47
+ inTool = true;
48
+ if (event.type === "tool_end")
49
+ inTool = false;
50
+ if (event.type === "plugin" && event.name === "review")
51
+ noteReview(event.data);
52
+ if (event.type === "message_end" && event.message.role === "assistant") {
53
+ pausesWithoutReply = 0;
54
+ replies += 1;
55
+ hooks.onReply();
56
+ }
57
+ }
58
+ };
59
+ const drive = async () => {
60
+ const commits = commitPlugin({ dir: workDir, onCommit: hooks.onCommit, onError: (_error, operation) => hooks.onCommitError?.(operation) });
61
+ let workReady = false;
62
+ try {
63
+ await createWorkDir(workDir, deps.setup);
64
+ workReady = true;
65
+ const commitNow = async () => {
66
+ await commits.flush();
67
+ return (await commitAll(workDir, "submit")) ?? (await headCommit(workDir)) ?? null;
68
+ };
69
+ const submit = async (submission) => {
70
+ const commit = await commitNow();
71
+ const steps = agent ? (await agent.usage()).turns : 0;
72
+ await hooks.onSubmit(submission, { commit, steps, elapsedMs: deps.clock.now() - startedAt });
73
+ };
74
+ // one function builds the agent and, for a branch review, its reviewer: the request prefix (system text, tools, messages) must be identical for the cache
75
+ const build = (sessionFile, plugins, client, tools) => createAgent({
76
+ model: client,
77
+ cwd: workDir,
78
+ ...(deps.createEnvironment ? { environment: deps.createEnvironment({ workDir, sharedDir: layout.sharedDir }) } : { confine: deps.setup.confine }),
79
+ tools: [...deps.setup.builtinTools, ...tools],
80
+ ...(deps.setup.bashSoftTimeoutMs === undefined ? {} : { bashSoftTimeoutMs: deps.setup.bashSoftTimeoutMs }),
81
+ plugins,
82
+ rules: deps.setup.rules,
83
+ sessionFile,
84
+ goal: deps.setup.goal,
85
+ });
86
+ configure = (sessionFile, plugins, client) => build(sessionFile, plugins, client, deps.setup.tools(async () => undefined, { commitNow: async () => null, workDir }));
87
+ agent = await build(layout.sessionFile(number), [...corePlugins(), commits, ...(deps.setup.plugins ?? [])], deps.client, deps.setup.tools(submit, { commitNow, workDir }));
88
+ return await runUntilEnd(agent);
89
+ }
90
+ catch (error) {
91
+ return { reason: "failed", detail: String(error) };
92
+ }
93
+ finally {
94
+ await agent?.close().catch(() => { });
95
+ if (workReady)
96
+ await commits.checkpoint();
97
+ }
98
+ };
99
+ const runUntilEnd = async (live) => {
100
+ let input = deps.resume && hasSession(layout.sessionFile(number)) ? undefined : deps.setup.prompt;
101
+ for (;;) {
102
+ if (cancelReason && cancelReason !== "rescue")
103
+ return { reason: "cancelled", cancelled: cancelReason };
104
+ const run = live.run(input);
105
+ advice.attach(run);
106
+ const watching = watch(run.events);
107
+ const result = await run.result;
108
+ advice.detach();
109
+ await watching;
110
+ inTool = false;
111
+ const next = afterRun({ cancelled: cancelReason, run: result, gateStopped: Boolean(deps.gate.stopped), pausesWithoutReply });
112
+ if (next.type === "end")
113
+ return next.end;
114
+ if (next.type === "rescue") {
115
+ cancelReason = undefined;
116
+ input = rescueMessage;
117
+ continue;
118
+ }
119
+ pausesWithoutReply += 1;
120
+ input = undefined;
121
+ await deps.clock.sleep(deps.pauseRetryMs);
122
+ }
123
+ };
124
+ const done = drive();
125
+ return {
126
+ number,
127
+ done,
128
+ cancel(reason) {
129
+ cancelReason = reason;
130
+ agent?.cancel();
131
+ },
132
+ rescue(message) {
133
+ cancelReason = "rescue";
134
+ rescueMessage = message;
135
+ agent?.cancel();
136
+ },
137
+ reviewTarget: () => {
138
+ const live = agent;
139
+ const build = configure;
140
+ if (!live || !build)
141
+ return undefined;
142
+ return {
143
+ workDir,
144
+ replies: () => replies,
145
+ fork: (path) => live.fork(path),
146
+ // the reviewer has the same plugins as the agent, except the commit plugin (it must not write to the work directory) and the safety review (its guard is stricter)
147
+ openReviewer: (sessionFile, guard, wrapClient) => build(sessionFile, [...corePlugins(), guard], wrapClient(deps.client)),
148
+ advise: (text) => advice.deliver(text),
149
+ };
150
+ },
151
+ excused: () => agent === undefined || inTool || deps.gate.paused || agent.pending().watching.length > 0,
152
+ };
153
+ }
154
+ function hasSession(path) {
155
+ return existsSync(path) && statSync(path).size > 0;
156
+ }
@@ -0,0 +1,12 @@
1
+ const REPLACEMENT_WAIT_MS = 1000;
2
+ const MAX_REPLACEMENT_WAIT_MS = 60_000;
3
+ const MAX_DOUBLINGS = 10;
4
+ /**
5
+ * How long to wait before an agent that failed is replaced: `baseMs`, doubled with every failure in a row, up to a minute. An agent that finished
6
+ * normally is replaced at once. Without the wait a broken connection makes every replacement fail at once and the run replaces agents in a storm.
7
+ */
8
+ export function replacementWait(failedAgent, consecutiveFailures, baseMs = REPLACEMENT_WAIT_MS) {
9
+ if (!failedAgent)
10
+ return 0;
11
+ return Math.min(MAX_REPLACEMENT_WAIT_MS, baseMs * 2 ** Math.min(Math.max(consecutiveFailures - 1, 0), MAX_DOUBLINGS));
12
+ }
@@ -0,0 +1,49 @@
1
+ /** Every kind of token counts in full, cache reads included (owner decision, docs/02 section 13). */
2
+ export function totalTokens(usage) {
3
+ return usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
4
+ }
5
+ /**
6
+ * A plain counter over the tokens of every request.
7
+ * Soft stop rule: refuse to start a request when used + inflight x mean request size >= budget.
8
+ * `inflight` counts the request that is about to start, so with one agent the margin is one mean request.
9
+ * No budget (undefined) never stops.
10
+ */
11
+ export class Budget {
12
+ used = 0;
13
+ requests = 0;
14
+ limit;
15
+ inflight;
16
+ constructor(limit, inflight) {
17
+ if (limit !== undefined && !(limit > 0))
18
+ throw new RangeError(`Budget must be positive, got ${limit}`);
19
+ this.limit = limit;
20
+ this.inflight = inflight;
21
+ }
22
+ record(usage) {
23
+ this.used += totalTokens(usage);
24
+ this.requests += 1;
25
+ }
26
+ /** Sets the counters again after a restart of the program (the totals come from the state file). */
27
+ restore(tokensUsed, requests) {
28
+ this.used = tokensUsed;
29
+ this.requests = requests;
30
+ }
31
+ get requestCount() {
32
+ return this.requests;
33
+ }
34
+ get tokensUsed() {
35
+ return this.used;
36
+ }
37
+ get meanRequestTokens() {
38
+ return this.requests === 0 ? 0 : this.used / this.requests;
39
+ }
40
+ /** The reason to refuse a new request, or undefined when it may start. */
41
+ refusal() {
42
+ if (this.limit === undefined)
43
+ return undefined;
44
+ const projected = this.used + (this.inflight() + 1) * this.meanRequestTokens;
45
+ if (projected < this.limit)
46
+ return undefined;
47
+ return `token budget reached: ${this.used} used, ${Math.round(projected)} projected, limit ${this.limit}`;
48
+ }
49
+ }
@@ -0,0 +1,103 @@
1
+ /** How many agents a machine can carry for a task, as a number the user sees before the run (docs/16 section A). A hint: nothing applies it by itself. */
2
+ const MEMORY_RESERVE_GB = 8;
3
+ /** The owner wants the machine kept full: a little more agents than slots, so the queue is never empty. */
4
+ const FILL_FACTOR = 1.25;
5
+ const PROFILE_DEFAULTS = { threadsPerJob: 2, memPerJobGb: 3, heavyShare: 0.8 };
6
+ /** The CPU part of a profile with its defaults. */
7
+ export const cpuOf = (profile) => ({ ...PROFILE_DEFAULTS, ...profile?.cpu });
8
+ /** The problems of a profile, as words; empty when it is fine. */
9
+ export function profileProblems(profile) {
10
+ const problems = [];
11
+ const cpu = profile.cpu;
12
+ if (cpu?.threadsPerJob !== undefined && !(cpu.threadsPerJob >= 1))
13
+ problems.push("profile.cpu.threadsPerJob must be at least 1");
14
+ if (cpu?.memPerJobGb !== undefined && !(cpu.memPerJobGb > 0))
15
+ problems.push("profile.cpu.memPerJobGb must be positive");
16
+ if (cpu?.heavyShare !== undefined && !(cpu.heavyShare > 0 && cpu.heavyShare <= 1))
17
+ problems.push("profile.cpu.heavyShare must be above 0 and at most 1");
18
+ if (profile.kind !== undefined && profile.kind !== "cpu" && profile.kind !== "gpu")
19
+ problems.push("profile.kind must be 'cpu' or 'gpu'");
20
+ if (profile.kind === "gpu" && !profile.gpu)
21
+ problems.push("profile.gpu is required with kind 'gpu'");
22
+ const gpu = profile.gpu;
23
+ if (gpu) {
24
+ if (!(gpu.vramPerJobGb > 0))
25
+ problems.push("profile.gpu.vramPerJobGb must be positive");
26
+ if (gpu.heavyShare !== undefined && !(gpu.heavyShare > 0 && gpu.heavyShare <= 1))
27
+ problems.push("profile.gpu.heavyShare must be above 0 and at most 1");
28
+ if (gpu.maxJobsPerGpu !== undefined && !(Number.isInteger(gpu.maxJobsPerGpu) && gpu.maxJobsPerGpu >= 1))
29
+ problems.push("profile.gpu.maxJobsPerGpu must be a whole number, at least 1");
30
+ }
31
+ return problems;
32
+ }
33
+ const slots = (value) => Math.max(1, Math.floor(value));
34
+ const agentsFor = (jobSlots, heavyShare) => Math.max(1, Math.ceil((jobSlots / heavyShare) * FILL_FACTOR));
35
+ /** GPU index of every GPU slot: per GPU the smaller of `maxJobsPerGpu` and what its memory holds (a GPU that holds no job gives none). */
36
+ export function gpuSlotMapOf(gpuMemMb, gpu) {
37
+ const map = [];
38
+ gpuMemMb.forEach((memMb, index) => {
39
+ const fits = Math.floor(memMb / 1024 / gpu.vramPerJobGb);
40
+ for (let job = 0; job < Math.min(gpu.maxJobsPerGpu ?? fits, fits); job += 1)
41
+ map.push(index);
42
+ });
43
+ return map;
44
+ }
45
+ /**
46
+ * CPU slots = free cores (the cores minus foreign load) / threads per job, cut by memory (free memory minus a reserve for the system, over memory per job).
47
+ * Agents = slots / heavy share, with a quarter more so the queue is never empty. A GPU task takes the smaller of that and the GPU kind's own number.
48
+ * Without a profile and without history the answer is one agent per core. The goal is a full machine at the ceiling, not headroom.
49
+ */
50
+ export function recommendCapacity(facts, profile, history) {
51
+ const empty = { gpuSlots: 0, gpuSlotMap: [], agentsByGpu: null };
52
+ const result = (cpuSlots, agents, rest) => {
53
+ const final = Math.max(1, Math.round(agents));
54
+ return { ...empty, cpuSlots: Math.max(1, Math.round(cpuSlots)), agents: final, maxUseful: 2 * final, ...rest };
55
+ };
56
+ const freeGb = facts.freeMemMb / 1024;
57
+ const available = Math.max(1, facts.cores - (facts.busyCores ?? 0));
58
+ if (history && (history.cpuPerAgent !== undefined || history.memPerAgentGb !== undefined)) {
59
+ const byCores = history.cpuPerAgent && history.cpuPerAgent > 0 ? slots(available / history.cpuPerAgent) : null;
60
+ const byMemory = history.memPerAgentGb && history.memPerAgentGb > 0 ? slots((freeGb - MEMORY_RESERVE_GB) / history.memPerAgentGb) : null;
61
+ const limits = [];
62
+ if (byCores !== null)
63
+ limits.push(["cores", byCores]);
64
+ if (byMemory !== null)
65
+ limits.push(["memory", byMemory]);
66
+ if (history.plateauRung !== undefined)
67
+ limits.push(["plateau", history.plateauRung]);
68
+ // a history with no usable figure (for example zero CPU per agent in the first seconds of a run) says nothing: fall through to the profile or the default
69
+ if (limits.length > 0) {
70
+ const [limitedBy, agents] = limits.reduce((best, entry) => (entry[1] < best[1] ? entry : best));
71
+ return result(history.heavyShare ? agents * history.heavyShare : agents, agents, { source: "history", limitedBy, byCores, byMemory });
72
+ }
73
+ }
74
+ if (!profile)
75
+ return result(facts.cores, facts.cores, { source: "default", limitedBy: "default", byCores: null, byMemory: null });
76
+ const cpu = cpuOf(profile);
77
+ const byCores = slots(available / cpu.threadsPerJob);
78
+ const byMemory = slots((freeGb - MEMORY_RESERVE_GB) / cpu.memPerJobGb);
79
+ const [limitedBy, cpuSlots] = byMemory < byCores ? ["memory", byMemory] : ["cores", byCores];
80
+ const cpuAgents = agentsFor(cpuSlots, cpu.heavyShare);
81
+ if (profile.kind !== "gpu" || !profile.gpu)
82
+ return result(cpuSlots, cpuAgents, { source: "profile", limitedBy, byCores, byMemory });
83
+ const gpuSlotMap = gpuSlotMapOf(facts.gpuMemMb ?? [], profile.gpu);
84
+ const gpuSlots = gpuSlotMap.length;
85
+ const agentsByGpu = gpuSlots === 0 ? 1 : agentsFor(gpuSlots, profile.gpu.heavyShare ?? PROFILE_DEFAULTS.heavyShare);
86
+ const gpuDecides = agentsByGpu < cpuAgents;
87
+ return result(cpuSlots, Math.min(cpuAgents, agentsByGpu), {
88
+ source: "profile",
89
+ limitedBy: gpuDecides ? "gpu" : limitedBy,
90
+ byCores,
91
+ byMemory,
92
+ gpuSlots,
93
+ gpuSlotMap,
94
+ agentsByGpu,
95
+ });
96
+ }
97
+ /** The line the examples print before a run. */
98
+ export function describeCapacity(capacity, chosen) {
99
+ const why = capacity.source === "default" ? "one per core, no task profile" : `limited by ${capacity.limitedBy}`;
100
+ const slotsText = capacity.gpuSlots > 0 ? `CPU slots ${capacity.cpuSlots}, GPU slots ${capacity.gpuSlots}` : `slots ${capacity.cpuSlots}`;
101
+ const used = chosen === undefined || chosen === capacity.agents ? "" : `; you asked for ${chosen}`;
102
+ return `This machine: recommended ${capacity.agents} agents (${slotsText}, source ${capacity.source}, ${why}; more than ${capacity.maxUseful} adds nothing)${used}. You may change it with --agents.`;
103
+ }
@@ -0,0 +1,16 @@
1
+ export const realClock = {
2
+ now: () => Date.now(),
3
+ sleep: (ms, signal) => new Promise((resolve, reject) => {
4
+ if (signal?.aborted)
5
+ return reject(signal.reason);
6
+ const onAbort = () => {
7
+ clearTimeout(timer);
8
+ reject(signal?.reason);
9
+ };
10
+ const timer = setTimeout(() => {
11
+ signal?.removeEventListener("abort", onAbort);
12
+ resolve();
13
+ }, ms);
14
+ signal?.addEventListener("abort", onAbort, { once: true });
15
+ }),
16
+ };
@@ -0,0 +1,48 @@
1
+ import { renderCsv } from "./csv.js";
2
+ import { better } from "./task.js";
3
+ export const resultsOf = (ledger) => ledger.filter((entry) => entry.type === "result");
4
+ /** Verified scores rank before self-reported ones; inside each group by score in the metric's direction; agents without a score last. */
5
+ export function rankCodeAgents(ledger, direction) {
6
+ const workDirs = new Map();
7
+ const results = new Map();
8
+ for (const entry of ledger) {
9
+ workDirs.set(entry.agent, entry.workDir);
10
+ if (entry.type === "result")
11
+ results.set(entry.agent, [...(results.get(entry.agent) ?? []), entry]);
12
+ }
13
+ const rows = [...workDirs].map(([agent, workDir]) => rowFor(agent, workDir, results.get(agent) ?? [], direction));
14
+ rows.sort((a, b) => compare(a, b, direction));
15
+ return rows.map((row, index) => ({ ...row, rank: index + 1 }));
16
+ }
17
+ function rowFor(agent, workDir, results, direction) {
18
+ const scored = results.filter((entry) => entry.status === "ok" && entry.score !== null);
19
+ const verified = scored.filter((entry) => !entry.selfReported);
20
+ const pool = verified.length > 0 ? verified : scored;
21
+ let best;
22
+ for (const entry of pool)
23
+ if (best === undefined || better(entry.score, best.score, direction))
24
+ best = entry;
25
+ return {
26
+ rank: 0,
27
+ agent,
28
+ score: best?.score ?? null,
29
+ selfReported: best?.selfReported ?? false,
30
+ submits: results.length,
31
+ errors: results.filter((entry) => entry.status === "error").length,
32
+ commit: best?.commit ?? null,
33
+ workDir,
34
+ };
35
+ }
36
+ function compare(a, b, direction) {
37
+ if ((a.score === null) !== (b.score === null))
38
+ return a.score === null ? 1 : -1;
39
+ if (a.selfReported !== b.selfReported)
40
+ return a.selfReported ? 1 : -1;
41
+ if (a.score !== null && b.score !== null && a.score !== b.score)
42
+ return better(a.score, b.score, direction) ? -1 : 1;
43
+ return a.agent - b.agent;
44
+ }
45
+ const CSV_HEADER = ["rank", "agent", "score", "self_reported", "submits", "errors", "commit", "work_dir"];
46
+ export function renderCodeCsv(rows) {
47
+ return renderCsv(CSV_HEADER, rows.map((row) => [row.rank, row.agent, row.score, row.selfReported, row.submits, row.errors, row.commit, row.workDir]));
48
+ }