@omacode/micromanager 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +30 -2
- package/THIRD_PARTY.md +100 -0
- package/decider/.python-version +1 -0
- package/decider/README.md +35 -0
- package/decider/decider/__init__.py +1 -0
- package/decider/decider/server.py +327 -0
- package/decider/pyproject.toml +34 -0
- package/decider/uv.lock +1255 -0
- package/dist/agenda.js +51 -0
- package/dist/agents.js +58 -0
- package/dist/artifact/handoff.js +281 -0
- package/dist/ask.js +200 -0
- package/dist/backends.js +219 -0
- package/dist/backlog.js +414 -0
- package/dist/bench.js +427 -0
- package/dist/board.js +1 -0
- package/dist/brief.js +202 -0
- package/dist/browser.js +679 -0
- package/dist/budget.js +61 -0
- package/dist/catalog.js +187 -0
- package/dist/checkchange.js +145 -0
- package/dist/checkpoint.js +94 -0
- package/dist/cli.js +764 -0
- package/dist/comfy-gate.js +258 -0
- package/dist/compact.js +142 -0
- package/dist/config.js +344 -0
- package/dist/context/capture.js +1 -0
- package/dist/context/digest.js +1 -0
- package/dist/context/embed.js +1 -0
- package/dist/context/index.js +2 -0
- package/dist/context/ledger.js +1 -0
- package/dist/context/manager.js +1 -0
- package/dist/context/memory.js +1 -0
- package/dist/context/policy.js +1 -0
- package/dist/context/prices.js +1 -0
- package/dist/context/recall.js +1 -0
- package/dist/context/rules.js +1 -0
- package/dist/context/search.js +1 -0
- package/dist/context/status.js +1 -0
- package/dist/context/store.js +1 -0
- package/dist/context/summary.js +1 -0
- package/dist/context/tokens.js +1 -0
- package/dist/context/tools.js +1 -0
- package/dist/continuation.js +184 -0
- package/dist/contract.js +294 -0
- package/dist/contractround.js +178 -0
- package/dist/control.js +1 -0
- package/dist/creative-tools.js +237 -0
- package/dist/dataset.js +175 -0
- package/dist/decide.js +676 -0
- package/dist/decider.js +171 -0
- package/dist/design-shell.js +448 -0
- package/dist/design.js +1410 -0
- package/dist/desktop.js +44 -0
- package/dist/egress.js +156 -0
- package/dist/eval.js +60 -0
- package/dist/evolver.js +302 -0
- package/dist/features.js +193 -0
- package/dist/followups.js +32 -0
- package/dist/forms.js +195 -0
- package/dist/gate.js +108 -0
- package/dist/gatebox.js +46 -0
- package/dist/grants.js +189 -0
- package/dist/graph.js +65 -0
- package/dist/guard/index.js +1 -0
- package/dist/guard/wire.js +1 -0
- package/dist/helpers.js +85 -0
- package/dist/hooks.js +158 -0
- package/dist/image-models.js +117 -0
- package/dist/integration.js +3 -0
- package/dist/journal.js +1 -0
- package/dist/look.js +363 -0
- package/dist/memory.js +1 -0
- package/dist/mode.js +97 -0
- package/dist/native.js +3348 -0
- package/dist/nogit.js +259 -0
- package/dist/outcomes.js +148 -0
- package/dist/permission.js +35 -0
- package/dist/pick.js +89 -0
- package/dist/pipelines.js +262 -0
- package/dist/plan.js +641 -0
- package/dist/plandoc.js +211 -0
- package/dist/plugin.js +4736 -0
- package/dist/policy.js +58 -0
- package/dist/pools.js +1 -0
- package/dist/preview.js +274 -0
- package/dist/profile.js +165 -0
- package/dist/progress.js +1 -0
- package/dist/promote.js +313 -0
- package/dist/redact.js +1 -0
- package/dist/registry.js +179 -0
- package/dist/riskscore.js +126 -0
- package/dist/roles.js +1 -0
- package/dist/routing.js +1 -0
- package/dist/runner.js +1892 -0
- package/dist/sandbox.js +3 -0
- package/dist/sandboxgate.js +90 -0
- package/dist/scheduler.js +170 -0
- package/dist/services-main.js +131 -0
- package/dist/services.js +265 -0
- package/dist/session.js +241 -0
- package/dist/setup.js +423 -0
- package/dist/shell/decide.js +1 -0
- package/dist/shell/index.js +2 -0
- package/dist/shell/sandbox.js +1 -0
- package/dist/shell/wire.js +1 -0
- package/dist/skills.js +103 -0
- package/dist/state.js +1 -0
- package/dist/store.js +1 -0
- package/dist/switcher.js +1 -0
- package/dist/synth.js +418 -0
- package/dist/tools.js +477 -0
- package/dist/trials.js +223 -0
- package/dist/usage.js +1 -0
- package/dist/wait.js +167 -0
- package/dist/watchdog.js +476 -0
- package/dist/web-guidance.js +43 -0
- package/dist/which.js +20 -0
- package/dist/worktree/git.js +545 -0
- package/dist/writeguard.js +311 -0
- package/evolver/mm_evolve/__init__.py +1 -0
- package/evolver/mm_evolve/entry.py +3 -0
- package/evolver/mm_evolve/evaluator.py +119 -0
- package/evolver/mm_evolve/llm.py +76 -0
- package/evolver/mm_evolve/run.py +89 -0
- package/evolver/mm_evolve/spec.py +62 -0
- package/evolver/pyproject.toml +21 -0
- package/evolver/uv.lock +772 -0
- package/package.json +74 -4
- package/skills/THIRD_PARTY.md +58 -0
- package/skills/code-review/SKILL.md +46 -0
- package/skills/deck/SKILL.md +98 -0
- package/skills/deliberate/SKILL.md +39 -0
- package/skills/design/SKILL.md +150 -0
- package/skills/diagnosing-bugs/SKILL.md +75 -0
- package/skills/image/SKILL.md +66 -0
- package/skills/orchestrator/SKILL.md +107 -0
- package/skills/receiving-code-review/SKILL.md +36 -0
- package/skills/research/SKILL.md +18 -0
- package/skills/tdd/SKILL.md +56 -0
- package/skills/tdd/mocking.md +59 -0
- package/skills/tdd/tests.md +77 -0
- package/skills/verification-before-completion/SKILL.md +50 -0
- package/skills/video/SKILL.md +97 -0
- package/skills/web/SKILL.md +60 -0
|
@@ -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"]
|