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,110 @@
|
|
|
1
|
+
import { realpathSync, rmSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { adviceMessage } from "./prompts.js";
|
|
4
|
+
import { parseReviewSnapshot, readReviewEvidence, reviewQuestion } from "./review-snapshot.js";
|
|
5
|
+
/** The deny hook, the stop at the first final text (before the goal check can run, docs/test-report S0) and the turn limit, as one plugin. */
|
|
6
|
+
export function reviewGuard(options) {
|
|
7
|
+
const workDir = realpathSync(options.workDir);
|
|
8
|
+
let agent;
|
|
9
|
+
let last = "";
|
|
10
|
+
let turns = 0;
|
|
11
|
+
return {
|
|
12
|
+
name: "branch-review-guard",
|
|
13
|
+
bind: (bound) => {
|
|
14
|
+
agent = bound;
|
|
15
|
+
},
|
|
16
|
+
text: () => last,
|
|
17
|
+
setup(api) {
|
|
18
|
+
api.on("tool.before", async (call, context) => {
|
|
19
|
+
if (call.name !== "read")
|
|
20
|
+
return { kind: "deny", reason: "Only read is available during a review." };
|
|
21
|
+
const path = call.args?.path;
|
|
22
|
+
if (typeof path !== "string")
|
|
23
|
+
return { kind: "deny", reason: "Only read of a file in the agent's directory is available during a review." };
|
|
24
|
+
// an absolute path stands for itself; a path that is not there yet is judged by its written form (found by the preflight: "/etc/hosts" was once let through because join() glued it to the directory)
|
|
25
|
+
const target = resolve(context.env.cwd, path);
|
|
26
|
+
let real = target;
|
|
27
|
+
try {
|
|
28
|
+
real = realpathSync(target);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
// not there: the tool will say "not found"; only the written form can be judged
|
|
32
|
+
}
|
|
33
|
+
if (real === workDir || real.startsWith(`${workDir}/`))
|
|
34
|
+
return { kind: "allow" };
|
|
35
|
+
return { kind: "deny", reason: "During a review only files in the agent's own directory can be read." };
|
|
36
|
+
});
|
|
37
|
+
api.on("event", (event) => {
|
|
38
|
+
if (event.type !== "message_end" || event.message.role !== "assistant")
|
|
39
|
+
return;
|
|
40
|
+
turns += 1;
|
|
41
|
+
const text = event.message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("");
|
|
42
|
+
const calls = event.message.content.some((part) => part.type === "tool_call");
|
|
43
|
+
if (!calls && event.message.stop === "stop")
|
|
44
|
+
last = text;
|
|
45
|
+
if (!calls || turns >= options.maxTurns)
|
|
46
|
+
agent?.cancel();
|
|
47
|
+
});
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Forks, asks, collects the answer, and always deletes the fork file. Never throws: an error is an outcome. */
|
|
52
|
+
export async function runReview(options) {
|
|
53
|
+
const started = options.now();
|
|
54
|
+
const repliesAtFork = options.target.replies();
|
|
55
|
+
let tokens = 0;
|
|
56
|
+
let cacheRead = 0;
|
|
57
|
+
let reviewer;
|
|
58
|
+
try {
|
|
59
|
+
if (options.signal.aborted)
|
|
60
|
+
return { outcome: "error", ms: 0, tokens: 0, error: "the run ended before the review began" };
|
|
61
|
+
await options.target.fork(options.forkPath);
|
|
62
|
+
const output = options.output ?? {};
|
|
63
|
+
const evidence = readReviewEvidence(options.forkPath);
|
|
64
|
+
const guard = reviewGuard({ workDir: options.workDir, maxTurns: options.maxTurns });
|
|
65
|
+
reviewer = await options.target.openReviewer(options.forkPath, guard, (client) => ({
|
|
66
|
+
model: client.model,
|
|
67
|
+
async *stream(request, signal) {
|
|
68
|
+
for await (const event of client.stream(request, signal)) {
|
|
69
|
+
if (event.type === "usage") {
|
|
70
|
+
tokens += event.usage.input + event.usage.output + event.usage.cacheRead + event.usage.cacheWrite;
|
|
71
|
+
cacheRead += event.usage.cacheRead;
|
|
72
|
+
}
|
|
73
|
+
yield event;
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
}));
|
|
77
|
+
guard.bind(reviewer);
|
|
78
|
+
// the cancel goes to the run itself, and is checked once more after the listener is in place, so that a stop in between cannot be missed
|
|
79
|
+
const run = reviewer.run(reviewQuestion(output, evidence));
|
|
80
|
+
const onAbort = () => run.cancel();
|
|
81
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
82
|
+
if (options.signal.aborted)
|
|
83
|
+
run.cancel();
|
|
84
|
+
try {
|
|
85
|
+
const result = await run.result;
|
|
86
|
+
if (result.reason === "error")
|
|
87
|
+
return { outcome: "error", ms: options.now() - started, tokens, cacheRead, error: result.error ?? "the reviewer's run failed" };
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
options.signal.removeEventListener("abort", onAbort);
|
|
91
|
+
}
|
|
92
|
+
if (options.signal.aborted)
|
|
93
|
+
return { outcome: "error", ms: options.now() - started, tokens, cacheRead, error: "the run ended during the review" };
|
|
94
|
+
const snapshot = parseReviewSnapshot(guard.text().trim(), output, evidence, { observedAt: started, observedTurn: repliesAtFork });
|
|
95
|
+
const ms = options.now() - started;
|
|
96
|
+
if (snapshot.steer === null)
|
|
97
|
+
return { outcome: "ok", ms, tokens, cacheRead, snapshot };
|
|
98
|
+
const age = Math.max(0, options.target.replies() - repliesAtFork);
|
|
99
|
+
options.target.advise(adviceMessage(snapshot.steer, age, ms / 1000));
|
|
100
|
+
return { outcome: "steer", text: snapshot.steer, ms, tokens, cacheRead, snapshot };
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
return { outcome: "error", ms: options.now() - started, tokens, cacheRead, error: error instanceof Error ? error.message : String(error) };
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
await reviewer?.close().catch(() => undefined);
|
|
107
|
+
for (const path of [options.forkPath, `${options.forkPath}.lock`])
|
|
108
|
+
rmSync(path, { force: true });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** When agents are due for a branch review (pure; no clock). */
|
|
2
|
+
/**
|
|
3
|
+
* Who is due for a review and when (docs/10 section 1.1). Agent `n` has the slot `(n - 1) mod ceiling` and is due at
|
|
4
|
+
* `start + slot / ceiling x T + k x T`, k = 1, 2, ...: with 30 agents and T = 7 minutes about one review every 14 seconds, never all at once.
|
|
5
|
+
* Pure: it knows no clock; the caller passes the time.
|
|
6
|
+
*/
|
|
7
|
+
export class ReviewScheduler {
|
|
8
|
+
everyMs;
|
|
9
|
+
ceiling;
|
|
10
|
+
started = new Map();
|
|
11
|
+
round = new Map();
|
|
12
|
+
constructor(everyMs, ceiling) {
|
|
13
|
+
if (!(everyMs > 0) || !(ceiling >= 1))
|
|
14
|
+
throw new RangeError("everyMs must be positive and ceiling at least 1");
|
|
15
|
+
this.everyMs = everyMs;
|
|
16
|
+
this.ceiling = ceiling;
|
|
17
|
+
}
|
|
18
|
+
slot(agent) {
|
|
19
|
+
return (agent - 1) % this.ceiling;
|
|
20
|
+
}
|
|
21
|
+
register(agent, startedAt) {
|
|
22
|
+
this.started.set(agent, startedAt);
|
|
23
|
+
this.round.set(agent, 1);
|
|
24
|
+
}
|
|
25
|
+
forget(agent) {
|
|
26
|
+
this.started.delete(agent);
|
|
27
|
+
this.round.delete(agent);
|
|
28
|
+
}
|
|
29
|
+
nextDue(agent) {
|
|
30
|
+
const start = this.started.get(agent);
|
|
31
|
+
if (start === undefined)
|
|
32
|
+
return undefined;
|
|
33
|
+
return start + (this.slot(agent) / this.ceiling) * this.everyMs + (this.round.get(agent) ?? 1) * this.everyMs;
|
|
34
|
+
}
|
|
35
|
+
/** The agents whose time has come, the longest overdue first. Asking does not use the due time up: a skipped review is offered again at the next check. */
|
|
36
|
+
dueAgents(now) {
|
|
37
|
+
return [...this.started.keys()]
|
|
38
|
+
.map((agent) => ({ agent, due: this.nextDue(agent) }))
|
|
39
|
+
.filter((entry) => entry.due <= now)
|
|
40
|
+
.sort((a, b) => a.due - b.due || a.agent - b.agent)
|
|
41
|
+
.map((entry) => entry.agent);
|
|
42
|
+
}
|
|
43
|
+
/** The review of this agent has begun: the next due time is the first one after `now`, so one due time never fires twice. */
|
|
44
|
+
begun(agent, now) {
|
|
45
|
+
let round = this.round.get(agent) ?? 1;
|
|
46
|
+
while (this.nextDueFor(agent, round) <= now)
|
|
47
|
+
round += 1;
|
|
48
|
+
this.round.set(agent, round);
|
|
49
|
+
}
|
|
50
|
+
nextDueFor(agent, round) {
|
|
51
|
+
return this.started.get(agent) + (this.slot(agent) / this.ceiling) * this.everyMs + round * this.everyMs;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { JsonlFile } from "./jsonl.js";
|
|
2
|
+
const statuses = ["working", "waiting", "blocked", "ready_for_review", "unknown"];
|
|
3
|
+
const assessments = ["on_track", "needs_attention", "unknown"];
|
|
4
|
+
const maxEvidence = 8;
|
|
5
|
+
const maxTextLength = 500;
|
|
6
|
+
function isRecord(value) {
|
|
7
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
}
|
|
9
|
+
function isText(value) {
|
|
10
|
+
return typeof value === "string" && value.trim().length > 0 && value.length <= maxTextLength;
|
|
11
|
+
}
|
|
12
|
+
function isChoice(value, options) {
|
|
13
|
+
return typeof value === "string" && options.some((option) => option === value);
|
|
14
|
+
}
|
|
15
|
+
export function reviewOutputProblems(settings) {
|
|
16
|
+
const problems = [];
|
|
17
|
+
if (settings.criteria !== undefined && !isText(settings.criteria))
|
|
18
|
+
problems.push("criteria must be nonempty and at most 500 characters");
|
|
19
|
+
const fields = settings.fields ?? {};
|
|
20
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
21
|
+
if (!/^[a-z][a-zA-Z0-9_]{0,39}$/.test(name) || Object.hasOwn(Object.prototype, name))
|
|
22
|
+
problems.push(`invalid field name '${name}'`);
|
|
23
|
+
if (!isText(field.description))
|
|
24
|
+
problems.push(`field '${name}' needs a description of at most 500 characters`);
|
|
25
|
+
if (!isChoice(field.type, ["number", "string", "boolean", "enum"]))
|
|
26
|
+
problems.push(`invalid type for '${name}'`);
|
|
27
|
+
if (field.type === "enum" &&
|
|
28
|
+
(!Array.isArray(field.values) || field.values.length < 2 || !field.values.every(isText) || new Set(field.values).size !== field.values.length)) {
|
|
29
|
+
problems.push(`field '${name}' needs distinct enum values in low-to-high order`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (settings.sort) {
|
|
33
|
+
const field = Object.hasOwn(fields, settings.sort.field) ? fields[settings.sort.field] : undefined;
|
|
34
|
+
if (field?.type !== "number" && field?.type !== "enum")
|
|
35
|
+
problems.push("sort must refer to a number or enum field");
|
|
36
|
+
if (!isChoice(settings.sort.direction, ["min", "max"]))
|
|
37
|
+
problems.push("sort direction must be min or max");
|
|
38
|
+
}
|
|
39
|
+
return problems;
|
|
40
|
+
}
|
|
41
|
+
export function readReviewEvidence(forkPath) {
|
|
42
|
+
return new JsonlFile(forkPath)
|
|
43
|
+
.readAll()
|
|
44
|
+
.flatMap((entry) => entry.type === "message" && entry.message.role === "tool" && entry.message.toolName
|
|
45
|
+
? [{ entryId: entry.id, tool: entry.message.toolName, failed: entry.message.isError === true }]
|
|
46
|
+
: [])
|
|
47
|
+
.slice(-maxEvidence);
|
|
48
|
+
}
|
|
49
|
+
const ref = (index) => `E${index + 1}`;
|
|
50
|
+
export function reviewQuestion(settings, evidence) {
|
|
51
|
+
const fields = Object.entries(settings.fields ?? {}).map(([name, field]) => `${name}: ${field.type === "enum" ? field.values.join(" | ") : field.type}. ${field.description}`);
|
|
52
|
+
const references = evidence.map((item, index) => `${ref(index)}: ${item.tool}${item.failed ? " (error)" : ""}`);
|
|
53
|
+
return [
|
|
54
|
+
"This is a review by an outside reviewer. Stop working as the agent. Inspect the forked conversation and only read files if needed.",
|
|
55
|
+
"Return one JSON object with exactly these keys: status, assessment, priority, summary, reason, evidenceRefs, steer, details.",
|
|
56
|
+
`status: ${statuses.join(" | ")}. assessment: ${assessments.join(" | ")}.`,
|
|
57
|
+
"priority: 0 for routine progress, 1 for a notable milestone, 2 for a blocker, 3 for an urgent issue, or null when evidence is insufficient.",
|
|
58
|
+
"summary and reason: one concise sentence each, at most 500 characters. Do not include secrets, host details or absolute paths.",
|
|
59
|
+
"evidenceRefs: choose up to two references from the listed recent tool results in chronological order. Cite only results that support the assessment. If there is insufficient evidence, use unknown status and assessment, null priority and steer, and an empty evidenceRefs array.",
|
|
60
|
+
"steer: null when there is no new actionable advice, otherwise a short suggestion of at most 500 characters supported by the cited evidence.",
|
|
61
|
+
`details: an object with optional task fields. ${fields.length ? fields.join("\n") : "Use {}."}`,
|
|
62
|
+
...(settings.criteria ? [`Task-specific criteria: ${settings.criteria}`] : []),
|
|
63
|
+
`Available references:\n${references.join("\n") || "(none)"}`,
|
|
64
|
+
].join("\n");
|
|
65
|
+
}
|
|
66
|
+
function detailValue(value, field) {
|
|
67
|
+
switch (field.type) {
|
|
68
|
+
case "number":
|
|
69
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
70
|
+
case "string":
|
|
71
|
+
return isText(value);
|
|
72
|
+
case "boolean":
|
|
73
|
+
return typeof value === "boolean";
|
|
74
|
+
case "enum":
|
|
75
|
+
return isChoice(value, field.values);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function parseDetails(value, settings) {
|
|
79
|
+
if (!isRecord(value))
|
|
80
|
+
throw new Error("details must be an object");
|
|
81
|
+
const fields = settings.fields ?? {};
|
|
82
|
+
const details = {};
|
|
83
|
+
for (const [key, candidate] of Object.entries(value)) {
|
|
84
|
+
const field = Object.hasOwn(fields, key) ? fields[key] : undefined;
|
|
85
|
+
if (!field || !detailValue(candidate, field))
|
|
86
|
+
throw new Error("invalid task detail");
|
|
87
|
+
details[key] = candidate;
|
|
88
|
+
}
|
|
89
|
+
return details;
|
|
90
|
+
}
|
|
91
|
+
function sortValue(settings, priority, details) {
|
|
92
|
+
if (!settings.sort)
|
|
93
|
+
return priority;
|
|
94
|
+
const value = details[settings.sort.field];
|
|
95
|
+
const field = settings.fields?.[settings.sort.field];
|
|
96
|
+
if (value === undefined || !field)
|
|
97
|
+
return null;
|
|
98
|
+
const order = field.type === "enum" ? field.values.indexOf(value) : value;
|
|
99
|
+
return settings.sort.direction === "min" ? -order : order;
|
|
100
|
+
}
|
|
101
|
+
const outputKeys = ["status", "assessment", "priority", "summary", "reason", "evidenceRefs", "steer", "details"];
|
|
102
|
+
export function parseReviewSnapshot(text, settings, evidence, observed) {
|
|
103
|
+
let value;
|
|
104
|
+
try {
|
|
105
|
+
value = JSON.parse(text.replace(/^```(?:json)?\s*\n([\s\S]*?)\n```$/i, "$1"));
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
throw new Error("expected one JSON object");
|
|
109
|
+
}
|
|
110
|
+
if (!isRecord(value) || Object.keys(value).length !== outputKeys.length || outputKeys.some((key) => !Object.hasOwn(value, key))) {
|
|
111
|
+
throw new Error("unexpected review fields");
|
|
112
|
+
}
|
|
113
|
+
const { status, assessment, priority, summary, reason, evidenceRefs, steer, details } = value;
|
|
114
|
+
if (!isChoice(status, statuses) || !isChoice(assessment, assessments))
|
|
115
|
+
throw new Error("invalid status or assessment");
|
|
116
|
+
if (priority !== null && ![0, 1, 2, 3].some((level) => level === priority))
|
|
117
|
+
throw new Error("invalid priority");
|
|
118
|
+
if (!isText(summary) || !isText(reason) || (steer !== null && !isText(steer)))
|
|
119
|
+
throw new Error("invalid review text");
|
|
120
|
+
if (!Array.isArray(evidenceRefs) || evidenceRefs.length > 2 || new Set(evidenceRefs).size !== evidenceRefs.length) {
|
|
121
|
+
throw new Error("invalid evidence references");
|
|
122
|
+
}
|
|
123
|
+
const chosen = evidenceRefs.map((key) => {
|
|
124
|
+
const index = evidence.findIndex((_, index) => key === ref(index));
|
|
125
|
+
const item = evidence[index];
|
|
126
|
+
if (!item)
|
|
127
|
+
throw new Error("unknown evidence reference");
|
|
128
|
+
return item;
|
|
129
|
+
});
|
|
130
|
+
if (chosen.length === 0 && (status !== "unknown" || assessment !== "unknown" || priority !== null || steer !== null)) {
|
|
131
|
+
throw new Error("review claims require evidence");
|
|
132
|
+
}
|
|
133
|
+
const checkedDetails = parseDetails(details, settings);
|
|
134
|
+
if (chosen.length === 0 && Object.keys(checkedDetails).length > 0)
|
|
135
|
+
throw new Error("task details require evidence");
|
|
136
|
+
const checkedPriority = priority;
|
|
137
|
+
return {
|
|
138
|
+
version: 1,
|
|
139
|
+
...observed,
|
|
140
|
+
status,
|
|
141
|
+
assessment,
|
|
142
|
+
priority: checkedPriority,
|
|
143
|
+
summary,
|
|
144
|
+
reason,
|
|
145
|
+
evidence: chosen,
|
|
146
|
+
steer: steer?.trim() ?? null,
|
|
147
|
+
details: checkedDetails,
|
|
148
|
+
sortValue: sortValue(settings, checkedPriority, checkedDetails),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { join, resolve } from "node:path";
|
|
2
|
+
/** The directory of the shims the agents' commands may use (`gpu`), first on their PATH. */
|
|
3
|
+
export const binDirOf = (root) => join(root, "bin");
|
|
4
|
+
/** The lock files and the log of the GPU slots. */
|
|
5
|
+
export const gpuLocksDirOf = (root) => join(root, "gpu-locks");
|
|
6
|
+
const agentName = (agent) => String(agent).padStart(3, "0");
|
|
7
|
+
/** The root becomes an absolute path: Lean runs in other directories and needs paths that mean the same everywhere. */
|
|
8
|
+
export function runLayout(rootPath) {
|
|
9
|
+
const root = resolve(rootPath);
|
|
10
|
+
const agentDir = (agent) => join(root, "agents", agentName(agent));
|
|
11
|
+
return {
|
|
12
|
+
root,
|
|
13
|
+
ledger: join(root, "ledger.jsonl"),
|
|
14
|
+
events: join(root, "events.jsonl"),
|
|
15
|
+
state: join(root, "state.json"),
|
|
16
|
+
reportDir: join(root, "report"),
|
|
17
|
+
leaderboardCsv: join(root, "report", "leaderboard.csv"),
|
|
18
|
+
reportHtml: join(root, "report", "report.html"),
|
|
19
|
+
leanDir: join(root, "lean"),
|
|
20
|
+
sharedDir: join(root, "shared"),
|
|
21
|
+
keeperDir: join(root, ".keeper"),
|
|
22
|
+
reviewDir: join(root, "reviews"),
|
|
23
|
+
machine: join(root, "machine.jsonl"),
|
|
24
|
+
agentDir,
|
|
25
|
+
workDir: (agent) => join(agentDir(agent), "work"),
|
|
26
|
+
sessionFile: (agent) => join(agentDir(agent), "session.jsonl"),
|
|
27
|
+
finishedMarker: (agent) => join(agentDir(agent), "finished"),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// What an agent cannot see about its own run, told to it in every request: how long it has worked, whether anything of it counts yet, how much disk it holds.
|
|
2
|
+
// A note at the end of the request (not kept in the log), in the same way as Sakura's limits notes. Two reminders when a line is crossed:
|
|
3
|
+
// no submit after a while (a run whose agents never submit produces nothing), and a work directory above its share of the disk.
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
const MEASURE_EVERY_MS = 2 * 60_000;
|
|
6
|
+
const GB = 1024 ** 3;
|
|
7
|
+
/** `du -sk`: the size on disk, without reading the files. 0 when it cannot be measured. */
|
|
8
|
+
const duBytes = (dir) => new Promise((resolve) => {
|
|
9
|
+
execFile("du", ["-sk", dir], { timeout: 60_000 }, (error, stdout) => resolve(error ? 0 : Number.parseInt(stdout, 10) * 1024 || 0));
|
|
10
|
+
});
|
|
11
|
+
export function runNotesPlugin(options) {
|
|
12
|
+
const startedAt = options.now();
|
|
13
|
+
const firstSubmitMinutes = options.firstSubmitMinutes ?? 20;
|
|
14
|
+
const shareGb = options.workDirGb ?? 20;
|
|
15
|
+
const measure = options.measure ?? duBytes;
|
|
16
|
+
let submits = options.submitsBefore;
|
|
17
|
+
let bytes;
|
|
18
|
+
let measuredAt = Number.NEGATIVE_INFINITY;
|
|
19
|
+
let measuring = false;
|
|
20
|
+
/** Starts a measurement when the last one is old; the note uses the last known size (the request does not wait for the disk). */
|
|
21
|
+
const refreshSize = () => {
|
|
22
|
+
if (measuring || options.now() - measuredAt < MEASURE_EVERY_MS)
|
|
23
|
+
return;
|
|
24
|
+
measuring = true;
|
|
25
|
+
measuredAt = options.now();
|
|
26
|
+
void measure(options.workDir).then((value) => {
|
|
27
|
+
bytes = value;
|
|
28
|
+
measuring = false;
|
|
29
|
+
}, () => {
|
|
30
|
+
measuring = false;
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
const note = () => {
|
|
34
|
+
const minutes = Math.floor((options.now() - startedAt) / 60_000);
|
|
35
|
+
const gb = bytes === undefined ? undefined : bytes / GB;
|
|
36
|
+
const parts = [`${minutes} minutes since you started`, `${submits} submit${submits === 1 ? "" : "s"} so far`];
|
|
37
|
+
if (gb !== undefined)
|
|
38
|
+
parts.push(`work directory ${gb.toFixed(1)} GB of a ${shareGb} GB share`);
|
|
39
|
+
let text = `[Run: ${parts.join("; ")}.`;
|
|
40
|
+
if (submits === 0 && minutes >= firstSubmitMinutes)
|
|
41
|
+
text += " Nothing of yours counts yet: submit a working baseline now, even a simple one, then improve it.";
|
|
42
|
+
if (gb !== undefined && gb > shareGb)
|
|
43
|
+
text +=
|
|
44
|
+
" Your work directory is over its share of the disk: delete intermediate files you no longer need (old pickles, checkpoints, copies of data) before you make more.";
|
|
45
|
+
return `${text}]`;
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
name: "infinity-run-notes",
|
|
49
|
+
compensates: "an agent cannot see how long it has worked, that nothing of it counts until it submits, or how much disk it fills",
|
|
50
|
+
submitted() {
|
|
51
|
+
submits += 1;
|
|
52
|
+
},
|
|
53
|
+
setup(api) {
|
|
54
|
+
api.on("context", ({ messages }) => {
|
|
55
|
+
refreshSize();
|
|
56
|
+
const message = { role: "user", content: [{ type: "text", text: note() }], ts: options.now() };
|
|
57
|
+
return [...messages, message];
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { JsonlFile } from "./jsonl.js";
|
|
3
|
+
import { writeReport } from "./report.js";
|
|
4
|
+
const REPORT_EVERY_MS = 60_000;
|
|
5
|
+
/**
|
|
6
|
+
* Everything the run writes down, behind a few verbs. It knows each agent's last commit, so that every ledger line carries the pointer
|
|
7
|
+
* (agent, workDir, commit) without the caller repeating it.
|
|
8
|
+
*/
|
|
9
|
+
export class RunRecorder {
|
|
10
|
+
layout;
|
|
11
|
+
metric;
|
|
12
|
+
clock;
|
|
13
|
+
ledger;
|
|
14
|
+
events;
|
|
15
|
+
lastCommit = new Map();
|
|
16
|
+
lastReportAt = Number.NEGATIVE_INFINITY;
|
|
17
|
+
constructor(layout, clock, metric) {
|
|
18
|
+
this.metric = metric;
|
|
19
|
+
this.layout = layout;
|
|
20
|
+
this.clock = clock;
|
|
21
|
+
mkdirSync(layout.root, { recursive: true });
|
|
22
|
+
this.ledger = new JsonlFile(layout.ledger);
|
|
23
|
+
this.events = new JsonlFile(layout.events);
|
|
24
|
+
}
|
|
25
|
+
event(event) {
|
|
26
|
+
this.events.append({ ...event, ts: this.clock.now() });
|
|
27
|
+
}
|
|
28
|
+
lifecycle(agent, event, detail = "") {
|
|
29
|
+
this.ledger.append({ type: "lifecycle", ...this.pointer(agent), event, detail });
|
|
30
|
+
}
|
|
31
|
+
commit(agent, commit, turn) {
|
|
32
|
+
this.lastCommit.set(agent, commit);
|
|
33
|
+
this.ledger.append({ type: "commit", ...this.pointer(agent), commit, turn });
|
|
34
|
+
}
|
|
35
|
+
result(agent, record) {
|
|
36
|
+
if (record.commit)
|
|
37
|
+
this.lastCommit.set(agent, record.commit);
|
|
38
|
+
this.ledger.append({ type: "result", ...this.pointer(agent), ...record });
|
|
39
|
+
// the files in report/ are snapshots; after a result they are rewritten at most once a minute (the viewer ranks from the ledger itself)
|
|
40
|
+
if (this.clock.now() - this.lastReportAt >= REPORT_EVERY_MS)
|
|
41
|
+
this.report();
|
|
42
|
+
}
|
|
43
|
+
/** Regenerates leaderboard.csv and report.html from the two logs. */
|
|
44
|
+
report() {
|
|
45
|
+
this.lastReportAt = this.clock.now();
|
|
46
|
+
writeReport(this.layout, this.metric);
|
|
47
|
+
}
|
|
48
|
+
pointer(agent) {
|
|
49
|
+
return { ts: this.clock.now(), agent, workDir: this.layout.workDir(agent), commit: this.lastCommit.get(agent) || null };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
export function saveState(path, state) {
|
|
3
|
+
const temporary = `${path}.tmp`;
|
|
4
|
+
writeFileSync(temporary, `${JSON.stringify(state)}\n`);
|
|
5
|
+
renameSync(temporary, path);
|
|
6
|
+
}
|
|
7
|
+
export function loadState(path) {
|
|
8
|
+
if (!existsSync(path))
|
|
9
|
+
return undefined;
|
|
10
|
+
try {
|
|
11
|
+
const state = JSON.parse(readFileSync(path, "utf8"));
|
|
12
|
+
return state.version === 1 ? state : undefined;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { existsSync, statSync } from "node:fs";
|
|
2
|
+
import { JsonlFile } from "./jsonl.js";
|
|
3
|
+
import { runLayout } from "./run-layout.js";
|
|
4
|
+
import { loadState } from "./run-state.js";
|
|
5
|
+
const QUIET_MS = 3 * 60_000;
|
|
6
|
+
/** The status of a run from its files. `now` is for tests. */
|
|
7
|
+
export function readRunStatus(runDir, now = Date.now()) {
|
|
8
|
+
const layout = runLayout(runDir);
|
|
9
|
+
const state = loadState(layout.state);
|
|
10
|
+
const events = new JsonlFile(layout.events).readAll();
|
|
11
|
+
const results = new JsonlFile(layout.ledger).readAll().filter((entry) => entry.type === "result");
|
|
12
|
+
const boundary = events.findLast((event) => event.type === "run_start" || event.type === "run_end");
|
|
13
|
+
const warnings = events.flatMap((event) => (event.type === "warning" ? [event.message] : []));
|
|
14
|
+
const touched = [layout.state, layout.events].filter(existsSync).map((file) => statSync(file).mtimeMs);
|
|
15
|
+
const quiet = touched.length === 0 || now - Math.max(...touched) > QUIET_MS;
|
|
16
|
+
const finished = boundary?.type === "run_end" ? boundary.reason : boundary?.type === "run_start" ? null : (state?.finished ?? null);
|
|
17
|
+
const rung = state ? (state.ladder.rungs[state.ladder.rungIndex] ?? null) : null;
|
|
18
|
+
return {
|
|
19
|
+
runDir: layout.root,
|
|
20
|
+
task: state?.task ?? null,
|
|
21
|
+
state: !state && events.length === 0 ? "empty" : finished !== null ? "finished" : quiet ? "stopped" : "running",
|
|
22
|
+
reason: finished,
|
|
23
|
+
startedAt: state?.startedAt ?? null,
|
|
24
|
+
tokensUsed: state?.tokensUsed ?? 0,
|
|
25
|
+
requests: state?.requests ?? 0,
|
|
26
|
+
bestScore: state?.bestScore ?? null,
|
|
27
|
+
agentsLive: state && finished === null && !quiet ? Object.keys(state.ladder.live).length : 0,
|
|
28
|
+
rung,
|
|
29
|
+
results: results.length,
|
|
30
|
+
warnings,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** The events of a run from position `from` on (default: all), and the position to ask for next time. Read from the file, so it works for any run directory. */
|
|
34
|
+
export function readRunEvents(runDir, from = 0) {
|
|
35
|
+
const all = new JsonlFile(runLayout(runDir).events).readAll();
|
|
36
|
+
return { events: all.slice(from), next: all.length };
|
|
37
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function percentile(sorted, fraction) {
|
|
2
|
+
if (sorted.length === 0)
|
|
3
|
+
return 0;
|
|
4
|
+
const index = Math.min(sorted.length - 1, Math.ceil(fraction * sorted.length) - 1);
|
|
5
|
+
return sorted[Math.max(0, index)] ?? 0;
|
|
6
|
+
}
|
|
7
|
+
export class RungMeter {
|
|
8
|
+
startedAt;
|
|
9
|
+
latencies = [];
|
|
10
|
+
tokens = 0;
|
|
11
|
+
throttleCount = 0;
|
|
12
|
+
constructor(now) {
|
|
13
|
+
this.startedAt = now;
|
|
14
|
+
}
|
|
15
|
+
recordReply(latencyMs, tokens) {
|
|
16
|
+
this.latencies.push(latencyMs);
|
|
17
|
+
this.tokens += tokens;
|
|
18
|
+
}
|
|
19
|
+
recordThrottle() {
|
|
20
|
+
this.throttleCount += 1;
|
|
21
|
+
}
|
|
22
|
+
/** The numbers of the rung that ends now; starts a new rung. */
|
|
23
|
+
closeRung(now) {
|
|
24
|
+
const sorted = [...this.latencies].sort((a, b) => a - b);
|
|
25
|
+
const minutes = Math.max(now - this.startedAt, 1) / 60_000;
|
|
26
|
+
const stats = {
|
|
27
|
+
replies: sorted.length,
|
|
28
|
+
throttles: this.throttleCount,
|
|
29
|
+
latencyP50Ms: percentile(sorted, 0.5),
|
|
30
|
+
latencyP95Ms: percentile(sorted, 0.95),
|
|
31
|
+
tokensPerMinute: this.tokens / minutes,
|
|
32
|
+
};
|
|
33
|
+
this.startedAt = now;
|
|
34
|
+
this.latencies = [];
|
|
35
|
+
this.tokens = 0;
|
|
36
|
+
this.throttleCount = 0;
|
|
37
|
+
return stats;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { reviewPlugin } from "sakura-agent";
|
|
2
|
+
import { createGuardRules } from "./review-rules.js";
|
|
3
|
+
const DEFAULT_BREAKER = 8;
|
|
4
|
+
/**
|
|
5
|
+
* The safety review in front of one agent's commands (docs/05 section 6): the framework's hard rules, then the guard rules of this run
|
|
6
|
+
* (which directories are the agent's own, which places are forbidden), then the reviewer model with the policy lists below.
|
|
7
|
+
*/
|
|
8
|
+
export function safetyReview(options) {
|
|
9
|
+
const extra = options.settings.policy ?? {};
|
|
10
|
+
return reviewPlugin({
|
|
11
|
+
llm: options.client,
|
|
12
|
+
policy: {
|
|
13
|
+
environment: [
|
|
14
|
+
"$defaults",
|
|
15
|
+
"The agent trains and tests models on this machine with its own shell; network access for packages, public models and public data is expected.",
|
|
16
|
+
...(extra.environment ?? []),
|
|
17
|
+
],
|
|
18
|
+
allow: [
|
|
19
|
+
"$defaults",
|
|
20
|
+
"Running the agent's own scripts (python, pip install, git inside its directory) and writing results, logs and models inside its directory.",
|
|
21
|
+
...(extra.allow ?? []),
|
|
22
|
+
],
|
|
23
|
+
soft_deny: ["$defaults", ...(extra.soft_deny ?? [])],
|
|
24
|
+
hard_deny: [
|
|
25
|
+
"$defaults",
|
|
26
|
+
"Looking for, reading or rebuilding the hidden data the score is computed on, or reading other agents' directories, the run's ledger or its state.",
|
|
27
|
+
"Changing or deleting the evaluator or the shared data.",
|
|
28
|
+
...(extra.hard_deny ?? []),
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
authorizers: [
|
|
32
|
+
createGuardRules({
|
|
33
|
+
agentDir: options.agentDir,
|
|
34
|
+
runRoot: options.runRoot,
|
|
35
|
+
sharedDir: options.sharedDir,
|
|
36
|
+
keeperDir: options.keeperDir,
|
|
37
|
+
hiddenOriginals: options.hiddenOriginals,
|
|
38
|
+
protectedPaths: options.protectedPaths,
|
|
39
|
+
}),
|
|
40
|
+
],
|
|
41
|
+
breaker: { consecutive: options.settings.breakerConsecutive ?? DEFAULT_BREAKER },
|
|
42
|
+
});
|
|
43
|
+
}
|