@omacode/micromanager 0.0.0-stage → 0.1.1

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 (109) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +27 -2
  3. package/evolver/mm_evolve/__init__.py +1 -0
  4. package/evolver/mm_evolve/entry.py +3 -0
  5. package/evolver/mm_evolve/evaluator.py +119 -0
  6. package/evolver/mm_evolve/llm.py +76 -0
  7. package/evolver/mm_evolve/run.py +89 -0
  8. package/evolver/mm_evolve/spec.py +62 -0
  9. package/evolver/pyproject.toml +21 -0
  10. package/evolver/uv.lock +772 -0
  11. package/package.json +55 -4
  12. package/skills/THIRD_PARTY.md +58 -0
  13. package/skills/code-review/SKILL.md +46 -0
  14. package/skills/deliberate/SKILL.md +39 -0
  15. package/skills/diagnosing-bugs/SKILL.md +75 -0
  16. package/skills/receiving-code-review/SKILL.md +36 -0
  17. package/skills/research/SKILL.md +18 -0
  18. package/skills/tdd/SKILL.md +56 -0
  19. package/skills/tdd/mocking.md +59 -0
  20. package/skills/tdd/tests.md +77 -0
  21. package/skills/verification-before-completion/SKILL.md +50 -0
  22. package/src/agenda.ts +56 -0
  23. package/src/agents.ts +74 -0
  24. package/src/ask.ts +243 -0
  25. package/src/backends.ts +144 -0
  26. package/src/backlog.ts +436 -0
  27. package/src/bench.ts +163 -0
  28. package/src/board.ts +1 -0
  29. package/src/brief.ts +151 -0
  30. package/src/browser.ts +624 -0
  31. package/src/budget.ts +73 -0
  32. package/src/catalog.ts +214 -0
  33. package/src/checkchange.ts +180 -0
  34. package/src/checkpoint.ts +99 -0
  35. package/src/cli.ts +117 -0
  36. package/src/compact.ts +162 -0
  37. package/src/config.ts +340 -0
  38. package/src/context/capture.ts +1 -0
  39. package/src/context/digest.ts +1 -0
  40. package/src/context/embed.ts +1 -0
  41. package/src/context/index.ts +2 -0
  42. package/src/context/ledger.ts +1 -0
  43. package/src/context/manager.ts +1 -0
  44. package/src/context/memory.ts +1 -0
  45. package/src/context/policy.ts +1 -0
  46. package/src/context/prices.ts +1 -0
  47. package/src/context/recall.ts +1 -0
  48. package/src/context/rules.ts +1 -0
  49. package/src/context/search.ts +1 -0
  50. package/src/context/status.ts +1 -0
  51. package/src/context/store.ts +1 -0
  52. package/src/context/summary.ts +1 -0
  53. package/src/context/tokens.ts +1 -0
  54. package/src/context/tools.ts +1 -0
  55. package/src/continuation.ts +122 -0
  56. package/src/contract.ts +342 -0
  57. package/src/contractround.ts +225 -0
  58. package/src/control.ts +1 -0
  59. package/src/dataset.ts +133 -0
  60. package/src/decide.ts +690 -0
  61. package/src/eval.ts +66 -0
  62. package/src/evolver.ts +369 -0
  63. package/src/followups.ts +50 -0
  64. package/src/forms.ts +191 -0
  65. package/src/gate.ts +90 -0
  66. package/src/grants.ts +239 -0
  67. package/src/graph.ts +74 -0
  68. package/src/guard/index.ts +1 -0
  69. package/src/guard/wire.ts +1 -0
  70. package/src/helpers.ts +105 -0
  71. package/src/hooks.ts +199 -0
  72. package/src/integration.ts +4 -0
  73. package/src/jev.ts +141 -0
  74. package/src/journal.ts +1 -0
  75. package/src/look.ts +390 -0
  76. package/src/memory.ts +1 -0
  77. package/src/native.ts +2455 -0
  78. package/src/nogit.ts +112 -0
  79. package/src/outcomes.ts +210 -0
  80. package/src/pick.ts +112 -0
  81. package/src/pipelines.ts +252 -0
  82. package/src/plan.ts +449 -0
  83. package/src/plugin.ts +3187 -0
  84. package/src/policy.ts +84 -0
  85. package/src/pools.ts +1 -0
  86. package/src/profile.ts +186 -0
  87. package/src/progress.ts +1 -0
  88. package/src/redact.ts +1 -0
  89. package/src/registry.ts +207 -0
  90. package/src/roles.ts +1 -0
  91. package/src/routing.ts +1 -0
  92. package/src/runner.ts +1506 -0
  93. package/src/sandbox.ts +4 -0
  94. package/src/scheduler.ts +200 -0
  95. package/src/session.ts +269 -0
  96. package/src/shell/decide.ts +1 -0
  97. package/src/shell/index.ts +2 -0
  98. package/src/shell/sandbox.ts +1 -0
  99. package/src/shell/wire.ts +1 -0
  100. package/src/skills.ts +111 -0
  101. package/src/state.ts +1 -0
  102. package/src/store.ts +1 -0
  103. package/src/switcher.ts +1 -0
  104. package/src/tools.ts +480 -0
  105. package/src/trials.ts +247 -0
  106. package/src/usage.ts +1 -0
  107. package/src/wait.ts +180 -0
  108. package/src/watchdog.ts +498 -0
  109. package/src/worktree/git.ts +378 -0
package/src/agents.ts ADDED
@@ -0,0 +1,74 @@
1
+ // Turns the role matrix into OpenCode agents. v2 does not load agent markdown files, so the agents are
2
+ // created in the plugin (ctx.agent.transform), each copied from the built-in "build" agent so it inherits the
3
+ // user's base rules (external directories, .env files), with the role's rules appended.
4
+
5
+ import { SUMMARIZER_SYSTEM } from "./context/summary.ts"
6
+ import { MICROMANAGER, ROLES, micromanagerSystem, type Rule } from "./roles.ts"
7
+
8
+ // The context manager's summarizer (src/context/summary.ts): no tools, it only reads the transcript it is given.
9
+ export const SUMMARIZER_AGENT = "summarizer"
10
+
11
+ export interface AgentInfo {
12
+ id: string
13
+ name: string
14
+ mode: "primary" | "subagent" | "all"
15
+ hidden: boolean
16
+ description?: string
17
+ system?: string
18
+ permissions: Rule[]
19
+ [key: string]: unknown
20
+ }
21
+
22
+ export interface AgentDraft {
23
+ get(id: string): AgentInfo | undefined
24
+ update(id: string, update: (agent: AgentInfo) => void): void
25
+ }
26
+
27
+ export function agentsFrom(base: AgentInfo): AgentInfo[] {
28
+ const copy = (): AgentInfo => ({ ...base, permissions: [...base.permissions] })
29
+ const roles = ROLES.map((role) => ({
30
+ ...copy(),
31
+ id: role.agent,
32
+ name: role.agent[0]!.toUpperCase() + role.agent.slice(1), // "Coder", "Reviewer", …
33
+ mode: "subagent" as const,
34
+ hidden: true, // only the micromanager delegates to them; build and plan never see them
35
+ description: role.description,
36
+ system: role.system,
37
+ permissions: [...base.permissions, ...role.rules],
38
+ }))
39
+ const micromanager: AgentInfo = {
40
+ ...copy(),
41
+ id: MICROMANAGER.agent,
42
+ name: "Micromanager",
43
+ mode: "primary",
44
+ hidden: false,
45
+ description: MICROMANAGER.description,
46
+ system: micromanagerSystem(),
47
+ permissions: [...base.permissions, ...MICROMANAGER.rules],
48
+ }
49
+ const summarizer: AgentInfo = {
50
+ ...copy(),
51
+ id: SUMMARIZER_AGENT,
52
+ name: "Summarizer",
53
+ mode: "subagent",
54
+ hidden: true,
55
+ description: "Compresses a long session's earlier turns for the context manager. Started by the plugin only.",
56
+ system: SUMMARIZER_SYSTEM,
57
+ permissions: [...base.permissions, { action: "*", resource: "*", effect: "deny" }],
58
+ }
59
+ return [micromanager, ...roles, summarizer]
60
+ }
61
+
62
+ export function installAgents(draft: AgentDraft): string[] {
63
+ const base = draft.get("build")
64
+ if (!base) throw new Error('no built-in "build" agent to copy the base rules from')
65
+ const agents = agentsFrom(base)
66
+ for (const agent of agents) {
67
+ // update() on an unknown id creates it (seen on opencode 2.0.18)
68
+ draft.update(agent.id, (target) => {
69
+ for (const key of Object.keys(target)) delete target[key]
70
+ Object.assign(target, agent)
71
+ })
72
+ }
73
+ return agents.map((a) => a.id)
74
+ }
package/src/ask.ts ADDED
@@ -0,0 +1,243 @@
1
+ // Asks: a worker's permission request that nobody could decide is paused and put to the micromanager, and through it
2
+ // to the user, instead of being refused.
3
+ //
4
+ // Background workers used to get "refused, not queued" for every request Jev was not sure about (live runs: 568 times
5
+ // "Jev unsure", 90 "the user must decide"), and a worker that cannot run its own verification cannot finish its task.
6
+ // OpenCode parks a request whose effect stays "ask" until someone replies (Permission.assert waits on a deferred,
7
+ // whatever the session), and the plugin can reply through ctx.permission.reply. So the request waits, the micromanager
8
+ // is woken with what is asked and why, and the answer comes from the one who can give it:
9
+ // - the micromanager, through answer_permission, for a request that clearly serves the task;
10
+ // - the user, in their own turn ("yes", "yes always", "no"), for anything else, and always for a hard rule: the
11
+ // micromanager is an LLM a worker's output can steer, so a hard rule never opens on its word;
12
+ // - nobody, after the timeout: then it is refused as before, and the worker carries on without it.
13
+ // "once" lets this call run; "job" also lets the exact same request run for the rest of the job; "refuse" fails it with
14
+ // the reason. OpenCode's own "always" is never used: it writes a rule into the project for good.
15
+
16
+ import { askForm, formInput } from "./forms.ts"
17
+
18
+ export type AskDecision = "once" | "job" | "refuse"
19
+ export type AskedBy = "micromanager" | "user" | "timeout"
20
+
21
+ export const ASK_TIMEOUT_MS = 10 * 60_000
22
+
23
+ export interface AskRequest {
24
+ readonly sessionID: string // the paused worker
25
+ readonly parent: string // the micromanager session that answers for it
26
+ readonly task: string // the worker's task, as the micromanager knows it ("T2 Wire percent into summary")
27
+ readonly agent: string
28
+ readonly action: string
29
+ readonly resources: readonly string[]
30
+ readonly reason: string // why it was not decided automatically
31
+ readonly hard: boolean // a hard rule: only the user may open it
32
+ }
33
+
34
+ export interface PendingAsk extends AskRequest {
35
+ readonly id: string // "A1", what the micromanager and the user refer to
36
+ readonly at: number
37
+ }
38
+
39
+ // How a paused request is let go or failed: bound to the plugin instance whose permission service holds it.
40
+ export type Reply = (decision: "once" | "reject", message?: string) => Promise<void>
41
+
42
+ export interface Answered {
43
+ readonly text: string // what the micromanager is told
44
+ readonly ask?: PendingAsk
45
+ }
46
+
47
+ // How a paused request ended, as a worker that waits for it wants to hear it.
48
+ export interface Settled {
49
+ readonly id: string
50
+ readonly decision: AskDecision
51
+ readonly by: AskedBy
52
+ readonly note: string
53
+ }
54
+
55
+ export function askKey(action: string, resources: readonly string[]): string {
56
+ return `${action}\0${resources.map((r) => r.trim().replace(/\s+/g, " ")).join("\0")}`
57
+ }
58
+
59
+ export function commandPrefix(resources: readonly string[]): string {
60
+ const first = resources[0] ?? ""
61
+ const parts = first.trim().split(/\s+/).filter(Boolean)
62
+ return parts.slice(0, 3).join(" ")
63
+ }
64
+
65
+ // The user's answer, in English or German, as short as people answer. Anything else is not an answer.
66
+ export function askAnswer(text: string): AskDecision | undefined {
67
+ const t = text.trim().toLowerCase().replace(/[.!?"']+$/g, "").replace(/^["']/, "").replace(/\s+/g, " ")
68
+ if (["yes always", "always", "allow always", "for the job", "yes for the job", "ja immer", "immer", "für den job"].includes(t)) return "job"
69
+ if (["yes", "y", "yeah", "yep", "sure", "ok", "okay", "allow", "allow it", "once", "allow once", "go ahead", "do it", "ja", "einmal", "ja einmal", "erlauben"].includes(t)) return "once"
70
+ if (["no", "n", "nope", "nah", "deny", "refuse", "no way", "nein", "ablehnen", "verweigern"].includes(t)) return "refuse"
71
+ return undefined
72
+ }
73
+
74
+ export class Asks {
75
+ readonly #pending = new Map<string, PendingAsk & { reply: Reply; timer?: ReturnType<typeof setTimeout>; settled: Promise<Settled>; resolve: (s: Settled) => void }>()
76
+ readonly #granted = new Map<string, Set<string>>() // micromanager session -> keys allowed for the job
77
+ readonly #refused = new Map<string, Set<string>>() // micromanager session -> keys the user or micromanager refused
78
+ readonly #journal: (entry: Record<string, unknown>) => void
79
+ readonly #timeoutMs: number
80
+ #n = 0
81
+ readonly #persistedGrants = new Map<string, Array<{ key: string; action: string; prefix: string; directory?: string; taskSession?: string }>>()
82
+
83
+ constructor(journal: (entry: Record<string, unknown>) => void = () => {}, timeoutMs = ASK_TIMEOUT_MS) {
84
+ this.#journal = journal
85
+ this.#timeoutMs = timeoutMs
86
+ }
87
+
88
+ loadPersistedGrants(jobId: string, grants: Array<{ key: string; action: string; prefix: string; directory?: string; taskSession?: string }> = []): void {
89
+ this.#persistedGrants.set(jobId, grants)
90
+ const set = new Set(grants.map((g) => g.key))
91
+ if (set.size) this.#granted.set(jobId, set)
92
+ }
93
+
94
+ persistedGrants(jobId: string): Array<{ key: string; action: string; prefix: string; directory?: string; taskSession?: string }> {
95
+ return this.#persistedGrants.get(jobId) ?? []
96
+ }
97
+
98
+ persistGrant(jobId: string, action: string, resources: readonly string[], directory?: string, taskSession?: string): void {
99
+ const key = askKey(action, resources)
100
+ const prefix = resources[0]?.split(/\s+/).slice(0, 3).join(" ") ?? action
101
+ const list = this.#persistedGrants.get(jobId) ?? []
102
+ if (list.some((g) => g.key === key)) return
103
+ list.push({ key, action, prefix, directory, taskSession })
104
+ this.#persistedGrants.set(jobId, list)
105
+ }
106
+
107
+ // What was decided before about exactly this request in this micromanager's job: asked once, never asked again.
108
+ standing(parent: string, action: string, resources: readonly string[]): "allow" | "deny" | undefined {
109
+ const key = askKey(action, resources)
110
+ if (this.#refused.get(parent)?.has(key)) return "deny"
111
+ if (this.#granted.get(parent)?.has(key)) return "allow"
112
+ return undefined
113
+ }
114
+
115
+ open(request: AskRequest, reply: Reply): PendingAsk {
116
+ let resolve!: (s: Settled) => void
117
+ const settled = new Promise<Settled>((r) => (resolve = r))
118
+ const ask: PendingAsk & { reply: Reply; timer?: ReturnType<typeof setTimeout>; settled: Promise<Settled>; resolve: (s: Settled) => void } = { ...request, id: `A${++this.#n}`, at: Date.now(), reply, settled, resolve }
119
+ this.#pending.set(ask.id, ask)
120
+ ask.timer = setTimeout(() => void this.answer(ask.id, "refuse", "timeout"), this.#timeoutMs)
121
+ ask.timer.unref?.()
122
+ this.#journal({ kind: "ask", event: "opened", id: ask.id, sessionID: ask.sessionID, parent: ask.parent, agent: ask.agent, action: ask.action, resources: ask.resources, reason: ask.reason, hard: ask.hard })
123
+ return strip(ask)
124
+ }
125
+
126
+ get(id: string): PendingAsk | undefined {
127
+ const ask = this.#pending.get(id)
128
+ return ask && strip(ask)
129
+ }
130
+
131
+ // The paused request of a worker, by its id ("A1") or by a short label that is part of what was asked. A worker that
132
+ // waits for its own request finds it by its session: it does not know the A-number.
133
+ find(id: string, sessionID?: string): PendingAsk | undefined {
134
+ const byId = this.#pending.get(id)
135
+ if (byId) return strip(byId)
136
+ const wanted = id.trim().toLowerCase()
137
+ if (!wanted) return undefined
138
+ const mine = [...this.#pending.values()].filter((a) => !sessionID || a.sessionID === sessionID)
139
+ const labelled = mine.find((a) => `${a.action} ${a.resources.join(" ")}`.toLowerCase().includes(wanted))
140
+ return labelled && strip(labelled)
141
+ }
142
+
143
+ // The promise a worker waits on: it settles when the request is answered, refused or dropped.
144
+ settled(id: string, sessionID?: string): Promise<Settled> | undefined {
145
+ const ask = this.find(id, sessionID)
146
+ if (!ask) return undefined
147
+ const pending = this.#pending.get(ask.id)
148
+ return pending?.settled
149
+ }
150
+
151
+ // The requests of this worker that wait: what it can wait for.
152
+ mine(sessionID: string): PendingAsk[] {
153
+ return [...this.#pending.values()].filter((a) => a.sessionID === sessionID).sort((a, b) => a.at - b.at).map(strip)
154
+ }
155
+
156
+ // The oldest request still waiting for this micromanager's answer: the one the user's next "yes" or "no" is about.
157
+ oldest(parent: string): PendingAsk | undefined {
158
+ return [...this.#pending.values()].filter((a) => a.parent === parent).sort((a, b) => a.at - b.at)[0]
159
+ }
160
+
161
+ waiting(sessionID: string): boolean {
162
+ return [...this.#pending.values()].some((a) => a.sessionID === sessionID)
163
+ }
164
+
165
+ async answer(id: string, decision: AskDecision, by: AskedBy, note = ""): Promise<Answered> {
166
+ const ask = this.#pending.get(id)
167
+ if (!ask) return { text: `There is no request ${id} waiting: it was answered already, or it timed out.` }
168
+ if (ask.hard && by === "micromanager" && decision !== "refuse") {
169
+ return { text: `${id} is a hard rule (${ask.reason}): only the user can allow it. Show them the request as it is and end your turn; their answer reaches the plugin by itself.`, ask: strip(ask) }
170
+ }
171
+ this.#pending.delete(id)
172
+ clearTimeout(ask.timer)
173
+ const key = askKey(ask.action, ask.resources)
174
+ const who = by === "timeout" ? "nobody answered in time" : `the ${by}`
175
+ if (decision === "refuse") {
176
+ if (by !== "timeout") this.#set(this.#refused, ask.parent, key)
177
+ // OpenCode fails every other paused request of the same session with a reject, so they leave the list too.
178
+ for (const [other, a] of this.#pending) if (a.sessionID === ask.sessionID) {
179
+ clearTimeout(a.timer)
180
+ this.#pending.delete(other)
181
+ a.resolve?.({ id: other, decision: "refuse", by, note: `This request is void: ${id} was answered and OpenCode fails the other requests of a session with it.` })
182
+ }
183
+ const message = by === "timeout"
184
+ ? `This is refused, not queued: nobody answered in time (${ask.reason}). It does not stop your task: carry on without it, and say in your report what you wanted it for and what you did instead. Report STATUS: NEEDS_CONTEXT only if you genuinely cannot proceed without it.`
185
+ : `Refused by the ${by}${note ? `: ${note}` : ""}. Do not try it another way; carry on without it, and say in your report what you wanted it for. Report STATUS: NEEDS_CONTEXT only if you genuinely cannot proceed without it.`
186
+ await ask.reply("reject", message).catch(() => undefined)
187
+ } else {
188
+ if (decision === "job") this.#set(this.#granted, ask.parent, key)
189
+ await ask.reply("once").catch(() => undefined)
190
+ }
191
+ this.#journal({ kind: "ask", event: "answered", id, sessionID: ask.sessionID, parent: ask.parent, action: ask.action, resources: ask.resources, decision, by, note: note.slice(0, 300), waitedMs: Date.now() - ask.at })
192
+ // A worker that waits for this request hears how it ended, whether the answer was the micromanager's or the user's.
193
+ ask.resolve?.({ id, decision, by, note })
194
+ const verdict = decision === "refuse" ? "refused" : decision === "job" ? "allowed for the rest of the job" : "allowed once"
195
+ return { text: `${id} ${verdict} (${who}); the worker ${decision === "refuse" ? "gets the refusal with the reason" : "goes on"}.`, ask: strip(ask) }
196
+ }
197
+
198
+ // The paused requests of sessions that ended or were stopped: nobody needs their answer any more, so they are failed
199
+ // quietly and leave the list, and the caller tells the micromanager they are void (src/plugin.ts release).
200
+ async drop(sessionIDs: readonly string[], why: string): Promise<PendingAsk[]> {
201
+ const dropped: PendingAsk[] = []
202
+ for (const [id, ask] of this.#pending) {
203
+ if (!sessionIDs.includes(ask.sessionID)) continue
204
+ this.#pending.delete(id)
205
+ clearTimeout(ask.timer)
206
+ await ask.reply("reject", `This request is void: ${why}.`).catch(() => undefined)
207
+ this.#journal({ kind: "ask", event: "dropped", id, sessionID: ask.sessionID, parent: ask.parent, why, waitedMs: Date.now() - ask.at })
208
+ // A worker that was waiting for this request hears that it is void, not that it was answered.
209
+ ask.resolve?.({ id, decision: "refuse", by: "timeout", note: `This request is void: ${why}.` })
210
+ dropped.push(strip(ask))
211
+ }
212
+ return dropped
213
+ }
214
+
215
+ #set(map: Map<string, Set<string>>, parent: string, key: string): void {
216
+ const set = map.get(parent) ?? new Set<string>()
217
+ set.add(key)
218
+ map.set(parent, set)
219
+ }
220
+
221
+ grantKey(action: string, resources: readonly string[]): string {
222
+ return askKey(action, resources)
223
+ }
224
+ }
225
+
226
+ // The pending ask as the outside sees it: without the reply it carries and the promise it settles.
227
+ function strip(ask: PendingAsk & { reply: Reply; timer?: ReturnType<typeof setTimeout>; settled: Promise<Settled>; resolve: (s: Settled) => void }): PendingAsk {
228
+ const { reply: _reply, timer: _timer, settled: _settled, resolve: _resolve, ...shown } = ask
229
+ return shown
230
+ }
231
+
232
+ // The note that wakes the micromanager. Everything needed to decide is in it.
233
+ export function askNote(ask: PendingAsk, timeoutMs = ASK_TIMEOUT_MS): string {
234
+ const what = `${ask.action}: ${ask.resources.join(" | ").slice(0, 600)}`
235
+ const minutes = Math.round(timeoutMs / 60_000)
236
+ const head = `[micromanager] ${ask.id}: worker ${ask.task} (${ask.agent}, session ${ask.sessionID}) is paused on a permission request until it is answered.\nRequest: ${what}\nWhy it was not decided automatically: ${ask.reason}`
237
+ const end = `Without an answer it is refused in ${minutes} minutes and the worker carries on without it.`
238
+ const form = formInput(askForm(ask.id, ask.task, what, ask.reason))
239
+ if (ask.hard) {
240
+ return `${head}\nThis is a hard rule: only the user can allow it. Ask them with the question tool, with exactly this input (a form that waits for their answer; it reaches the plugin by itself):\n${form} ${end}`
241
+ }
242
+ return `${head}\nDecide it: if it clearly serves the worker's task and reaches nothing outside the project, call answer_permission with id ${ask.id} and decision once (this call) or job (this exact request for the rest of the job), inside the execute tool: await tools.answer_permission({ id: "${ask.id}", decision: "once", note: "" }). If it is risky, outside the task, or you are not sure, ask the user instead with the question tool, with exactly this input (their answer reaches the plugin by itself):\n${form}\nTo refuse it yourself, call answer_permission with decision refuse and a note why. ${end}`
243
+ }
@@ -0,0 +1,144 @@
1
+ // Decision backends per node (design.md §20): cloud Jev, the local GLiNER decision server, Open-Jev, or rules.
2
+ // All speak the Jev wire format, so one client (src/jev.ts) serves them; only URL, model and key differ.
3
+ //
4
+ // Shadow mode: the primary backend decides, a secondary one answers the same request in parallel and is only
5
+ // journaled, so GLiNER can be measured against Jev and retrained on its answers.
6
+
7
+ import { randomUUID } from "node:crypto"
8
+
9
+ import { Jev, type Decision, type Question } from "./jev.ts"
10
+ import { record } from "./journal.ts"
11
+
12
+ export type BackendName = "typesafe" | "gliner" | "openjev" | "rules"
13
+
14
+ export interface Asker {
15
+ ask(state: string, questions: Record<string, Question>): Promise<Decision>
16
+ }
17
+
18
+ export interface BackendConfig {
19
+ readonly default: BackendName
20
+ readonly nodes: Readonly<Record<string, BackendName>> // node -> backend, e.g. { G0: "gliner" }
21
+ readonly shadow?: BackendName // answers in parallel, journaled only
22
+ readonly urls: Readonly<Partial<Record<Exclude<BackendName, "rules">, string>>>
23
+ // The user's choice for now (2026-10-05): cloud only, Jev included. Nodes meant for GLiNER or Open-Jev ask cloud
24
+ // Jev, local-only requests too, and nothing runs in shadow mode.
25
+ readonly cloudOnly?: boolean
26
+ }
27
+
28
+ // Guards start on GLiNER, everything else on cloud Jev (oc-voice's verdict, Phase A9). G0 never leaves the machine.
29
+ export const DEFAULT_BACKENDS: BackendConfig = {
30
+ default: "typesafe",
31
+ nodes: { G0: "gliner", "G0.injection": "gliner", G: "gliner" },
32
+ urls: {
33
+ typesafe: "https://api.typesafe.ai/v1/systemone",
34
+ gliner: "http://127.0.0.1:8781/v1/systemone",
35
+ openjev: "http://127.0.0.1:8782/v1/systemone",
36
+ },
37
+ }
38
+
39
+ const LOCAL: ReadonlySet<BackendName> = new Set(["gliner", "openjev", "rules"])
40
+ // Nodes whose questions carry user and task text that must never reach the cloud.
41
+ const ALWAYS_LOCAL = new Set(["G0", "G0.injection"])
42
+
43
+ export class RulesBackend implements Asker {
44
+ // Answers nothing: every caller falls back to its code default, as without Jev.
45
+ async ask(): Promise<Decision> {
46
+ return { answers: {}, model: "rules", latencyMs: 0 }
47
+ }
48
+ }
49
+
50
+ export function makeAskers(config: BackendConfig, jevKey: string | undefined, fetcher?: typeof fetch): Partial<Record<BackendName, Asker>> {
51
+ const out: Partial<Record<BackendName, Asker>> = { rules: new RulesBackend() }
52
+ if (jevKey && config.urls.typesafe) out.typesafe = new Jev(jevKey, { url: config.urls.typesafe, fetch: fetcher })
53
+ // Local servers take any key; their timeout is short so a dead server costs little.
54
+ // GLiNER answers four guards in about 0.4 s on the CPU; 5 s leaves room for a loaded machine.
55
+ if (config.urls.gliner) out.gliner = new Jev("local", { url: config.urls.gliner, model: "gliner", timeoutMs: 5000, fetch: fetcher })
56
+ if (config.urls.openjev) out.openjev = new Jev("local", { url: config.urls.openjev, model: "openjev", timeoutMs: 5000, fetch: fetcher })
57
+ return out
58
+ }
59
+
60
+ export interface Asked {
61
+ readonly id: string // journal id; labels refer to it
62
+ readonly backend: BackendName
63
+ readonly decision: Decision
64
+ readonly error?: string // the backend that should have answered failed; rules answered instead
65
+ }
66
+
67
+ export interface AskOptions {
68
+ readonly localOnly?: boolean // a sensitive or refusal_likely job: no cloud backend
69
+ readonly job?: string
70
+ readonly task?: string
71
+ }
72
+
73
+ export class Decider {
74
+ readonly #config: BackendConfig
75
+ readonly #askers: Partial<Record<BackendName, Asker>>
76
+ readonly #journal: (entry: Record<string, unknown>) => void
77
+
78
+ constructor(config: BackendConfig, askers: Partial<Record<BackendName, Asker>>, journal: (entry: Record<string, unknown>) => void = record) {
79
+ this.#config = config
80
+ this.#askers = askers
81
+ this.#journal = journal
82
+ }
83
+
84
+ // The backend a node uses: its configured one, kept local when it has to be, rules when nothing else is there.
85
+ backendFor(node: string, localOnly = false): BackendName {
86
+ const wanted = this.#config.nodes[node] ?? this.#config.default
87
+ if (this.#config.cloudOnly) {
88
+ const cloud: BackendName = wanted === "gliner" || wanted === "openjev" ? "typesafe" : wanted
89
+ return this.#askers[cloud] ? cloud : "rules"
90
+ }
91
+ const local = localOnly || ALWAYS_LOCAL.has(node)
92
+ const chain: BackendName[] = local && !LOCAL.has(wanted) ? ["gliner", "openjev", "rules"] : [wanted, "rules"]
93
+ return chain.find((b) => this.#askers[b] !== undefined) ?? "rules"
94
+ }
95
+
96
+ async ask(node: string, state: Record<string, unknown>, questions: Record<string, Question>, options: AskOptions = {}): Promise<Asked> {
97
+ const id = randomUUID()
98
+ const backend = this.backendFor(node, options.localOnly)
99
+ const text = JSON.stringify(state)
100
+ const shadowName = this.#config.shadow
101
+ const shadowAllowed = !this.#config.cloudOnly && shadowName && shadowName !== backend && this.#askers[shadowName] && (LOCAL.has(shadowName) || !(options.localOnly || ALWAYS_LOCAL.has(node)))
102
+ const shadow = shadowAllowed ? this.#askers[shadowName]!.ask(text, questions).catch((err: unknown) => err as Error) : undefined
103
+ let decision: Decision
104
+ let error: string | undefined
105
+ try {
106
+ decision = await this.#askers[backend]!.ask(text, questions)
107
+ } catch (err) {
108
+ error = err instanceof Error ? err.message : String(err)
109
+ decision = await new RulesBackend().ask()
110
+ }
111
+ const shadowResult = shadow ? await shadow : undefined
112
+ this.#journal({
113
+ kind: "decision",
114
+ id,
115
+ node,
116
+ job: options.job,
117
+ task: options.task,
118
+ backend: error ? "rules" : backend,
119
+ error,
120
+ state,
121
+ questions,
122
+ answers: decision.answers,
123
+ model: decision.model,
124
+ latencyMs: decision.latencyMs,
125
+ ...(shadowResult && shadowName
126
+ ? shadowResult instanceof Error
127
+ ? { shadow: { backend: shadowName, error: shadowResult.message } }
128
+ : { shadow: { backend: shadowName, answers: shadowResult.answers, latencyMs: shadowResult.latencyMs } }
129
+ : {}),
130
+ })
131
+ return { id, backend: error ? "rules" : backend, decision, error }
132
+ }
133
+ }
134
+
135
+ // A label for a journaled decision: the user's answer, an override, or an outcome observed later (design.md §15).
136
+ export function label(
137
+ decisionId: string,
138
+ question: string,
139
+ value: string | number,
140
+ source: "user" | "user_override" | "outcome" | "planning_answer",
141
+ journal: (entry: Record<string, unknown>) => void = record,
142
+ ): void {
143
+ journal({ kind: "label", decision: decisionId, question, value, source })
144
+ }