@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/policy.ts ADDED
@@ -0,0 +1,84 @@
1
+ // Who makes a decision: the decision model, the user, a preset or the rules (design.md §22).
2
+ //
3
+ // A policy is set per decision key ("N6.pipeline", "G0.locality", …) or per node ("N6" covers all its keys), on
4
+ // five levels; the most specific level wins. Guards and hard rules are never switched off by a config-level
5
+ // preset: only a single decision may override a guard, explicitly.
6
+
7
+ export type Policy =
8
+ | { readonly kind: "auto" } // the decision model decides; below its floor, rules or the user
9
+ | { readonly kind: "ask" } // always the user
10
+ | { readonly kind: "fixed"; readonly value: string } // the user's preset: the node is skipped
11
+ | { readonly kind: "rule" } // the rules fallback only
12
+
13
+ export const LEVELS = ["decision", "task", "job", "project", "global"] as const
14
+ export type Level = (typeof LEVELS)[number]
15
+ import type { PolicySet } from "@omacode/state/schema"
16
+ export type { PolicySet }
17
+ export type Policies = Partial<Record<Level, PolicySet>>
18
+
19
+ export interface Resolved {
20
+ readonly policy: Policy
21
+ readonly level?: Level // undefined: nobody set one, the default applies
22
+ readonly key?: string // the key that matched: the full key or its node
23
+ }
24
+
25
+ // Guard nodes: a preset above the single decision is ignored for them.
26
+ const GUARDED = new Set(["G0", "G"])
27
+
28
+ export function parsePolicy(text: string): Policy | undefined {
29
+ const t = text.trim()
30
+ if (t === "auto" || t === "ask" || t === "rule") return { kind: t }
31
+ if (t.startsWith("fixed:") && t.length > "fixed:".length) return { kind: "fixed", value: t.slice("fixed:".length) }
32
+ return undefined
33
+ }
34
+
35
+ export function resolvePolicy(key: string, policies: Policies): Resolved {
36
+ const node = key.split(".")[0] ?? key
37
+ const guarded = GUARDED.has(node)
38
+ for (const level of LEVELS) {
39
+ if (guarded && level !== "decision") continue
40
+ const set = policies[level]
41
+ if (!set) continue
42
+ for (const candidate of [key, node]) {
43
+ const raw = set[candidate]
44
+ if (raw === undefined) continue
45
+ const policy = parsePolicy(raw)
46
+ if (policy) return { policy, level, key: candidate }
47
+ }
48
+ }
49
+ return { policy: { kind: "auto" } }
50
+ }
51
+
52
+ export function validatePolicies(set: Readonly<Record<string, unknown>>): string[] {
53
+ return Object.entries(set).flatMap(([key, value]) =>
54
+ typeof value === "string" && parsePolicy(value) && /^[A-Z][A-Za-z0-9]*(\.[a-z_]+)?$/.test(key)
55
+ ? []
56
+ : [`decisions.${key}: expected a key like "N6.pipeline" and "auto", "ask", "rule" or "fixed:<value>"`],
57
+ )
58
+ }
59
+
60
+ // Chat shortcuts that set policies, matched on exact phrases before any model (design.md §22).
61
+ export interface Pin {
62
+ readonly level: "job" | "task"
63
+ readonly taskId?: string
64
+ readonly key: string
65
+ readonly value: string
66
+ }
67
+
68
+ const SHORTCUTS: readonly { readonly re: RegExp; readonly pin: (m: RegExpMatchArray) => Pin }[] = [
69
+ { re: /^(always|only) local$/i, pin: () => ({ level: "job", key: "G0.locality", value: "fixed:local" }) },
70
+ { re: /^no planning session$/i, pin: () => ({ level: "job", key: "N2.clarity", value: "fixed:clear" }) },
71
+ { re: /^pipeline (P\d)$/i, pin: (m) => ({ level: "job", key: "N6.pipeline", value: `fixed:${m[1]!.toUpperCase()}` }) },
72
+ { re: /^ask me (about|before) everything$/i, pin: () => ({ level: "job", key: "N5", value: "ask" }) },
73
+ { re: /^([A-Za-z][\w.-]*) use ([\w./:-]+)$/, pin: (m) => ({ level: "task", taskId: m[1], key: "N5.model", value: `fixed:${m[2]}` }) },
74
+ { re: /^skip review for ([A-Za-z][\w.-]*)$/i, pin: (m) => ({ level: "task", taskId: m[1], key: "N6.review", value: "fixed:skip" }) },
75
+ ]
76
+
77
+ export function matchShortcut(text: string): Pin | undefined {
78
+ const t = text.trim().replace(/[.!]+$/, "")
79
+ for (const s of SHORTCUTS) {
80
+ const m = t.match(s.re)
81
+ if (m) return s.pin(m)
82
+ }
83
+ return undefined
84
+ }
package/src/pools.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "@omacode/tui/pools"
package/src/profile.ts ADDED
@@ -0,0 +1,186 @@
1
+ // N5 + N5b: one decision request per task classifies it and sets its profile (design.md §8.1). Code combines the
2
+ // isolated answers: the role matrix is the upper bound, a profile only narrows it, and a contradiction is cut
3
+ // back to the matrix at the cost of confidence.
4
+
5
+ import type { Asked } from "./backends.ts"
6
+ import { CHOICE_FLOOR, CLASSIFY, NOUL_FLOOR, roleChoice, RISKS, skillQuestion, type Risk } from "./catalog.ts"
7
+ import type { Question } from "./jev.ts"
8
+ import { recallQuestions, recalled } from "./memory.ts"
9
+ import { resolvePolicy, type Policies } from "./policy.ts"
10
+ import { ROLES, TEST_RUNNERS, roleById, type Role, type Rule } from "./roles.ts"
11
+ import type { Acceptance, Task } from "./state.ts"
12
+
13
+ import type { BudgetTier, PermProfile, Profile, ToolGroup } from "@omacode/state/schema"
14
+ export type { BudgetTier, PermProfile, Profile, ToolGroup }
15
+
16
+ // Profiles deny tool groups, never single tools: in Phase A a worker without read read the file through grep.
17
+ export const TOOL_GROUPS: Record<ToolGroup, readonly string[]> = {
18
+ shell: ["shell"],
19
+ web: ["webfetch", "websearch"],
20
+ }
21
+
22
+ // What a role is for: these groups are never narrowed away from it.
23
+ const ROLE_NEEDS: Partial<Record<string, readonly ToolGroup[]>> = { test: ["shell"], review: ["shell"], research: ["web"] }
24
+
25
+ // Roles that change files; a task with declared files needs one of them, a task without files must not get one.
26
+ export const WRITERS = new Set(["code", "test", "visual", "write", "debug"])
27
+
28
+ export interface Skill {
29
+ readonly name: string
30
+ readonly description: string
31
+ readonly roles: readonly string[] // the roles that may load it
32
+ }
33
+
34
+
35
+ // The questions for one task: the fixed set, the role choice, and one noul per skill the planner's role may load.
36
+ export function classifyQuestions(task: Task, skills: readonly Skill[], memory: readonly string[] = []): Record<string, Question> {
37
+ const roles = Object.fromEntries(ROLES.map((r) => [r.id, r.description]))
38
+ const allowed = skills.filter((s) => s.roles.includes(task.role))
39
+ return {
40
+ role: roleChoice(roles),
41
+ ...CLASSIFY,
42
+ ...Object.fromEntries(allowed.map((s) => [`skill.${s.name}`, skillQuestion(s.name, s.description)])),
43
+ ...recallQuestions(memory),
44
+ }
45
+ }
46
+
47
+ // The task alone, not the job (Phase D: a new function in a job that also fixed a bug was classified as a bug fix).
48
+ // Probe on that case: is_bug_fix 0.91 with the goal, 0.84 with it as background, 0.08 without it, while the bug fix
49
+ // task itself stays at 0.94. The planner writes each task's description for a worker that knows nothing else.
50
+ export function classifyState(_goal: string, task: Task, acceptance: readonly Acceptance[]): Record<string, unknown> {
51
+ return {
52
+ task: { id: task.id, title: task.title, description: task.description, files: task.files, plannerRole: task.role },
53
+ acceptance: acceptance.map((a) => `${a.text}${a.verify ? ` (checked with: ${a.verify})` : ""}`),
54
+ }
55
+ }
56
+
57
+ // A role can use an action unless it denies it outright with no exception. For the shell of a role that only reads,
58
+ // what counts is whether it may run the tests: every reader may run reading commands (git log, ls, grep), and a task
59
+ // that needs the shell needs it to run something (review allows the test runners, oracle does not).
60
+ const canUse = (role: Role, action: string) => {
61
+ if (action === "shell" && !WRITERS.has(role.id)) return TEST_RUNNERS.some((cmd) => role.rules.some((r) => r.action === "shell" && r.resource === cmd && r.effect === "allow"))
62
+ return (
63
+ !role.rules.some((r) => r.action === action && r.resource === "*" && r.effect === "deny") ||
64
+ role.rules.some((r) => r.action === action && r.resource !== "*" && r.effect !== "deny")
65
+ )
66
+ }
67
+
68
+ // The first role in the same write class that may use the group, for a task whose role cannot do what it needs.
69
+ function roleThatCan(group: ToolGroup, writer: boolean): Role | undefined {
70
+ const order = writer ? ["code", "test", "debug", "visual"] : ["review", "research", "explore"]
71
+ return order.map((id) => roleById(id)!).find((r) => TOOL_GROUPS[group].every((a) => canUse(r, a)))
72
+ }
73
+
74
+ const MAX_SKILLS = 3
75
+
76
+ export function combine(task: Task, acceptance: readonly Acceptance[], asked: Asked | undefined, policies: Policies, skills: readonly Skill[] = [], memory: readonly string[] = []): Profile {
77
+ const a = asked?.decision.answers ?? {}
78
+ const noul = (q: string) => (a[q]?.type === "noul" ? (a[q] as { noul: number }).noul : undefined)
79
+ const yes = (q: string) => (noul(q) ?? 0) >= NOUL_FLOOR
80
+ const choice = (q: string) => (a[q]?.type === "choice" ? (a[q] as { choice: string; confidence: number }) : undefined)
81
+ const fixed = (key: string) => {
82
+ const p = resolvePolicy(`N5.${key}`, policies).policy
83
+ return p.kind === "fixed" ? p.value : undefined
84
+ }
85
+ let confidence = 1
86
+ const take = <T extends string>(q: string, allowed: readonly string[], fallback: T): T => {
87
+ const c = choice(q)
88
+ if (!c || c.confidence < CHOICE_FLOOR || !allowed.includes(c.choice)) return fallback
89
+ confidence = Math.min(confidence, c.confidence)
90
+ return c.choice as T
91
+ }
92
+
93
+ // Role: the planner's, unless the model is sure of another in the same write class, or the user pinned one.
94
+ const writer = task.files.length > 0
95
+ let role = task.role
96
+ let roleReason = "the planner's role"
97
+ const pinnedRole = fixed("role")
98
+ const modelRole = choice("role")
99
+ if (pinnedRole && roleById(pinnedRole)) [role, roleReason] = [pinnedRole, "preset"]
100
+ else if (modelRole && modelRole.choice !== role && modelRole.confidence >= CHOICE_FLOOR && WRITERS.has(modelRole.choice) === writer) {
101
+ ;[role, roleReason] = [modelRole.choice, `the decision model (${modelRole.confidence.toFixed(2)}) over the planner's ${task.role}`]
102
+ confidence = Math.min(confidence, modelRole.confidence)
103
+ }
104
+
105
+ // A task that needs a group its role denies gets a role that has it (live test: "run the tests" went to oracle,
106
+ // which has no shell, and the worker could only read). Without a model answer, a verify command means shell.
107
+ const tools: Record<ToolGroup, number | undefined> = { shell: noul("tool.shell"), web: noul("tool.web") }
108
+ let penalty = 1 // each contradiction cut back to the matrix
109
+ const needsShell = tools.shell !== undefined ? tools.shell >= NOUL_FLOOR : !writer && acceptance.some((x) => x.verify) && /\b(run|test|build|lint)/i.test(`${task.title} ${task.description}`)
110
+ for (const [group, needed] of [["shell", needsShell], ["web", tools.web !== undefined && tools.web >= NOUL_FLOOR]] as const) {
111
+ const current = roleById(role)!
112
+ if (!needed || TOOL_GROUPS[group].every((x) => canUse(current, x))) continue
113
+ const other = pinnedRole ? undefined : roleThatCan(group, writer)
114
+ if (other) [role, roleReason] = [other.id, `${current.id} has no ${group}, the task needs it`]
115
+ penalty *= 0.8
116
+ }
117
+
118
+ const score = a.difficulty?.type === "score" ? a.difficulty.score : undefined
119
+ const pinnedDifficulty = Number(fixed("difficulty"))
120
+ const difficulty = Number.isFinite(pinnedDifficulty) && fixed("difficulty") !== undefined ? Math.max(0, Math.min(1, pinnedDifficulty)) : score !== undefined ? Math.max(0, Math.min(4, score)) / 4 : 0.5
121
+ const risk = (fixed("risk") as Risk | undefined) ?? take<Risk>("risk", Object.keys(RISKS), "internal")
122
+ const perm = (fixed("perm_profile") as PermProfile | undefined) ?? take<PermProfile>("perm_profile", ["strict", "normal", "trusted"], "strict")
123
+ const budget = (fixed("budget_tier") as BudgetTier | undefined) ?? take<BudgetTier>("budget_tier", ["S", "M", "L"], "M")
124
+ const picked = skills
125
+ .filter((s) => s.roles.includes(role))
126
+ .map((s) => ({ name: s.name, p: noul(`skill.${s.name}`) ?? 0 }))
127
+ .filter((s) => s.p >= NOUL_FLOOR)
128
+ .sort((x, y) => y.p - x.p)
129
+ .slice(0, MAX_SKILLS)
130
+ .map((s) => s.name)
131
+ return {
132
+ role,
133
+ roleReason,
134
+ difficulty,
135
+ risk,
136
+ testOracle: noul("has_test_oracle") !== undefined ? yes("has_test_oracle") : acceptance.some((x) => x.verify),
137
+ testFirst: yes("test_first_possible"),
138
+ bugFix: yes("is_bug_fix"),
139
+ approachUncertain: yes("approach_uncertain"),
140
+ bugUnknownCause: yes("bug_unknown_cause"),
141
+ vision: yes("needs_vision"),
142
+ tools,
143
+ skills: picked,
144
+ perm,
145
+ budget,
146
+ injection: yes("injection"),
147
+ confidence: confidence * penalty,
148
+ source: asked && Object.keys(a).length > 0 ? "model" : "rules",
149
+ decision: asked?.id,
150
+ recall: recalled(memory, a as never, NOUL_FLOOR),
151
+ }
152
+ }
153
+
154
+ // The worker session's own permission rules (Phase A, A5): groups the task does not need are denied, by how strict
155
+ // the profile is. They are appended to the role's rules, so they can only take rights away.
156
+ export function narrowing(profile: Profile): Rule[] {
157
+ if (profile.perm === "trusted") return []
158
+ const below = profile.perm === "strict" ? NOUL_FLOOR : 0.2
159
+ const keep = new Set(ROLE_NEEDS[profile.role] ?? [])
160
+ const out: Rule[] = []
161
+ for (const group of Object.keys(TOOL_GROUPS) as ToolGroup[]) {
162
+ const p = profile.tools[group]
163
+ if (p === undefined || p >= below || keep.has(group)) continue
164
+ for (const action of TOOL_GROUPS[group]) out.push({ action, resource: "*", effect: "deny" })
165
+ }
166
+ return out
167
+ }
168
+
169
+ // One line for the plan, the journal and the user.
170
+ export function profileText(p: Profile): string {
171
+ const groups = (Object.keys(p.tools) as ToolGroup[]).filter((g) => p.tools[g] !== undefined).map((g) => `${g} ${p.tools[g]!.toFixed(2)}`)
172
+ return [
173
+ `role ${p.role}${p.roleReason === "the planner's role" ? "" : ` (${p.roleReason})`}`,
174
+ `difficulty ${p.difficulty.toFixed(2)}`,
175
+ `risk ${p.risk}`,
176
+ p.testOracle ? "test oracle" : "no test oracle",
177
+ p.testFirst ? "test first possible" : undefined,
178
+ p.bugFix ? "bug fix" : undefined,
179
+ p.approachUncertain ? "approach uncertain" : undefined,
180
+ p.vision ? "needs vision" : undefined,
181
+ `${p.perm} rights${groups.length ? ` (${groups.join(", ")})` : ""}`,
182
+ `budget ${p.budget}`,
183
+ p.skills.length ? `skills ${p.skills.join(", ")}` : undefined,
184
+ p.source === "rules" ? "rules only" : undefined,
185
+ ].filter(Boolean).join(" · ")
186
+ }
@@ -0,0 +1 @@
1
+ export * from "@omacode/tui/progress"
package/src/redact.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "@omacode/guard/redact"
@@ -0,0 +1,207 @@
1
+ // The model registry and the router over it (design.md §19): which models exist, where they run, what they can
2
+ // do, and which one a task gets. Local when capable; cloud for hard tasks, long contexts, or busy hardware.
3
+
4
+ import { MODELS, family, roleById } from "./roles.ts"
5
+
6
+ export type Location = "local" | "cloud"
7
+ export type Device = "cuda" | "igpu" | "npu" | "cloud"
8
+ export type Tier = "quick" | "agent" | "deep"
9
+
10
+ export interface ModelEntry {
11
+ readonly id: string // "provider/model", as OpenCode names it
12
+ readonly location: Location
13
+ readonly device: Device
14
+ readonly censored: boolean
15
+ readonly family: string
16
+ readonly tier: Tier
17
+ readonly vision: boolean
18
+ readonly ctx: number
19
+ readonly tokPerSec?: number
20
+ readonly resident?: boolean // always loaded (the iGPU model)
21
+ readonly swapGroup?: string // models that share one GPU through llama-swap
22
+ readonly disabled?: boolean // known but not routed to
23
+ readonly note?: string
24
+ readonly budget?: number // the monthly usage limit in $ on the $10 OpenCode Go plan; absent for a free model
25
+ }
26
+
27
+ const TIER_RANK: Record<Tier, number> = { quick: 0, agent: 1, deep: 2 }
28
+
29
+ // Cloud models (OpenCode Go) and the local fleet of ~/Models/bench/ROSTER.md (2026-10-04). Local models run with
30
+ // a 16k context. The NPU is reserved for Whisper plus one small quick model (Phase A).
31
+ export const DEFAULT_REGISTRY: readonly ModelEntry[] = [
32
+ // Vision and context as the host lists them (GET /api/model), budgets from opencode.ai/docs/go (2026-10-19).
33
+ { id: MODELS.glm, location: "cloud", device: "cloud", censored: true, family: "glm", tier: "agent", vision: true, ctx: 1000000, budget: 60 },
34
+ { id: MODELS.deepseek, location: "cloud", device: "cloud", censored: true, family: "deepseek", tier: "agent", vision: true, ctx: 1000000, budget: 80 },
35
+ { id: MODELS.mimo, location: "cloud", device: "cloud", censored: true, family: "mimo", tier: "agent", vision: true, ctx: 1048576, budget: 15 },
36
+ { id: MODELS.mimoFlash, location: "cloud", device: "cloud", censored: true, family: "mimo", tier: "agent", vision: true, ctx: 1048576, budget: 60 },
37
+ { id: MODELS.gemini, location: "cloud", device: "cloud", censored: true, family: "gemini", tier: "agent", vision: true, ctx: 1048576, budget: 60, note: "doubled for a limited time ($30 normally)" },
38
+ { id: MODELS.step, location: "cloud", device: "cloud", censored: true, family: "step", tier: "agent", vision: true, ctx: 1000000, budget: 60, note: "quadrupled for a limited time ($15 normally)" },
39
+ { id: MODELS.qwen, location: "cloud", device: "cloud", censored: true, family: "qwen", tier: "agent", vision: true, ctx: 1000000, budget: 30 },
40
+ { id: MODELS.haiku, location: "cloud", device: "cloud", censored: true, family: "claude", tier: "agent", vision: true, ctx: 1000000, budget: 15 },
41
+ { id: MODELS.minimax, location: "cloud", device: "cloud", censored: true, family: "minimax", tier: "agent", vision: true, ctx: 1000000, note: "free for a limited time" },
42
+ { id: "llamaswap/oss-u", location: "local", device: "cuda", censored: false, family: "gpt-oss", tier: "deep", vision: false, ctx: 16384, tokPerSec: 53, swapGroup: "cuda0" },
43
+ { id: "llamaswap/ornith-u", location: "local", device: "cuda", censored: false, family: "ornith", tier: "agent", vision: true, ctx: 16384, tokPerSec: 40, swapGroup: "cuda0" },
44
+ { id: "llamaswap/ornith-u-s", location: "local", device: "cuda", censored: false, family: "ornith", tier: "agent", vision: true, ctx: 16384, tokPerSec: 45, swapGroup: "cuda0" },
45
+ { id: "llamaswap/ornith", location: "local", device: "cuda", censored: true, family: "ornith", tier: "agent", vision: true, ctx: 16384, tokPerSec: 35, swapGroup: "cuda0" },
46
+ { id: "llamaswap/mimo", location: "local", device: "cuda", censored: true, family: "mimo", tier: "agent", vision: true, ctx: 16384, tokPerSec: 39, swapGroup: "cuda0" },
47
+ { id: "llamaigpu/qwen3.8-u", location: "local", device: "igpu", censored: false, family: "qwen", tier: "agent", vision: true, ctx: 16384, tokPerSec: 6.5, resident: true },
48
+ { id: "flmnpu/qwen3:4b", location: "local", device: "npu", censored: true, family: "qwen", tier: "quick", vision: false, ctx: 16384, tokPerSec: 19, note: "quick tier only; skipped a required tool in Phase A" },
49
+ { id: "flmnpu/qwen3vl-it:4b", location: "local", device: "npu", censored: true, family: "qwen", tier: "quick", vision: true, ctx: 16384, tokPerSec: 19 },
50
+ { id: "flmnpu/gpt-oss:20b", location: "local", device: "npu", censored: true, family: "gpt-oss", tier: "deep", vision: false, ctx: 16384, disabled: true, note: "the NPU stays free for Whisper" },
51
+ ]
52
+
53
+ // Entries from the config replace or add models by id.
54
+ export function mergeRegistry(base: readonly ModelEntry[], extra: readonly Partial<ModelEntry>[]): ModelEntry[] {
55
+ const out = new Map(base.map((m) => [m.id, m]))
56
+ for (const e of extra) {
57
+ if (!e.id) continue
58
+ const known = out.get(e.id)
59
+ out.set(e.id, { ...(known ?? defaultsFor(e.id)), ...e } as ModelEntry)
60
+ }
61
+ return [...out.values()]
62
+ }
63
+
64
+ // A model the registry does not know: cautious defaults (local, censored, agent tier, small context).
65
+ function defaultsFor(id: string): ModelEntry {
66
+ const cloud = id.startsWith("opencode-go/") || id.startsWith("opencode/")
67
+ return { id, location: cloud ? "cloud" : "local", device: cloud ? "cloud" : "cuda", censored: true, family: family(id), tier: "agent", vision: false, ctx: cloud ? 128000 : 16384 }
68
+ }
69
+
70
+ // --- availability -----------------------------------------------------------------------------------------
71
+
72
+ export interface Availability {
73
+ readonly reachable: boolean
74
+ readonly loaded?: boolean // llama-swap: the model is in memory, no swap needed
75
+ readonly busy?: boolean // llama-vulkan: every slot is processing
76
+ }
77
+
78
+ export interface Endpoints {
79
+ readonly llamaswap?: string // http://127.0.0.1:8000
80
+ readonly llamaigpu?: string // http://127.0.0.1:8092
81
+ readonly flmnpu?: string // http://127.0.0.1:52625
82
+ }
83
+
84
+ export const DEFAULT_ENDPOINTS: Endpoints = {
85
+ llamaswap: "http://127.0.0.1:8000",
86
+ llamaigpu: "http://127.0.0.1:8092",
87
+ flmnpu: "http://127.0.0.1:52625",
88
+ }
89
+
90
+ async function getJson(fetcher: typeof fetch, url: string, timeoutMs: number): Promise<unknown> {
91
+ const res = await fetcher(url, { signal: AbortSignal.timeout(timeoutMs) })
92
+ if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`)
93
+ return res.json()
94
+ }
95
+
96
+ // Reads what the local servers report (Phase A, A8): llama-swap's loaded status, llama-vulkan's slots, FLM's
97
+ // model list. Cloud models count as reachable; their limits are the budget's job.
98
+ export async function probe(
99
+ registry: readonly ModelEntry[],
100
+ endpoints: Endpoints = DEFAULT_ENDPOINTS,
101
+ fetcher: typeof fetch = fetch,
102
+ timeoutMs = 1500,
103
+ ): Promise<Map<string, Availability>> {
104
+ const out = new Map<string, Availability>()
105
+ const name = (id: string) => id.slice(id.indexOf("/") + 1)
106
+ const [swap, igpuHealth, igpuSlots, npu] = await Promise.all([
107
+ endpoints.llamaswap ? getJson(fetcher, `${endpoints.llamaswap}/v1/models`, timeoutMs).catch(() => undefined) : undefined,
108
+ endpoints.llamaigpu ? getJson(fetcher, `${endpoints.llamaigpu}/health`, timeoutMs).catch(() => undefined) : undefined,
109
+ endpoints.llamaigpu ? getJson(fetcher, `${endpoints.llamaigpu}/slots`, timeoutMs).catch(() => undefined) : undefined,
110
+ endpoints.flmnpu ? getJson(fetcher, `${endpoints.flmnpu}/v1/models`, timeoutMs).catch(() => undefined) : undefined,
111
+ ])
112
+ const swapModels = new Map(((swap as { data?: { id: string; status?: { value?: string } }[] } | undefined)?.data ?? []).map((m) => [m.id, m.status?.value]))
113
+ const slots = Array.isArray(igpuSlots) ? (igpuSlots as { is_processing?: boolean }[]) : []
114
+ const npuIds = new Set(((npu as { data?: { id: string }[] } | undefined)?.data ?? []).map((m) => m.id))
115
+ for (const m of registry) {
116
+ if (m.location === "cloud") out.set(m.id, { reachable: true })
117
+ else if (m.id.startsWith("llamaswap/")) {
118
+ const status = swapModels.get(name(m.id))
119
+ out.set(m.id, { reachable: status !== undefined, loaded: status === "loaded" })
120
+ } else if (m.id.startsWith("llamaigpu/")) {
121
+ const ok = (igpuHealth as { status?: string } | undefined)?.status === "ok"
122
+ out.set(m.id, { reachable: ok, loaded: ok, busy: slots.length > 0 && slots.every((s) => s.is_processing) })
123
+ } else if (m.id.startsWith("flmnpu/")) {
124
+ out.set(m.id, { reachable: npuIds.has(name(m.id)) })
125
+ } else out.set(m.id, { reachable: false })
126
+ }
127
+ return out
128
+ }
129
+
130
+ // --- routing ------------------------------------------------------------------------------------------------
131
+
132
+ export interface RouteNeeds {
133
+ readonly role: string
134
+ readonly difficulty?: number // 0..1; picks the tier
135
+ readonly vision?: boolean
136
+ readonly ctx?: number // tokens the task needs in context
137
+ readonly sensitive?: boolean // must not leave the machine
138
+ readonly refusalLikely?: boolean // a censored model would refuse: local and uncensored only
139
+ readonly avoidFamilies?: readonly string[] // a reviewer never checks its own family's work
140
+ readonly preferCloud?: boolean // e.g. the user pinned the cloud
141
+ readonly loadedModel?: string // the model already loaded on cuda0 (batching avoids swaps)
142
+ }
143
+
144
+ export interface Route {
145
+ readonly model?: string
146
+ readonly reason: string
147
+ readonly ranked: readonly string[]
148
+ }
149
+
150
+ export function tierFor(difficulty = 0.5): Tier {
151
+ return difficulty <= 0.33 ? "quick" : difficulty <= 0.66 ? "agent" : "deep"
152
+ }
153
+
154
+ // Roles that do agentic work never go to the NPU's quick model.
155
+ const QUICK_ROLES = new Set(["explore", "write"])
156
+
157
+ export function route(registry: readonly ModelEntry[], needs: RouteNeeds, availability?: Map<string, Availability>): Route {
158
+ const tier = tierFor(needs.difficulty)
159
+ const avail = (id: string) => availability?.get(id) ?? { reachable: true }
160
+ const local = needs.sensitive || needs.refusalLikely
161
+ const candidates = registry.filter((m) =>
162
+ !m.disabled &&
163
+ avail(m.id).reachable &&
164
+ (!needs.vision || m.vision) &&
165
+ m.ctx >= (needs.ctx ?? 0) &&
166
+ (!local || m.location === "local") &&
167
+ (!needs.refusalLikely || !m.censored) &&
168
+ (m.device !== "npu" || (tier === "quick" && QUICK_ROLES.has(needs.role))) &&
169
+ !(needs.avoidFamilies ?? []).includes(m.family),
170
+ )
171
+ if (candidates.length === 0) {
172
+ const why = [needs.refusalLikely && "uncensored", local && "local", needs.vision && "vision", needs.ctx && `ctx ≥ ${needs.ctx}`].filter(Boolean).join(", ")
173
+ return { reason: `no reachable model fits (${why || "any"})`, ranked: [] }
174
+ }
175
+ // Local when capable: a local model covers the tier, and nothing pins the cloud.
176
+ const localCovers = candidates.some((m) => m.location === "local" && TIER_RANK[m.tier] >= TIER_RANK[tier] && !avail(m.id).busy)
177
+ const wantLocal = local || (localCovers && !needs.preferCloud)
178
+ // The role matrix's models in their order (src/roles.ts) break ties, so roles spread over the families instead of
179
+ // all landing on the alphabetically first one (live test: deepseek got every role).
180
+ const preferred = roleById(needs.role)?.models ?? []
181
+ const rank = (id: string) => (preferred.includes(id) ? preferred.indexOf(id) : preferred.length)
182
+ const score = (m: ModelEntry): number[] => {
183
+ const a = avail(m.id)
184
+ return [
185
+ m.location === (wantLocal ? "local" : "cloud") ? 0 : 1,
186
+ TIER_RANK[m.tier] >= TIER_RANK[tier] ? 0 : 1, // covers the tier
187
+ a.busy ? 1 : 0,
188
+ m.resident || a.loaded || m.id === needs.loadedModel || m.location === "cloud" ? 0 : 1, // no swap
189
+ Math.abs(TIER_RANK[m.tier] - TIER_RANK[tier]), // no bigger than needed
190
+ -(m.tokPerSec ?? 0),
191
+ rank(m.id),
192
+ ]
193
+ }
194
+ const ranked = [...candidates].sort((a, b) => {
195
+ const x = score(a), y = score(b)
196
+ for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return x[i]! - y[i]!
197
+ return a.id.localeCompare(b.id)
198
+ })
199
+ const best = ranked[0]!
200
+ const reason = [
201
+ best.location,
202
+ `${tier} task`,
203
+ needs.refusalLikely ? "uncensored" : needs.sensitive ? "sensitive" : undefined,
204
+ avail(best.id).loaded || best.resident ? "already loaded" : best.location === "local" ? "needs a swap" : undefined,
205
+ ].filter(Boolean).join(", ")
206
+ return { model: best.id, reason, ranked: ranked.map((m) => m.id) }
207
+ }
package/src/roles.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "@omacode/state/roles"
package/src/routing.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "@omacode/state/routing"