@omacode/micromanager 0.1.1 → 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 (213) hide show
  1. package/README.md +7 -4
  2. package/THIRD_PARTY.md +100 -0
  3. package/decider/.python-version +1 -0
  4. package/decider/README.md +35 -0
  5. package/decider/decider/__init__.py +1 -0
  6. package/decider/decider/server.py +327 -0
  7. package/decider/pyproject.toml +34 -0
  8. package/decider/uv.lock +1255 -0
  9. package/dist/agenda.js +51 -0
  10. package/dist/agents.js +58 -0
  11. package/dist/artifact/handoff.js +281 -0
  12. package/dist/ask.js +200 -0
  13. package/dist/backends.js +219 -0
  14. package/dist/backlog.js +414 -0
  15. package/dist/bench.js +427 -0
  16. package/dist/board.js +1 -0
  17. package/dist/brief.js +202 -0
  18. package/dist/browser.js +679 -0
  19. package/dist/budget.js +61 -0
  20. package/dist/catalog.js +187 -0
  21. package/dist/checkchange.js +145 -0
  22. package/dist/checkpoint.js +94 -0
  23. package/dist/cli.js +764 -0
  24. package/dist/comfy-gate.js +258 -0
  25. package/dist/compact.js +142 -0
  26. package/dist/config.js +344 -0
  27. package/dist/context/capture.js +1 -0
  28. package/dist/context/digest.js +1 -0
  29. package/dist/context/embed.js +1 -0
  30. package/dist/context/index.js +2 -0
  31. package/dist/context/ledger.js +1 -0
  32. package/dist/context/manager.js +1 -0
  33. package/dist/context/memory.js +1 -0
  34. package/dist/context/policy.js +1 -0
  35. package/dist/context/prices.js +1 -0
  36. package/dist/context/recall.js +1 -0
  37. package/dist/context/rules.js +1 -0
  38. package/dist/context/search.js +1 -0
  39. package/dist/context/status.js +1 -0
  40. package/dist/context/store.js +1 -0
  41. package/dist/context/summary.js +1 -0
  42. package/dist/context/tokens.js +1 -0
  43. package/dist/context/tools.js +1 -0
  44. package/dist/continuation.js +184 -0
  45. package/dist/contract.js +294 -0
  46. package/dist/contractround.js +178 -0
  47. package/dist/control.js +1 -0
  48. package/dist/creative-tools.js +237 -0
  49. package/dist/dataset.js +175 -0
  50. package/dist/decide.js +676 -0
  51. package/dist/decider.js +171 -0
  52. package/dist/design-shell.js +448 -0
  53. package/dist/design.js +1410 -0
  54. package/dist/desktop.js +44 -0
  55. package/dist/egress.js +156 -0
  56. package/dist/eval.js +60 -0
  57. package/dist/evolver.js +302 -0
  58. package/dist/features.js +193 -0
  59. package/dist/followups.js +32 -0
  60. package/dist/forms.js +195 -0
  61. package/dist/gate.js +108 -0
  62. package/dist/gatebox.js +46 -0
  63. package/dist/grants.js +189 -0
  64. package/dist/graph.js +65 -0
  65. package/dist/guard/index.js +1 -0
  66. package/dist/guard/wire.js +1 -0
  67. package/dist/helpers.js +85 -0
  68. package/dist/hooks.js +158 -0
  69. package/dist/image-models.js +117 -0
  70. package/{src/integration.ts → dist/integration.js} +1 -2
  71. package/dist/journal.js +1 -0
  72. package/dist/look.js +363 -0
  73. package/dist/memory.js +1 -0
  74. package/dist/mode.js +97 -0
  75. package/dist/native.js +3348 -0
  76. package/dist/nogit.js +259 -0
  77. package/dist/outcomes.js +148 -0
  78. package/dist/permission.js +35 -0
  79. package/dist/pick.js +89 -0
  80. package/dist/pipelines.js +262 -0
  81. package/dist/plan.js +641 -0
  82. package/dist/plandoc.js +211 -0
  83. package/dist/plugin.js +4736 -0
  84. package/dist/policy.js +58 -0
  85. package/dist/pools.js +1 -0
  86. package/dist/preview.js +274 -0
  87. package/dist/profile.js +165 -0
  88. package/dist/progress.js +1 -0
  89. package/dist/promote.js +313 -0
  90. package/dist/redact.js +1 -0
  91. package/dist/registry.js +179 -0
  92. package/dist/riskscore.js +126 -0
  93. package/dist/roles.js +1 -0
  94. package/dist/routing.js +1 -0
  95. package/dist/runner.js +1892 -0
  96. package/{src/sandbox.ts → dist/sandbox.js} +1 -2
  97. package/dist/sandboxgate.js +90 -0
  98. package/dist/scheduler.js +170 -0
  99. package/dist/services-main.js +131 -0
  100. package/dist/services.js +265 -0
  101. package/dist/session.js +241 -0
  102. package/dist/setup.js +423 -0
  103. package/dist/shell/decide.js +1 -0
  104. package/dist/shell/index.js +2 -0
  105. package/dist/shell/sandbox.js +1 -0
  106. package/dist/shell/wire.js +1 -0
  107. package/dist/skills.js +103 -0
  108. package/dist/state.js +1 -0
  109. package/dist/store.js +1 -0
  110. package/dist/switcher.js +1 -0
  111. package/dist/synth.js +418 -0
  112. package/dist/tools.js +477 -0
  113. package/dist/trials.js +223 -0
  114. package/dist/usage.js +1 -0
  115. package/dist/wait.js +167 -0
  116. package/dist/watchdog.js +476 -0
  117. package/dist/web-guidance.js +43 -0
  118. package/dist/which.js +20 -0
  119. package/dist/worktree/git.js +545 -0
  120. package/dist/writeguard.js +311 -0
  121. package/package.json +36 -17
  122. package/skills/deck/SKILL.md +98 -0
  123. package/skills/design/SKILL.md +150 -0
  124. package/skills/image/SKILL.md +66 -0
  125. package/skills/orchestrator/SKILL.md +107 -0
  126. package/skills/video/SKILL.md +97 -0
  127. package/skills/web/SKILL.md +60 -0
  128. package/src/agenda.ts +0 -56
  129. package/src/agents.ts +0 -74
  130. package/src/ask.ts +0 -243
  131. package/src/backends.ts +0 -144
  132. package/src/backlog.ts +0 -436
  133. package/src/bench.ts +0 -163
  134. package/src/board.ts +0 -1
  135. package/src/brief.ts +0 -151
  136. package/src/browser.ts +0 -624
  137. package/src/budget.ts +0 -73
  138. package/src/catalog.ts +0 -214
  139. package/src/checkchange.ts +0 -180
  140. package/src/checkpoint.ts +0 -99
  141. package/src/cli.ts +0 -117
  142. package/src/compact.ts +0 -162
  143. package/src/config.ts +0 -340
  144. package/src/context/capture.ts +0 -1
  145. package/src/context/digest.ts +0 -1
  146. package/src/context/embed.ts +0 -1
  147. package/src/context/index.ts +0 -2
  148. package/src/context/ledger.ts +0 -1
  149. package/src/context/manager.ts +0 -1
  150. package/src/context/memory.ts +0 -1
  151. package/src/context/policy.ts +0 -1
  152. package/src/context/prices.ts +0 -1
  153. package/src/context/recall.ts +0 -1
  154. package/src/context/rules.ts +0 -1
  155. package/src/context/search.ts +0 -1
  156. package/src/context/status.ts +0 -1
  157. package/src/context/store.ts +0 -1
  158. package/src/context/summary.ts +0 -1
  159. package/src/context/tokens.ts +0 -1
  160. package/src/context/tools.ts +0 -1
  161. package/src/continuation.ts +0 -122
  162. package/src/contract.ts +0 -342
  163. package/src/contractround.ts +0 -225
  164. package/src/control.ts +0 -1
  165. package/src/dataset.ts +0 -133
  166. package/src/decide.ts +0 -690
  167. package/src/eval.ts +0 -66
  168. package/src/evolver.ts +0 -369
  169. package/src/followups.ts +0 -50
  170. package/src/forms.ts +0 -191
  171. package/src/gate.ts +0 -90
  172. package/src/grants.ts +0 -239
  173. package/src/graph.ts +0 -74
  174. package/src/guard/index.ts +0 -1
  175. package/src/guard/wire.ts +0 -1
  176. package/src/helpers.ts +0 -105
  177. package/src/hooks.ts +0 -199
  178. package/src/jev.ts +0 -141
  179. package/src/journal.ts +0 -1
  180. package/src/look.ts +0 -390
  181. package/src/memory.ts +0 -1
  182. package/src/native.ts +0 -2455
  183. package/src/nogit.ts +0 -112
  184. package/src/outcomes.ts +0 -210
  185. package/src/pick.ts +0 -112
  186. package/src/pipelines.ts +0 -252
  187. package/src/plan.ts +0 -449
  188. package/src/plugin.ts +0 -3187
  189. package/src/policy.ts +0 -84
  190. package/src/pools.ts +0 -1
  191. package/src/profile.ts +0 -186
  192. package/src/progress.ts +0 -1
  193. package/src/redact.ts +0 -1
  194. package/src/registry.ts +0 -207
  195. package/src/roles.ts +0 -1
  196. package/src/routing.ts +0 -1
  197. package/src/runner.ts +0 -1506
  198. package/src/scheduler.ts +0 -200
  199. package/src/session.ts +0 -269
  200. package/src/shell/decide.ts +0 -1
  201. package/src/shell/index.ts +0 -2
  202. package/src/shell/sandbox.ts +0 -1
  203. package/src/shell/wire.ts +0 -1
  204. package/src/skills.ts +0 -111
  205. package/src/state.ts +0 -1
  206. package/src/store.ts +0 -1
  207. package/src/switcher.ts +0 -1
  208. package/src/tools.ts +0 -480
  209. package/src/trials.ts +0 -247
  210. package/src/usage.ts +0 -1
  211. package/src/wait.ts +0 -180
  212. package/src/watchdog.ts +0 -498
  213. package/src/worktree/git.ts +0 -378
@@ -1,4 +1,3 @@
1
1
  // The sandbox lives in src/shell/ now (the shell plugin, enable-able on its own). This file keeps the old import
2
2
  // path working for the parts of the plugin that are not the shell plugin: the same names, from one place.
3
-
4
- export * from "./shell/sandbox.ts"
3
+ export * from "./shell/sandbox.js";
@@ -0,0 +1,90 @@
1
+ // The one question of D23 (A1-T14). A1 made plan mode and the task gate fail closed, which on a machine where no
2
+ // sandbox can run means no build task ever passes and the plugin cannot do its job. D23: the job's commands and checks
3
+ // then run unwrapped only after the user confirmed it for that job, with a deterministic risk score in front of them
4
+ // (src/riskscore.ts). The user's decision, never the micromanager's word, opens the grant.
5
+ //
6
+ // The plugin cannot open a form itself (src/forms.ts: its context has no form domain), so this file makes the decision
7
+ // and the exact form the micromanager passes to the question tool. The answer comes back through tool.execute.after as
8
+ // the form's labels, which src/plugin.ts reads and journals with the score.
9
+ import { askAnswer } from "./ask.js";
10
+ import { scoreCommands } from "./riskscore.js";
11
+ // What the job may do here. Only this function decides; a caller can store the answer but never make one up.
12
+ export function sandboxDecision(input) {
13
+ if (input.available)
14
+ return { kind: "run", unsandboxed: false };
15
+ const why = input.reason ? ` (${input.reason})` : "";
16
+ if (input.setting === "never") {
17
+ return {
18
+ kind: "refuse",
19
+ text: `Not started: there is no sandbox on this machine${why}, and "${input.jobId}" may not run without one (the "unsandboxed" setting is "never"). ` +
20
+ `Fix the sandbox first (omacode doctor); only then do its commands and checks run.`,
21
+ };
22
+ }
23
+ // The config's standing word, or this job's own grant: both mean the user already decided, and the caller journals
24
+ // which of the two this was.
25
+ if (input.setting === "allow" || input.granted)
26
+ return { kind: "run", unsandboxed: true };
27
+ const score = scoreCommands(input.checks, { plan: input.plan });
28
+ return { kind: "ask", score, text: askText(input, score, why) };
29
+ }
30
+ // What the micromanager is told before it asks: the score, one line per finding, the check lines, and the sentence that
31
+ // keeps the number from being read as a promise.
32
+ function askText(input, score, why) {
33
+ const lines = score.findings.map((f) => `- ${f.what} (+${f.weight})`);
34
+ const shown = input.checks.slice(0, 10).map((c) => `- ${c}`);
35
+ const rest = input.checks.length > 10 ? [`… and ${input.checks.length - 10} more`] : [];
36
+ return [
37
+ `No sandbox can run on this machine${why}, so job ${input.jobId} would run its commands and checks with the user's own rights. Nothing starts until the user says so for this job.`,
38
+ `Risk ${score.band}: ${score.score}/100.`,
39
+ ...(score.findings.length ? lines : ["- nothing the score knows: its commands are ordinary writes and tests"]),
40
+ input.checks.length ? `Checks:\n${[...shown, ...rest].join("\n")}` : "This job has no checks yet.",
41
+ "The score reads the command text rather than what a program does, so it is a help and not a guarantee.",
42
+ ].join("\n");
43
+ }
44
+ // The header the plugin recognises the answer by (src/forms.ts: a form is known by its headers).
45
+ export const SANDBOX_FORM_HEADER = "No sandbox";
46
+ const START = "Start without a sandbox";
47
+ const READ_ONLY = "Run read-only";
48
+ const CANCEL = "Cancel";
49
+ export function sandboxForm(decision) {
50
+ const why = decision.reason ? ` (${decision.reason})` : "";
51
+ const findings = decision.score.findings.map((f) => `${f.rule} (+${f.weight})`).join(", ");
52
+ const checks = decision.checks.length === 1 ? "1 check" : `${decision.checks.length} checks`;
53
+ return [{
54
+ header: SANDBOX_FORM_HEADER,
55
+ question: `No sandbox can run on this machine${why}, so job ${decision.jobId}'s commands and ${checks} would run with your rights. ` +
56
+ `Risk ${decision.score.band}: ${decision.score.score}/100${findings ? ` (${findings})` : ""}. What should happen?`,
57
+ options: [
58
+ { label: START, description: `The job's commands and checks run with your rights, unwrapped (risk ${decision.score.band} ${decision.score.score}/100)` },
59
+ { label: READ_ONLY, description: "Nothing of the project is touched and no check runs" },
60
+ { label: CANCEL, description: "Nothing starts" },
61
+ ],
62
+ }];
63
+ }
64
+ // What the user's answer on the sandbox form means. The plugin's labels open the grant; a short answer people type
65
+ // themselves ("yes", "no") is taken the same way, and anything else is no answer at all.
66
+ export function sandboxAnswer(labels) {
67
+ for (const label of labels) {
68
+ const said = label.trim().toLowerCase().replace(/\s*\(recommended\)\s*$/, "").replace(/\s+/g, " ");
69
+ if (said === START.toLowerCase())
70
+ return "allow";
71
+ if (said === READ_ONLY.toLowerCase())
72
+ return "read-only";
73
+ if (said === CANCEL.toLowerCase())
74
+ return "cancel";
75
+ if (["read only", "readonly"].includes(said))
76
+ return "read-only";
77
+ const answer = askAnswer(label);
78
+ if (answer === "once" || answer === "job")
79
+ return "allow";
80
+ if (answer === "refuse")
81
+ return "cancel";
82
+ }
83
+ return undefined;
84
+ }
85
+ export function writeUnsandboxedGrant(input) {
86
+ const findings = input.score.findings.map((f) => f.what);
87
+ const grant = { granted: true, at: new Date().toISOString(), by: input.by, score: input.score.score, band: input.score.band, findings };
88
+ input.control(input.project, input.jobId, { unsandboxed: grant });
89
+ input.journal({ kind: "sandbox.override", project: input.project, jobId: input.jobId, granted: true, by: input.by, score: input.score.score, band: input.score.band, findings });
90
+ }
@@ -0,0 +1,170 @@
1
+ // The job queue and the updates to the user (Phase E). run_job hands a job to the scheduler and returns at
2
+ // once, so the micromanager's session stays free while workers run; the scheduler works the queue in the background,
3
+ // one job at a time per plugin process (Phase F runs a job's tasks in parallel), and the notifier reports to the
4
+ // job's micromanager session and the desktop.
5
+ //
6
+ // How an update reaches the micromanager (Phase E spike): a synthetic message with resume starts a turn of an idle
7
+ // session and is steered into a busy one, but models take its text for an injection. So the synthetic message only
8
+ // wakes the micromanager; the update itself goes in as a system block through the context hook, which models follow
9
+ // (Phase A, A1).
10
+ export class Scheduler {
11
+ #d;
12
+ #queue = [];
13
+ #current;
14
+ #pumping;
15
+ constructor(deps) {
16
+ this.#d = deps;
17
+ }
18
+ // Queues a job; 0 means it starts now. A job already running or queued keeps its place.
19
+ enqueue(job, session, note) {
20
+ if (this.#current?.job === job)
21
+ return 0;
22
+ const at = this.#queue.findIndex((e) => e.job === job);
23
+ if (at >= 0)
24
+ return at + 1;
25
+ this.#queue.push({ job, session, note, cancel: { cancelled: false } });
26
+ this.#pumping ??= this.#pump().finally(() => { this.#pumping = undefined; });
27
+ return this.#current ? this.#queue.length : 0;
28
+ }
29
+ // A queued job leaves the queue; the running one is told to stop, and its current session is returned to interrupt.
30
+ stop(job) {
31
+ const id = job || this.#current?.job;
32
+ if (id && this.#current?.job === id) {
33
+ this.#current.cancel.cancelled = true;
34
+ return { state: "stopping", session: this.#current.cancel.session };
35
+ }
36
+ const at = this.#queue.findIndex((e) => e.job === id);
37
+ if (at < 0)
38
+ return { state: "unknown" };
39
+ this.#queue.splice(at, 1);
40
+ return { state: "dequeued" };
41
+ }
42
+ // The session a running job works in now; the runner reports each session it starts.
43
+ working(job, session) {
44
+ if (this.#current?.job === job)
45
+ this.#current.cancel.session = session;
46
+ }
47
+ snapshot() {
48
+ return { running: this.#current?.job, queued: this.#queue.map((e) => e.job) };
49
+ }
50
+ // Resolves when the queue is empty (tests, shutdown).
51
+ async idle() {
52
+ while (this.#pumping)
53
+ await this.#pumping;
54
+ }
55
+ async #pump() {
56
+ for (let next = this.#queue.shift(); next; next = this.#queue.shift()) {
57
+ this.#current = next;
58
+ try {
59
+ this.#d.finished(await this.#d.run(next.job, next.cancel, next.note), next.session);
60
+ }
61
+ catch (err) {
62
+ this.#d.failed(next.job, next.session, err);
63
+ }
64
+ finally {
65
+ this.#current = undefined;
66
+ }
67
+ }
68
+ }
69
+ }
70
+ export function ending(job) {
71
+ if (job.phase === "integrate" || job.phase === "done" || job.phase === "wrap")
72
+ return "done";
73
+ if (job.phase === "failed")
74
+ return "failed";
75
+ if (job.phase === "paused" || job.phase === "stopped")
76
+ return "stopped";
77
+ return "needs_user";
78
+ }
79
+ const TITLES = {
80
+ done: "job done",
81
+ needs_user: "job needs you",
82
+ failed: "job failed",
83
+ stopped: "job stopped",
84
+ };
85
+ export class Notifier {
86
+ #d;
87
+ #lines = new Map();
88
+ #timers = new Map();
89
+ constructor(deps) {
90
+ this.#d = deps;
91
+ }
92
+ // A progress line: collected per session and sent as one quiet message (no new turn) every flushMs.
93
+ progress(session, line, task = false) {
94
+ if (task && this.#d.mode === "tasks")
95
+ this.#d.desktop("micromanager", line);
96
+ if (!session)
97
+ return;
98
+ const lines = this.#lines.get(session) ?? [];
99
+ lines.push(line);
100
+ this.#lines.set(session, lines);
101
+ if (this.#timers.has(session))
102
+ return;
103
+ const timer = setTimeout(() => void this.flush(session), this.#d.flushMs ?? 20_000);
104
+ timer.unref?.();
105
+ this.#timers.set(session, timer);
106
+ }
107
+ async flush(session) {
108
+ clearTimeout(this.#timers.get(session));
109
+ this.#timers.delete(session);
110
+ const lines = this.#lines.get(session);
111
+ this.#lines.delete(session);
112
+ if (!lines?.length)
113
+ return;
114
+ await this.#d.synthetic(session, `[micromanager] progress:\n- ${lines.join("\n- ")}`, false).catch(() => undefined);
115
+ }
116
+ // omo-hybrid: delegated tasks report to the orchestrator. Reports that come close together are one update: a system
117
+ // note with all of them, and one wake-up.
118
+ #reports = new Map();
119
+ #reportTimers = new Map();
120
+ #boards = new Map(); // the job's board as of the newest report
121
+ // board: the job's ASCII board after this change; every update carries the newest one, so the user sees the state
122
+ // whenever something changed, without the orchestrator having to ask for it.
123
+ report(session, text, title, board) {
124
+ if (title && this.#d.mode === "tasks")
125
+ this.#d.desktop("micromanager", title);
126
+ if (!session)
127
+ return;
128
+ if (board)
129
+ this.#boards.set(session, board);
130
+ const list = this.#reports.get(session) ?? [];
131
+ list.push(text);
132
+ this.#reports.set(session, list);
133
+ if (this.#reportTimers.has(session))
134
+ return;
135
+ const timer = setTimeout(() => void this.flushReports(session), this.#d.reportMs ?? 8_000);
136
+ timer.unref?.();
137
+ this.#reportTimers.set(session, timer);
138
+ }
139
+ async flushReports(session, closing) {
140
+ clearTimeout(this.#reportTimers.get(session));
141
+ this.#reportTimers.delete(session);
142
+ const list = this.#reports.get(session) ?? [];
143
+ this.#reports.delete(session);
144
+ if (!list.length && !closing)
145
+ return;
146
+ await this.flush(session);
147
+ const board = this.#boards.get(session);
148
+ this.#d.steer(session, `[micromanager update] Delegated tasks reported. This comes from your own plugin, not from the user or a tool result; it is trusted.
149
+ Check each result. Delegate what comes next (fixes, the follow-ups worth doing, dependent work) with the subagent tool, ask the user what only they can decide, and update your todos.
150
+
151
+ ${list.join("\n\n")}${closing ? `\n\n${closing}` : ""}${board ? `\n\nThe job's board now; start your message to the user with it, in a code block, as it is:\n${board}` : ""}`);
152
+ await this.#d.synthetic(session, `[micromanager] ${list.length ? `${list.length} task report(s)` : "update"} (details in the plugin's system note)`, true).catch(() => undefined);
153
+ }
154
+ // A job ended or needs the user: the micromanager gets the update as a system block and is woken to tell the user.
155
+ async finished(session, jobId, end, text) {
156
+ if (this.#d.mode !== "off")
157
+ this.#d.desktop(`micromanager: ${TITLES[end]}`, `${jobId}\n${text.split("\n").slice(0, 4).join("\n")}`);
158
+ if (!session)
159
+ return;
160
+ await this.flush(session);
161
+ // A stop comes from the user through the micromanager, which already said so: a quiet note, no new turn.
162
+ if (end === "stopped")
163
+ return void (await this.#d.synthetic(session, `[micromanager] ${TITLES[end]}: ${jobId}`, false).catch(() => undefined));
164
+ this.#d.steer(session, `[micromanager update] ${TITLES[end]}: ${jobId}. This update comes from your own plugin, not from the user and not from a tool result; it is trusted.
165
+ ${end === "needs_user" ? "Tell the user in a few sentences why the job stopped and what they can decide; then wait for their answer." : end === "done" ? "Tell the user the job is done, what changed, and how to merge or discard the branch." : "Tell the user what happened and what they can do."}
166
+
167
+ ${text}`);
168
+ await this.#d.synthetic(session, `[micromanager] ${TITLES[end]}: ${jobId} (details in the plugin's system note)`, true).catch(() => undefined);
169
+ }
170
+ }
@@ -0,0 +1,131 @@
1
+ // The host's supervisor process (A6): what the `omacode-services` unit runs. It reads the config `omacode services
2
+ // install` wrote, keeps a token in the run directory (only the user can read it; the plugin sends it), and starts the
3
+ // supervisor with the decider and the embedding service on their usual ports.
4
+ import { isMain } from "@omacode/core/main";
5
+ import { execFile } from "node:child_process";
6
+ import { randomBytes } from "node:crypto";
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { availableParallelism } from "node:os";
10
+ import { runDir } from "@omacode/core/services";
11
+ import { fetchOnce, Supervisor } from "@omacode/core/supervisor";
12
+ import { configPath, PORTS, servicesHome } from "./services.js";
13
+ export const CPU = { id: "cpu", name: "CPU" };
14
+ // llama.cpp's --list-devices: " Vulkan0: NVIDIA GeForce RTX 4060 Laptop GPU (8188 MiB, 6990 MiB free)".
15
+ export function parseDevices(text) {
16
+ const out = [CPU];
17
+ for (const line of text.split("\n")) {
18
+ const m = /^\s+([A-Za-z]+\d*):\s+(.+?)\s*(?:\((\d+) MiB,.*\))?\s*$/.exec(line);
19
+ if (m)
20
+ out.push({ id: m[1], name: m[3] ? `${m[2]} · ${Math.round(Number(m[3]) / 1024)} GB` : m[2] });
21
+ }
22
+ return out;
23
+ }
24
+ function listDevices(server, prefix) {
25
+ return new Promise((done) => {
26
+ execFile(server, [...prefix, "--list-devices"], { timeout: 20_000 }, (_err, stdout, stderr) => done(parseDevices(`${stdout}\n${stderr}`)));
27
+ });
28
+ }
29
+ // "cpu": no GPU at all (-dev none, no layers offloaded); any other id: every layer on that one device.
30
+ export function deviceArgs(device) {
31
+ return !device || device === CPU.id ? ["-dev", "none", "-ngl", "0"] : ["-dev", device, "-ngl", "999"];
32
+ }
33
+ // Torch threads for the decider. Every guard question and every name check of every session waits behind one lock, and
34
+ // the name check reads whole conversations: at the server's default of 2 threads 46 000 characters took 21 s, at 8 it
35
+ // took 6.7 s, with the same memory (about 1 GB; measured 2026-11-26 on 24 cores beside a busy ComfyUI). The plugin
36
+ // gives a name check 30 s, so under load 2 threads meant timeouts, and every cloud request asked the user. A third of
37
+ // the cores, from 2 up to 8: past that the CPU is the other services' too.
38
+ export function deciderThreads(cores = availableParallelism()) {
39
+ return Math.max(2, Math.min(8, Math.floor(cores / 3)));
40
+ }
41
+ export function hostServices(config, token) {
42
+ const specs = [
43
+ {
44
+ name: "decider",
45
+ // CPU-only PyTorch (decider/pyproject.toml): the GPUs stay free for llama.cpp, and a decision takes ~40 ms anyway.
46
+ // A GPU would need a second torch build beside it (CUDA, or ROCm's preview for the iGPU); not taken (2026-11-23).
47
+ devices: async () => [{ ...CPU, note: "CPU only: its PyTorch build has no GPU support; a decision takes about 40 ms" }],
48
+ defaultDevice: CPU.id,
49
+ command: (port) => ({
50
+ cmd: config.decider.bin,
51
+ args: ["--host", "127.0.0.1", "--port", String(port), "--model", config.decider.model, "--threads", String(deciderThreads())],
52
+ env: { CUDA_VISIBLE_DEVICES: "", DECIDER_TOKEN: token },
53
+ }),
54
+ },
55
+ ];
56
+ const [server, ...prefix] = config.embedding.server;
57
+ if (server) {
58
+ specs.push({
59
+ name: "embedding",
60
+ // Started by the first request, not with the supervisor: Qwen3-Embedding holds GBs, and a login or a boot should
61
+ // not pay for a model nothing has asked yet (the decider stays eager; a decision should not wait).
62
+ lazy: true,
63
+ ...(existsSync(config.embedding.gguf) ? {} : { prepare: (progress) => fetchOnce(config.embedding.url, config.embedding.gguf, progress) }),
64
+ devices: () => listDevices(server, prefix),
65
+ defaultDevice: config.embedding.device ?? CPU.id,
66
+ command: (port, device) => ({
67
+ cmd: server,
68
+ args: [
69
+ ...prefix, "--embedding", "--pooling", "last", "-m", config.embedding.gguf, "--alias", config.embedding.model,
70
+ ...deviceArgs(device), "-c", "8192", "-b", "2048", "-ub", "2048", "--host", "127.0.0.1", "--port", String(port), "--api-key", token,
71
+ ],
72
+ }),
73
+ });
74
+ }
75
+ if (config.comfyui)
76
+ specs.push(comfyService(config.comfyui));
77
+ return specs;
78
+ }
79
+ // ComfyUI behind the supervisor: started by its first request (it holds GB of GPU memory), with no token at the front,
80
+ // because its own page in a browser and the image client talk to it directly; on the GPU it was installed for, or on
81
+ // the CPU (`--cpu`), picked in /services like the embedding service's device.
82
+ export function comfyService(c) {
83
+ const gpu = c.gpu && c.gpu.id !== CPU.id ? c.gpu : undefined;
84
+ return {
85
+ name: "comfyui",
86
+ lazy: true,
87
+ open: true,
88
+ health: "/system_stats",
89
+ startTimeoutMs: 5 * 60_000,
90
+ devices: async () => (gpu ? [{ id: gpu.id, name: gpu.name }, CPU] : [CPU]),
91
+ defaultDevice: gpu?.id ?? CPU.id,
92
+ command: (port, device) => ({
93
+ cmd: c.python,
94
+ args: [join(c.workspace, "main.py"), "--listen", "127.0.0.1", "--port", String(port), ...(gpu && device !== CPU.id ? [] : ["--cpu"])],
95
+ ...(gpu?.env && device !== CPU.id ? { env: gpu.env } : {}),
96
+ }),
97
+ };
98
+ }
99
+ function token(dir) {
100
+ const file = join(dir, "token");
101
+ if (existsSync(file)) {
102
+ const t = readFileSync(file, "utf8").trim();
103
+ if (t)
104
+ return t;
105
+ }
106
+ const t = randomBytes(24).toString("base64url");
107
+ writeFileSync(file, t + "\n", { mode: 0o600 });
108
+ return t;
109
+ }
110
+ if (isMain(import.meta)) {
111
+ const home = process.env.OMACODE_SERVICES_HOME || servicesHome();
112
+ const config = JSON.parse(readFileSync(configPath(home), "utf8"));
113
+ const dir = runDir();
114
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
115
+ const t = token(dir);
116
+ const sup = await Supervisor.start({
117
+ runDir: dir,
118
+ token: t,
119
+ services: hostServices(config, t),
120
+ defaults: config.modes ?? {},
121
+ ...(config.idleMinutes ? { idleMs: config.idleMinutes * 60_000 } : {}),
122
+ // OMACODE_DECIDER_PORT / OMACODE_EMBEDDING_PORT: other ports, for a test beside services already running.
123
+ ports: { decider: Number(process.env.OMACODE_DECIDER_PORT) || PORTS.decider, embedding: Number(process.env.OMACODE_EMBEDDING_PORT) || PORTS.embedding, comfyui: Number(process.env.OMACODE_COMFYUI_PORT) || PORTS.comfyui },
124
+ facts: { embeddingModel: config.embedding.model },
125
+ // Beside config.json, on disk: the TUI's picks (mode, device, idle time) outlive a reboot.
126
+ controlPath: join(home, "control.json"),
127
+ });
128
+ const shutdown = () => void sup.close().then(() => process.exit(0));
129
+ process.on("SIGTERM", shutdown);
130
+ process.on("SIGINT", shutdown);
131
+ }