@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.
Files changed (146) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/THIRD_PARTY.md +100 -0
  4. package/decider/.python-version +1 -0
  5. package/decider/README.md +35 -0
  6. package/decider/decider/__init__.py +1 -0
  7. package/decider/decider/server.py +327 -0
  8. package/decider/pyproject.toml +34 -0
  9. package/decider/uv.lock +1255 -0
  10. package/dist/agenda.js +51 -0
  11. package/dist/agents.js +58 -0
  12. package/dist/artifact/handoff.js +281 -0
  13. package/dist/ask.js +200 -0
  14. package/dist/backends.js +219 -0
  15. package/dist/backlog.js +414 -0
  16. package/dist/bench.js +427 -0
  17. package/dist/board.js +1 -0
  18. package/dist/brief.js +202 -0
  19. package/dist/browser.js +679 -0
  20. package/dist/budget.js +61 -0
  21. package/dist/catalog.js +187 -0
  22. package/dist/checkchange.js +145 -0
  23. package/dist/checkpoint.js +94 -0
  24. package/dist/cli.js +764 -0
  25. package/dist/comfy-gate.js +258 -0
  26. package/dist/compact.js +142 -0
  27. package/dist/config.js +344 -0
  28. package/dist/context/capture.js +1 -0
  29. package/dist/context/digest.js +1 -0
  30. package/dist/context/embed.js +1 -0
  31. package/dist/context/index.js +2 -0
  32. package/dist/context/ledger.js +1 -0
  33. package/dist/context/manager.js +1 -0
  34. package/dist/context/memory.js +1 -0
  35. package/dist/context/policy.js +1 -0
  36. package/dist/context/prices.js +1 -0
  37. package/dist/context/recall.js +1 -0
  38. package/dist/context/rules.js +1 -0
  39. package/dist/context/search.js +1 -0
  40. package/dist/context/status.js +1 -0
  41. package/dist/context/store.js +1 -0
  42. package/dist/context/summary.js +1 -0
  43. package/dist/context/tokens.js +1 -0
  44. package/dist/context/tools.js +1 -0
  45. package/dist/continuation.js +184 -0
  46. package/dist/contract.js +294 -0
  47. package/dist/contractround.js +178 -0
  48. package/dist/control.js +1 -0
  49. package/dist/creative-tools.js +237 -0
  50. package/dist/dataset.js +175 -0
  51. package/dist/decide.js +676 -0
  52. package/dist/decider.js +171 -0
  53. package/dist/design-shell.js +448 -0
  54. package/dist/design.js +1410 -0
  55. package/dist/desktop.js +44 -0
  56. package/dist/egress.js +156 -0
  57. package/dist/eval.js +60 -0
  58. package/dist/evolver.js +302 -0
  59. package/dist/features.js +193 -0
  60. package/dist/followups.js +32 -0
  61. package/dist/forms.js +195 -0
  62. package/dist/gate.js +108 -0
  63. package/dist/gatebox.js +46 -0
  64. package/dist/grants.js +189 -0
  65. package/dist/graph.js +65 -0
  66. package/dist/guard/index.js +1 -0
  67. package/dist/guard/wire.js +1 -0
  68. package/dist/helpers.js +85 -0
  69. package/dist/hooks.js +158 -0
  70. package/dist/image-models.js +117 -0
  71. package/dist/integration.js +3 -0
  72. package/dist/journal.js +1 -0
  73. package/dist/look.js +363 -0
  74. package/dist/memory.js +1 -0
  75. package/dist/mode.js +97 -0
  76. package/dist/native.js +3348 -0
  77. package/dist/nogit.js +259 -0
  78. package/dist/outcomes.js +148 -0
  79. package/dist/permission.js +35 -0
  80. package/dist/pick.js +89 -0
  81. package/dist/pipelines.js +262 -0
  82. package/dist/plan.js +641 -0
  83. package/dist/plandoc.js +211 -0
  84. package/dist/plugin.js +4736 -0
  85. package/dist/policy.js +58 -0
  86. package/dist/pools.js +1 -0
  87. package/dist/preview.js +274 -0
  88. package/dist/profile.js +165 -0
  89. package/dist/progress.js +1 -0
  90. package/dist/promote.js +313 -0
  91. package/dist/redact.js +1 -0
  92. package/dist/registry.js +179 -0
  93. package/dist/riskscore.js +126 -0
  94. package/dist/roles.js +1 -0
  95. package/dist/routing.js +1 -0
  96. package/dist/runner.js +1892 -0
  97. package/dist/sandbox.js +3 -0
  98. package/dist/sandboxgate.js +90 -0
  99. package/dist/scheduler.js +170 -0
  100. package/dist/services-main.js +131 -0
  101. package/dist/services.js +265 -0
  102. package/dist/session.js +241 -0
  103. package/dist/setup.js +423 -0
  104. package/dist/shell/decide.js +1 -0
  105. package/dist/shell/index.js +2 -0
  106. package/dist/shell/sandbox.js +1 -0
  107. package/dist/shell/wire.js +1 -0
  108. package/dist/skills.js +103 -0
  109. package/dist/state.js +1 -0
  110. package/dist/store.js +1 -0
  111. package/dist/switcher.js +1 -0
  112. package/dist/synth.js +418 -0
  113. package/dist/tools.js +477 -0
  114. package/dist/trials.js +223 -0
  115. package/dist/usage.js +1 -0
  116. package/dist/wait.js +167 -0
  117. package/dist/watchdog.js +476 -0
  118. package/dist/web-guidance.js +43 -0
  119. package/dist/which.js +20 -0
  120. package/dist/worktree/git.js +545 -0
  121. package/dist/writeguard.js +311 -0
  122. package/evolver/mm_evolve/__init__.py +1 -0
  123. package/evolver/mm_evolve/entry.py +3 -0
  124. package/evolver/mm_evolve/evaluator.py +119 -0
  125. package/evolver/mm_evolve/llm.py +76 -0
  126. package/evolver/mm_evolve/run.py +89 -0
  127. package/evolver/mm_evolve/spec.py +62 -0
  128. package/evolver/pyproject.toml +21 -0
  129. package/evolver/uv.lock +772 -0
  130. package/package.json +74 -4
  131. package/skills/THIRD_PARTY.md +58 -0
  132. package/skills/code-review/SKILL.md +46 -0
  133. package/skills/deck/SKILL.md +98 -0
  134. package/skills/deliberate/SKILL.md +39 -0
  135. package/skills/design/SKILL.md +150 -0
  136. package/skills/diagnosing-bugs/SKILL.md +75 -0
  137. package/skills/image/SKILL.md +66 -0
  138. package/skills/orchestrator/SKILL.md +107 -0
  139. package/skills/receiving-code-review/SKILL.md +36 -0
  140. package/skills/research/SKILL.md +18 -0
  141. package/skills/tdd/SKILL.md +56 -0
  142. package/skills/tdd/mocking.md +59 -0
  143. package/skills/tdd/tests.md +77 -0
  144. package/skills/verification-before-completion/SKILL.md +50 -0
  145. package/skills/video/SKILL.md +97 -0
  146. package/skills/web/SKILL.md +60 -0
@@ -0,0 +1,237 @@
1
+ // The optional creative tools install.sh offers after the plugin (roadmap A6-T6/T7): HyperFrames for decks and video,
2
+ // Manim for math animations, ComfyUI for images. Each is found or not, and each can be installed at a pinned version
3
+ // under the user's omacode data directory (<data>/tools), never system-wide and never as a new folder in the home:
4
+ //
5
+ // omacode tools status what is there, and which version
6
+ // omacode tools gpus where ComfyUI could run: NVIDIA, an AMD GPU ROCm can use, the CPU
7
+ // omacode tools install <tool> [--gpu <id>] install one; ComfyUI on the GPU picked (default: the first one found)
8
+ //
9
+ // This module only plans: it detects, and turns an install into the commands to run, so the plan is testable and the
10
+ // CLI can run the steps with their output on the terminal (a ComfyUI install takes minutes and several GB).
11
+ //
12
+ // Pins (2026-11-23): Manim 0.22.1 (2026-10-27), comfy-cli 1.25.0 (2026-11-03), ComfyUI 0.44.2 (2026-11-06), all older
13
+ // than two weeks. HyperFrames 0.9.54 (2026-11-15) is younger: it is the version the deck and video adapters are tested
14
+ // against (B3), kept by the user's decision. Licences: HyperFrames Apache-2.0, Manim MIT, comfy-cli and ComfyUI
15
+ // GPL-3.0 (separate programs the plugin talks to over HTTP or argv, not linked). comfy-mcp 0.10.0 (Comfy-Org, AGPL-3.0-or-later or a commercial licence)
16
+ // is the MCP server agents use to run ComfyUI workflows (src/comfy-gate.ts keeps it in check); it is a separate program
17
+ // OpenCode starts, registered in opencode.json under mcp.servers.comfy.
18
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
19
+ import { homedir } from "node:os";
20
+ import { join } from "node:path";
21
+ import { userDataDir } from "@omacode/core/paths";
22
+ import { TELEMETRY_OFF } from "@omacode/core/telemetry";
23
+ export const PINS = { hyperframes: "0.9.54", manim: "0.22.1", comfyCli: "1.25.0", comfyui: "0.44.2", comfyMcp: "0.10.0", webGuidance: "1.0.0" };
24
+ export const TOOL_NAMES = ["hyperframes", "manim", "comfyui", "comfy-mcp", "web-guidance"];
25
+ // modern-web-guidance (Google Chrome, Apache-2.0, 2026-11-10): the guides and their local search, taken from the npm
26
+ // tarball at its pin and checked against the registry's sha512 before anything is unpacked. Its installer, its npx
27
+ // @latest calls and its Chrome-extensions skill are not used (src/web-guidance.ts adapts the skill).
28
+ export const WEB_GUIDANCE_INTEGRITY = "sha512-vafIZwC8AS6QjM2yyoflZbnc7n3/TVOMLbEMRdPTwcFy0f9/Tq8s5rJQ8UIqRt2KPl9ixravyaMR4nTGuUrcmg==";
29
+ export const WEB_GUIDANCE_SKILL_VERSION = "2026_11_09-5bcc021b";
30
+ // The sha512 check, as a step: node computes it and exits 1 on a mismatch.
31
+ const VERIFY_SHA512 = 'const [f, want] = process.argv.slice(1); const got = "sha512-" + require("node:crypto").createHash("sha512").update(require("node:fs").readFileSync(f)).digest("base64"); if (got !== want) { console.error("checksum mismatch: " + got); process.exit(1) }';
32
+ export const TOOL_INFO = {
33
+ hyperframes: { title: "HyperFrames", what: "decks and videos from HTML (the deck and video adapters)", size: "about 300 MB, Chromium on first use" },
34
+ manim: { title: "Manim", what: "math animations (without LaTeX: formulas need a TeX install of your own)", size: "about 200 MB" },
35
+ comfyui: { title: "ComfyUI", what: "images from local models (the image adapter); no model is downloaded", size: "4–8 GB with PyTorch" },
36
+ "comfy-mcp": { title: "comfy-mcp", what: "lets agents run ComfyUI workflows, checked by the plugin (needs ComfyUI; AGPL-3.0-or-later)", size: "about 100 MB" },
37
+ "web-guidance": { title: "Modern Web Guidance", what: "the browser makers' guides to modern HTML, CSS and JavaScript, searched offline by agents building websites", size: "about 17 MB" },
38
+ };
39
+ export function home(env = process.env) {
40
+ return { home: env.HOME || homedir(), data: userDataDir(), env, sys: "/sys", dev: "/dev" };
41
+ }
42
+ export const toolsDir = (h) => join(h.data, "tools");
43
+ export const hyperframesPrefix = (h) => join(toolsDir(h), "hyperframes");
44
+ export const webGuidanceDir = (h) => join(toolsDir(h), "modern-web-guidance");
45
+ // Where an install puts ComfyUI: COMFYUI_WORKSPACE, else the tools directory.
46
+ export const comfyWorkspace = (h) => h.env.COMFYUI_WORKSPACE || join(toolsDir(h), "comfyui");
47
+ // Where a ComfyUI may already be, installed by hand or by comfy-cli's default: found, it is offered instead of a
48
+ // second install (one is GB of PyTorch).
49
+ export const comfyCandidates = (h) => [...new Set([comfyWorkspace(h), join(h.home, "Apps", "ComfyUI"), join(h.home, "ComfyUI"), join(h.home, "comfy", "ComfyUI")])];
50
+ const comfyVersion = (dir) => {
51
+ try {
52
+ return /"([^"]+)"/.exec(readFileSync(join(dir, "comfyui_version.py"), "utf8"))?.[1];
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ };
58
+ const localBin = (h) => join(h.home, ".local", "bin");
59
+ const version = (text) => /\bv?(\d+\.\d+(?:\.\d+)?(?:[-.a-z0-9]*)?)/i.exec(text)?.[1];
60
+ export async function detect(run, h = home()) {
61
+ const cwd = h.home;
62
+ const ask = async (cmd, args) => {
63
+ const r = await run(cmd, args, { cwd, timeoutMs: 30_000, env: TELEMETRY_OFF }).catch(() => undefined);
64
+ return r && r.code === 0 ? version(`${r.stdout}\n${r.stderr}`) : undefined;
65
+ };
66
+ const hf = await ask("hyperframes", ["--version"]);
67
+ const manim = await ask("manim", ["--version"]);
68
+ const workspace = comfyCandidates(h).find((dir) => comfyVersion(dir));
69
+ const comfy = workspace ? comfyVersion(workspace) : undefined;
70
+ // comfy-mcp starts an MCP server when run, so it is found in uv's tool list rather than by asking it.
71
+ const uvTools = await run("uv", ["tool", "list"], { cwd, timeoutMs: 30_000 }).catch(() => undefined);
72
+ const mcp = uvTools && uvTools.code === 0 ? /^comfy-mcp v(\S+)/m.exec(uvTools.stdout)?.[1] : undefined;
73
+ let guidance;
74
+ try {
75
+ guidance = readFileSync(join(webGuidanceDir(h), "skill-version.txt"), "utf8").trim();
76
+ }
77
+ catch {
78
+ guidance = existsSync(join(webGuidanceDir(h), "modern-web.mjs")) ? "unknown" : undefined;
79
+ }
80
+ return [
81
+ { name: "hyperframes", found: Boolean(hf), ...(hf ? { version: hf } : {}) },
82
+ { name: "manim", found: Boolean(manim), ...(manim ? { version: manim } : {}) },
83
+ { name: "comfyui", found: Boolean(comfy), ...(comfy ? { version: comfy, where: workspace } : {}) },
84
+ { name: "comfy-mcp", found: Boolean(mcp), ...(mcp ? { version: mcp } : {}) },
85
+ { name: "web-guidance", found: guidance !== undefined, ...(guidance !== undefined ? { version: guidance === WEB_GUIDANCE_SKILL_VERSION ? PINS.webGuidance : `unknown (${guidance})`, where: webGuidanceDir(h) } : {}) },
86
+ ];
87
+ }
88
+ // gfx targets of AMD's APUs (integrated graphics): 10.3.5/6 (Rembrandt, Raphael), 11.0.3 (Phoenix), 11.5.x (Strix).
89
+ const APU_GFX = new Set([100305, 100306, 110003, 110500, 110501, 110502]);
90
+ // What the integrated Radeons run as where ROCm's PyTorch has no kernels of their own: the nearest discrete family.
91
+ const GFX_OVERRIDE = { 100305: "10.3.0", 100306: "10.3.0", 110003: "11.0.0", 110500: "11.0.0", 110501: "11.0.0", 110502: "11.0.0" };
92
+ export async function gpus(run, h = home()) {
93
+ const out = [];
94
+ const nv = await run("nvidia-smi", ["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"], { cwd: h.home, timeoutMs: 15_000 }).catch(() => undefined);
95
+ if (nv && nv.code === 0) {
96
+ for (const line of nv.stdout.split("\n").map((l) => l.trim()).filter(Boolean)) {
97
+ const [name, mib] = line.split(",").map((x) => x.trim());
98
+ out.push({ id: "nvidia", name: `${name}${mib ? ` · ${Math.round(Number(mib) / 1024)} GB` : ""}`, flags: ["--nvidia"] });
99
+ break;
100
+ }
101
+ }
102
+ // ROCm needs /dev/kfd, readable and writable by the user (the render group, or a world-writable node as on Arch).
103
+ const kfd = join(h.dev, "kfd");
104
+ const nodes = join(h.sys, "class", "kfd", "kfd", "topology", "nodes");
105
+ if (existsSync(kfd) && existsSync(nodes)) {
106
+ for (const node of readdirSync(nodes).sort()) {
107
+ let props = "";
108
+ try {
109
+ props = readFileSync(join(nodes, node, "properties"), "utf8");
110
+ }
111
+ catch {
112
+ continue;
113
+ }
114
+ const gfx = Number(/gfx_target_version (\d+)/.exec(props)?.[1] ?? 0);
115
+ if (!gfx)
116
+ continue;
117
+ const target = `gfx${Math.floor(gfx / 10000)}${Math.floor((gfx % 10000) / 100)}${(gfx % 100).toString(16)}`;
118
+ let name = target;
119
+ try {
120
+ // amdgpu names a node after its marketing name on some kernels and "ip discovery" on others
121
+ const own = readFileSync(join(nodes, node, "name"), "utf8").trim();
122
+ name = own && !/ip discovery/i.test(own) ? own : "AMD Radeon";
123
+ }
124
+ catch {
125
+ // the node has no name file
126
+ }
127
+ if (APU_GFX.has(gfx)) {
128
+ out.push({
129
+ id: "amd-igpu",
130
+ name: `${name} (${target}, integrated)`,
131
+ flags: ["--amd"],
132
+ note: "integrated Radeon: shares the system RAM; ROCm's PyTorch for it is a preview, checked after the install",
133
+ env: { HSA_OVERRIDE_GFX_VERSION: GFX_OVERRIDE[gfx] },
134
+ });
135
+ }
136
+ else {
137
+ out.push({ id: "amd", name: `${name} (${target})`, flags: ["--amd"] });
138
+ }
139
+ }
140
+ }
141
+ out.push({ id: "cpu", name: "CPU", flags: ["--cpu"], note: "slow: minutes per image" });
142
+ return out;
143
+ }
144
+ // The commands that install a tool, in order. A tool already there at another version is installed over.
145
+ export function installSteps(tool, h = home(), gpu) {
146
+ if (tool === "hyperframes") {
147
+ const prefix = hyperframesPrefix(h);
148
+ return [
149
+ { say: `HyperFrames ${PINS.hyperframes} into ${prefix}`, cmd: "npm", args: ["install", "--prefix", prefix, "--no-audit", "--no-fund", `hyperframes@${PINS.hyperframes}`] },
150
+ { say: `make ${localBin(h)}`, cmd: "mkdir", args: ["-p", localBin(h)] },
151
+ { say: `link ${join(localBin(h), "hyperframes")}`, cmd: "ln", args: ["-sfn", join(prefix, "node_modules", ".bin", "hyperframes"), join(localBin(h), "hyperframes")] },
152
+ ];
153
+ }
154
+ if (tool === "manim") {
155
+ return [{ say: `Manim ${PINS.manim} as a uv tool`, cmd: "uv", args: ["tool", "install", "--force", "--python", "3.12", `manim==${PINS.manim}`] }];
156
+ }
157
+ if (tool === "web-guidance") {
158
+ const dir = webGuidanceDir(h);
159
+ const tgz = join(toolsDir(h), `modern-web-guidance-${PINS.webGuidance}.tgz`);
160
+ return [
161
+ { say: `make ${dir}`, cmd: "mkdir", args: ["-p", toolsDir(h)] },
162
+ { say: `modern-web-guidance ${PINS.webGuidance} from npm (no install script runs)`, cmd: "npm", args: ["pack", `modern-web-guidance@${PINS.webGuidance}`, "--pack-destination", toolsDir(h), "--ignore-scripts", "--silent"] },
163
+ { say: "check it against the pinned sha512", cmd: "node", args: ["-e", VERIFY_SHA512, tgz, WEB_GUIDANCE_INTEGRITY] },
164
+ { say: "clear an older copy", cmd: "rm", args: ["-rf", dir] },
165
+ { say: "make the directory", cmd: "mkdir", args: ["-p", dir] },
166
+ { say: "unpack the guides and their search", cmd: "tar", args: ["xzf", tgz, "-C", dir, "--strip-components=3", "package/skills/modern-web-guidance"] },
167
+ { say: "unpack its licence and notices", cmd: "tar", args: ["xzf", tgz, "-C", dir, "--strip-components=1", "package/LICENSE", "package/THIRD_PARTY_NOTICES"] },
168
+ { say: "remove the download", cmd: "rm", args: ["-f", tgz] },
169
+ ];
170
+ }
171
+ if (tool === "comfy-mcp") {
172
+ // comfy-mcp finds ComfyUI through comfy-cli's default workspace.
173
+ return [
174
+ { say: `comfy-mcp ${PINS.comfyMcp} as a uv tool`, cmd: "uv", args: ["tool", "install", "--force", `comfy-mcp==${PINS.comfyMcp}`] },
175
+ { say: `comfy-cli's default workspace: ${comfyWorkspace(h)}`, cmd: "comfy", args: ["--skip-prompt", "set-default", comfyWorkspace(h)] },
176
+ ];
177
+ }
178
+ const device = gpu ?? { id: "cpu", name: "CPU", flags: ["--cpu"] };
179
+ const workspace = comfyWorkspace(h);
180
+ // comfy-cli asks about analytics on its first run; it is answered once, with no.
181
+ return [
182
+ { say: `comfy-cli ${PINS.comfyCli} as a uv tool`, cmd: "uv", args: ["tool", "install", "--force", `comfy-cli==${PINS.comfyCli}`] },
183
+ { say: "comfy-cli: no analytics", cmd: "comfy", args: ["--skip-prompt", "tracking", "disable"] },
184
+ {
185
+ say: `ComfyUI ${PINS.comfyui} into ${workspace}, for ${device.name}`,
186
+ cmd: "comfy",
187
+ args: ["--skip-prompt", "--workspace", workspace, "install", "--version", PINS.comfyui, "--skip-manager", ...device.flags],
188
+ },
189
+ ];
190
+ }
191
+ // ComfyUI's Python: comfy-cli installs ComfyUI's requirements into the environment it runs in (its uv tool), or into
192
+ // the workspace's own .venv when there is one.
193
+ export function comfyPython(h = home(), workspace = comfyWorkspace(h)) {
194
+ const own = [".venv", "venv"].map((v) => join(workspace, v, "bin", "python")).find((p) => existsSync(p));
195
+ if (own)
196
+ return own;
197
+ return join(h.env.UV_TOOL_DIR || join(h.home, ".local", "share", "uv", "tools"), "comfy-cli", "bin", "python");
198
+ }
199
+ // After a ComfyUI install on a GPU: whether its PyTorch sees the GPU, first as it is and, for an integrated Radeon,
200
+ // then as the discrete family it is close to. A "no" keeps the install (the CPU still works) and says so; the
201
+ // integrated Radeons are where this is expected to fail first.
202
+ export const TORCH_PROBE = "import torch; print('gpu' if torch.cuda.is_available() else 'cpu', torch.cuda.get_device_name(0) if torch.cuda.is_available() else '')";
203
+ export function torchChecks(gpu, h = home(), workspace = comfyWorkspace(h)) {
204
+ if (gpu.id === "cpu")
205
+ return [];
206
+ const step = (env) => ({ say: `does ComfyUI's PyTorch see ${gpu.name}${env ? ` (as ${Object.values(env).join(" ")})` : ""}?`, cmd: comfyPython(h, workspace), args: ["-c", TORCH_PROBE], ...(env ? { env } : {}) });
207
+ return gpu.env ? [step(), step(gpu.env)] : [step()];
208
+ }
209
+ // The line to start ComfyUI with after the install, with the environment the check found it needs.
210
+ export function comfyLaunch(env = {}, h = home()) {
211
+ const vars = Object.entries(env).map(([k, v]) => `${k}=${v} `).join("");
212
+ return `${vars}comfy --workspace ${comfyWorkspace(h)} launch -- --listen 127.0.0.1 --port 8188`;
213
+ }
214
+ // The comfy MCP server in OpenCode's config (mcp.servers.comfy), added once and nothing else changed. A config that is
215
+ // not plain JSON (comments) is left alone: rewriting it would drop the comments, so the user is told the entry instead.
216
+ export const COMFY_MCP_ENTRY = (h = home()) => ({ type: "local", command: [join(localBin(h), "comfy-mcp")] });
217
+ export function addComfyMcp(configFile, h = home()) {
218
+ const entry = COMFY_MCP_ENTRY(h);
219
+ let config = {};
220
+ if (existsSync(configFile)) {
221
+ try {
222
+ config = JSON.parse(readFileSync(configFile, "utf8"));
223
+ }
224
+ catch {
225
+ return { changed: false, say: `${configFile} is not plain JSON; add this under "mcp": { "servers": { … } } by hand: "comfy": ${JSON.stringify(entry)}` };
226
+ }
227
+ }
228
+ const mcp = (config["mcp"] && typeof config["mcp"] === "object" ? config["mcp"] : {});
229
+ const servers = (mcp["servers"] && typeof mcp["servers"] === "object" ? mcp["servers"] : {});
230
+ if (servers["comfy"])
231
+ return { changed: false, say: `${configFile} already has an MCP server named comfy` };
232
+ servers["comfy"] = entry;
233
+ mcp["servers"] = servers;
234
+ config["mcp"] = mcp;
235
+ writeFileSync(configFile, `${JSON.stringify(config, null, 2)}\n`);
236
+ return { changed: true, say: `added the comfy MCP server to ${configFile} (restart OpenCode to load it)` };
237
+ }
@@ -0,0 +1,175 @@
1
+ // Training rows from the journal (design.md §15, §20): Open-Jev JSONL for a local decider, GLiNER2 JSO lines for the
2
+ // decision server's fine-tune.
3
+ //
4
+ // A row's target is, in this order: a label the user gave or an outcome (one-hot, the strongest), else the cloud
5
+ // decider's own probabilities (a soft distillation target). Answers of GLiNER or the rules are never targets.
6
+ //
7
+ // LOCAL_NODES is what the local model is expected to answer (A2b-T1): the three clean guards, the permission node with
8
+ // its own questions, and every planning/working node that otherwise asks the user. A local model trained on the guards
9
+ // alone makes the ask storm worse, not better.
10
+ import { createHash } from "node:crypto";
11
+ import { GUARDS } from "./catalog.js";
12
+ import { PERMISSION_NODE, PERMISSION_QUESTIONS, RELEVANCE_QUESTION } from "./decide.js";
13
+ import { record } from "./journal.js";
14
+ // The nodes the local model must answer. The guards are named as the plugin names them; `G` is the gate as a whole.
15
+ // N13 is the permission node: its questions are the ones a local decider needs to cut the ask storm.
16
+ export const LOCAL_NODES = ["G0", "G0.injection", "G", "N1", "N2", "N4", "N5", "N7", "N8", "N10", PERMISSION_NODE, "N14", "N15", "N16", "git"];
17
+ // The questions each locally-served node answers. Nodes whose questions are built per task (N4, N7, N5, …) are not
18
+ // listed: their rows come from the journal with the questions that were actually asked.
19
+ export function localQuestions(node, withRelevance = false) {
20
+ if (node === "G0" || node === "G")
21
+ return GUARDS;
22
+ if (node === "G0.injection")
23
+ return { injection: GUARDS.injection };
24
+ if (node === PERMISSION_NODE)
25
+ return withRelevance ? { ...PERMISSION_QUESTIONS, path_relevance: RELEVANCE_QUESTION } : PERMISSION_QUESTIONS;
26
+ return undefined;
27
+ }
28
+ // How strong a label is (A2b-T2): the user's own word first, then an observed outcome, then nothing — the cloud answer
29
+ // is the fallback target in target(), not a label. An outcome never overwrites what the user said.
30
+ const LABEL_STRENGTH = { user: 4, user_override: 4, planning_answer: 3, outcome: 2 };
31
+ // Joins every decision question with its strongest label; among labels of equal strength the newest wins.
32
+ export function labeled(entries) {
33
+ const labels = new Map();
34
+ for (const e of entries) {
35
+ if (e.kind === "label" && typeof e.decision === "string" && typeof e.question === "string") {
36
+ const key = `${e.decision}/${e.question}`;
37
+ const source = String(e.source);
38
+ const seen = labels.get(key);
39
+ if (seen && (LABEL_STRENGTH[seen.source] ?? 0) > (LABEL_STRENGTH[source] ?? 0))
40
+ continue;
41
+ labels.set(key, { value: e.value, source });
42
+ }
43
+ }
44
+ const out = [];
45
+ for (const e of entries) {
46
+ if (e.kind !== "decision" || typeof e.id !== "string")
47
+ continue;
48
+ const questions = (e.questions ?? {});
49
+ const answers = (e.answers ?? {});
50
+ for (const [qid, question] of Object.entries(questions)) {
51
+ out.push({ entry: e, qid, question, answer: answers[qid], label: labels.get(`${e.id}/${qid}`) });
52
+ }
53
+ }
54
+ return out;
55
+ }
56
+ export function options(q) {
57
+ if (q.type === "choice")
58
+ return Object.keys(q.criteria);
59
+ if (q.type === "noul")
60
+ return ["no", "yes"];
61
+ return [...q.criteria];
62
+ }
63
+ // The target distribution over options(), or undefined when nothing may serve as a target.
64
+ export function target(row) {
65
+ const opts = options(row.question);
66
+ if (row.label) {
67
+ const v = row.label.value;
68
+ const index = row.question.type === "noul"
69
+ ? (v === "yes" || v === 1 ? 1 : 0)
70
+ : row.question.type === "score" && typeof v === "number" ? Math.round(v) : opts.indexOf(String(v));
71
+ if (index < 0 || index >= opts.length)
72
+ return undefined;
73
+ return { probs: opts.map((_, i) => (i === index ? 1 : 0)), source: row.label.source };
74
+ }
75
+ if (row.entry.backend !== "cloud" || !row.answer)
76
+ return undefined;
77
+ const a = row.answer;
78
+ if (a.type === "noul")
79
+ return { probs: [1 - a.noul, a.noul], source: "decider" };
80
+ const p = opts.map((o, i) => a.probabilities[o] ?? a.probabilities[String(i)] ?? 0);
81
+ const sum = p.reduce((x, y) => x + y, 0);
82
+ if (sum <= 0)
83
+ return undefined;
84
+ return { probs: p.map((x) => x / sum), source: "decider" };
85
+ }
86
+ // 80 / 5 / 5 / 10 by a hash of the group, so one job or task never spans two splits.
87
+ export function splitOf(group) {
88
+ const n = parseInt(createHash("sha256").update(group).digest("hex").slice(0, 8), 16) % 100;
89
+ return n < 80 ? "train" : n < 85 ? "calibration" : n < 90 ? "validation" : "test";
90
+ }
91
+ // --- permission outcomes (A2b-T2) -------------------------------------------------------------------------
92
+ // What a permission decision turned out to be worth, recorded after the fact: the worker was allowed and the work
93
+ // succeeded, the denial held and the worker found another way, or the user overrode the automatic verdict. It labels
94
+ // the `answer` question; the user's own label still wins over it (labeled()).
95
+ export const PERMISSION_OUTCOMES = ["allowed-and-succeeded", "denied-and-retried", "user-overrode"];
96
+ export function permissionTarget(outcome, automatic) {
97
+ if (outcome === "allowed-and-succeeded")
98
+ return "allow";
99
+ if (outcome === "denied-and-retried")
100
+ return "deny";
101
+ // The user overrode it, so the automatic verdict was the wrong one.
102
+ return automatic === "allow" ? "deny" : "allow";
103
+ }
104
+ export function labelPermission(decisionId, outcome, automatic, journal = record) {
105
+ journal({ kind: "label", decision: decisionId, question: "answer", value: permissionTarget(outcome, automatic), source: "outcome", outcome });
106
+ }
107
+ const groupOf = (e) => String(e.task ?? e.job ?? e.id);
108
+ export function openJevRows(entries) {
109
+ return labeled(entries).flatMap((row) => {
110
+ const t = target(row);
111
+ if (!t)
112
+ return [];
113
+ const group = groupOf(row.entry);
114
+ return [{
115
+ id: `${row.entry.id}/${row.qid}`,
116
+ group_id: group,
117
+ split: splitOf(group),
118
+ source: "micromanager",
119
+ state: row.entry.state,
120
+ question: row.question.instructions,
121
+ kind: row.question.type,
122
+ options: options(row.question),
123
+ target: t.probs,
124
+ metadata: {
125
+ node: row.entry.node,
126
+ qid: row.qid,
127
+ backend: row.entry.backend,
128
+ label_source: t.source,
129
+ time: row.entry.time,
130
+ ...(row.question.type === "choice" ? { option_meanings: row.question.criteria } : {}),
131
+ ...(row.question.type === "score" ? { score_values: options(row.question).map((_, i) => i) } : {}),
132
+ },
133
+ }];
134
+ });
135
+ }
136
+ // The text the decision server builds from a state object: the task text first, so a short GLiNER window keeps
137
+ // it. decider/decider/server.py renders the same way.
138
+ const FIRST = ["text", "utterance", "task", "question"];
139
+ export function renderState(state) {
140
+ if (typeof state === "string")
141
+ return state;
142
+ if (!state || typeof state !== "object")
143
+ return String(state);
144
+ const entries = Object.entries(state);
145
+ entries.sort(([a], [b]) => {
146
+ const ia = FIRST.indexOf(a), ib = FIRST.indexOf(b);
147
+ return (ia < 0 ? FIRST.length : ia) - (ib < 0 ? FIRST.length : ib);
148
+ });
149
+ return entries.map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n");
150
+ }
151
+ const YES_NO = { yes: "Yes, the statement is true for this text.", no: "No, the statement is false for this text." };
152
+ const safe = (s) => s.replace(/\(/g, ", ").replace(/[)[\]]/g, "");
153
+ // GLiNER2 JSO lines (oc-voice training/tasks.py): hard labels only, the argmax of the target. Score questions are part
154
+ // of the export too (path_relevance, complexity, risk): their levels are the labels, numbered as the wire format asks
155
+ // them. Choice questions keep their option ids, so the model's task/label names match what the server sends.
156
+ export function glinerRows(entries) {
157
+ return labeled(entries).flatMap((row) => {
158
+ const t = target(row);
159
+ if (!t)
160
+ return [];
161
+ const names = options(row.question);
162
+ const index = t.probs.indexOf(Math.max(...t.probs));
163
+ const described = row.question.type === "noul"
164
+ ? Object.fromEntries(Object.entries(YES_NO).map(([k, v]) => [k, safe(v)]))
165
+ : row.question.type === "choice"
166
+ ? Object.fromEntries(Object.entries(row.question.criteria).map(([k, v]) => [k, safe(v)]))
167
+ : Object.fromEntries(names.map((level, i) => [String(i), safe(level)]));
168
+ const trueLabel = row.question.type === "score" ? String(index) : names[index];
169
+ return [{
170
+ input: renderState(row.entry.state),
171
+ node: row.entry.node,
172
+ output: { classifications: [{ task: row.qid, labels: described, true_label: trueLabel, prompt: safe(row.question.instructions), label_descriptions: described }] },
173
+ }];
174
+ });
175
+ }