@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/trials.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// Best-of-n trials (after Dr. Zero, arXiv 2601.07055: the pass rate of n rollouts as the difficulty signal).
|
|
2
|
+
//
|
|
3
|
+
// A hard writer task runs as n attempts at once, each a task of its own in its own worktree, on n different model
|
|
4
|
+
// families where the pool has them. The checks are the verifier: the first attempt whose checks pass and that merges
|
|
5
|
+
// cleanly wins, the others are stopped and done over by it (replacedBy, so whatever waits for the first attempt waits
|
|
6
|
+
// for the winner). How many of the n passed (k) is what the outcome log keeps for the router:
|
|
7
|
+
// - k = 0: the task is too big or too vague for one worker; the micromanager splits it, with what each attempt hit.
|
|
8
|
+
// - 0 < k < n: n was worth it; the task class gets trials from the start next time (src/outcomes.ts needsTrials).
|
|
9
|
+
//
|
|
10
|
+
// Native.delegate makes the first attempt; the micromanager starts the others when the plugin tells it to ("Attempt:
|
|
11
|
+
// T5 · job-…"), because only its subagent calls make children that OpenCode reports back to it.
|
|
12
|
+
import { taskAcceptance } from "./brief.js";
|
|
13
|
+
import { better } from "./contract.js";
|
|
14
|
+
import { HEADER } from "./hooks.js";
|
|
15
|
+
import { family, roleById } from "./roles.js";
|
|
16
|
+
import { chain } from "@omacode/state/routing";
|
|
17
|
+
// Who decides by default, by role id; "*" for every other role.
|
|
18
|
+
export const DEFAULT_PICK = { visual: "user", "*": "best" };
|
|
19
|
+
// The pick for a new trial: the prompt's "Pick:" line, else the setting for its role.
|
|
20
|
+
export function pickFor(role, setting = DEFAULT_PICK, line) {
|
|
21
|
+
return line ?? setting[role] ?? setting["*"] ?? "first";
|
|
22
|
+
}
|
|
23
|
+
export const TRIAL_EVALUATOR_REQUIRED = "Method: trial (Best-of-N) requires automated Checks: or a Contract: so candidates can be evaluated objectively.";
|
|
24
|
+
// Pattern 3: Best-of-N trials require an objective automated evaluator (Checks:, acceptance verify, or Contract:).
|
|
25
|
+
export function hasObjectiveEvaluator(job, task, d, entry) {
|
|
26
|
+
if ((entry?.checks?.length ?? 0) > 0)
|
|
27
|
+
return true;
|
|
28
|
+
if ((d?.checks?.length ?? 0) > 0)
|
|
29
|
+
return true;
|
|
30
|
+
if (task && taskAcceptance(job, task).some((a) => Boolean(a.verify?.trim())))
|
|
31
|
+
return true;
|
|
32
|
+
if (d?.contract?.trim())
|
|
33
|
+
return true;
|
|
34
|
+
if (task?.contract?.id)
|
|
35
|
+
return true;
|
|
36
|
+
if (task?.freeze?.length || Object.keys(task?.frozen ?? {}).length > 0)
|
|
37
|
+
return true;
|
|
38
|
+
if (job.contracts?.some((c) => c.status === "frozen"))
|
|
39
|
+
return true;
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
// Pattern 3: prefer affordable cross-family Flash/easy or medium legs across trial attempts instead of expensive hard legs.
|
|
43
|
+
export function trialLegTier(role, routing, avoidFamilies = [], baseTier) {
|
|
44
|
+
const candidates = ["medium", "easy"];
|
|
45
|
+
for (const tier of candidates) {
|
|
46
|
+
const pool = chain(role, routing, tier);
|
|
47
|
+
if (pool.some((m) => !avoidFamilies.includes(family(m))))
|
|
48
|
+
return tier;
|
|
49
|
+
}
|
|
50
|
+
return baseTier ?? "medium";
|
|
51
|
+
}
|
|
52
|
+
// Who decides the trial a task belongs to: a contract always decides by score.
|
|
53
|
+
export function pickOf(task) {
|
|
54
|
+
return task.contract ? "contract" : task.trial?.pick ?? "first";
|
|
55
|
+
}
|
|
56
|
+
export const DEFAULT_GRACE = { factor: 0.5, minMs: 2 * 60_000, maxMs: 10 * 60_000 };
|
|
57
|
+
export function graceMs(g, elapsedMs) {
|
|
58
|
+
if (g.factor <= 0)
|
|
59
|
+
return 0;
|
|
60
|
+
return Math.max(0, Math.min(Math.max(g.factor * elapsedMs, g.minMs), g.maxMs));
|
|
61
|
+
}
|
|
62
|
+
// What each attempt is told about how its trial is decided.
|
|
63
|
+
const HOW = {
|
|
64
|
+
first: "The first whose checks pass is merged and the others are stopped, so take the approach you think is most likely to pass",
|
|
65
|
+
best: "Of the attempts whose checks pass, the best is merged: by how many of the checks' cases pass, then a review of the changes, then cost and size. Once one passes, the others get a short grace window to finish. Aim for a correct, clean and small change, not only for passing",
|
|
66
|
+
contract: "Of the attempts whose checks pass, the one with the best score is merged once all are done, so aim for the best result the contract can measure, not only for passing",
|
|
67
|
+
user: "Every attempt runs to its end, and the user picks the one they like best from a comparison of all that pass. Make your own best version; do not hedge between styles",
|
|
68
|
+
};
|
|
69
|
+
// An attempt that is getting nowhere, by the watchdog's counts: it is stopped when a "best" trial's grace window opens
|
|
70
|
+
// rather than paid for until the window closes.
|
|
71
|
+
export function idleAttempt(p) {
|
|
72
|
+
if (!p)
|
|
73
|
+
return false;
|
|
74
|
+
return (p.writes === 0 && p.calls >= 20) || p.callsSinceWrite >= 25 || p.recentFailures >= 8;
|
|
75
|
+
}
|
|
76
|
+
const share = (q) => q.graded ?? -1;
|
|
77
|
+
const money = (n) => `$${(n ?? 0).toFixed(4)}`;
|
|
78
|
+
// The passed attempts best first, and why the first is first: the share of cases passed, then the review of the two
|
|
79
|
+
// best (when there is one), then cost, then size. review is asked only when the two best are tied on cases.
|
|
80
|
+
export async function rankQuality(held, review) {
|
|
81
|
+
const byCases = [...held].sort((a, b) => share(b) - share(a) || (a.cost ?? 0) - (b.cost ?? 0) || a.size - b.size);
|
|
82
|
+
if (byCases.length < 2)
|
|
83
|
+
return { order: byCases.map((q) => q.task), how: "the only attempt that passed" };
|
|
84
|
+
const [a, b] = byCases;
|
|
85
|
+
if (share(a) > share(b))
|
|
86
|
+
return { order: byCases.map((q) => q.task), how: `more cases passed (${Math.round(share(a) * 100)}% against ${Math.round(share(b) * 100)}%)` };
|
|
87
|
+
const verdict = review ? await review(a, b).catch(() => undefined) : undefined;
|
|
88
|
+
if (verdict && verdict.better !== "equal") {
|
|
89
|
+
const first = verdict.better === "A" ? a : b;
|
|
90
|
+
return { order: [first.task, ...byCases.filter((q) => q !== first).map((q) => q.task)], how: `on review: ${verdict.why.slice(0, 200)}` };
|
|
91
|
+
}
|
|
92
|
+
const tied = verdict ? "the review found them equal" : "tied on the checks";
|
|
93
|
+
if ((a.cost ?? 0) !== (b.cost ?? 0))
|
|
94
|
+
return { order: byCases.map((q) => q.task), how: `${tied}; cheaper (${money(a.cost)} against ${money(b.cost)})` };
|
|
95
|
+
if (a.size !== b.size)
|
|
96
|
+
return { order: byCases.map((q) => q.task), how: `${tied}; smaller change (${a.size} against ${b.size} lines)` };
|
|
97
|
+
return { order: byCases.map((q) => q.task), how: `${tied}, at the same cost and size` };
|
|
98
|
+
}
|
|
99
|
+
// The pairwise review's prompt: the task, and the two changes as A and B.
|
|
100
|
+
export function reviewPrompt(task, a, b) {
|
|
101
|
+
return [
|
|
102
|
+
"Two workers solved the same task, and both pass its checks. Judge which change is better: correct in the cases the checks may miss, simpler, easier to maintain, closer to what the task asked. Do not prefer the longer one.",
|
|
103
|
+
"Answer with one line of JSON and nothing else: {\"better\": \"A\" | \"B\" | \"equal\", \"why\": \"one sentence\"}",
|
|
104
|
+
"",
|
|
105
|
+
"Task:",
|
|
106
|
+
task.slice(0, 4000),
|
|
107
|
+
"",
|
|
108
|
+
"Change A:",
|
|
109
|
+
a,
|
|
110
|
+
"",
|
|
111
|
+
"Change B:",
|
|
112
|
+
b,
|
|
113
|
+
].join("\n");
|
|
114
|
+
}
|
|
115
|
+
// The review's answer, or undefined when it is not the JSON asked for.
|
|
116
|
+
export function parseReview(text) {
|
|
117
|
+
const m = text.match(/\{[^{}]*"better"[^{}]*\}/);
|
|
118
|
+
if (!m)
|
|
119
|
+
return undefined;
|
|
120
|
+
try {
|
|
121
|
+
const r = JSON.parse(m[0]);
|
|
122
|
+
if (r.better !== "A" && r.better !== "B" && r.better !== "equal")
|
|
123
|
+
return undefined;
|
|
124
|
+
return { better: r.better, why: typeof r.why === "string" ? r.why : "" };
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// The difficulty from which a task runs as a trial: N5's "hard" and "very hard" (tierFor's deep tier).
|
|
131
|
+
export const DEEP = 0.67;
|
|
132
|
+
export const DEFAULT_TRIALS = 1;
|
|
133
|
+
export const MAX_TRIALS = 4;
|
|
134
|
+
// How many attempts a writer task gets. setting: the user's "trials" (1 turns trials off); parallel: tasks of the job at
|
|
135
|
+
// once, which a trial must fit into; retry: the task is started again after a failed attempt (Replaces:, or a planned
|
|
136
|
+
// task that ran before); learned: the outcome log says tasks of this class mostly fail on one worker.
|
|
137
|
+
export function trialSize(o) {
|
|
138
|
+
const n = Math.min(o.setting, o.parallel, MAX_TRIALS);
|
|
139
|
+
if (n < 2)
|
|
140
|
+
return 1;
|
|
141
|
+
return (o.difficulty !== undefined && o.difficulty >= DEEP) || o.retry || o.learned ? n : 1;
|
|
142
|
+
}
|
|
143
|
+
// The attempts of the trial a task belongs to, the first one first; [] for a task in no trial.
|
|
144
|
+
export function attempts(job, task) {
|
|
145
|
+
if (!task.trial)
|
|
146
|
+
return [];
|
|
147
|
+
return job.tasks.filter((t) => t.trial?.of === task.trial.of);
|
|
148
|
+
}
|
|
149
|
+
const LIVE = new Set(["running", "gating", "fixing", "reviewing", "passed"]);
|
|
150
|
+
// Where a trial stands: the winner once one merged, the attempts still at work, the ones that passed and wait for the
|
|
151
|
+
// trial to be decided by score (held, src/contract.ts), and the ones that failed.
|
|
152
|
+
export function standing(job, task) {
|
|
153
|
+
const all = attempts(job, task);
|
|
154
|
+
const winner = all.find((t) => t.status === "merged");
|
|
155
|
+
const held = all.filter((t) => t.held && t.status === "passed");
|
|
156
|
+
const live = all.filter((t) => !held.includes(t) && LIVE.has(t.status) && t.stages.at(-1)?.stage !== "end");
|
|
157
|
+
const failed = all.filter((t) => t !== winner && !live.includes(t) && !held.includes(t) && t.status !== "cancelled");
|
|
158
|
+
return { winner, live, held, failed, all };
|
|
159
|
+
}
|
|
160
|
+
// The held attempts best first, by the contract: the held-out score where there is one, else the visible one.
|
|
161
|
+
export function ranked(c, held) {
|
|
162
|
+
const invalid = { valid: false, values: {} };
|
|
163
|
+
return [...held].sort((a, b) => better(c, b.score ?? invalid, a.score ?? invalid));
|
|
164
|
+
}
|
|
165
|
+
// The prompt line that starts another attempt; native.ts parseDelegation reads it back.
|
|
166
|
+
export const attemptLine = (task, job) => `Attempt: ${task} · ${job}`;
|
|
167
|
+
// How the micromanager hears that a trial is decided.
|
|
168
|
+
const DECIDED = {
|
|
169
|
+
first: () => "the first whose checks pass is merged, and the others are stopped",
|
|
170
|
+
best: () => "and of those whose checks pass, the best by quality is merged after a short grace window for the others",
|
|
171
|
+
contract: (head) => `and of those whose checks pass, the one with the best score against contract ${head.contract?.id ?? "?"} is merged once all are done`,
|
|
172
|
+
user: () => "every attempt runs to its end, and the user picks one from a comparison of those that pass",
|
|
173
|
+
};
|
|
174
|
+
// What the micromanager reads after starting the first attempt: start the rest now, in one message.
|
|
175
|
+
export function fanOutText(job, head) {
|
|
176
|
+
if (!head.trial || head.trial.of !== head.id)
|
|
177
|
+
return undefined;
|
|
178
|
+
const missing = head.trial.n - attempts(job, head).length;
|
|
179
|
+
if (missing <= 0)
|
|
180
|
+
return undefined;
|
|
181
|
+
const agent = roleById(head.role)?.agent ?? head.role;
|
|
182
|
+
const why = head.difficulty !== undefined && head.difficulty >= DEEP ? `it is hard (difficulty ${head.difficulty.toFixed(2)})` : "an earlier attempt at this work failed";
|
|
183
|
+
return [
|
|
184
|
+
`${HEADER} ${head.id} runs as a trial of ${head.trial.n} attempts, because ${why}: each attempt works in its own worktree on another model, ${DECIDED[pickOf(head)](head)}.`,
|
|
185
|
+
`Start the other ${missing} attempt${missing > 1 ? "s" : ""} now, in one message, with the subagent tool (background = true), each with agent ${agent}, description "${head.id} attempt", and only this prompt:`,
|
|
186
|
+
attemptLine(head.id, job.id),
|
|
187
|
+
"The plugin gives each the same task, files and checks. Do not wait for the first attempt, and do not start the task again yourself: the trial's result comes to you as a note.",
|
|
188
|
+
].join("\n");
|
|
189
|
+
}
|
|
190
|
+
// What the worker of an attempt is told on top of its task.
|
|
191
|
+
export function attemptBrief(task) {
|
|
192
|
+
if (!task.trial)
|
|
193
|
+
return "";
|
|
194
|
+
const index = Number(task.title.match(/\(attempt (\d+)\//)?.[1] ?? 1);
|
|
195
|
+
return `You are attempt ${index} of ${task.trial.n} at this task: other workers try the same task at the same time, each in its own worktree on another model. ${HOW[pickOf(task)]}, and do not wait for anyone.`;
|
|
196
|
+
}
|
|
197
|
+
// Why each failed attempt failed, from its last failing stage: the brief for splitting the task.
|
|
198
|
+
export function failureDigest(failed) {
|
|
199
|
+
return failed
|
|
200
|
+
.map((t) => {
|
|
201
|
+
const last = [...t.stages].reverse().find((s) => s.result === "fail");
|
|
202
|
+
return `- ${t.id} on ${t.model ?? "?"}: ${last ? `${last.stage}: ${(last.evidence ?? "").slice(0, 300)}` : t.summary?.slice(0, 300) ?? "no reason recorded"}`;
|
|
203
|
+
})
|
|
204
|
+
.join("\n");
|
|
205
|
+
}
|
|
206
|
+
// The micromanager's note when every attempt of a trial failed (k = 0).
|
|
207
|
+
export function allFailedText(job, head, failed) {
|
|
208
|
+
return [
|
|
209
|
+
`${HEADER} All ${failed.length} attempts at ${head.id} ${head.title.replace(/ \(attempt \d+\/\d+\)$/, "")} failed, on different models, so the task is too big or too unclear for one worker:`,
|
|
210
|
+
failureDigest(failed),
|
|
211
|
+
`Split it into smaller tasks that each can pass a check of their own (the todo tool, with "after" for their order and "replaces": ["${head.id}"]), using what the attempts hit above; or, if a check is what is wrong, correct it and start the task again. Ask the user if the goal itself is unclear.`,
|
|
212
|
+
].join("\n");
|
|
213
|
+
}
|
|
214
|
+
// The micromanager's note when an attempt fails while others still run: nothing to do yet.
|
|
215
|
+
export function attemptFailedText(task, live) {
|
|
216
|
+
return `${HEADER} ${task.id} (${task.title}) failed, but ${live.map((t) => t.id).join(", ")} of its trial still ${live.length > 1 ? "run" : "runs"}: nothing to do, the trial's result comes as a note.`;
|
|
217
|
+
}
|
|
218
|
+
// The micromanager's note when an attempt won. score: how it won on score, for a trial decided by its contract.
|
|
219
|
+
export function wonText(job, winner, stopped, failed, head, score) {
|
|
220
|
+
const label = { score: "with the best score", quality: "as the best attempt", user: "as the user's pick" }[score?.by ?? "score"];
|
|
221
|
+
const by = score ? ` ${label} (${score.how})${score.beaten.length ? `, ahead of ${score.beaten.map((t) => t.id).join(", ")}` : ""}` : "";
|
|
222
|
+
return `${HEADER} ${winner.id} won the trial of ${head ?? winner.trial?.of ?? winner.id}${by}: merged into ${job.integrationBranch}${failed ? ` after ${failed} other attempt${failed > 1 ? "s" : ""} failed` : ""}.${stopped.length ? ` Stopped: ${stopped.map((t) => t.id).join(", ")}; their work is not needed.` : ""}`;
|
|
223
|
+
}
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@omacode/tui/usage";
|
package/dist/wait.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// A worker's wait (the tool "wait"): block instead of polling.
|
|
2
|
+
//
|
|
3
|
+
// A worker that starts a long command has to poll it: `sleep 5` and read the log again. Every poll is a shell command,
|
|
4
|
+
// every shell command asks the permission layer again, and the worker is cut by the checkpoint before the command is
|
|
5
|
+
// done. The wait tool takes that loop away: one call blocks until the thing it waits for has happened or the timeout
|
|
6
|
+
// ticks, and it says what happened when it returns.
|
|
7
|
+
//
|
|
8
|
+
// What it waits for:
|
|
9
|
+
// - a process (pid): until it is gone;
|
|
10
|
+
// - a file (path): until it has the line (line) or the text (match) it is waiting for;
|
|
11
|
+
// - a paused permission request (id): until it is answered, refused or dropped.
|
|
12
|
+
// The permission answer itself is not this tool's job: it only tells the worker how the request ended.
|
|
13
|
+
//
|
|
14
|
+
// It runs nothing new: it watches, so it needs no permission of its own, and it never writes anything.
|
|
15
|
+
import { readFileSync } from "node:fs";
|
|
16
|
+
// How long a wait lasts when the caller says nothing. A worker waiting on a build wants more than a moment and less
|
|
17
|
+
// than the patience of the user.
|
|
18
|
+
export const WAIT_DEFAULT_MS = 60_000;
|
|
19
|
+
// The longest a wait may block, whatever the caller asks for.
|
|
20
|
+
export const WAIT_MAX_MS = 10 * 60_000;
|
|
21
|
+
// How often a wait looks at what it waits for.
|
|
22
|
+
const POLL_MS = 250;
|
|
23
|
+
// Whether a process is still there. A pid the host does not know is a process that is gone: the answer is what the
|
|
24
|
+
// worker asked for.
|
|
25
|
+
function alive(pid) {
|
|
26
|
+
try {
|
|
27
|
+
process.kill(pid, 0);
|
|
28
|
+
}
|
|
29
|
+
catch (err) {
|
|
30
|
+
// EPERM means it is there but this process may not signal it.
|
|
31
|
+
return err?.code === "EPERM";
|
|
32
|
+
}
|
|
33
|
+
// A process that has exited but is not reaped yet is still a pid the host knows. It is over all the same: nobody
|
|
34
|
+
// waits for a corpse.
|
|
35
|
+
return !zombie(pid);
|
|
36
|
+
}
|
|
37
|
+
// Whether a process is a corpse waiting to be reaped (Linux keeps its state in /proc).
|
|
38
|
+
function zombie(pid) {
|
|
39
|
+
try {
|
|
40
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
41
|
+
// The state is the field after the name in parentheses: "R" runs, "Z" is a corpse.
|
|
42
|
+
const after = stat.slice(stat.lastIndexOf(")") + 1).trim();
|
|
43
|
+
return after.startsWith("Z");
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// No /proc (not Linux) or no such pid: not a corpse.
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// A watch on a process: it is done when the process is gone.
|
|
51
|
+
export function watchPid(pid) {
|
|
52
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
53
|
+
return failed(`pid ${pid} is no process id`);
|
|
54
|
+
if (!alive(pid))
|
|
55
|
+
return { done: Promise.resolve({ detail: `the process ${pid} is already gone` }), progress: () => `process ${pid}` };
|
|
56
|
+
let timer;
|
|
57
|
+
const done = new Promise((resolve) => {
|
|
58
|
+
timer = setInterval(() => {
|
|
59
|
+
if (alive(pid))
|
|
60
|
+
return;
|
|
61
|
+
clearInterval(timer);
|
|
62
|
+
resolve({ detail: `the process ${pid} has ended` });
|
|
63
|
+
}, POLL_MS);
|
|
64
|
+
timer.unref?.();
|
|
65
|
+
});
|
|
66
|
+
return { done, progress: () => `process ${pid}`, stop: () => { if (timer)
|
|
67
|
+
clearInterval(timer); } };
|
|
68
|
+
}
|
|
69
|
+
// A watch on a file: it is done when the file has the line it waits for, or holds the text it waits for. The file may
|
|
70
|
+
// not be there yet: a command that writes a log creates it when it starts.
|
|
71
|
+
export function watchFile(file, match, line) {
|
|
72
|
+
if (!file)
|
|
73
|
+
return failed("wait needs a file to watch");
|
|
74
|
+
const path = file.replace(/^~(?=\/|$)/, process.env.HOME ?? "~");
|
|
75
|
+
const read = () => {
|
|
76
|
+
try {
|
|
77
|
+
return readFileSync(path, "utf8");
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const count = (text) => {
|
|
84
|
+
// A trailing newline ends the last line, it does not begin a new one.
|
|
85
|
+
const all = text.split("\n");
|
|
86
|
+
return text.endsWith("\n") ? all.length - 1 : all.length;
|
|
87
|
+
};
|
|
88
|
+
const hit = (text) => {
|
|
89
|
+
if (text === undefined)
|
|
90
|
+
return false;
|
|
91
|
+
if (match)
|
|
92
|
+
return text.includes(match);
|
|
93
|
+
if (line !== undefined)
|
|
94
|
+
return count(text) >= line;
|
|
95
|
+
// Nothing to look for: the file has to be there and have something in it.
|
|
96
|
+
return count(text) > 0;
|
|
97
|
+
};
|
|
98
|
+
const what = match ? `"${match}" in ${path}` : line !== undefined ? `${line} lines in ${path}` : `${path} to have content`;
|
|
99
|
+
if (hit(read()))
|
|
100
|
+
return { done: Promise.resolve({ detail: `the file ${path} already has it` }), progress: () => what };
|
|
101
|
+
let timer;
|
|
102
|
+
const done = new Promise((resolve) => {
|
|
103
|
+
timer = setInterval(() => {
|
|
104
|
+
const text = read();
|
|
105
|
+
if (!hit(text))
|
|
106
|
+
return;
|
|
107
|
+
clearInterval(timer);
|
|
108
|
+
resolve({ detail: match ? `the file ${path} holds "${match}"` : line !== undefined ? `the file ${path} has ${count(text)} lines` : `the file ${path} has content` });
|
|
109
|
+
}, POLL_MS);
|
|
110
|
+
timer.unref?.();
|
|
111
|
+
});
|
|
112
|
+
const progress = () => {
|
|
113
|
+
const text = read();
|
|
114
|
+
const how = match ? `"${match}" in it` : line !== undefined ? `${line} lines in it` : "content in it";
|
|
115
|
+
return text === undefined ? `file ${path} (not there yet, waiting for ${how})` : `file ${path} (${count(text)} lines, waiting for ${how})`;
|
|
116
|
+
};
|
|
117
|
+
return { done, progress, stop: () => { if (timer)
|
|
118
|
+
clearInterval(timer); } };
|
|
119
|
+
}
|
|
120
|
+
// A watch on a paused permission request: it is done when the request is answered, refused or dropped.
|
|
121
|
+
export function watchAsk(settled, what) {
|
|
122
|
+
const done = settled.then((s) => ({ detail: `the request ${s.id} was ${s.decision === "refuse" ? "refused" : "allowed"} (${s.by})${s.note ? `: ${s.note}` : ""}` }));
|
|
123
|
+
return { done, progress: () => what };
|
|
124
|
+
}
|
|
125
|
+
function failed(why) {
|
|
126
|
+
return { done: Promise.reject(new Error(why)), progress: () => why };
|
|
127
|
+
}
|
|
128
|
+
// The wait itself: it blocks until the watch is done or the timeout ticks. It never leaves the caller hanging.
|
|
129
|
+
export async function waitFor(watch, timeoutMs) {
|
|
130
|
+
const started = Date.now();
|
|
131
|
+
let timer;
|
|
132
|
+
const timeout = new Promise((resolve) => {
|
|
133
|
+
timer = setTimeout(() => resolve({ timedOut: true }), Math.max(0, timeoutMs));
|
|
134
|
+
timer.unref?.();
|
|
135
|
+
});
|
|
136
|
+
try {
|
|
137
|
+
const result = await Promise.race([watch.done, timeout]);
|
|
138
|
+
if ("timedOut" in result) {
|
|
139
|
+
return { outcome: "timeout", text: `Timed out after ${Math.round(timeoutMs / 1000)}s waiting for ${watch.progress()}. Nothing happened that the wait could see.`, waitedMs: Date.now() - started };
|
|
140
|
+
}
|
|
141
|
+
return { outcome: "done", text: `Done after ${Math.round((Date.now() - started) / 100) / 10}s: ${result.detail}.`, waitedMs: Date.now() - started };
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
return { outcome: "failed", text: `The wait failed: ${err instanceof Error ? err.message : String(err)}`, waitedMs: Date.now() - started };
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
if (timer)
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
// A watch that timed out keeps looking otherwise: it stops here.
|
|
150
|
+
watch.stop?.();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
// The timeout the caller asked for, in milliseconds: a number of seconds, or "60s", or "2m".
|
|
154
|
+
export function waitTimeoutMs(raw, fallback = WAIT_DEFAULT_MS) {
|
|
155
|
+
const text = raw.trim().toLowerCase();
|
|
156
|
+
if (!text)
|
|
157
|
+
return fallback;
|
|
158
|
+
const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/.exec(text);
|
|
159
|
+
if (!m)
|
|
160
|
+
return fallback;
|
|
161
|
+
const value = Number(m[1]);
|
|
162
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
163
|
+
return fallback;
|
|
164
|
+
const unit = m[2] ?? "s";
|
|
165
|
+
const ms = unit === "ms" ? value : unit === "s" ? value * 1000 : unit === "m" ? value * 60_000 : value * 3_600_000;
|
|
166
|
+
return Math.min(Math.round(ms), WAIT_MAX_MS);
|
|
167
|
+
}
|