@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
package/README.md CHANGED
@@ -4,8 +4,9 @@ An OpenCode plugin that turns one chat into a job: it plans with you, splits the
4
4
  its own worktree with a role-scoped worker, reviews the result and merges what passes.
5
5
 
6
6
  ```bash
7
+ opencode plugin add @omacode/full # orchestrator + guard + sandbox + context + the TUI
7
8
  opencode plugin add @omacode/micromanager # the orchestrator alone
8
- opencode plugin add @omacode/full # orchestrator + guard + sandbox + context
9
+ npx -p @omacode/micromanager omacode doctor # the command line: doctor, preflight, services, tools, uninstall
9
10
  ```
10
11
 
11
12
  The orchestrator delegates; it never edits files or runs commands itself. Every worker runs under a role
@@ -15,10 +16,12 @@ back, and a merge train waits for the checks.
15
16
 
16
17
  ## What it needs
17
18
 
18
- - OpenCode v2 and Node.js 22.12 or later.
19
+ - OpenCode v2 (tested with 2.2.5) and Node.js 22.18 or later. The package ships JavaScript built from the sources.
19
20
  - On Linux, the sandbox uses `bubblewrap`, `socat` and `ripgrep`; without them the plugin still runs, unwrapped.
20
- - The decision model (Jev) is configured under `jev` in `micromanager.jsonc`; a local decision server can replace it
21
- for the local-first guards.
21
+ - The decision client is configured under `decider` in `micromanager.jsonc`: `{ "mode": "local" }` (the default) keeps
22
+ every decision on this machine and needs no key; `{ "mode": "cloud" }` may send one to the cloud client, after a
23
+ redaction and a per-call preview, once a session has opted in. The guards (injection, sensitive) stay local
24
+ unless that session's user lets them go, and a payload carrying the `sensitive` flag is never sent.
22
25
 
23
26
  Configuration, the job flow, the roles and the design notes live in the repository:
24
27
  <https://github.com/RentschlerTobias/Omacode#readme>.
package/THIRD_PARTY.md ADDED
@@ -0,0 +1,100 @@
1
+ # Third-party software
2
+
3
+ What omacode installs, downloads or relies on, under which licence, and what that means for what you make with it.
4
+ Generated by `node scripts/third-party.mjs` from `licenses/components.json`; the machine-readable form is
5
+ `licenses/third-party.json`. Image models you add yourself are not listed here: the model registry
6
+ (`npm run models -- status`) holds their licences, and the plugin checks them before every ComfyUI run.
7
+
8
+ **Installed by:** `minimal`, `coding`, `creator`, `full` are the install.sh profiles; `downloaded` is fetched on first
9
+ use by something installed; `you` is needed but not installed by omacode; `planned` is not installed yet.
10
+ **Telemetry:** what a tool reports to its maker on its own. omacode sets DO_NOT_TRACK=1, HYPERFRAMES_NO_TELEMETRY=1 and
11
+ DISABLE_TELEMETRY=1 for everything it starts and for every agent shell (`packages/core/src/telemetry.ts`).
12
+
13
+ ## Programs and models
14
+
15
+ | Name | Version | Licence | Installed by | Where | Commercial use of what you make | When you pass it on | Telemetry |
16
+ |---|---|---|---|---|---|---|---|
17
+ | omacode | 1.0.0 | `Apache-2.0` | minimal | global | yes | keep LICENSE when redistributing | none |
18
+ | OpenCode | | `MIT` | you | global | yes | keep the copyright notice | none found in 2.2.5 (an embedded component honours DO_NOT_TRACK, which omacode sets) |
19
+ | uv | | `MIT OR Apache-2.0` | you | global | n/a | keep the copyright notice | not checked |
20
+ | bubblewrap | | `LGPL-2.1-or-later` | you | global | n/a | none for use; LGPL terms when redistributing it | none |
21
+ | llama.cpp (llama-server)<br><sub>taken from PATH (or LLAMA_SERVER) for the embedding service; omacode does not install it</sub> | | `MIT` | you | global | n/a | keep the copyright notice | not checked |
22
+ | GLiNER2.5-multi-Decide<br><sub>the decider's base model, downloaded on its first start when no tuned model ships</sub> | | `Apache-2.0` | coding | global | n/a | keep the licence notice | none (model weights) |
23
+ | omacode guard model (tuned)<br><sub>to be published on Hugging Face as T1ddaeus/omacode-guard; until then local only</sub> | | `Apache-2.0` | coding | global | n/a | fine-tune of hivetrace/gliner-guard-uniencoder (Apache-2.0), which is built on jhu-clsp/mmBERT-small (MIT); keep both notices | none (model weights) |
24
+ | gliner-guard-uniencoder<br><sub>the base of the tuned guard model; not installed on its own</sub> | | `Apache-2.0` | planned | global | n/a | keep the licence notice; built on jhu-clsp/mmBERT-small (MIT) | none (model weights) |
25
+ | Qwen3-Embedding (0.6B, 4B, 8B GGUF)<br><sub>downloaded on the embedding service's first start</sub> | | `Apache-2.0` | coding | global | n/a | keep the licence notice | none (model weights) |
26
+ | HyperFrames | 0.9.54 | `Apache-2.0` | creator | global | yes | keep the licence notice | usage events to PostHog; off with HYPERFRAMES_NO_TELEMETRY or DO_NOT_TRACK, which omacode sets on every run and agent shell |
27
+ | chrome-headless-shell (Chrome for Testing)<br><sub>HyperFrames downloads it on first use</sub> | | `BSD-3-Clause AND LicenseRef-Chromium-third-party` | downloaded | global | yes | keep the Chromium notices | not checked |
28
+ | Manim (Community) | 0.22.1 | `MIT` | full | global | yes | keep the copyright notice | not checked |
29
+ | ComfyUI<br><sub>a separate program omacode talks to over HTTP; LICENSE is GPL v3 with no 'or later' grant found</sub> | 0.44.2 | `GPL-3.0-only` | creator | global | yes for ComfyUI itself; the image model's licence decides (the model registry checks it before every run) | GPL terms when you redistribute ComfyUI; none for images | not checked |
30
+ | PyTorch (in ComfyUI's environment) | | `Apache-2.0 AND Apache-2.0 WITH LLVM-exception AND BSD-2-Clause AND BSD-3-Clause AND BSL-1.0 AND MIT` | creator | global | yes | keep the notices | not checked |
31
+ | comfy-cli<br><sub>installs and manages ComfyUI; a separate program</sub> | 1.25.0 | `GPL-3.0-only` | creator | global | yes | GPL terms when redistributing it | usage tracking; omacode turns it off at install (comfy tracking disable) |
32
+ | comfy-mcp<br><sub>a separate program OpenCode starts as an MCP server; used unmodified</sub> | 0.10.0 | `AGPL-3.0-or-later OR LicenseRef-Comfy-Commercial` | creator | global | yes | AGPL terms when you modify it and offer it to others over a network | not checked |
33
+ | Modern Web Guidance (modern-web-guidance)<br><sub>Google Chrome's guides and their offline search, taken from the npm tarball at its pin (sha512-checked); the skill is adapted to run the local copy, and its installer and Chrome-extensions skill are not used</sub> | 1.0.0 | `Apache-2.0` | creator | global | yes | keep LICENSE and THIRD_PARTY_NOTICES (both installed beside the guides) | usage events to Google Clearcut on install, update, uninstall, list and legacy-scan; off with DISABLE_TELEMETRY, which omacode sets; search and retrieve report nothing |
34
+
35
+ ## npm packages the plugin runs with
36
+
37
+ | Package | Version | Licence |
38
+ |---|---|---|
39
+ | @anthropic-ai/sandbox-runtime | 0.0.81 | `Apache-2.0` |
40
+ | @pondwader/socks5-server | 1.0.10 | `MIT` |
41
+ | axe-core | 4.14.0 | `MPL-2.0` |
42
+ | commander | 12.1.0 | `MIT` |
43
+ | node-forge | 1.4.0 | `(BSD-3-Clause OR GPL-2.0)` |
44
+ | playwright-core | 1.64.1 | `Apache-2.0` |
45
+ | zod | 3.25.76 | `MIT` |
46
+
47
+ ## The decider's Python environment (omacode-services)
48
+
49
+ Pinned by `decider/uv.lock`; read from an installed environment.
50
+
51
+ | Package | Version | Licence |
52
+ |---|---|---|
53
+ | accelerate | 1.15.0 | `Apache` |
54
+ | annotated-doc | 0.0.7 | `MIT` |
55
+ | annotated-types | 0.8.0 | `MIT` |
56
+ | anyio | 4.16.0 | `MIT` |
57
+ | certifi | 2026.7.22 | `MPL-2.0` |
58
+ | charset-normalizer | 3.5.2 | `MIT` |
59
+ | click | 8.5.1 | `BSD-3-Clause` |
60
+ | filelock | 4.0.10 | `MIT` |
61
+ | fsspec | 2026.9.0 | `BSD-3-Clause` |
62
+ | gliner2 | 2.1.0 | `Apache-2.0` |
63
+ | h11 | 0.16.0 | `MIT` |
64
+ | hf-xet | 1.6.0 | `Apache-2.0` |
65
+ | httpcore2 | 2.16.2 | `BSD-3-Clause` |
66
+ | httpx2 | 2.16.2 | `BSD-3-Clause` |
67
+ | huggingface_hub | 2.4.0 | `Apache-2.0` |
68
+ | idna | 3.20 | `BSD-3-Clause` |
69
+ | Jinja2 | 3.1.6 | `BSD License` |
70
+ | markdown-it-py | 4.3.0 | `MIT License` |
71
+ | MarkupSafe | 3.0.4 | `BSD-3-Clause` |
72
+ | mdurl | 0.1.2 | `MIT License` |
73
+ | mpmath | 1.3.0 | `BSD` |
74
+ | networkx | 3.7 | `BSD-3-Clause` |
75
+ | numpy | 2.5.3 | `BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0` |
76
+ | packaging | 26.3 | `Apache-2.0 OR BSD-2-Clause` |
77
+ | peft | 0.21.2 | `Apache` |
78
+ | protobuf | 7.36.2 | `3-Clause BSD License` |
79
+ | psutil | 7.2.2 | `BSD-3-Clause` |
80
+ | pydantic | 2.13.5 | `MIT` |
81
+ | pydantic_core | 2.46.5 | `MIT` |
82
+ | Pygments | 2.21.0 | `BSD-2-Clause` |
83
+ | PyYAML | 6.0.3 | `MIT` |
84
+ | regex | 2026.9.29 | `Apache-2.0 AND CNRI-Python` |
85
+ | requests | 2.34.2 | `Apache-2.0` |
86
+ | rich | 15.0.0 | `MIT` |
87
+ | safetensors | 0.8.0 | `Apache Software License` |
88
+ | sentencepiece | 0.2.2 | `Apache-2.0` |
89
+ | setuptools | 84.0.0 | `MIT` |
90
+ | shellingham | 1.5.4 | `ISC License` |
91
+ | sympy | 1.14.0 | `BSD` |
92
+ | tokenizers | 0.23.3 | `Apache Software License` |
93
+ | torch | 2.14.1+cpu | `Apache-2.0 AND Apache-2.0 WITH LLVM-exception AND BSD-2-Clause AND BSD-3-Clause AND BSL-1.0 AND MIT` |
94
+ | tqdm | 4.70.1 | `MPL-2.0 AND MIT` |
95
+ | transformers | 5.22.0 | `Apache 2.0 License` |
96
+ | truststore | 0.10.5 | `MIT` |
97
+ | typer | 0.29.2 | `MIT` |
98
+ | typing_extensions | 4.16.0 | `PSF-2.0` |
99
+ | typing-inspection | 0.4.4 | `MIT` |
100
+ | urllib3 | 2.8.0 | `MIT` |
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,35 @@
1
+ # decider
2
+
3
+ The local decider for micromanager: GLiNER2 on the CPU behind the `/v1/systemone` wire format
4
+ (`POST /v1/systemone {model, state, questions}`), so the plugin talks to it with the same client as to the cloud
5
+ decision service. It answers choice, noul and score questions; see `decider/server.py` for the mapping. The 4060
6
+ stays free for llama-swap and the NPU for Whisper.
7
+
8
+ ```bash
9
+ uv run decider --port 8781 --model fastino/GLiNER2.5-multi-Decide # or a fine-tuned checkpoint directory
10
+ curl -s localhost:8781/health
11
+ python3 -m unittest discover -s tests -t . # tests need no torch
12
+ ```
13
+
14
+ `POST /v1/entities {texts, labels, threshold}` returns the spans of each label in each text, for the names and
15
+ addresses `src/redact.ts` swaps for placeholders. The decision checkpoint is trained to classify and finds few of them
16
+ (2026-10-27: no name in a German invoice line at 0.5); `--entity-model <checkpoint>` serves the endpoint from an
17
+ extraction checkpoint instead, loaded on its first request.
18
+
19
+ The zero-shot model is only a starting point: in Phase A it scored about 0.5 on every guard. Guards need a
20
+ fine-tune on our own labels (`npm run export-dataset -- --target gliner` in the repo root) before the plugin lets
21
+ them decide anything; until then a guard "yes" only asks the user.
22
+
23
+ ## Training data
24
+
25
+ The guards' and entities' training sets are not in the repository: they are made on demand into `decider/data/`
26
+ (ignored by git) and stay on the machine that trains.
27
+
28
+ ```bash
29
+ node packages/micromanager/src/cli.ts synth-guards --public --rows # decider/data/guards.jsonl (+ .rows.jsonl)
30
+ node packages/micromanager/src/cli.ts synth-entities # decider/data/entities.jsonl
31
+ ```
32
+
33
+ Only synthetic cases (written by a model, see the command's help) and public datasets (deepset/prompt-injections,
34
+ Apache-2.0) go in, never the user's journal. The credential cases look like real keys on purpose, so the guard learns
35
+ them; they are fake, but secret scanners flag them, which is one more reason they are not committed.
@@ -0,0 +1 @@
1
+ """Local GLiNER2 decision server for micromanager."""
@@ -0,0 +1,327 @@
1
+ """A local decision server: GLiNER2 behind the decision wire format, on the CPU (design.md §20).
2
+
3
+ POST /v1/systemone {model, state, questions} -> {model, answers, latency_ms}
4
+ POST /v1/entities {texts, labels, threshold} -> {entities: [[{label, text, start, end, score}], …], latency_ms}
5
+ GET /health -> {status: "ok", model}
6
+
7
+ With DECIDER_TOKEN set, every POST needs "Authorization: Bearer <token>" and answers 401 without it; /health stays open.
8
+
9
+ Each question is its own forward pass, so a question's scores never depend on which others ride along:
10
+ - choice -> a single-label task over the criteria (option id -> meaning);
11
+ - noul -> a yes/no task; the answer is P(yes) normalised over yes and no;
12
+ - score -> a single-label task over the rubric levels "0", "1", …; the score is the probability-weighted level.
13
+
14
+ The entity endpoint finds the spans of each label in each text (names and addresses for src/redact.ts); long texts
15
+ are read in overlapping chunks.
16
+
17
+ The classifier is injected, so tests run without torch; the real one loads GLiNER2 lazily on the first request.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import hmac
24
+ import json
25
+ import os
26
+ import select
27
+ import socket
28
+ import threading
29
+ import time
30
+ from collections.abc import Callable, Mapping
31
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
32
+ from typing import Any, Protocol
33
+
34
+ YES_NO = {"yes": "Yes, the statement is true for this text.", "no": "No, the statement is false for this text."}
35
+ FIRST = ("text", "utterance", "task", "question")
36
+ # The encoder runs eager attention (DeBERTa rejects SDPA), so the attention matrix is n² and a 24 000-character state
37
+ # peaked at 13.7 GB and took 72 s for one decision (measured 2026-11-18). 4 000 characters stays under 0.5 GB and 5 s.
38
+ MAX_CHARS = 2000
39
+ # The entity endpoint reads in chunks of 384 tokens (gliner2 extract_entities_long), so its memory does not grow with
40
+ # the text and the decision clamp does not apply: before 2026-11-21 it did, and a name past character 2 000 of a text
41
+ # was never found, so never redacted. This bound is time, not memory: about 50 chunks.
42
+ MAX_ENTITY_CHARS = 64_000
43
+
44
+
45
+ def clamp(text: str, limit: int = MAX_CHARS) -> tuple[str, bool]:
46
+ """The head of the text, which is where render_state puts the task; the tail is what blew the memory up."""
47
+ return (text, False) if len(text) <= limit else (text[:limit], True)
48
+
49
+
50
+ class Classifier(Protocol):
51
+ def probabilities(self, text: str, task: str, labels: Mapping[str, str], instruction: str) -> dict[str, float]: ...
52
+
53
+
54
+ class EntityFinder(Protocol):
55
+ def entities(self, text: str, labels: list[str], threshold: float) -> list[dict[str, Any]]: ...
56
+
57
+
58
+ def render_state(state: Any) -> str:
59
+ """The text GLiNER reads: task text first, so a short window keeps it. src/dataset.ts renderState matches."""
60
+ if isinstance(state, str):
61
+ try:
62
+ state = json.loads(state)
63
+ except ValueError:
64
+ return state
65
+ if not isinstance(state, dict):
66
+ return str(state)
67
+ order = sorted(state.items(), key=lambda kv: FIRST.index(kv[0]) if kv[0] in FIRST else len(FIRST))
68
+ return "\n".join(f"{k}: {v if isinstance(v, str) else json.dumps(v, separators=(',', ':'))}" for k, v in order)
69
+
70
+
71
+ def safe(value: str) -> str:
72
+ """GLiNER2 rejects its own marker characters in labels and instructions."""
73
+ return value.replace("(", ", ").replace(")", "").replace("[", "").replace("]", "")
74
+
75
+
76
+ def normalise(probs: Mapping[str, float]) -> dict[str, float]:
77
+ total = sum(probs.values()) or 1.0
78
+ return {k: v / total for k, v in probs.items()}
79
+
80
+
81
+ def answer(classifier: Classifier, text: str, qid: str, question: Mapping[str, Any]) -> dict[str, Any] | None:
82
+ kind = question.get("type")
83
+ instruction = safe(str(question.get("instructions", "")))
84
+ if kind == "choice":
85
+ criteria = {str(k): safe(str(v)) for k, v in dict(question.get("criteria", {})).items()}
86
+ if not criteria:
87
+ return None
88
+ probs = normalise(classifier.probabilities(text, qid, criteria, instruction))
89
+ choice = max(probs, key=lambda k: probs[k])
90
+ return {"choice": choice, "confidence": probs[choice], "probabilities": probs}
91
+ if kind == "noul":
92
+ probs = normalise(classifier.probabilities(text, qid, YES_NO, instruction))
93
+ return {"noul": probs.get("yes", 0.0)}
94
+ if kind == "score":
95
+ levels = [safe(str(c)) for c in question.get("criteria", [])]
96
+ if len(levels) < 2:
97
+ return None
98
+ probs = normalise(classifier.probabilities(text, qid, {str(i): c for i, c in enumerate(levels)}, instruction))
99
+ score = sum(int(k) * p for k, p in probs.items())
100
+ return {"score": score, "confidence": max(probs.values()), "probabilities": probs}
101
+ return None
102
+
103
+
104
+ class Abandoned(Exception):
105
+ """The client went away; the rest of its questions are not worth the CPU."""
106
+
107
+
108
+ def client_gone(sock: socket.socket) -> bool:
109
+ """True when the peer closed the connection (readable, and a peek returns nothing)."""
110
+ try:
111
+ readable, _, _ = select.select([sock], [], [], 0)
112
+ return bool(readable) and sock.recv(1, socket.MSG_PEEK) == b""
113
+ except OSError:
114
+ return True
115
+
116
+
117
+ def decide(classifier: Classifier, body: Mapping[str, Any], model: str, alive: Callable[[], bool] = lambda: True, max_chars: int = MAX_CHARS) -> dict[str, Any]:
118
+ t0 = time.perf_counter()
119
+ text, truncated = clamp(render_state(body.get("state", "")), max_chars)
120
+ questions = body.get("questions") or {}
121
+ answers: dict[str, Any] = {}
122
+ for qid, question in dict(questions).items():
123
+ if not alive():
124
+ raise Abandoned
125
+ if isinstance(question, Mapping):
126
+ result = answer(classifier, text, str(qid), question)
127
+ if result is not None:
128
+ answers[str(qid)] = result
129
+ out = {"model": model, "answers": answers, "latency_ms": (time.perf_counter() - t0) * 1000}
130
+ if truncated:
131
+ out["truncated"] = True
132
+ out["chars"] = len(text)
133
+ return out
134
+
135
+
136
+ def extract(finder: Any, body: Mapping[str, Any], alive: Callable[[], bool] = lambda: True, max_chars: int = MAX_ENTITY_CHARS) -> dict[str, Any]:
137
+ """The spans of each label in each text. Labels go to GLiNER2 without its marker characters and come back as asked."""
138
+ t0 = time.perf_counter()
139
+ texts = body.get("texts")
140
+ labels = body.get("labels")
141
+ threshold = body.get("threshold", 0.5)
142
+ if not isinstance(texts, list) or not all(isinstance(t, str) for t in texts):
143
+ raise ValueError("texts must be a list of strings")
144
+ if not isinstance(labels, list) or not labels or not all(isinstance(lbl, str) and lbl.strip() for lbl in labels):
145
+ raise ValueError("labels must be a non-empty list of strings")
146
+ if not isinstance(threshold, (int, float)) or not 0 < threshold < 1:
147
+ raise ValueError("threshold must be a number between 0 and 1")
148
+ asked = {safe(lbl): lbl for lbl in labels}
149
+ out: list[list[dict[str, Any]]] = []
150
+ truncated = False
151
+ for text in texts:
152
+ if not alive():
153
+ raise Abandoned
154
+ text, cut = clamp(text, max_chars)
155
+ truncated = truncated or cut
156
+ spans = finder.entities(text, list(asked), float(threshold)) if text.strip() else []
157
+ out.append([
158
+ {"label": asked.get(str(s.get("label")), str(s.get("label"))), "text": s.get("text"), "start": s.get("start"), "end": s.get("end"), "score": s.get("score")}
159
+ for s in spans
160
+ ])
161
+ result = {"entities": out, "latency_ms": (time.perf_counter() - t0) * 1000}
162
+ if truncated:
163
+ result["truncated"] = True
164
+ return result
165
+
166
+
167
+ class GlinerClassifier:
168
+ """GLiNER2 on the CPU, loaded on first use; one forward pass at a time."""
169
+
170
+ def __init__(self, model: str, threads: int | None = None, entity_model: str | None = None) -> None:
171
+ self.model_id = model
172
+ # The decision model is trained to classify and finds few names; an extraction checkpoint can serve the entity
173
+ # endpoint instead, loaded on its first request.
174
+ self.entity_model_id = entity_model or model
175
+ self._threads = threads
176
+ self._clf: Any = None
177
+ self._extractor: Any = None
178
+ self._entity_extractor: Any = None
179
+ self._lock = threading.Lock()
180
+
181
+ def preload(self) -> None:
182
+ """Loads the model now, so the first request does not pay for it (2-3 s on the CPU)."""
183
+ with self._lock:
184
+ self._load()
185
+
186
+ def _load(self) -> Any:
187
+ if self._clf is None:
188
+ import torch
189
+ from gliner2 import AutoExtractor
190
+ from gliner2.classification import Classifier as GClassifier
191
+
192
+ if self._threads:
193
+ torch.set_num_threads(self._threads)
194
+ extractor = AutoExtractor.from_pretrained(self.model_id)
195
+ extractor.to("cpu")
196
+ self._extractor = extractor
197
+ self._clf = GClassifier(extractor, device="cpu")
198
+ return self._clf
199
+
200
+ def probabilities(self, text: str, task: str, labels: Mapping[str, str], instruction: str) -> dict[str, float]:
201
+ from gliner2.classification import ClassificationSchema
202
+
203
+ with self._lock:
204
+ clf = self._load()
205
+ schema = ClassificationSchema.from_dict(
206
+ {"tasks": {task: {"labels": dict(labels), "min_labels": 1, "max_labels": 1, "instruction": instruction}}}
207
+ )
208
+ return dict(clf.classify(text, schema).probabilities(task))
209
+
210
+
211
+ def _load_entities(self) -> Any:
212
+ if self._entity_extractor is None:
213
+ if self.entity_model_id == self.model_id:
214
+ self._load()
215
+ self._entity_extractor = self._extractor
216
+ else:
217
+ from gliner2 import AutoExtractor
218
+
219
+ extractor = AutoExtractor.from_pretrained(self.entity_model_id)
220
+ extractor.to("cpu")
221
+ self._entity_extractor = extractor
222
+ return self._entity_extractor
223
+
224
+ def entities(self, text: str, labels: list[str], threshold: float) -> list[dict[str, Any]]:
225
+ with self._lock:
226
+ result = self._load_entities().extract_entities_long(text, labels, threshold=threshold, include_confidence=True, include_spans=True)
227
+ found = result.get("entities", {}) if isinstance(result, dict) else {}
228
+ return [
229
+ {"label": label, "text": span.get("text"), "start": span.get("start"), "end": span.get("end"), "score": span.get("confidence")}
230
+ for label, spans in found.items()
231
+ for span in spans or []
232
+ if isinstance(span, dict)
233
+ ]
234
+
235
+
236
+ def make_handler(
237
+ classifier: Classifier, model: str, max_chars: int = MAX_CHARS, token: str | None = None, max_entity_chars: int = MAX_ENTITY_CHARS
238
+ ) -> type[BaseHTTPRequestHandler]:
239
+ expected = f"Bearer {token}" if token else None
240
+
241
+ class Handler(BaseHTTPRequestHandler):
242
+ def _authorized(self) -> bool:
243
+ # Without a token every caller is served, as on a single-user desktop. With one (the container sets
244
+ # DECIDER_TOKEN), /health stays open for the supervisor and everything else needs the header: under
245
+ # Apptainer the loopback is shared with every user of the machine.
246
+ if expected is None or hmac.compare_digest(self.headers.get("Authorization", ""), expected):
247
+ return True
248
+ self._send(401, {"error": "missing or wrong token"})
249
+ return False
250
+
251
+ def _send(self, status: int, payload: Mapping[str, Any]) -> None:
252
+ data = json.dumps(payload).encode()
253
+ self.send_response(status)
254
+ self.send_header("Content-Type", "application/json")
255
+ self.send_header("Content-Length", str(len(data)))
256
+ self.end_headers()
257
+ self.wfile.write(data)
258
+
259
+ def do_GET(self) -> None: # noqa: N802 (http.server naming)
260
+ if self.path == "/health":
261
+ self._send(200, {"status": "ok", "model": model})
262
+ else:
263
+ self._send(404, {"error": "not found"})
264
+
265
+ def do_POST(self) -> None: # noqa: N802
266
+ if not self._authorized():
267
+ return
268
+ path = self.path.rstrip("/")
269
+ if path not in ("/v1/systemone", "/systemone", "/v1/entities"):
270
+ self._send(404, {"error": "not found"})
271
+ return
272
+ try:
273
+ length = int(self.headers.get("Content-Length", "0"))
274
+ body = json.loads(self.rfile.read(length) or b"{}")
275
+ if not isinstance(body, dict):
276
+ raise ValueError("body is not an object")
277
+ except ValueError as exc:
278
+ self._send(400, {"error": f"bad request: {exc}"})
279
+ return
280
+ alive = lambda: not client_gone(self.connection) # noqa: E731
281
+ if path == "/v1/entities":
282
+ if not hasattr(classifier, "entities"):
283
+ self._send(501, {"error": "this server finds no entities"})
284
+ return
285
+ try:
286
+ self._send(200, extract(classifier, body, alive=alive, max_chars=max_entity_chars))
287
+ except ValueError as exc:
288
+ self._send(400, {"error": f"bad request: {exc}"})
289
+ except (Abandoned, BrokenPipeError):
290
+ return
291
+ except Exception as exc: # a model error must not kill the server
292
+ self._send(500, {"error": f"{type(exc).__name__}: {exc}"})
293
+ return
294
+ try:
295
+ self._send(200, decide(classifier, body, model, alive=alive, max_chars=max_chars))
296
+ except (Abandoned, BrokenPipeError):
297
+ return # the client timed out and left; nobody reads the answer
298
+ except Exception as exc: # a model error must not kill the server
299
+ self._send(500, {"error": f"{type(exc).__name__}: {exc}"})
300
+
301
+ def log_message(self, format: str, *args: Any) -> None: # quiet; systemd keeps errors
302
+ return
303
+
304
+ return Handler
305
+
306
+
307
+ def main() -> None:
308
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
309
+ parser.add_argument("--host", default="127.0.0.1")
310
+ parser.add_argument("--port", type=int, default=8781)
311
+ parser.add_argument("--model", default="fastino/GLiNER2.5-multi-Decide", help="a model id or a fine-tuned checkpoint directory")
312
+ parser.add_argument("--entity-model", default=None, help="the checkpoint for /v1/entities (names and addresses); default: --model")
313
+ parser.add_argument("--threads", type=int, default=2, help="torch threads: 8 arenas cost more memory than they win on one request")
314
+ parser.add_argument("--max-chars", type=int, default=MAX_CHARS, help="the longest text one decision reads; eager attention is n²")
315
+ parser.add_argument("--max-entity-chars", type=int, default=MAX_ENTITY_CHARS, help="the longest text the entity endpoint reads; it reads in chunks")
316
+ parser.add_argument("--no-preload", action="store_true", help="load the model on the first request instead of at start")
317
+ args = parser.parse_args()
318
+ classifier = GlinerClassifier(args.model, args.threads, args.entity_model)
319
+ if not args.no_preload:
320
+ classifier.preload()
321
+ server = ThreadingHTTPServer((args.host, args.port), make_handler(classifier, "gliner", args.max_chars, os.environ.get("DECIDER_TOKEN") or None, args.max_entity_chars))
322
+ print(f"decider on http://{args.host}:{args.port} ({args.model}, CPU)", flush=True)
323
+ server.serve_forever()
324
+
325
+
326
+ if __name__ == "__main__":
327
+ main()
@@ -0,0 +1,34 @@
1
+ [project]
2
+ name = "decider"
3
+ version = "0.1.0"
4
+ description = "Local GLiNER2 decision server for the Omacode plugins: guards, decisions and names, on the CPU"
5
+ requires-python = ">=3.12"
6
+ dependencies = [
7
+ # gliner2 2.1 and transformers 5: the decider's successor (container plan P6), gliner-guard-uniencoder tuned in
8
+ # train/, names its tokenizer TokenizersBackend, which transformers 4 cannot load. Pinned to releases older than two
9
+ # weeks (2026-11-21).
10
+ "gliner2[local]==2.1.0",
11
+ "transformers==5.22.0",
12
+ "protobuf>=5",
13
+ "sentencepiece>=0.2",
14
+ "torch>=2.6",
15
+ ]
16
+
17
+ [project.scripts]
18
+ decider = "decider.server:main"
19
+
20
+ # CPU-only torch: the 4060 stays free for llama-swap and the NPU for Whisper.
21
+ [tool.uv.sources]
22
+ torch = { index = "pytorch-cpu" }
23
+
24
+ [[tool.uv.index]]
25
+ name = "pytorch-cpu"
26
+ url = "https://download.pytorch.org/whl/cpu"
27
+ explicit = true
28
+
29
+ [build-system]
30
+ requires = ["hatchling"]
31
+ build-backend = "hatchling.build"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["decider"]