@omacode/micromanager 0.0.0-stage → 1.0.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.
- package/LICENSE +201 -0
- package/README.md +30 -2
- package/THIRD_PARTY.md +100 -0
- package/decider/.python-version +1 -0
- package/decider/README.md +35 -0
- package/decider/decider/__init__.py +1 -0
- package/decider/decider/server.py +327 -0
- package/decider/pyproject.toml +34 -0
- package/decider/uv.lock +1255 -0
- package/dist/agenda.js +51 -0
- package/dist/agents.js +58 -0
- package/dist/artifact/handoff.js +281 -0
- package/dist/ask.js +200 -0
- package/dist/backends.js +219 -0
- package/dist/backlog.js +414 -0
- package/dist/bench.js +427 -0
- package/dist/board.js +1 -0
- package/dist/brief.js +202 -0
- package/dist/browser.js +679 -0
- package/dist/budget.js +61 -0
- package/dist/catalog.js +187 -0
- package/dist/checkchange.js +145 -0
- package/dist/checkpoint.js +94 -0
- package/dist/cli.js +764 -0
- package/dist/comfy-gate.js +258 -0
- package/dist/compact.js +142 -0
- package/dist/config.js +344 -0
- package/dist/context/capture.js +1 -0
- package/dist/context/digest.js +1 -0
- package/dist/context/embed.js +1 -0
- package/dist/context/index.js +2 -0
- package/dist/context/ledger.js +1 -0
- package/dist/context/manager.js +1 -0
- package/dist/context/memory.js +1 -0
- package/dist/context/policy.js +1 -0
- package/dist/context/prices.js +1 -0
- package/dist/context/recall.js +1 -0
- package/dist/context/rules.js +1 -0
- package/dist/context/search.js +1 -0
- package/dist/context/status.js +1 -0
- package/dist/context/store.js +1 -0
- package/dist/context/summary.js +1 -0
- package/dist/context/tokens.js +1 -0
- package/dist/context/tools.js +1 -0
- package/dist/continuation.js +184 -0
- package/dist/contract.js +294 -0
- package/dist/contractround.js +178 -0
- package/dist/control.js +1 -0
- package/dist/creative-tools.js +237 -0
- package/dist/dataset.js +175 -0
- package/dist/decide.js +676 -0
- package/dist/decider.js +171 -0
- package/dist/design-shell.js +448 -0
- package/dist/design.js +1410 -0
- package/dist/desktop.js +44 -0
- package/dist/egress.js +156 -0
- package/dist/eval.js +60 -0
- package/dist/evolver.js +302 -0
- package/dist/features.js +193 -0
- package/dist/followups.js +32 -0
- package/dist/forms.js +195 -0
- package/dist/gate.js +108 -0
- package/dist/gatebox.js +46 -0
- package/dist/grants.js +189 -0
- package/dist/graph.js +65 -0
- package/dist/guard/index.js +1 -0
- package/dist/guard/wire.js +1 -0
- package/dist/helpers.js +85 -0
- package/dist/hooks.js +158 -0
- package/dist/image-models.js +117 -0
- package/dist/integration.js +3 -0
- package/dist/journal.js +1 -0
- package/dist/look.js +363 -0
- package/dist/memory.js +1 -0
- package/dist/mode.js +97 -0
- package/dist/native.js +3348 -0
- package/dist/nogit.js +259 -0
- package/dist/outcomes.js +148 -0
- package/dist/permission.js +35 -0
- package/dist/pick.js +89 -0
- package/dist/pipelines.js +262 -0
- package/dist/plan.js +641 -0
- package/dist/plandoc.js +211 -0
- package/dist/plugin.js +4736 -0
- package/dist/policy.js +58 -0
- package/dist/pools.js +1 -0
- package/dist/preview.js +274 -0
- package/dist/profile.js +165 -0
- package/dist/progress.js +1 -0
- package/dist/promote.js +313 -0
- package/dist/redact.js +1 -0
- package/dist/registry.js +179 -0
- package/dist/riskscore.js +126 -0
- package/dist/roles.js +1 -0
- package/dist/routing.js +1 -0
- package/dist/runner.js +1892 -0
- package/dist/sandbox.js +3 -0
- package/dist/sandboxgate.js +90 -0
- package/dist/scheduler.js +170 -0
- package/dist/services-main.js +131 -0
- package/dist/services.js +265 -0
- package/dist/session.js +241 -0
- package/dist/setup.js +423 -0
- package/dist/shell/decide.js +1 -0
- package/dist/shell/index.js +2 -0
- package/dist/shell/sandbox.js +1 -0
- package/dist/shell/wire.js +1 -0
- package/dist/skills.js +103 -0
- package/dist/state.js +1 -0
- package/dist/store.js +1 -0
- package/dist/switcher.js +1 -0
- package/dist/synth.js +418 -0
- package/dist/tools.js +477 -0
- package/dist/trials.js +223 -0
- package/dist/usage.js +1 -0
- package/dist/wait.js +167 -0
- package/dist/watchdog.js +476 -0
- package/dist/web-guidance.js +43 -0
- package/dist/which.js +20 -0
- package/dist/worktree/git.js +545 -0
- package/dist/writeguard.js +311 -0
- package/evolver/mm_evolve/__init__.py +1 -0
- package/evolver/mm_evolve/entry.py +3 -0
- package/evolver/mm_evolve/evaluator.py +119 -0
- package/evolver/mm_evolve/llm.py +76 -0
- package/evolver/mm_evolve/run.py +89 -0
- package/evolver/mm_evolve/spec.py +62 -0
- package/evolver/pyproject.toml +21 -0
- package/evolver/uv.lock +772 -0
- package/package.json +74 -4
- package/skills/THIRD_PARTY.md +58 -0
- package/skills/code-review/SKILL.md +46 -0
- package/skills/deck/SKILL.md +98 -0
- package/skills/deliberate/SKILL.md +39 -0
- package/skills/design/SKILL.md +150 -0
- package/skills/diagnosing-bugs/SKILL.md +75 -0
- package/skills/image/SKILL.md +66 -0
- package/skills/orchestrator/SKILL.md +107 -0
- package/skills/receiving-code-review/SKILL.md +36 -0
- package/skills/research/SKILL.md +18 -0
- package/skills/tdd/SKILL.md +56 -0
- package/skills/tdd/mocking.md +59 -0
- package/skills/tdd/tests.md +77 -0
- package/skills/verification-before-completion/SKILL.md +50 -0
- package/skills/video/SKILL.md +97 -0
- package/skills/web/SKILL.md +60 -0
package/dist/desktop.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// What the plugin hands to the desktop: notifications only. Previews, presenters and comparison pages are never opened
|
|
2
|
+
// by the plugin; they start with --no-open and their URL or path goes into the answer, so they work the same with and
|
|
3
|
+
// without a display (container plan P3-T3).
|
|
4
|
+
//
|
|
5
|
+
// Without a display (a container, an SSH session, a server) a notification has nowhere to go: notify-send would fail
|
|
6
|
+
// on every call. It is not attempted then, and the caller hears it once, so the answer in the chat is the one place the
|
|
7
|
+
// user is told.
|
|
8
|
+
import { execFile } from "node:child_process";
|
|
9
|
+
// Whether there is a desktop to notify. macOS always has one for the user's own processes; Linux has one when a
|
|
10
|
+
// Wayland or X display is named. OMACODE_HEADLESS=1 says there is none (an image sets it), OMACODE_HEADLESS=0 that
|
|
11
|
+
// there is one whatever the variables say.
|
|
12
|
+
export function hasDesktop(env = process.env, platform = process.platform) {
|
|
13
|
+
if (env.OMACODE_HEADLESS === "1")
|
|
14
|
+
return false;
|
|
15
|
+
if (env.OMACODE_HEADLESS === "0")
|
|
16
|
+
return true;
|
|
17
|
+
if (platform === "darwin")
|
|
18
|
+
return true;
|
|
19
|
+
return Boolean(env.WAYLAND_DISPLAY || env.DISPLAY);
|
|
20
|
+
}
|
|
21
|
+
let toldHeadless = false;
|
|
22
|
+
// A desktop notification: `notify-send` on Linux, `osascript` on macOS, which has no notify-send. The command is
|
|
23
|
+
// chosen here once, so the plugin installs unchanged on both (`opencode plugin add` from git). Failure is the
|
|
24
|
+
// caller's business: a notification is a courtesy and never a reason a job stops. Without a desktop nothing runs, and
|
|
25
|
+
// `failed` hears it the first time only.
|
|
26
|
+
export function notifyDesktop(title, body, failed, desktop = hasDesktop(), run = execFile) {
|
|
27
|
+
if (!desktop) {
|
|
28
|
+
if (!toldHeadless && failed)
|
|
29
|
+
failed(new Error("no desktop (no WAYLAND_DISPLAY or DISPLAY): notifications go to the chat only"));
|
|
30
|
+
toldHeadless = true;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const darwin = process.platform === "darwin";
|
|
34
|
+
const args = darwin ? ["-e", `display notification ${appleScript(body)} with title ${appleScript(title)}`] : ["-a", "omacode", title, body];
|
|
35
|
+
run(darwin ? "osascript" : "notify-send", args, (err) => {
|
|
36
|
+
if (err && failed)
|
|
37
|
+
failed(err);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
// An AppleScript string literal: quotes and backslashes escape as in JSON. A newline would come out as a literal
|
|
41
|
+
// backslash-n (AppleScript has no \n escape), so the body is folded to one line first.
|
|
42
|
+
function appleScript(text) {
|
|
43
|
+
return JSON.stringify(text.replace(/\s*\n\s*/g, " "));
|
|
44
|
+
}
|
package/dist/egress.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// The gate every payload that leaves the machine passes (D13, A2-T6). It sits in front of the one function that
|
|
2
|
+
// performs a request — src/decider.ts DecisionClient.ask — so no call site can get past it: not the plugin's three
|
|
3
|
+
// direct asks, not the context package's N17, not the CLI's benches. A remote destination and no confirmation means no
|
|
4
|
+
// request at all.
|
|
5
|
+
//
|
|
6
|
+
// Three things happen here, in this order:
|
|
7
|
+
// - the deterministic redaction of src/redact.ts (secrets, e-mail, phone, IBAN, card, home paths, IP addresses, and
|
|
8
|
+
// the values the server was told are secret) is applied to the state text and to the questions. Only the result
|
|
9
|
+
// is previewed and sent; the preview never sees the unredacted text either;
|
|
10
|
+
// - "unredactable" is decided, as A2-T5 defines it: the payload carries a `sensitive` guard flag, or the redaction
|
|
11
|
+
// changed nothing in a text of more than 20 words. The preview says so, and a per-session guard override is refused
|
|
12
|
+
// for such a payload before it ever gets here (src/backends.ts);
|
|
13
|
+
// - the user is shown what would leave and must say "send". There is no other way through: without a preview channel
|
|
14
|
+
// (a CLI run, a session that is itself waiting) the call is kept local, journalled with that reason, and the
|
|
15
|
+
// caller falls back to its own default.
|
|
16
|
+
//
|
|
17
|
+
// With a local name/address detector on, the preview says so: the names and addresses it found are already placeholders
|
|
18
|
+
// by the time this function runs (the vault redacts them), so "send" is the offered answer. Without one, every payload
|
|
19
|
+
// is uncertain, and the preview says that too.
|
|
20
|
+
import { egressFindings, redactEgress } from "./redact.js";
|
|
21
|
+
// A text this long is not "trivial": if the redaction left every word of it alone, nobody knows whether it is safe.
|
|
22
|
+
export const PREVIEW_WORDS = 20;
|
|
23
|
+
export function summary(outcome) {
|
|
24
|
+
return {
|
|
25
|
+
verdict: outcome.verdict,
|
|
26
|
+
unredactable: outcome.unredactable,
|
|
27
|
+
changed: outcome.changed,
|
|
28
|
+
words: outcome.words,
|
|
29
|
+
reason: outcome.reason,
|
|
30
|
+
destination: outcome.destination,
|
|
31
|
+
...(outcome.why ? { why: outcome.why } : {}),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
// A request that did not happen, with the gate's own account of why. src/backends.ts journals that account, so a
|
|
35
|
+
// refused cloud call is legible in the journal instead of looking like a backend that was down.
|
|
36
|
+
export class EgressRefused extends Error {
|
|
37
|
+
outcome;
|
|
38
|
+
constructor(outcome) {
|
|
39
|
+
super(`kept local: ${outcome.reason}`);
|
|
40
|
+
this.outcome = outcome;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// Whether a payload carries a `sensitive` guard flag. The state is JSON by the time the client sees it (src/backends.ts
|
|
44
|
+
// stringifies the object), so it is parsed when it can be, and read as text when it cannot.
|
|
45
|
+
export function carriesSensitive(state) {
|
|
46
|
+
const flagged = (v, depth = 0) => {
|
|
47
|
+
if (depth > 8 || v === null || typeof v !== "object")
|
|
48
|
+
return false;
|
|
49
|
+
if (Array.isArray(v))
|
|
50
|
+
return v.some((x) => flagged(x, depth + 1));
|
|
51
|
+
for (const [key, value] of Object.entries(v)) {
|
|
52
|
+
if (key === "sensitive" && (value === true || (typeof value === "number" && value >= 0.5)))
|
|
53
|
+
return true;
|
|
54
|
+
if (key === "flagged" && Array.isArray(value) && value.includes("sensitive"))
|
|
55
|
+
return true;
|
|
56
|
+
if (flagged(value, depth + 1))
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
return false;
|
|
60
|
+
};
|
|
61
|
+
try {
|
|
62
|
+
return flagged(JSON.parse(state));
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return /"(?:sensitive)"\s*:\s*(?:true|[1-9][0-9]*|0?\.\d*[1-9])/.test(state);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function wordsOf(text) {
|
|
69
|
+
return text.trim() ? text.trim().split(/\s+/).length : 0;
|
|
70
|
+
}
|
|
71
|
+
// The A2-T5 definition of "unredactable", in one place: a payload that carries a `sensitive` guard flag, or a text of
|
|
72
|
+
// more than 20 words whose redaction changed nothing. The gate uses it for the preview, and the per-session guard
|
|
73
|
+
// override is refused for one (src/backends.ts) — the same rule, so the two paths cannot drift.
|
|
74
|
+
export function unredactableText(text, secrets = []) {
|
|
75
|
+
const why = carriesSensitive(text)
|
|
76
|
+
? "it carries a sensitive guard flag"
|
|
77
|
+
: redactEgress(text, secrets) === text && wordsOf(text) > PREVIEW_WORDS
|
|
78
|
+
? `the redaction changed nothing in ${wordsOf(text)} words`
|
|
79
|
+
: undefined;
|
|
80
|
+
return why === undefined ? { unredactable: false } : { unredactable: true, why };
|
|
81
|
+
}
|
|
82
|
+
const rulesOf = (findings) => [...new Set(findings.map((f) => f.rule))].sort();
|
|
83
|
+
// The questions carry the same private data the state does, so they are redacted the same way. The caller's questions
|
|
84
|
+
// stay as they are: the local backends read them, and the journal keeps them.
|
|
85
|
+
export function redactQuestions(questions, secrets = []) {
|
|
86
|
+
const text = JSON.stringify(questions);
|
|
87
|
+
const redacted = redactEgress(text, secrets);
|
|
88
|
+
return JSON.parse(redacted);
|
|
89
|
+
}
|
|
90
|
+
// The gate. `payload` is what the caller wanted to send; only `outcome.text` and `outcome.questions` may leave.
|
|
91
|
+
export async function egress(payload, options) {
|
|
92
|
+
const secrets = options.secrets ?? [];
|
|
93
|
+
const text = redactEgress(payload.text, secrets);
|
|
94
|
+
const questions = redactQuestions(payload.questions, secrets);
|
|
95
|
+
const changed = text !== payload.text || JSON.stringify(questions) !== JSON.stringify(payload.questions);
|
|
96
|
+
const words = wordsOf(payload.text);
|
|
97
|
+
const sensitive = carriesSensitive(payload.text);
|
|
98
|
+
// Only a text of some length can be "unchanged by redaction": "run the tests" carries nothing to redact and nothing
|
|
99
|
+
// worth hiding.
|
|
100
|
+
const why = sensitive ? "it carries a sensitive guard flag" : !changed && words > PREVIEW_WORDS ? `the redaction changed nothing in ${words} words` : undefined;
|
|
101
|
+
const unredactable = why !== undefined;
|
|
102
|
+
const base = {
|
|
103
|
+
text,
|
|
104
|
+
questions,
|
|
105
|
+
changed,
|
|
106
|
+
words,
|
|
107
|
+
unredactable,
|
|
108
|
+
destination: options.destination,
|
|
109
|
+
...(why ? { why } : {}),
|
|
110
|
+
};
|
|
111
|
+
if (!options.confirm) {
|
|
112
|
+
return { ...base, verdict: "no-channel", reason: "no preview channel here, so nothing is sent" };
|
|
113
|
+
}
|
|
114
|
+
const answer = await options.confirm({
|
|
115
|
+
destination: options.destination,
|
|
116
|
+
...(options.node ? { node: options.node } : {}),
|
|
117
|
+
...(options.session ? { session: options.session } : {}),
|
|
118
|
+
...(options.job ? { job: options.job } : {}),
|
|
119
|
+
...(options.task ? { task: options.task } : {}),
|
|
120
|
+
text,
|
|
121
|
+
questions: Object.keys(questions),
|
|
122
|
+
words,
|
|
123
|
+
changed,
|
|
124
|
+
unredactable,
|
|
125
|
+
...(why ? { why } : {}),
|
|
126
|
+
replaced: rulesOf([...egressFindings(payload.text, secrets), ...egressFindings(JSON.stringify(payload.questions), secrets)]),
|
|
127
|
+
...(options.names !== undefined ? { names: options.names } : {}),
|
|
128
|
+
});
|
|
129
|
+
if (answer === "send")
|
|
130
|
+
return { ...base, verdict: "send", reason: "the user confirmed the preview" };
|
|
131
|
+
if (answer === "cancel")
|
|
132
|
+
return { ...base, verdict: "cancel", reason: "the user cancelled the send" };
|
|
133
|
+
if (answer === "keep-local")
|
|
134
|
+
return { ...base, verdict: "keep-local", reason: "the user kept it on this machine" };
|
|
135
|
+
return { ...base, verdict: "keep-local", reason: "nobody confirmed the preview, so nothing is sent" };
|
|
136
|
+
}
|
|
137
|
+
// Whether a URL leaves this machine. Loopback names are the local decision servers; anything else — a LAN address, a
|
|
138
|
+
// hostname, an unknown scheme — is treated as remote, so the gate decides and an unresolvable case is never sent.
|
|
139
|
+
export function remote(url) {
|
|
140
|
+
let host;
|
|
141
|
+
try {
|
|
142
|
+
host = new URL(url).hostname.replaceAll("[", "").replaceAll("]", "").toLowerCase();
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
return !(host === "localhost" || host.endsWith(".localhost") || host === "::1" || host === "0.0.0.0" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host));
|
|
148
|
+
}
|
|
149
|
+
export function hostOf(url) {
|
|
150
|
+
try {
|
|
151
|
+
return new URL(url).host;
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return url;
|
|
155
|
+
}
|
|
156
|
+
}
|
package/dist/eval.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// The eval harness (design.md §15): replays journaled decisions that have a label against a floor and reports,
|
|
2
|
+
// per node and question, how often the model would have decided alone, how often it would have been wrong, and
|
|
3
|
+
// how well its confidence matches its accuracy. Floors change only together with a run of this.
|
|
4
|
+
import { labeled, options } from "./dataset.js";
|
|
5
|
+
// The chosen option and its confidence; a noul is decided when it is clearly yes or clearly no.
|
|
6
|
+
export function verdict(answer) {
|
|
7
|
+
if (answer.type === "noul")
|
|
8
|
+
return answer.noul >= 0.5 ? { choice: "yes", confidence: answer.noul } : { choice: "no", confidence: 1 - answer.noul };
|
|
9
|
+
if (answer.type === "choice")
|
|
10
|
+
return { choice: answer.choice, confidence: answer.confidence };
|
|
11
|
+
return { choice: String(Math.round(answer.score)), confidence: answer.confidence };
|
|
12
|
+
}
|
|
13
|
+
function truth(row) {
|
|
14
|
+
const v = row.label?.value;
|
|
15
|
+
if (v === undefined)
|
|
16
|
+
return undefined;
|
|
17
|
+
if (row.question.type === "noul")
|
|
18
|
+
return v === "yes" || v === 1 ? "yes" : "no";
|
|
19
|
+
if (row.question.type === "score")
|
|
20
|
+
return String(Math.round(Number(v)));
|
|
21
|
+
return options(row.question).includes(String(v)) ? String(v) : undefined;
|
|
22
|
+
}
|
|
23
|
+
export function evaluate(entries, floor, backend) {
|
|
24
|
+
const groups = new Map();
|
|
25
|
+
for (const row of labeled(entries)) {
|
|
26
|
+
if (!row.answer || (backend && row.entry.backend !== backend))
|
|
27
|
+
continue;
|
|
28
|
+
const t = truth(row);
|
|
29
|
+
if (t === undefined)
|
|
30
|
+
continue;
|
|
31
|
+
const v = verdict(row.answer);
|
|
32
|
+
const key = `${String(row.entry.node)}.${row.qid}`;
|
|
33
|
+
groups.set(key, [...(groups.get(key) ?? []), { confidence: v.confidence, correct: v.choice === t }]);
|
|
34
|
+
}
|
|
35
|
+
return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([key, rows]) => {
|
|
36
|
+
const auto = rows.filter((r) => r.confidence >= floor);
|
|
37
|
+
const bins = Array.from({ length: 5 }, (_, i) => rows.filter((r) => Math.min(4, Math.floor(r.confidence * 5)) === i));
|
|
38
|
+
const ece = bins.reduce((sum, bin) => {
|
|
39
|
+
if (bin.length === 0)
|
|
40
|
+
return sum;
|
|
41
|
+
const conf = bin.reduce((s, r) => s + r.confidence, 0) / bin.length;
|
|
42
|
+
const acc = bin.filter((r) => r.correct).length / bin.length;
|
|
43
|
+
return sum + (bin.length / rows.length) * Math.abs(conf - acc);
|
|
44
|
+
}, 0);
|
|
45
|
+
return {
|
|
46
|
+
key,
|
|
47
|
+
labeled: rows.length,
|
|
48
|
+
automatic: auto.length / rows.length,
|
|
49
|
+
wrong: auto.length === 0 ? 0 : auto.filter((r) => !r.correct).length / auto.length,
|
|
50
|
+
ece,
|
|
51
|
+
};
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
export function formatReport(reports, floor) {
|
|
55
|
+
if (reports.length === 0)
|
|
56
|
+
return "no labeled decisions in the journal yet";
|
|
57
|
+
const pct = (x) => `${(x * 100).toFixed(0)}%`.padStart(5);
|
|
58
|
+
const lines = reports.map((r) => `${r.key.padEnd(28)} ${String(r.labeled).padStart(5)} ${pct(r.automatic)} ${pct(r.wrong)} ${r.ece.toFixed(3)}`);
|
|
59
|
+
return [`floor ${floor}`, `${"node.question".padEnd(28)} label auto wrong ece`, ...lines].join("\n");
|
|
60
|
+
}
|
package/dist/evolver.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// The evolver (design.md §26): OpenEvolve run against a task's fitness contract, in the Python sidecar evolver/.
|
|
2
|
+
// This side prepares the run and watches it:
|
|
3
|
+
// - the evolving file with EVOLVE-BLOCK markers around the one block that may change (in a copy, never the worktree);
|
|
4
|
+
// - the spec the sidecar reads: the task's checks, the contract's evaluator, scores, guards and baseline;
|
|
5
|
+
// - a bridge: an OpenAI-compatible endpoint on 127.0.0.1 with a one-run token, through which OpenEvolve's own client
|
|
6
|
+
// reaches the models. The plugin answers it with its session API (a tool-less session per call), so the evolver
|
|
7
|
+
// needs no API key and every call is charged to the job like any worker's;
|
|
8
|
+
// - the sidecar process (uv run mm-evolve), its progress from evals.jsonl, and its result.json.
|
|
9
|
+
// The best candidate then goes through the task's gate like any writer's change (src/native.ts finishEvolved).
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { createServer } from "node:http";
|
|
14
|
+
import { extname, join } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
export function evolverDir() {
|
|
17
|
+
return fileURLToPath(new URL("../evolver", import.meta.url));
|
|
18
|
+
}
|
|
19
|
+
// --- the block that may change ------------------------------------------------------------------------------------
|
|
20
|
+
const COMMENT = { ".py": "#", ".sh": "#", ".rb": "#", ".r": "#", ".jl": "#", ".lua": "--", ".sql": "--", ".hs": "--" };
|
|
21
|
+
// The file with EVOLVE-BLOCK markers around the block: a line range ("12-40", 1-based, inclusive) or a function's
|
|
22
|
+
// name, found by its definition and, for brace languages, its balanced braces (Python and the like by indentation).
|
|
23
|
+
export function markBlock(text, file, block) {
|
|
24
|
+
const lines = text.split("\n");
|
|
25
|
+
const c = COMMENT[extname(file).toLowerCase()] ?? "//";
|
|
26
|
+
let range;
|
|
27
|
+
const r = block.trim().match(/^(\d+)\s*-\s*(\d+)$/);
|
|
28
|
+
if (r) {
|
|
29
|
+
range = [Number(r[1]), Number(r[2])];
|
|
30
|
+
if (range[0] < 1 || range[1] > lines.length || range[0] > range[1])
|
|
31
|
+
return { problem: `lines ${block} are not inside ${file} (${lines.length} lines)` };
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
const name = block.trim().replace(/[^\w$]/g, "");
|
|
35
|
+
if (!name)
|
|
36
|
+
return { problem: "block: a function's name or a line range like 12-40" };
|
|
37
|
+
const def = new RegExp(`(function\\*?\\s+${name}\\b|\\b${name}\\s*[:=]\\s*(async\\s*)?(function|\\()|^\\s*(async\\s+)?def\\s+${name}\\b|\\bfn\\s+${name}\\b|\\bfunc\\s+${name}\\b|^\\s*(export\\s+)?(async\\s+)?(static\\s+)?${name}\\s*\\([^)]*\\)\\s*[:{])`);
|
|
38
|
+
const start = lines.findIndex((l) => def.test(l));
|
|
39
|
+
if (start < 0)
|
|
40
|
+
return { problem: `no definition of ${name} in ${file}; give the block as a line range instead` };
|
|
41
|
+
let end = start;
|
|
42
|
+
if (c === "#") {
|
|
43
|
+
const indent = lines[start].search(/\S/);
|
|
44
|
+
end = start + 1;
|
|
45
|
+
while (end < lines.length && (lines[end].trim() === "" || lines[end].search(/\S/) > indent))
|
|
46
|
+
end++;
|
|
47
|
+
while (end > start + 1 && lines[end - 1].trim() === "")
|
|
48
|
+
end--;
|
|
49
|
+
end--;
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
let depth = 0;
|
|
53
|
+
let opened = false;
|
|
54
|
+
for (end = start; end < lines.length; end++) {
|
|
55
|
+
for (const ch of lines[end].replace(/(["'`])(?:\\.|(?!\1).)*\1/g, "")) {
|
|
56
|
+
if (ch === "{") {
|
|
57
|
+
depth++;
|
|
58
|
+
opened = true;
|
|
59
|
+
}
|
|
60
|
+
if (ch === "}")
|
|
61
|
+
depth--;
|
|
62
|
+
}
|
|
63
|
+
if (opened && depth <= 0)
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
if (!opened || end >= lines.length)
|
|
67
|
+
return { problem: `could not find where ${name} ends in ${file}; give the block as a line range instead` };
|
|
68
|
+
}
|
|
69
|
+
range = [start + 1, end + 1];
|
|
70
|
+
}
|
|
71
|
+
const [a, b] = range;
|
|
72
|
+
const out = [...lines.slice(0, a - 1), `${c} EVOLVE-BLOCK-START`, ...lines.slice(a - 1, b), `${c} EVOLVE-BLOCK-END`, ...lines.slice(b)];
|
|
73
|
+
return { text: out.join("\n"), lines: range };
|
|
74
|
+
}
|
|
75
|
+
export function specOf(o) {
|
|
76
|
+
const c = o.contract;
|
|
77
|
+
return {
|
|
78
|
+
workdir: o.workdir,
|
|
79
|
+
file: o.file,
|
|
80
|
+
initial: o.initial,
|
|
81
|
+
checks: [...o.checks],
|
|
82
|
+
evaluator: c.evaluator,
|
|
83
|
+
scores: c.scores.map((s) => ({ name: s.name, direction: s.direction })),
|
|
84
|
+
guards: c.guards.map((g) => ({ name: g.name, direction: g.direction, tolerance: g.tolerance })),
|
|
85
|
+
baseline: { ...(c.baseline?.values ?? {}) },
|
|
86
|
+
output: o.output,
|
|
87
|
+
models: o.models.map((name) => ({ name, weight: 1 })),
|
|
88
|
+
iterations: o.iterations,
|
|
89
|
+
timeout_s: Math.round(c.timeoutMs / 1000),
|
|
90
|
+
target: { ...(c.stop.target ?? {}) },
|
|
91
|
+
full_rewrite: o.fullRewrite ?? false,
|
|
92
|
+
held_out_dir: o.heldOutDir ?? null,
|
|
93
|
+
runner: [...o.runner],
|
|
94
|
+
api_base: `${o.bridge.url}/v1`,
|
|
95
|
+
api_key: o.bridge.token,
|
|
96
|
+
quick_evaluator: c.quick && c.baseline?.quick ? c.quick.evaluator : null,
|
|
97
|
+
quick_baseline: { ...(c.baseline?.quick ?? {}) },
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
// An OpenAI-compatible /v1/chat/completions on 127.0.0.1, for one run: a random token, and every call answered by
|
|
101
|
+
// generate (a model id and the system and user text). Anything else is 404; a wrong token 401.
|
|
102
|
+
export async function startBridge(generate) {
|
|
103
|
+
const token = randomBytes(24).toString("hex");
|
|
104
|
+
const used = { calls: 0, failed: 0, tokens: 0, cost: 0 };
|
|
105
|
+
const server = createServer((req, res) => {
|
|
106
|
+
const send = (code, body) => {
|
|
107
|
+
res.writeHead(code, { "content-type": "application/json" });
|
|
108
|
+
res.end(JSON.stringify(body));
|
|
109
|
+
};
|
|
110
|
+
if (req.method !== "POST" || !req.url?.endsWith("/chat/completions"))
|
|
111
|
+
return send(404, { error: { message: "not found" } });
|
|
112
|
+
if (req.headers.authorization !== `Bearer ${token}`)
|
|
113
|
+
return send(401, { error: { message: "wrong token" } });
|
|
114
|
+
let raw = "";
|
|
115
|
+
req.on("data", (chunk) => (raw += chunk.toString("utf8")));
|
|
116
|
+
req.on("end", () => {
|
|
117
|
+
void (async () => {
|
|
118
|
+
try {
|
|
119
|
+
const body = JSON.parse(raw);
|
|
120
|
+
const text = (m) => (typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.map((p) => p.text ?? "").join("") : "");
|
|
121
|
+
const messages = body.messages ?? [];
|
|
122
|
+
const system = messages.filter((m) => m.role === "system").map(text).join("\n\n");
|
|
123
|
+
const prompt = messages.filter((m) => m.role !== "system").map(text).join("\n\n");
|
|
124
|
+
const g = await generate(String(body.model ?? ""), system, prompt);
|
|
125
|
+
used.calls++;
|
|
126
|
+
used.tokens += g.tokens;
|
|
127
|
+
used.cost += g.cost;
|
|
128
|
+
send(200, {
|
|
129
|
+
id: `mm-${used.calls}`,
|
|
130
|
+
object: "chat.completion",
|
|
131
|
+
created: Math.floor(Date.now() / 1000),
|
|
132
|
+
model: body.model,
|
|
133
|
+
choices: [{ index: 0, message: { role: "assistant", content: g.text }, finish_reason: "stop" }],
|
|
134
|
+
usage: { prompt_tokens: 0, completion_tokens: g.tokens, total_tokens: g.tokens },
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
used.failed++;
|
|
139
|
+
send(500, { error: { message: err instanceof Error ? err.message : String(err) } });
|
|
140
|
+
}
|
|
141
|
+
})();
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
145
|
+
const port = server.address().port;
|
|
146
|
+
return {
|
|
147
|
+
url: `http://127.0.0.1:${port}`,
|
|
148
|
+
token,
|
|
149
|
+
calls: () => ({ ...used }),
|
|
150
|
+
close: () => new Promise((resolve) => server.close(() => resolve())),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
// Why the evolved best may not be merged although it won on the visible corpus: invalid on the held-out cases, or worse
|
|
154
|
+
// there than today's code on the deciding score. The evolution never saw those cases, so this is where it shows
|
|
155
|
+
// whether it learned the task or the corpus. Undefined when it may go on to the gate.
|
|
156
|
+
export function heldOutProblem(c, held) {
|
|
157
|
+
if (!held)
|
|
158
|
+
return undefined;
|
|
159
|
+
if (held.valid !== 1)
|
|
160
|
+
return `the best candidate is invalid on the held-out cases (${held.error ?? "no valid result"})`;
|
|
161
|
+
const first = c.scores[0];
|
|
162
|
+
const base = first && c.baseline?.heldOut?.[first.name];
|
|
163
|
+
const now = first && held[first.name];
|
|
164
|
+
if (base === undefined || typeof now !== "number")
|
|
165
|
+
return undefined;
|
|
166
|
+
const worse = first.direction === "min" ? now > base : now < base;
|
|
167
|
+
return worse ? `on the held-out cases the best candidate is worse than today's code (${first.name} ${now} against ${base})` : undefined;
|
|
168
|
+
}
|
|
169
|
+
// --- the offer ----------------------------------------------------------------------------------------------------
|
|
170
|
+
// Whether the evolver suits a writer measured against this contract: the code's half of the rule (the decider's local_block is
|
|
171
|
+
// the other). A frozen contract, a full measurement of at most maxEvalSeconds (the "evolver.maxEvalSeconds" setting,
|
|
172
|
+
// 600 by default: multi-step algorithms of minutes are what is worth speeding up), and one or two files.
|
|
173
|
+
export const EVOLVER_MAX_EVAL_S = 600;
|
|
174
|
+
export function evolverFits(c, files, maxEvalSeconds = EVOLVER_MAX_EVAL_S) {
|
|
175
|
+
return c.status === "frozen" && c.costPerEval !== undefined && c.costPerEval * c.repeats <= maxEvalSeconds && files.length >= 1 && files.length <= 2;
|
|
176
|
+
}
|
|
177
|
+
// The share of candidates that pass a contract's quick stage and get the full measurement, before a run has measured
|
|
178
|
+
// it: most model-written variants are no better than their parent.
|
|
179
|
+
export const QUICK_PASS = 0.3;
|
|
180
|
+
// What a run would take: iterations from the contract's stop rule (30 at most by default), each a model call (about
|
|
181
|
+
// 25 s) and a measurement: the full one, or with a quick stage that one and the full one for the share that pass it.
|
|
182
|
+
// The call is priced at what earlier evolver calls cost.
|
|
183
|
+
export function estimate(c, perCall, quickPass = QUICK_PASS) {
|
|
184
|
+
const iterations = Math.min(c.stop.evaluations ?? 30, 30);
|
|
185
|
+
const full = (c.costPerEval ?? 1) * c.repeats;
|
|
186
|
+
const measure = c.quick?.costPerEval !== undefined ? c.quick.costPerEval + quickPass * full : full;
|
|
187
|
+
return { iterations, minutes: Math.max(1, Math.round((iterations * (25 + measure)) / 60)), cost: Math.round(iterations * perCall * 1000) / 1000 };
|
|
188
|
+
}
|
|
189
|
+
// Minutes as the form says them: "45 min", "about 3.5 h".
|
|
190
|
+
export function duration(minutes) {
|
|
191
|
+
return minutes < 90 ? `${minutes} min` : `${Math.round(minutes / 30) / 2} h`;
|
|
192
|
+
}
|
|
193
|
+
const METHOD = { evolver: "Evolver", trial: "Trial", worker: "One worker" };
|
|
194
|
+
// The question when a task suits the evolver: the user decides how it is done, with what each way costs.
|
|
195
|
+
export function evolverForm(id, title, files, c, e) {
|
|
196
|
+
return [{
|
|
197
|
+
header: `Method ${id}`,
|
|
198
|
+
question: `"${title.slice(0, 100)}" improves ${files.join(", ")} against contract ${c.id}, which measures in ${c.costPerEval}s${c.quick?.costPerEval !== undefined ? ` (its quick stage in ${c.quick.costPerEval}s)` : ""}, and its gain lies in one function or block. How should it be done?`,
|
|
199
|
+
options: [
|
|
200
|
+
{ label: `${METHOD.evolver} (Recommended)`, description: `OpenEvolve tries about ${e.iterations} variants in the sandbox${c.quick ? `, each on the quick stage first and in full only when it is better there` : ""}, the best goes through the checks; about ${duration(e.minutes)} and ${e.cost} in model calls` },
|
|
201
|
+
{ label: METHOD.trial, description: "Two or more workers on different models at once; the best score wins" },
|
|
202
|
+
{ label: METHOD.worker, description: "One worker, as usual" },
|
|
203
|
+
],
|
|
204
|
+
}];
|
|
205
|
+
}
|
|
206
|
+
export function readMethod(header, answers) {
|
|
207
|
+
const m = header.match(/^Method (M\d+)$/);
|
|
208
|
+
if (!m)
|
|
209
|
+
return undefined;
|
|
210
|
+
const clean = answers.map((a) => a.trim().replace(/\s*\(recommended\)\s*$/i, "").toLowerCase());
|
|
211
|
+
const method = Object.keys(METHOD).find((k) => clean.includes(METHOD[k].toLowerCase()));
|
|
212
|
+
if (method)
|
|
213
|
+
return { id: m[1], method };
|
|
214
|
+
const said = answers.find((a) => a.trim());
|
|
215
|
+
return { id: m[1], ...(said ? { said: said.trim() } : {}) };
|
|
216
|
+
}
|
|
217
|
+
// What evals.jsonl says so far: how many candidates were measured, how many were valid, and the best by
|
|
218
|
+
// combined_score.
|
|
219
|
+
export function progressOf(evals) {
|
|
220
|
+
let evaluations = 0;
|
|
221
|
+
let valid = 0;
|
|
222
|
+
let best;
|
|
223
|
+
for (const line of evals.split("\n")) {
|
|
224
|
+
if (!line.trim())
|
|
225
|
+
continue;
|
|
226
|
+
let row;
|
|
227
|
+
try {
|
|
228
|
+
row = JSON.parse(line);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
evaluations++;
|
|
234
|
+
if (row.valid === 1) {
|
|
235
|
+
valid++;
|
|
236
|
+
if (!best || (row.combined_score ?? 0) > (best.combined_score ?? 0))
|
|
237
|
+
best = row;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return { evaluations, valid, ...(best ? { best } : {}) };
|
|
241
|
+
}
|
|
242
|
+
// The sidecar on a spec: `uv run --project evolver mm-evolve spec.json`, stdin closed (a child that reads stdin waits
|
|
243
|
+
// for an end that never comes). onProgress is called whenever evals.jsonl grew. stop() ends the process group.
|
|
244
|
+
// In the container image the evolver's environment is built with the image and read-only (OMACODE_EVOLVER_PREBUILT),
|
|
245
|
+
// so `uv run` must not try to sync it.
|
|
246
|
+
export function evolverRunArgs(dir, specPath, env = process.env) {
|
|
247
|
+
return ["run", "--quiet", ...(env.OMACODE_EVOLVER_PREBUILT ? ["--no-sync"] : []), "--project", dir, "mm-evolve", specPath];
|
|
248
|
+
}
|
|
249
|
+
export function runEvolver(spec, onProgress, opts = {}) {
|
|
250
|
+
mkdirSync(spec.output, { recursive: true });
|
|
251
|
+
const specPath = join(spec.output, "spec.json");
|
|
252
|
+
writeFileSync(specPath, JSON.stringify(spec, null, 2));
|
|
253
|
+
const child = spawn(opts.uv ?? "uv", evolverRunArgs(opts.dir ?? evolverDir(), specPath), { stdio: ["ignore", "pipe", "pipe"], detached: true });
|
|
254
|
+
let tail = "";
|
|
255
|
+
child.stdout?.on("data", (d) => (tail = (tail + d.toString("utf8")).slice(-20_000)));
|
|
256
|
+
child.stderr?.on("data", (d) => (tail = (tail + d.toString("utf8")).slice(-20_000)));
|
|
257
|
+
let seen = 0;
|
|
258
|
+
const evals = join(spec.output, "evals.jsonl");
|
|
259
|
+
const poll = setInterval(() => {
|
|
260
|
+
if (!existsSync(evals))
|
|
261
|
+
return;
|
|
262
|
+
const text = readFileSync(evals, "utf8");
|
|
263
|
+
if (text.length === seen)
|
|
264
|
+
return;
|
|
265
|
+
seen = text.length;
|
|
266
|
+
onProgress(progressOf(text));
|
|
267
|
+
}, opts.pollMs ?? 5000);
|
|
268
|
+
poll.unref?.();
|
|
269
|
+
const done = new Promise((resolve) => {
|
|
270
|
+
child.on("error", (err) => {
|
|
271
|
+
clearInterval(poll);
|
|
272
|
+
resolve({ problem: `the evolver did not start: ${err.message}` });
|
|
273
|
+
});
|
|
274
|
+
child.on("close", (code) => {
|
|
275
|
+
clearInterval(poll);
|
|
276
|
+
if (existsSync(evals))
|
|
277
|
+
onProgress(progressOf(readFileSync(evals, "utf8")));
|
|
278
|
+
const out = join(spec.output, "result.json");
|
|
279
|
+
if (code === 0 && existsSync(out)) {
|
|
280
|
+
try {
|
|
281
|
+
return resolve({ result: JSON.parse(readFileSync(out, "utf8")) });
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
// fall through: a result that cannot be read is no result
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
resolve({ problem: `the evolver ended with code ${code}: ${tail.trim().split("\n").slice(-3).join(" | ").slice(0, 400)}` });
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
return {
|
|
291
|
+
done,
|
|
292
|
+
stop: () => {
|
|
293
|
+
try {
|
|
294
|
+
if (child.pid)
|
|
295
|
+
process.kill(-child.pid, "SIGTERM");
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
child.kill("SIGTERM");
|
|
299
|
+
}
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
}
|