@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
package/dist/cli.js ADDED
@@ -0,0 +1,764 @@
1
+ #!/usr/bin/env node
2
+ // Command line: npm run eval -- [--floor 0.8] [--backend cloud] [--journal path]
3
+ // npm run export-dataset -- [--target openjev|gliner|router] [--out file] [--journal path]
4
+ // npm run bench -- [--guard-cases bench/guard_cases.json] [--permission-cases bench/permission_cases.json] [--out path]
5
+ // npm run bench-guards -- [--cases bench/guard_cases.json] [--url http://127.0.0.1:8781/v1/systemone] [--repeat]
6
+ // npm run bench-n7 -- [--cases bench/followup_cases.json]
7
+ // node src/cli.ts status [--project dir] [--all] [--watch] (an ASCII board of the newest job, or of all)
8
+ // node src/cli.ts memory-adopt [--project dir] [--yes] [slug…] (take memory kept under old keys, from
9
+ // before renames or moves, into the project)
10
+ // node src/cli.ts migrate [--project dir] [--apply] (move the state directory from an old name to
11
+ // the current one, core/paths.ts; a dry run without --apply)
12
+ // node src/cli.ts migrate --user [--apply] (the same for the user's state, memory and settings files)
13
+ // node src/cli.ts synth-guards [--model provider/model] [--per 25] [--public] [--topics g/id,…] [--langs de,en]
14
+ // [--relabel] [--rows] [--out decider/data/guards.jsonl]
15
+ // node src/cli.ts synth-entities [--model provider/model] [--per 20] [--contexts a,b] [--langs de,en]
16
+ // [--out decider/data/entities.jsonl]
17
+ // (P6-T3a: made-up names and addresses with their spans)
18
+ // (P6-T2: synthetic and public training cases for the guards)
19
+ // node src/cli.ts services install [--embedding 0.6b|4b|8b] [--replace] | status | mode <service> <on|auto|off> | device <service> <cpu|Vulkan0|…> | idle <minutes> | remove [--purge]
20
+ // (A6: the decider and the embedding service as one user service)
21
+ // node src/cli.ts models status | register <file> --license <SPDX|LicenseRef-…> --territory <EU,…> [--use <text>] [--name <name>]
22
+ // (the image models ComfyUI can load, against the registry)
23
+ // node src/cli.ts tools status | gpus | install <hyperframes|manim|comfyui>[,…] [--gpu <id>] | register comfyui [--gpu <id>] [--workspace <dir>] | ask
24
+ // (A6-T6/T7: the optional creative tools, pinned, into the home)
25
+ // node src/cli.ts sandboxed --dir D -- <command…> (one command in the writer's sandbox of D, offline;
26
+ // the evolver's candidates run under it, src/evolver.ts)
27
+ import { spawnSync } from "node:child_process";
28
+ import { isMain } from "@omacode/core/main";
29
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
30
+ import { dirname as dir, join, resolve } from "node:path";
31
+ import { createInterface } from "node:readline/promises";
32
+ import { adopt, adoptCandidates } from "@omacode/context/adopt";
33
+ import { MemoryStore } from "@omacode/context/store";
34
+ import { applyMigration, applyUserMigration, planMigration, planUserMigration } from "@omacode/state/migrate";
35
+ import { DEFAULT_BACKENDS, Decider, cloudKey, makeAskers } from "./backends.js";
36
+ import { benchPath, buildReport, drift, formatBench, formatDrift, formatN7, formatSweep, guardMetrics, loadCases, loadGuardCorpus, loadN7, loadPermissionCorpus, scoreCases, scoreN7, scorePermissions, sweep, writeBench } from "./bench.js";
37
+ import { GUARD_FLOOR } from "./catalog.js";
38
+ import { loadSettings } from "./config.js";
39
+ import { glinerRows, openJevRows } from "./dataset.js";
40
+ import { evaluate, formatReport } from "./eval.js";
41
+ import { journalPath, readJournal } from "./journal.js";
42
+ import { board } from "./board.js";
43
+ import { listJobs } from "./store.js";
44
+ import { outcomesPath, readOutcomes, routerRows } from "./outcomes.js";
45
+ import { cleanEnv, rulesFor, startSandbox } from "./sandbox.js";
46
+ import { servicesView, setIdleMinutes, setServiceDevice, setServiceMode } from "@omacode/core/service-control";
47
+ import { SERVICE_MODES } from "@omacode/core/supervisor";
48
+ import { EMBEDDING_SIZES, install as installServices, remove as removeServices, status as servicesStatus } from "./services.js";
49
+ import { exec } from "./worktree/git.js";
50
+ import { installParts, installTool, outcomeText, registerComfyTool } from "./features.js";
51
+ import { failed as anyFailed, formatChecks, isPresent, machineChecks, OFFER_IDS, OFFERS, OPENCODE_INSTALL, packageManager, paths as setupPaths, planFor, pluginChecks, preflight, PROFILE_IDS, PROFILES, realProbe, requiredNeeds, systemInstall, toolChecks, uninstallPlan } from "./setup.js";
52
+ import { findChromium } from "@omacode/core/chromium";
53
+ import { readConfig as readServicesConfig, unitPath } from "./services.js";
54
+ import { hashFile, modelFiles } from "./comfy-gate.js";
55
+ import { MODEL_REGISTRY, readModelRegistry, registerModel, registryWith, resolveModel, TERRITORIES } from "@omacode/core/models";
56
+ import { comfyCandidates, comfyWorkspace, home, detect as detectTools, gpus as toolGpus, TOOL_INFO, TOOL_NAMES } from "./creative-tools.js";
57
+ import { ENTITY_CONTEXTS, entityRows, normal, opencodeAsk, publicCases, relabel, synthesize, synthesizeEntities, TOPICS, trainingRows } from "./synth.js";
58
+ function flag(args, name) {
59
+ const i = args.indexOf(`--${name}`);
60
+ return i >= 0 ? args[i + 1] : undefined;
61
+ }
62
+ // A word as the shell reads it back: single-quoted unless it needs nothing.
63
+ const quote = (w) => (/^[\w@%+=:,./-]+$/.test(w) ? w : `'${w.replace(/'/g, "'\\''")}'`);
64
+ export async function main(argv) {
65
+ const [command, ...args] = argv;
66
+ if (command === "sandboxed") {
67
+ // Model-written code the evolver measures: it may write its own directory and nothing else, reaches no network
68
+ // beyond the package registries, and gets the cleaned environment. Without a sandbox it does not run at all.
69
+ const dir = flag(args, "dir");
70
+ const sep = args.indexOf("--");
71
+ if (!dir || sep < 0 || sep === args.length - 1) {
72
+ console.error("usage: sandboxed --dir D -- <command…>");
73
+ return 2;
74
+ }
75
+ const box = await startSandbox();
76
+ if (!box.available) {
77
+ console.error(`no sandbox here (${box.reason}); the command is not run`);
78
+ return 126;
79
+ }
80
+ try {
81
+ // The held-out corpus lies in the plugin's state directory, which the sandbox keeps from every worker; the
82
+ // evaluator measuring the best candidate on it (MM_CORPUS_DIR) may read that one directory, read-only.
83
+ const rules = rulesFor({ role: "code", writer: true, dir, worktree: dir, domains: [] });
84
+ const corpus = process.env.MM_CORPUS === "heldout" ? process.env.MM_CORPUS_DIR : undefined;
85
+ const allowed = corpus ? { ...rules, filesystem: { ...rules.filesystem, allowRead: [...rules.filesystem.allowRead, corpus] } } : rules;
86
+ const wrapped = await box.wrap(args.slice(sep + 1).map(quote).join(" "), allowed);
87
+ const r = spawnSync("bash", ["-c", wrapped], { cwd: dir, stdio: "inherit", env: cleanEnv(process.env, ["MM_CORPUS", "MM_CORPUS_DIR", "MM_REPEAT"]) });
88
+ return r.status ?? 1;
89
+ }
90
+ finally {
91
+ await box.stop();
92
+ }
93
+ }
94
+ if (command === "memory-adopt")
95
+ return await memoryAdopt(args);
96
+ if (command === "synth-guards")
97
+ return await synthGuards(args);
98
+ if (command === "synth-entities")
99
+ return await synthEntities(args);
100
+ if (command === "tools")
101
+ return await tools(args);
102
+ if (command === "models")
103
+ return await models(args);
104
+ if (command === "preflight")
105
+ return await preflightCommand();
106
+ if (command === "doctor")
107
+ return await doctorCommand();
108
+ if (command === "setup")
109
+ return await setupCommand(args);
110
+ if (command === "uninstall")
111
+ return await uninstallCommand(args);
112
+ if (command === "services") {
113
+ const [verb] = args;
114
+ if (verb === "status") {
115
+ console.log(servicesStatus());
116
+ return 0;
117
+ }
118
+ if (verb === "mode") {
119
+ const [, name, mode] = args;
120
+ const known = servicesView().services.map((v) => v.name);
121
+ if (!name || !known.includes(name) || !SERVICE_MODES.includes(mode)) {
122
+ console.error(`usage: services mode <${known.join("|") || "decider|embedding"}> <${SERVICE_MODES.join("|")}>`);
123
+ return 1;
124
+ }
125
+ setServiceMode(name, mode);
126
+ console.log(`${name}: ${mode} (the supervisor applies it within a second)`);
127
+ return 0;
128
+ }
129
+ if (verb === "device") {
130
+ const [, name, device] = args;
131
+ const service = servicesView().services.find((v) => v.name === name);
132
+ const ids = service?.devices?.map((d) => d.id) ?? [];
133
+ const only = service?.devices?.length === 1 ? service.devices[0] : undefined;
134
+ if (only) {
135
+ console.error(`${service.name}: ${only.note ?? `runs on ${only.name} only`}`);
136
+ return 1;
137
+ }
138
+ if (!service || ids.length < 2 || !device || !ids.includes(device)) {
139
+ const choices = servicesView().services.filter((v) => (v.devices?.length ?? 0) > 1).map((v) => `${v.name}: ${v.devices.map((d) => `${d.id} (${d.name})`).join(", ")}`);
140
+ console.error(`usage: services device <service> <device>\n${choices.join("\n") || "no service with a choice of device (is omacode-services running?)"}`);
141
+ return 1;
142
+ }
143
+ setServiceDevice(service.name, device);
144
+ console.log(`${name}: moving to ${device}${service.state === "running" ? " (restarts now)" : ""}`);
145
+ return 0;
146
+ }
147
+ if (verb === "idle") {
148
+ const minutes = Number(args[1]);
149
+ if (!Number.isFinite(minutes) || minutes <= 0) {
150
+ console.error("usage: services idle <minutes>");
151
+ return 1;
152
+ }
153
+ setIdleMinutes(minutes);
154
+ console.log(`services in auto stop after ${minutes} min without a request`);
155
+ return 0;
156
+ }
157
+ if (verb === "remove") {
158
+ console.log(await removeServices(exec, { purge: args.includes("--purge") }));
159
+ return 0;
160
+ }
161
+ if (verb === "install") {
162
+ const size = flag(args, "embedding");
163
+ if (size && !(size in EMBEDDING_SIZES)) {
164
+ console.error(`--embedding must be one of ${Object.keys(EMBEDDING_SIZES).join(", ")}`);
165
+ return 1;
166
+ }
167
+ const r = await installServices(exec, { ...(size ? { embedding: size } : {}), replace: args.includes("--replace"), log: (line) => console.log(line) });
168
+ if (!r.ok)
169
+ console.error(r.text);
170
+ return r.ok ? 0 : 1;
171
+ }
172
+ console.error("usage: services install [--embedding 0.6b|4b|8b] [--replace] | status | mode <service> <on|auto|off> | device <service> <cpu|Vulkan0|…> | idle <minutes> | remove [--purge]");
173
+ return 1;
174
+ }
175
+ if (command === "migrate" && args.includes("--user")) {
176
+ const plan = planUserMigration();
177
+ const apply = args.includes("--apply");
178
+ if (plan.moves.length === 0 && plan.problems.length === 0) {
179
+ console.log("the user's state, memory and settings are on their current names; nothing to move");
180
+ return 0;
181
+ }
182
+ for (const move of plan.moves)
183
+ console.log(`${apply ? "" : "dry run: "}${move.what}: ${move.from} → ${move.to}`);
184
+ for (const problem of plan.problems)
185
+ console.log(` cannot move: ${problem}`);
186
+ for (const warning of plan.warnings)
187
+ console.log(` note: ${warning}`);
188
+ if (!apply) {
189
+ if (!plan.problems.length)
190
+ console.log("run it again with --apply to move");
191
+ return plan.problems.length ? 1 : 0;
192
+ }
193
+ // omacode-services runs out of the data directory: stopped while it moves, its unit rewritten, started again.
194
+ const unit = unitPath(process.platform);
195
+ const active = process.platform !== "darwin" && spawnSync("systemctl", ["--user", "is-active", "--quiet", "omacode-services.service"]).status === 0;
196
+ if (active)
197
+ spawnSync("systemctl", ["--user", "stop", "omacode-services.service"], { stdio: "inherit" });
198
+ const result = applyUserMigration(plan, { files: [unit], binDir: resolve(process.env.HOME ?? "", ".local", "bin") });
199
+ console.log(result.text);
200
+ if (active) {
201
+ spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "inherit" });
202
+ spawnSync("systemctl", ["--user", "start", "omacode-services.service"], { stdio: "inherit" });
203
+ console.log("omacode-services started again from the new place");
204
+ }
205
+ return plan.problems.length ? 1 : 0;
206
+ }
207
+ if (command === "migrate") {
208
+ const project = resolve(flag(args, "project") ?? process.env.INIT_CWD ?? process.cwd());
209
+ const plan = planMigration(project);
210
+ console.log(`project ${project}`);
211
+ if (!plan.from) {
212
+ console.log(plan.note);
213
+ return plan.problems.length ? 1 : 0;
214
+ }
215
+ console.log(`${args.includes("--apply") ? "" : "dry run: "}${plan.note}`);
216
+ for (const problem of plan.problems)
217
+ console.log(` cannot move now: ${problem}`);
218
+ if (!args.includes("--apply")) {
219
+ if (!plan.problems.length)
220
+ console.log("run it again with --apply to move");
221
+ return plan.problems.length ? 1 : 0;
222
+ }
223
+ const result = applyMigration(plan);
224
+ console.log(result.text);
225
+ return result.moved ? 0 : 1;
226
+ }
227
+ if (command === "status") {
228
+ const project = flag(args, "project") ?? process.cwd();
229
+ const draw = () => {
230
+ const jobs = listJobs(project);
231
+ const shown = args.includes("--all") ? jobs : jobs.slice(0, 1);
232
+ const width = Math.max(80, (process.stdout.columns ?? 120) - 2);
233
+ return shown.length ? shown.map((j) => board(j, width)).join("\n\n") : `no micromanager job in ${project}`;
234
+ };
235
+ if (!args.includes("--watch")) {
236
+ console.log(draw());
237
+ return 0;
238
+ }
239
+ for (;;) {
240
+ process.stdout.write(`\x1b[2J\x1b[H${draw()}\n\n(redraws every 2 s; ctrl-c ends)\n`);
241
+ await new Promise((r) => setTimeout(r, 2000));
242
+ }
243
+ }
244
+ if (command === "bench") {
245
+ // The A2b gate: guards and permission cases through the local decider only, one table, one stored verdict. Local
246
+ // mode by construction, so no key is read and no cloud URL is touched; a bench run never becomes a training row
247
+ // (the journal is not written).
248
+ const config = { ...DEFAULT_BACKENDS };
249
+ const decider = new Decider(config, makeAskers(config, undefined), () => { });
250
+ let guardCases;
251
+ let permission;
252
+ try {
253
+ guardCases = loadGuardCorpus(flag(args, "guard-cases") ?? "bench/guard_cases.json");
254
+ permission = await scorePermissions(decider, loadPermissionCorpus(flag(args, "permission-cases") ?? "bench/permission_cases.json"));
255
+ }
256
+ catch (err) {
257
+ console.error(err instanceof Error ? err.message : String(err));
258
+ return 2;
259
+ }
260
+ const guardRows = await scoreCases(decider, guardCases);
261
+ const report = buildReport({ guardCases: guardCases.length, guardRows, permission });
262
+ console.log(formatBench(report));
263
+ console.log(`\nper guard (floor ${GUARD_FLOOR}):`);
264
+ console.log(["guard positives flagged precision recall", ...guardMetrics(guardRows).map((m) => `${m.guard.padEnd(13)} ${String(m.positives).padStart(9)} ${String(m.flagged).padStart(8)} ${`${(m.precision * 100).toFixed(0)}%`.padStart(10)} ${`${(m.recall * 100).toFixed(0)}%`.padStart(7)}`)].join("\n"));
265
+ try {
266
+ console.log(`\nN7 (not gated, printed for the record):\n${formatN7(await scoreN7(decider, loadN7(flag(args, "n7-cases") ?? "bench/followup_cases.json")))}`);
267
+ }
268
+ catch (err) {
269
+ console.log(`\nN7: no answers (${err instanceof Error ? err.message : String(err)})`);
270
+ }
271
+ const out = flag(args, "out") ?? benchPath();
272
+ writeBench(report, out);
273
+ console.log(`\nstored: ${out}`);
274
+ return 0;
275
+ }
276
+ if (command === "bench-guards") {
277
+ // Guards are local-only; the config is "local", so no cloud client is built and the egress gate is never consulted.
278
+ const config = { ...DEFAULT_BACKENDS, urls: { ...DEFAULT_BACKENDS.urls, gliner: flag(args, "url") ?? DEFAULT_BACKENDS.urls.gliner } };
279
+ const decider = new Decider(config, makeAskers(config, undefined), () => { });
280
+ const cases = loadCases(flag(args, "cases") ?? "bench/guard_cases.json");
281
+ const rows = await scoreCases(decider, cases);
282
+ console.log(formatSweep(sweep(rows)));
283
+ if (args.includes("--repeat"))
284
+ console.log(`\nrepeat run:\n${formatDrift(drift(rows, await scoreCases(decider, cases)))}`);
285
+ return 0;
286
+ }
287
+ if (command === "bench-n7") {
288
+ // N7 follows the configured decider mode, like the plugin: "local" asks the local server and reads no key,
289
+ // "cloud" reads the key. The journal is not written, so bench runs never become training rows.
290
+ //
291
+ // The clients go through the same egress gate as the plugin's (A2-T6), and this process has nobody to show a preview
292
+ // to, so in cloud mode every payload is kept local and nothing leaves the machine. That is not a failure of the
293
+ // bench: it is the gate doing its job where no confirmation can arrive, and it is said out loud.
294
+ const config = { ...DEFAULT_BACKENDS, mode: loadSettings().mode };
295
+ if (config.mode === "cloud")
296
+ console.error("cloud bench: no preview channel in this process, so every decision is kept local and nothing is sent (A2-T6)");
297
+ const decider = new Decider(config, makeAskers(config, cloudKey(config)), () => { });
298
+ console.log(formatN7(await scoreN7(decider, loadN7(flag(args, "cases") ?? "bench/followup_cases.json"))));
299
+ return 0;
300
+ }
301
+ const entries = readJournal(flag(args, "journal") ?? journalPath());
302
+ if (command === "eval") {
303
+ const floor = Number(flag(args, "floor") ?? 0.8);
304
+ console.log(formatReport(evaluate(entries, floor, flag(args, "backend")), floor));
305
+ return 0;
306
+ }
307
+ if (command === "export-dataset") {
308
+ const targetName = flag(args, "target") ?? "openjev";
309
+ if (targetName !== "openjev" && targetName !== "gliner" && targetName !== "router") {
310
+ console.error(`unknown target ${targetName}: openjev, gliner or router`);
311
+ return 2;
312
+ }
313
+ // router: the outcome log (src/outcomes.ts), one row per task with a trial's attempts joined, not the journal.
314
+ const rows = targetName === "router" ? routerRows(readOutcomes(flag(args, "outcomes") ?? outcomesPath())) : targetName === "gliner" ? glinerRows(entries) : openJevRows(entries);
315
+ const text = rows.map((r) => JSON.stringify(r)).join("\n") + (rows.length ? "\n" : "");
316
+ const out = flag(args, "out");
317
+ if (out)
318
+ writeFileSync(out, text);
319
+ else
320
+ process.stdout.write(text);
321
+ console.error(`${rows.length} ${targetName} rows${out ? ` -> ${out}` : ""}`);
322
+ return 0;
323
+ }
324
+ console.error("usage: cli.ts bench|eval|export-dataset|bench-guards|bench-n7 [options]");
325
+ return 2;
326
+ }
327
+ if (isMain(import.meta))
328
+ process.exit(await main(process.argv.slice(2)));
329
+ // memory-adopt: without slugs it proposes the keys that look like this project's (its folder name, its jobs'
330
+ // worktrees) and asks before moving them; with slugs it moves exactly those, which is how a key under another name is
331
+ // taken in. --yes skips the question, for a script; without a terminal and without --yes nothing is moved.
332
+ async function memoryAdopt(args) {
333
+ // npm run starts in the repository; INIT_CWD is the directory it was called from.
334
+ const project = resolve(flag(args, "project") ?? process.env.INIT_CWD ?? process.cwd());
335
+ const yes = args.includes("--yes");
336
+ const skip = new Set(["--project", flag(args, "project")]);
337
+ const named = args.filter((a) => !a.startsWith("--") && !skip.has(a));
338
+ const store = new MemoryStore();
339
+ const { id, candidates } = adoptCandidates(store, project);
340
+ const known = new Map(store.projects().map((p) => [p.project, p]));
341
+ const unknown = named.filter((slug) => !known.has(slug));
342
+ if (unknown.length > 0) {
343
+ console.error(`no memory is kept under ${unknown.join(", ")}; memory-adopt without slugs lists what there is`);
344
+ return 1;
345
+ }
346
+ const slugs = named.length > 0 ? named.filter((slug) => slug !== id) : candidates.map((c) => c.slug);
347
+ console.log(`project ${project}\nits memory key: ${id} (${known.get(id)?.entries ?? 0} entries)\n`);
348
+ if (slugs.length === 0) {
349
+ console.log(named.length > 0 ? "nothing to adopt" : "no old keys look like this project's. Name one to take it in: memory-adopt <slug>");
350
+ return 0;
351
+ }
352
+ for (const slug of slugs) {
353
+ const c = candidates.find((x) => x.slug === slug);
354
+ const p = known.get(slug);
355
+ console.log(` ${slug} ${p.entries} entries, last ${p.updated.slice(0, 10)}${c ? ` (${c.why})` : ""}`);
356
+ for (const line of c?.sample ?? [])
357
+ console.log(` · ${line}`);
358
+ }
359
+ if (!yes) {
360
+ if (!process.stdin.isTTY) {
361
+ console.log("\nnothing moved: run it in a terminal to be asked, or pass --yes");
362
+ return 0;
363
+ }
364
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
365
+ const answer = (await rl.question(`\nmove these ${slugs.length} keys into ${id}? [y/N] `)).trim().toLowerCase();
366
+ rl.close();
367
+ if (answer !== "y" && answer !== "yes" && answer !== "j" && answer !== "ja") {
368
+ console.log("nothing moved");
369
+ return 0;
370
+ }
371
+ }
372
+ const { moved } = adopt(store, project, slugs);
373
+ console.log(`moved ${moved} entries into ${id}`);
374
+ return 0;
375
+ }
376
+ // synth-guards (P6-T2): adds cases to the guards' training set, never removing one; a text already in the file is not
377
+ // added again. --public adds the public dataset instead of synthetic cases. --rows writes the GLiNER2 training rows next
378
+ // to it (guards.rows.jsonl).
379
+ async function synthGuards(args) {
380
+ const out = resolve(flag(args, "out") ?? "decider/data/guards.jsonl");
381
+ const model = flag(args, "model") ?? "opencode-go/deepseek-v4.1-flash";
382
+ const have = existsSync(out) ? readFileSync(out, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
383
+ const seen = new Set(have.map((c) => normal(c.text)));
384
+ mkdirSync(dir(out), { recursive: true });
385
+ const ask = opencodeAsk(model, dir(out));
386
+ const log = (line) => console.error(line);
387
+ if (args.includes("--relabel")) {
388
+ const r = await relabel(ask, have, Number(flag(args, "concurrency") ?? 4), log);
389
+ writeFileSync(out, r.cases.map((c) => JSON.stringify(c)).join("\n") + "\n");
390
+ if (args.includes("--rows"))
391
+ writeFileSync(out.replace(/\.jsonl$/, ".rows.jsonl"), trainingRows(r.cases).map((row) => JSON.stringify(row)).join("\n") + "\n");
392
+ console.log(`relabelled: ${r.changed} cases changed a label, ${r.dropped} dropped, ${r.failed} batches unanswered; ${r.cases.length} in ${out}`);
393
+ return 0;
394
+ }
395
+ const { cases, stats } = args.includes("--public")
396
+ ? await publicCases(ask, fetch, seen, log, Number(flag(args, "concurrency") ?? 4))
397
+ : await synthesize(ask, model, {
398
+ per: Number(flag(args, "per") ?? 25),
399
+ seen,
400
+ log,
401
+ concurrency: Number(flag(args, "concurrency") ?? 4),
402
+ // --topics injection/persona,sensitive/personal and --langs de: fill in batches the model refused before.
403
+ ...(flag(args, "topics") ? { topics: TOPICS.filter((t) => flag(args, "topics").split(",").includes(`${t.guard}/${t.id}`)) } : {}),
404
+ ...(flag(args, "langs") ? { langs: flag(args, "langs").split(",") } : {}),
405
+ });
406
+ const all = [...have, ...cases];
407
+ writeFileSync(out, all.map((c) => JSON.stringify(c)).join("\n") + "\n");
408
+ if (args.includes("--rows"))
409
+ writeFileSync(out.replace(/\.jsonl$/, ".rows.jsonl"), trainingRows(all).map((r) => JSON.stringify(r)).join("\n") + "\n");
410
+ console.log(`${stats.kept} new cases (${stats.generated} written, ${stats.disagreed} dropped by the labelling pass, ${stats.duplicates} duplicates, ${stats.failedCalls} failed calls); ${all.length} in ${out}`);
411
+ return 0;
412
+ }
413
+ // synth-entities (P6-T3a): adds made-up texts with names and addresses to the entity training set, never removing one,
414
+ // and writes the GLiNER2 rows beside it (entities.rows.jsonl).
415
+ async function synthEntities(args) {
416
+ const out = resolve(flag(args, "out") ?? "decider/data/entities.jsonl");
417
+ const model = flag(args, "model") ?? "opencode-go/deepseek-v4.1-flash";
418
+ const have = existsSync(out) ? readFileSync(out, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
419
+ mkdirSync(dir(out), { recursive: true });
420
+ const { cases, stats } = await synthesizeEntities(opencodeAsk(model, dir(out)), model, {
421
+ per: Number(flag(args, "per") ?? 20),
422
+ seen: new Set(have.map((c) => normal(c.text))),
423
+ concurrency: Number(flag(args, "concurrency") ?? 4),
424
+ log: (line) => console.error(line),
425
+ // --contexts contract,data and --langs de: fill in batches whose check went unanswered before.
426
+ ...(flag(args, "contexts") ? { contexts: ENTITY_CONTEXTS.filter((c) => flag(args, "contexts").split(",").includes(c.id)) } : {}),
427
+ ...(flag(args, "langs") ? { langs: flag(args, "langs").split(",") } : {}),
428
+ });
429
+ const all = [...have, ...cases];
430
+ writeFileSync(out, all.map((c) => JSON.stringify(c)).join("\n") + "\n");
431
+ writeFileSync(out.replace(/\.jsonl$/, ".rows.jsonl"), entityRows(all).map((r) => JSON.stringify(r)).join("\n") + "\n");
432
+ console.log(`${stats.kept} new cases (${stats.generated} written, ${stats.disagreed} dropped by the checks, ${stats.duplicates} duplicates, ${stats.failedCalls} unchecked batches); ${all.length} in ${out}`);
433
+ return 0;
434
+ }
435
+ // `tools status | gpus | install <tool>[,<tool>…] [--gpu <id>] | ask`: the optional creative tools (creative-tools.ts).
436
+ // ask is install.sh's question round: each tool with what it is for and whether it is there, then y/N; ComfyUI also
437
+ // asks for the device among the ones found.
438
+ async function tools(args) {
439
+ const [verb, list] = args;
440
+ if (verb === "status") {
441
+ for (const t of await detectTools(exec))
442
+ console.log(`${TOOL_INFO[t.name].title.padEnd(12)} ${t.found ? `found ${t.version ?? ""}${t.where ? ` in ${t.where}` : ""}` : "not found"}`);
443
+ return 0;
444
+ }
445
+ if (verb === "gpus") {
446
+ for (const g of await toolGpus(exec))
447
+ console.log(`${g.id.padEnd(9)} ${g.name}${g.note ? ` (${g.note})` : ""}`);
448
+ return 0;
449
+ }
450
+ if (verb === "install") {
451
+ const names = (list ?? "").split(",").map((x) => x.trim()).filter(Boolean);
452
+ const bad = names.filter((n) => !TOOL_NAMES.includes(n));
453
+ if (!names.length || bad.length) {
454
+ console.error(`usage: tools install <${TOOL_NAMES.join("|")}>[,…] [--gpu nvidia|amd|amd-igpu|cpu]${bad.length ? `\nunknown: ${bad.join(", ")}` : ""}`);
455
+ return 1;
456
+ }
457
+ const found = await toolGpus(exec);
458
+ const wanted = flag(args, "gpu");
459
+ const gpu = wanted ? found.find((g) => g.id === wanted) : found[0];
460
+ if (wanted && !gpu) {
461
+ console.error(`no ${wanted} here; found: ${found.map((g) => g.id).join(", ")}`);
462
+ return 1;
463
+ }
464
+ let failed = 0;
465
+ for (const name of names)
466
+ failed += (await installTool(name, console.log, gpu)) ? 0 : 1;
467
+ return failed ? 1 : 0;
468
+ }
469
+ if (verb === "register") {
470
+ if (list !== "comfyui") {
471
+ console.error("usage: tools register comfyui [--gpu <id>]");
472
+ return 1;
473
+ }
474
+ const where = flag(args, "workspace") ?? (await detectTools(exec)).find((t) => t.name === "comfyui")?.where;
475
+ if (!where) {
476
+ console.error(`no ComfyUI found (looked in ${comfyCandidates(home()).join(", ")}); --workspace <dir> names one`);
477
+ return 1;
478
+ }
479
+ const found = await toolGpus(exec);
480
+ const wanted = flag(args, "gpu");
481
+ const gpu = wanted ? found.find((g) => g.id === wanted) : found[0];
482
+ if (!gpu) {
483
+ console.error(`no ${wanted} here; found: ${found.map((g) => g.id).join(", ")}`);
484
+ return 1;
485
+ }
486
+ return (await registerComfyTool(console.log, gpu, where)) ? 0 : 1;
487
+ }
488
+ if (verb === "ask") {
489
+ if (!process.stdin.isTTY) {
490
+ console.log("no terminal: no optional tools asked about (install.sh --with hyperframes,manim,comfyui installs them)");
491
+ return 0;
492
+ }
493
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
494
+ try {
495
+ const yes = async (q) => /^(y|yes|j|ja)$/i.test((await rl.question(`${q} [y/N] `)).trim());
496
+ console.log("\nOptional tools (each is installed into your home at a pinned version; all can be added later with npm run tools -- install <name>):");
497
+ const there = await detectTools(exec);
498
+ const picked = [];
499
+ for (const t of there) {
500
+ const info = TOOL_INFO[t.name];
501
+ console.log(`\n${info.title}: ${info.what}. ${info.size}.`);
502
+ if (t.found) {
503
+ console.log(` found ${t.version ?? ""}${t.where ? ` in ${t.where}` : ""}`);
504
+ // A ComfyUI already there is offered to omacode-services rather than installed twice.
505
+ if (t.name === "comfyui" && t.where && (await yes(" start it on demand with omacode-services?"))) {
506
+ const devices = await toolGpus(exec);
507
+ devices.forEach((g, i) => console.log(` ${i + 1}) ${g.name}${g.note ? ` — ${g.note}` : ""}`));
508
+ const answer = (await rl.question(` run it on [1-${devices.length}, default 1]: `)).trim();
509
+ await registerComfyTool(console.log, devices[Math.max(0, Math.min(devices.length - 1, (Number(answer) || 1) - 1))], t.where);
510
+ }
511
+ continue;
512
+ }
513
+ if (t.name === "comfy-mcp" && !there.some((x) => x.name === "comfyui" && x.found) && !picked.some((p) => p.name === "comfyui")) {
514
+ console.log(" skipped: it needs ComfyUI");
515
+ continue;
516
+ }
517
+ if (!(await yes(` install ${info.title}?`)))
518
+ continue;
519
+ if (t.name !== "comfyui") {
520
+ picked.push({ name: t.name });
521
+ continue;
522
+ }
523
+ const devices = await toolGpus(exec);
524
+ devices.forEach((g, i) => console.log(` ${i + 1}) ${g.name}${g.note ? ` — ${g.note}` : ""}`));
525
+ const answer = (await rl.question(` run ComfyUI on [1-${devices.length}, default 1]: `)).trim();
526
+ const gpu = devices[Math.max(0, Math.min(devices.length - 1, (Number(answer) || 1) - 1))];
527
+ picked.push({ name: "comfyui", gpu });
528
+ }
529
+ rl.close();
530
+ let failed = 0;
531
+ for (const p of picked)
532
+ failed += (await installTool(p.name, console.log, p.gpu)) ? 0 : 1;
533
+ return failed ? 1 : 0;
534
+ }
535
+ finally {
536
+ rl.close();
537
+ }
538
+ }
539
+ console.error(`usage: tools status | gpus | install <${TOOL_NAMES.join("|")}>[,…] [--gpu <id>] | ask`);
540
+ return 1;
541
+ }
542
+ // Runs a tool's steps with their output on the terminal; false at the first one that fails.
543
+ // `models status | register`: the model files ComfyUI can load (its model folders and extra_model_paths.yaml), each
544
+ // hashed (cached, as the ComfyUI gate does) and checked against the registry; `register` records one with the licence
545
+ // the user states. Nothing here guesses a licence.
546
+ async function models(args) {
547
+ const [verb, target] = args;
548
+ const workspace = readServicesConfig()?.comfyui?.workspace ?? comfyWorkspace(home());
549
+ const files = new Map(modelFiles(workspace).map((f) => [f.file, f.name]));
550
+ const registry = registryWith(readModelRegistry().entries, MODEL_REGISTRY);
551
+ if (verb === "status") {
552
+ for (const [file, name] of [...files].sort((a, b) => a[1].localeCompare(b[1]))) {
553
+ const hash = await hashFile(file);
554
+ const v = resolveModel({ declared: name, hash }, registry);
555
+ const what = v.status === "allowed" ? `${v.spdx} (${v.territories.join(", ")})` : v.status === "blocked" ? `BLOCKED: ${v.reason}` : v.status === "territory" ? `${v.spdx}: not for ${v.territory}` : "not registered";
556
+ console.log(`${v.status.padEnd(9)} ${name.padEnd(44)} ${hash.slice(0, 12)} ${what}`);
557
+ }
558
+ return 0;
559
+ }
560
+ if (verb === "register") {
561
+ const license = flag(args, "license");
562
+ const territory = (flag(args, "territory") ?? "").split(",").map((t) => t.trim()).filter(Boolean);
563
+ const match = [...files].filter(([file, name]) => name === target || file === resolve(target ?? ""));
564
+ if (!target || !license || !territory.length || match.length !== 1) {
565
+ console.error(`usage: models register <file name> --license <SPDX or LicenseRef-…> --territory <${TERRITORIES.join("|")}>[,…] [--use <text>] [--name <name>]${target && match.length !== 1 ? `\n${match.length ? "more than one file is" : "no model file is"} named ${target}; models status lists them` : ""}`);
566
+ return 1;
567
+ }
568
+ const [file, name] = match[0];
569
+ const hash = await hashFile(file);
570
+ try {
571
+ const { path, entry } = registerModel({ hash, name: flag(args, "name") ?? name, license, territory: territory, ...(flag(args, "use") ? { use: flag(args, "use") } : {}) });
572
+ console.log(`registered ${entry.name} (${hash.slice(0, 12)}…) as ${entry.spdx} for ${entry.territories.join(", ")} in ${path}`);
573
+ return 0;
574
+ }
575
+ catch (err) {
576
+ console.error(err instanceof Error ? err.message : String(err));
577
+ return 1;
578
+ }
579
+ }
580
+ console.error("usage: models status | register <file name> --license <…> --territory <…> [--use <text>] [--name <name>]");
581
+ return 1;
582
+ }
583
+ // `preflight`: what this machine has before an install (setup.ts). Exit 1 when something blocks the install.
584
+ async function preflightCommand() {
585
+ const checks = await preflight(realProbe(exec));
586
+ console.log(formatChecks(checks));
587
+ return anyFailed(checks) ? 1 : 0;
588
+ }
589
+ // `doctor`: the installed state, each finding with its fix.
590
+ async function doctorCommand() {
591
+ const probe = realProbe(exec);
592
+ const at = setupPaths(unitPath());
593
+ const checks = [
594
+ ...(await preflight(probe)),
595
+ ...pluginChecks(at),
596
+ ...(await machineChecks(probe, at)),
597
+ ...toolChecks(await detectTools(exec), at.opencodeJson),
598
+ ];
599
+ console.log(formatChecks(checks));
600
+ const bad = checks.filter((c) => c.level === "fail").length;
601
+ const warn = checks.filter((c) => c.level === "warn").length;
602
+ console.log(`\n${bad ? `${bad} problem${bad === 1 ? "" : "s"}` : "no problem"}${warn ? `, ${warn} warning${warn === 1 ? "" : "s"}` : ""}`);
603
+ return bad ? 1 : 0;
604
+ }
605
+ // `setup required [--yes]`: what the plugin cannot run without, installed after one question (setup.ts).
606
+ // `setup ask`: each optional part asked on its own. `setup <minimal|coding|creator|full> [--gpu <id>]`: the same
607
+ // answers given up front. Each runs the system packages first, then the services, then the creative tools.
608
+ async function setupCommand(args) {
609
+ const probe = realProbe(exec);
610
+ const tty = Boolean(process.stdin.isTTY && process.stdout.isTTY);
611
+ const yesAll = args.includes("--yes");
612
+ const ask = async (question, byDefault) => {
613
+ if (!tty)
614
+ return byDefault && yesAll;
615
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
616
+ try {
617
+ const a = (await rl.question(`${question} ${byDefault ? "[Y/n]" : "[y/N]"} `)).trim();
618
+ return a === "" ? byDefault : /^(y|yes|j|ja)$/i.test(a);
619
+ }
620
+ finally {
621
+ rl.close();
622
+ }
623
+ };
624
+ const run = (c) => {
625
+ console.log(`→ ${c.say}\n ${[c.cmd, ...c.args].join(" ")}`);
626
+ return spawnSync(c.cmd, [...c.args], { stdio: "inherit" }).status === 0;
627
+ };
628
+ // uv's own installer puts it in ~/.local/bin, which this process may not have on its PATH yet.
629
+ // and OpenCode's into ~/.opencode/bin
630
+ process.env.PATH = `${join(process.env.HOME ?? "", ".opencode", "bin")}:${join(process.env.HOME ?? "", ".local", "bin")}:${process.env.PATH ?? ""}`;
631
+ if (args[0] === "required") {
632
+ const checks = await preflight(probe);
633
+ console.log(formatChecks(checks));
634
+ const needs = requiredNeeds(probe);
635
+ const noOpencode = checks.some((c) => c.area === "opencode" && c.level === "fail");
636
+ if (!needs.length && !noOpencode)
637
+ return anyFailed(checks) ? 1 : 0;
638
+ const sys = systemInstall(packageManager(probe), needs);
639
+ const commands = [...sys.commands, ...(noOpencode ? [OPENCODE_INSTALL] : [])];
640
+ console.log(`\nNeeded and missing: ${[...needs, ...(noOpencode ? ["opencode"] : [])].join(", ")}`);
641
+ for (const c of commands)
642
+ console.log(` ${c.say}: ${[c.cmd, ...c.args].join(" ")}`);
643
+ for (const m of sys.manual)
644
+ console.log(` install by hand: ${m}`);
645
+ if (commands.length && (await ask("Install them now?", true))) {
646
+ for (const c of commands)
647
+ if (!run(c))
648
+ console.error(` "${c.say}" failed`);
649
+ }
650
+ else if (commands.length) {
651
+ console.log("Not installed. Without git there are no micromanager jobs, without bubblewrap no sandbox for plan mode.");
652
+ }
653
+ const after = await preflight(realProbe(exec));
654
+ const blocking = after.filter((c) => c.level === "fail");
655
+ if (blocking.length)
656
+ console.log(formatChecks(blocking));
657
+ return blocking.length ? 1 : 0;
658
+ }
659
+ const there = { services: existsSync(unitPath()), which: probe.which, chromium: Boolean(findChromium()), tools: await detectTools(exec) };
660
+ let chosen = [];
661
+ if (args[0] === "ask") {
662
+ if (!tty) {
663
+ console.log("no terminal: no optional part asked about (./install.sh --profile coding|creator|full, or --with <tools>)");
664
+ return 0;
665
+ }
666
+ // --system: only what needs sudo, which only a terminal can give; the rest is offered inside OpenCode.
667
+ const systemOnly = args.includes("--system");
668
+ console.log(systemOnly
669
+ ? "\nOptional system packages (they need sudo, so they are asked here; each only if you say yes):"
670
+ : "\nOptional parts. Each is installed only if you say yes; all can be added later with ./install.sh --tools.");
671
+ for (const id of OFFER_IDS) {
672
+ const o = OFFERS[id];
673
+ if (systemOnly && !o.system)
674
+ continue;
675
+ if (isPresent(id, there)) {
676
+ console.log(`\n${o.title}: already there.`);
677
+ continue;
678
+ }
679
+ if (o.after && !isPresent(o.after, there) && !chosen.includes(o.after))
680
+ continue;
681
+ console.log(`\n${o.title}: ${o.what}. ${o.size.charAt(0).toUpperCase()}${o.size.slice(1)}.`);
682
+ if (await ask(` Install ${o.title}?`, false))
683
+ chosen.push(id);
684
+ }
685
+ if (systemOnly)
686
+ console.log("\nThe other parts (local services, HyperFrames, ComfyUI, comfy-mcp, Manim) need no sudo: OpenCode offers them on its first start, in /setup, and when an agent needs one. ./install.sh --tools asks about them here instead.");
687
+ }
688
+ else if (args[0] === "with") {
689
+ const names = (args[1] ?? "").split(",").map((x) => x.trim()).filter(Boolean);
690
+ const bad = names.filter((n) => !OFFER_IDS.includes(n));
691
+ if (!names.length || bad.length) {
692
+ console.error(`usage: setup with <${OFFER_IDS.join("|")}>[,…]${bad.length ? `\nunknown: ${bad.join(", ")}` : ""}`);
693
+ return 1;
694
+ }
695
+ chosen = names;
696
+ }
697
+ else if (PROFILE_IDS.includes(args[0] ?? "")) {
698
+ const profile = PROFILES[args[0]];
699
+ chosen = [...profile.offers];
700
+ console.log(`${profile.title}: ${chosen.length ? chosen.map((id) => OFFERS[id].title).join(", ") : "only the plugin"} (downloads ${profile.download}).`);
701
+ }
702
+ else {
703
+ console.error(`usage: setup required [--yes] | ask | with <parts> | <${PROFILE_IDS.join("|")}> [--gpu <id>]`);
704
+ return 1;
705
+ }
706
+ const plan = planFor(chosen, there);
707
+ if (!plan.system.length && !plan.services && !plan.tools.length) {
708
+ console.log("nothing to install");
709
+ return 0;
710
+ }
711
+ if (plan.system.includes("uv") && !chosen.includes("services") && chosen.length)
712
+ console.log("uv is needed for that and is installed too.");
713
+ // ComfyUI's device: asked in a terminal, else --gpu, else the first one found.
714
+ let gpu;
715
+ if (plan.tools.includes("comfyui")) {
716
+ const devices = await toolGpus(exec);
717
+ const wanted = flag(args, "gpu");
718
+ gpu = wanted ? devices.find((g) => g.id === wanted) : devices[0];
719
+ if (args[0] === "ask" && devices.length > 1) {
720
+ devices.forEach((g, i) => console.log(` ${i + 1}) ${g.name}${g.note ? ` — ${g.note}` : ""}`));
721
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
722
+ const answer = (await rl.question(` Run ComfyUI on [1-${devices.length}, default 1]: `)).trim();
723
+ rl.close();
724
+ gpu = devices[Math.max(0, Math.min(devices.length - 1, (Number(answer) || 1) - 1))];
725
+ }
726
+ }
727
+ const outcome = await installParts(chosen, { run: exec, log: console.log, allowSudo: true, there, ...(gpu ? { gpu } : {}) });
728
+ console.log(outcomeText(outcome));
729
+ return outcome.ok ? 0 : 1;
730
+ }
731
+ // `uninstall [--purge] [--dry-run]`: the plan first, then the removal. Never the user's data: state, memory, settings.
732
+ async function uninstallCommand(args) {
733
+ const at = setupPaths(unitPath());
734
+ const purge = args.includes("--purge");
735
+ const plan = uninstallPlan(at, { purge });
736
+ console.log(plan.remove.length ? "Removes:" : "Nothing of omacode's install is left to remove.");
737
+ for (const r of plan.remove)
738
+ console.log(` - ${r.path}: ${r.what}`);
739
+ console.log("Keeps:");
740
+ for (const k of plan.keep)
741
+ console.log(` - ${k.path}: ${k.what}`);
742
+ if (args.includes("--dry-run"))
743
+ return 0;
744
+ if (existsSync(at.unit))
745
+ console.log(await removeServices(exec, { purge }));
746
+ rmSync(at.pluginLink, { force: true });
747
+ rmSync(at.tuiDir, { recursive: true, force: true });
748
+ try {
749
+ const cli = JSON.parse(readFileSync(at.cliJson, "utf8"));
750
+ if (Array.isArray(cli.plugins) && cli.plugins.includes(at.tuiDir)) {
751
+ cli.plugins = cli.plugins.filter((x) => x !== at.tuiDir);
752
+ if (!cli.plugins.length)
753
+ delete cli.plugins;
754
+ writeFileSync(at.cliJson, `${JSON.stringify(cli, null, 2)}\n`);
755
+ }
756
+ }
757
+ catch {
758
+ // no cli.json, or not plain JSON: nothing of ours to take out
759
+ }
760
+ if (purge)
761
+ rmSync(join(at.data, "tools"), { recursive: true, force: true });
762
+ console.log("omacode is removed; restart OpenCode");
763
+ return 0;
764
+ }