@0perator/operator 0.1.326 → 0.1.329
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/dist/background/notices.js +40 -0
- package/dist/cli.js +29 -15
- package/dist/config/persona.js +3 -2
- package/dist/engine/agent.js +21 -2
- package/dist/engine/aurora.js +1 -1
- package/dist/engine/cli.js +1171 -0
- package/dist/engine/loop-guard.js +71 -6
- package/dist/router/models.js.bak +78 -0
- package/dist/router/models.js.bak-1791259923 +78 -0
- package/dist/router/models.js.bak-pre-gateway +78 -0
- package/dist/router/models.js.bak-pre-patch2 +78 -0
- package/dist/router/models.js.bak2 +78 -0
- package/dist/services/model-autodetect.js +240 -0
- package/dist/session.js +10 -3
- package/dist/tools/native-redirect.js +140 -0
- package/dist/tools/power-tools.js +627 -0
- package/dist/tools/registry.js.bak-1791259948 +1914 -0
- package/dist/tools/registry.js.bak-pre-plugins +1914 -0
- package/dist/ui/BusTray.js +70 -0
- package/dist/ui/resize.js +160 -0
- package/package.json +1 -1
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// Model auto-detect boot — connect to whatever model is HEALTHY, local or remote, instead of hard-launching
|
|
2
|
+
// one port and freezing the boot when it is down. (Incident 2026-10-10: the JL2 Aurora gguf vanished, the
|
|
3
|
+
// boot kickstarted com.imi.aurora-serve and HARD-WAITED 90s on a dead :8097, then quit — bricking Operator
|
|
4
|
+
// while cortana, a healthy 35B, answered on JL1:8112 the whole time.)
|
|
5
|
+
//
|
|
6
|
+
// The shape, and the split that makes it testable:
|
|
7
|
+
// • buildCandidates() PURE — the ordered list to try: (a) the active model's endpoint, (b) same-model
|
|
8
|
+
// standbys (failover, fleet nodes), (c) every other registry profile; cloud/BYO last.
|
|
9
|
+
// • detectBoot() the decision flow over an INJECTED probe/launch/sleep (no network in tests):
|
|
10
|
+
// probe → first healthy by priority wins → (only if none) wait out a model that is
|
|
11
|
+
// already loading → cloud tier → Service-lever launch as the LAST resort → degraded.
|
|
12
|
+
// • probeCandidate() the real network probe (short timeout, /health and /v1/models raced in parallel).
|
|
13
|
+
// Nothing here knows what "aurora" is: every entry is just {base, model, ctx}. Aurora is one candidate.
|
|
14
|
+
import { authHeaders } from "../engine/aurora.js";
|
|
15
|
+
import { endpointBase } from "../router/models.js";
|
|
16
|
+
const norm = (base) => base.replace(/\/+$/, "").toLowerCase();
|
|
17
|
+
const keyOf = (c) => `${norm(c.base)}|${c.model}`;
|
|
18
|
+
/** host:port of a base, for the one-line "→ model: …" notice. Falls back to the raw string. */
|
|
19
|
+
export function hostPort(base) {
|
|
20
|
+
try {
|
|
21
|
+
return new URL(base).host;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return base;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** The ordered candidate list. PURE. Priority: active → standbys → registry (local/LAN first, cloud last);
|
|
28
|
+
* de-duplicated on base+model so the registry's own copy of the active profile never probes twice. */
|
|
29
|
+
export function buildCandidates(i) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
const add = (c) => {
|
|
33
|
+
const k = keyOf(c);
|
|
34
|
+
if (seen.has(k))
|
|
35
|
+
return;
|
|
36
|
+
seen.add(k);
|
|
37
|
+
out.push(c);
|
|
38
|
+
};
|
|
39
|
+
const a = i.active;
|
|
40
|
+
// An active BYO profile (the owner's /model qwen3.8-max) carries its vendor key + dialect on the registry entry.
|
|
41
|
+
const ap = i.registry.find((p) => p.id === a.id);
|
|
42
|
+
add({ id: a.id, label: a.label ?? a.id, base: a.base, model: a.model, ctx: a.ctx, profileId: a.id, token: a.token ?? (ap?.byo ? i.byoToken?.(ap.byo) : undefined), transport: a.transport ?? ap?.transport, cloud: false, source: "active" });
|
|
43
|
+
if (i.enabled === false)
|
|
44
|
+
return out;
|
|
45
|
+
for (const s of i.standby) {
|
|
46
|
+
if (!s.base)
|
|
47
|
+
continue;
|
|
48
|
+
add({ id: s.id, label: s.id, base: s.base, model: s.model, ctx: s.ctx, cloud: false, source: "standby" });
|
|
49
|
+
}
|
|
50
|
+
const profiles = i.registry.filter((p) => p.kind === "single" && !!p.endpoint && p.autodetect !== false);
|
|
51
|
+
const cloud = (p) => !!p.byo;
|
|
52
|
+
for (const p of [...profiles.filter((p) => !cloud(p)), ...(i.allowCloud === false ? [] : profiles.filter(cloud))]) {
|
|
53
|
+
const token = p.byo ? i.byoToken?.(p.byo) : undefined;
|
|
54
|
+
if (p.byo && !token)
|
|
55
|
+
continue; // a connector with no resolvable key can never answer — don't list a guaranteed ✗
|
|
56
|
+
add({ id: p.id, label: p.label, base: endpointBase(p.endpoint), model: p.model ?? p.id, ctx: p.ctx ?? a.ctx, profileId: p.id, token, transport: p.transport, cloud: cloud(p), source: "registry" });
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
/** The router chain to adopt for a chosen candidate: it first, then the other LOCAL candidates that serve the
|
|
61
|
+
* SAME model (the aurora nodes), so a mid-session death still hops to a sibling instead of stranding. A
|
|
62
|
+
* different model is never mixed in — a failover must not silently change which model answers. PURE. */
|
|
63
|
+
export function routerChain(chosen, all) {
|
|
64
|
+
const toEp = (c) => ({ name: c.id, base: c.base, model: c.model, ctxLimit: c.ctx, token: c.token, transport: c.transport });
|
|
65
|
+
const sib = all.filter((c) => c !== chosen && !c.cloud && !chosen.cloud && c.model === chosen.model && keyOf(c) !== keyOf(chosen));
|
|
66
|
+
return [toEp(chosen), ...sib.map(toEp)];
|
|
67
|
+
}
|
|
68
|
+
/** Probe one candidate. `/health` (llama.cpp, mlx_lm, gateways) and `/v1/models` (Ollama, any OpenAI-compatible
|
|
69
|
+
* server with no /health) are raced IN PARALLEL under ONE short timeout, so the worst case is the timeout, not
|
|
70
|
+
* a serial pair. ready = a 2xx that doesn't say it is still starting; loading = the port answered 503 (llama.cpp
|
|
71
|
+
* serves 503 while it mmaps the model — alive, must not be restarted); down = refused / timed out / 4xx. Never throws. */
|
|
72
|
+
export async function probeCandidate(c, o = {}) {
|
|
73
|
+
const f = o.fetchImpl ?? fetch;
|
|
74
|
+
const ctrl = new AbortController();
|
|
75
|
+
const timer = setTimeout(() => ctrl.abort(), o.timeoutMs ?? 2500);
|
|
76
|
+
const onAbort = () => ctrl.abort();
|
|
77
|
+
o.signal?.addEventListener("abort", onAbort, { once: true });
|
|
78
|
+
const headers = authHeaders({ base: c.base, model: c.model, token: c.token });
|
|
79
|
+
const base = c.base.replace(/\/+$/, "");
|
|
80
|
+
const get = async (path) => {
|
|
81
|
+
try {
|
|
82
|
+
const r = await f(`${base}${path}`, { signal: ctrl.signal, headers });
|
|
83
|
+
if (r.status === 503)
|
|
84
|
+
return "loading";
|
|
85
|
+
if (!r.ok)
|
|
86
|
+
return "down";
|
|
87
|
+
if (path !== "/health")
|
|
88
|
+
return "ready";
|
|
89
|
+
const j = await r.json().catch(() => undefined);
|
|
90
|
+
return j && typeof j.status === "string" && j.status !== "ok" ? "loading" : "ready"; // 200 {"status":"loading model"} is alive-but-not-serving
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return "down";
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
try {
|
|
97
|
+
// First `ready` wins at once (a healthy endpoint must not wait on its slower sibling request); otherwise the
|
|
98
|
+
// verdict is "loading" if either request saw a 503, else "down".
|
|
99
|
+
return await new Promise((resolve) => {
|
|
100
|
+
const seen = [];
|
|
101
|
+
for (const p of [get("/health"), get("/v1/models")]) {
|
|
102
|
+
void p.then((s) => {
|
|
103
|
+
if (s === "ready")
|
|
104
|
+
return resolve("ready");
|
|
105
|
+
seen.push(s);
|
|
106
|
+
if (seen.length === 2)
|
|
107
|
+
resolve(seen.includes("loading") ? "loading" : "down");
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
o.signal?.removeEventListener("abort", onAbort);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** Fire every probe in parallel, then walk them in PRIORITY order: the first `ready` wins the moment every
|
|
118
|
+
* higher-priority candidate has settled — so a healthy active endpoint returns at once and never waits on a
|
|
119
|
+
* dead LAN host's timeout further down the list. Stragglers are aborted. */
|
|
120
|
+
async function pickFirstReady(cands, deps) {
|
|
121
|
+
const ctrl = new AbortController();
|
|
122
|
+
const memo = new Map(); // one probe per base+token — qwen3.8-max and -flash share a host
|
|
123
|
+
const run = (c) => {
|
|
124
|
+
const k = `${norm(c.base)}|${c.token ? "t" : ""}`;
|
|
125
|
+
let p = memo.get(k);
|
|
126
|
+
if (!p) {
|
|
127
|
+
p = deps.probe(c, ctrl.signal).catch(() => "down");
|
|
128
|
+
memo.set(k, p);
|
|
129
|
+
}
|
|
130
|
+
return p;
|
|
131
|
+
};
|
|
132
|
+
const pending = cands.map(run);
|
|
133
|
+
const attempts = [];
|
|
134
|
+
try {
|
|
135
|
+
for (let i = 0; i < cands.length; i++) {
|
|
136
|
+
const status = await pending[i];
|
|
137
|
+
attempts.push({ candidate: cands[i], status });
|
|
138
|
+
if (status === "ready")
|
|
139
|
+
return { chosen: cands[i], attempts };
|
|
140
|
+
}
|
|
141
|
+
return { attempts };
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
ctrl.abort();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** The boot decision flow. Never throws, never blocks longer than: one probe timeout (+ `waitSec` if a model is
|
|
148
|
+
* already loading, + the caller-bounded launch when nothing is healthy and one is configured). */
|
|
149
|
+
export async function detectBoot(cands, deps) {
|
|
150
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
151
|
+
const now = deps.now ?? Date.now;
|
|
152
|
+
const waitSec = deps.waitSec ?? 25;
|
|
153
|
+
const local = cands.filter((c) => !c.cloud);
|
|
154
|
+
const cloud = cands.filter((c) => c.cloud);
|
|
155
|
+
const tried = [];
|
|
156
|
+
const note = (a) => { for (const x of a)
|
|
157
|
+
if (!tried.some((t) => t.candidate === x.candidate))
|
|
158
|
+
tried.push(x); };
|
|
159
|
+
const done = (chosen, launch) => {
|
|
160
|
+
const failed = tried.filter((t) => t.candidate !== chosen && t.status !== "ready");
|
|
161
|
+
if (launch?.state === "started")
|
|
162
|
+
return { kind: "launched", chosen, tried: failed, launch };
|
|
163
|
+
return { kind: chosen === cands[0] ? "primary" : "alternate", chosen, tried: failed };
|
|
164
|
+
};
|
|
165
|
+
const first = await pickFirstReady(local, deps);
|
|
166
|
+
note(first.attempts);
|
|
167
|
+
if (first.chosen)
|
|
168
|
+
return done(first.chosen);
|
|
169
|
+
// Something is already coming up on its own (llama.cpp 503 while it mmaps): wait it out, bounded — never
|
|
170
|
+
// restart a mid-load model, and never freeze on it past `waitSec`.
|
|
171
|
+
const loading = local.filter((c) => tried.some((t) => t.candidate === c && t.status === "loading"));
|
|
172
|
+
if (loading.length) {
|
|
173
|
+
deps.onProgress?.(`${loading[0].label} is loading…`);
|
|
174
|
+
const deadline = now() + waitSec * 1000;
|
|
175
|
+
while (now() < deadline) {
|
|
176
|
+
await sleep(1000);
|
|
177
|
+
const r = await pickFirstReady(loading, deps);
|
|
178
|
+
for (const a of r.attempts) {
|
|
179
|
+
const t = tried.find((x) => x.candidate === a.candidate);
|
|
180
|
+
if (t)
|
|
181
|
+
t.status = a.status;
|
|
182
|
+
}
|
|
183
|
+
if (r.chosen)
|
|
184
|
+
return done(r.chosen);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (cloud.length) {
|
|
188
|
+
deps.onProgress?.("no local model answered — trying connected cloud models…");
|
|
189
|
+
const r = await pickFirstReady(cloud, deps);
|
|
190
|
+
note(r.attempts);
|
|
191
|
+
if (r.chosen)
|
|
192
|
+
return done(r.chosen);
|
|
193
|
+
}
|
|
194
|
+
// LAST resort — and never while something is mid-load (that service is already starting itself).
|
|
195
|
+
let launch;
|
|
196
|
+
if (deps.launch && !loading.length) {
|
|
197
|
+
deps.onProgress?.("no model reachable — trying the local launchd model…");
|
|
198
|
+
launch = await deps.launch().catch((e) => ({ state: "down", detail: String(e?.message ?? e) }));
|
|
199
|
+
if (launch.state === "up" || launch.state === "started") {
|
|
200
|
+
const r = await pickFirstReady(local, deps);
|
|
201
|
+
for (const a of r.attempts) {
|
|
202
|
+
const t = tried.find((x) => x.candidate === a.candidate);
|
|
203
|
+
if (t)
|
|
204
|
+
t.status = a.status;
|
|
205
|
+
else
|
|
206
|
+
tried.push(a);
|
|
207
|
+
}
|
|
208
|
+
if (r.chosen)
|
|
209
|
+
return done(r.chosen, launch);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return { kind: "degraded", tried, launch };
|
|
213
|
+
}
|
|
214
|
+
/** What a boot outcome says about ONE base, for the dashboard's service tiles. undefined = it was never probed
|
|
215
|
+
* (e.g. a healthy higher-priority endpoint won before the walk reached it) — never claim a state we didn't observe. PURE. */
|
|
216
|
+
export function stateOfBase(o, base) {
|
|
217
|
+
const b = norm(base);
|
|
218
|
+
if (o.kind !== "degraded" && norm(o.chosen.base) === b)
|
|
219
|
+
return o.kind === "launched" ? "started" : "up";
|
|
220
|
+
return o.tried.some((t) => norm(t.candidate.base) === b) ? "down" : undefined;
|
|
221
|
+
}
|
|
222
|
+
const mark = (s) => (s === "ready" ? "✓" : s === "loading" ? "…" : "✗");
|
|
223
|
+
/** The scrollback notice for an outcome — "" for the happy path (the services line already confirms it). PURE. */
|
|
224
|
+
export function describeOutcome(o) {
|
|
225
|
+
if (o.kind === "primary")
|
|
226
|
+
return "";
|
|
227
|
+
if (o.kind === "degraded") {
|
|
228
|
+
const rows = o.tried.map((t) => ` ${mark(t.status)} ${t.candidate.id} ${hostPort(t.candidate.base)} ${t.status}`);
|
|
229
|
+
const lane = o.launch ? `\n launch: ${o.launch.detail ?? o.launch.state}` : "";
|
|
230
|
+
return `no model reachable — tried:\n${rows.join("\n")}${lane}\nOperator is open but has no model yet. Pick one with /model <id>, pin an endpoint with /route <name>, or point Operator at a running model in your settings and relaunch. The next message re-checks.`;
|
|
231
|
+
}
|
|
232
|
+
const c = o.chosen;
|
|
233
|
+
const where = `${c.id} @ ${hostPort(c.base)}`;
|
|
234
|
+
const cloudNote = c.cloud ? " (cloud — your own API key; nothing local was reachable)" : "";
|
|
235
|
+
// Two endpoints can share an id (KODE_AURORA re-points the active operator-1m while the registry still lists its
|
|
236
|
+
// own) — name the host only where the id alone would be ambiguous.
|
|
237
|
+
const nameOf = (c) => (o.tried.filter((t) => t.candidate.id === c.id).length > 1 ? `${c.id}@${hostPort(c.base)}` : c.id);
|
|
238
|
+
const skipped = o.tried.length ? `\n skipped: ${o.tried.map((t) => `${nameOf(t.candidate)} (${t.status})`).join(", ")}` : "";
|
|
239
|
+
return `→ model: ${where}${cloudNote}${o.kind === "launched" ? " (launched)" : ""}${skipped}`;
|
|
240
|
+
}
|
package/dist/session.js
CHANGED
|
@@ -78,14 +78,15 @@ function makeSpawnTool(handler) {
|
|
|
78
78
|
name: "spawn_agent",
|
|
79
79
|
safe: false,
|
|
80
80
|
description: "Spawn sub-agents: isolated sessions on the same model, each with its own shell; only each one's final report " +
|
|
81
|
-
"returns
|
|
81
|
+
"returns — delivered as a message at the start of your NEXT turn, never mid-turn. Pass every subtask in `tasks` — one entry spawns " +
|
|
82
82
|
"one sub-agent, several run in parallel (2 at a time plus 2 queued by default — settings.background.maxConcurrent; " +
|
|
83
83
|
"past the cap the call tells you). When you decide to delegate, make THIS call in the same round — never announce " +
|
|
84
84
|
"\"I'll spawn sub-agents\" without calling spawn_agent. Keep working meanwhile: NEVER sleep, poll or wait for a " +
|
|
85
85
|
"result (agent_status checks state, message_agent steers, stop_agent halts; a sub-agent id is NOT a shell job id — " +
|
|
86
86
|
"bash_output/bash_kill will just error). NEVER re-spawn a task because its result hasn't arrived — it is still " +
|
|
87
87
|
"working. Then finish only what does NOT depend on them, give a one-line status and END YOUR TURN — reports " +
|
|
88
|
-
"re-enter as new messages; a turn that keeps polling holds the model slot and starves the sub-agents
|
|
88
|
+
"re-enter as new messages; a turn that keeps polling holds the model slot and starves the sub-agents (on a " +
|
|
89
|
+
"single-slot endpoint the engine ends the turn itself once you have dispatched and have no independent work in the round).\n" +
|
|
89
90
|
"USE FOR: reasoning-heavy subtasks, work that would flood your context, or independent parallel workstreams " +
|
|
90
91
|
"(research per area, review per module, search per tree, drafting a file).\n" +
|
|
91
92
|
"DO NOT USE FOR: a single tool call; mechanical steps with no reasoning; anything that needs the user (sub-agents " +
|
|
@@ -324,6 +325,8 @@ export class Session {
|
|
|
324
325
|
maxTurnTokens;
|
|
325
326
|
maxTurnWallClockMs;
|
|
326
327
|
loopGuard;
|
|
328
|
+
liveAgents;
|
|
329
|
+
wakeTurn = false; // the turn in flight was started by the shell to deliver a report / job notice, not typed by the owner
|
|
327
330
|
hooks;
|
|
328
331
|
cwd;
|
|
329
332
|
unattended;
|
|
@@ -432,6 +435,7 @@ export class Session {
|
|
|
432
435
|
this.maxTurnTokens = cfg.maxTurnTokens;
|
|
433
436
|
this.maxTurnWallClockMs = cfg.maxTurnWallClockMs;
|
|
434
437
|
this.loopGuard = cfg.loopGuard;
|
|
438
|
+
this.liveAgents = cfg.liveAgents;
|
|
435
439
|
this.hooks = cfg.hooks;
|
|
436
440
|
this.cwd = cfg.cwd;
|
|
437
441
|
this.unattended = cfg.unattended === true;
|
|
@@ -1036,9 +1040,10 @@ export class Session {
|
|
|
1036
1040
|
// `turnDirective` is an optional strong, high-priority instruction appended to THIS turn's system prompt
|
|
1037
1041
|
// (e.g. the classifier gate's options-vs-act directive). Per-turn + reversible: it touches only this turn,
|
|
1038
1042
|
// the same way thinkDirective/budgetDirective fold into sysWithThink.
|
|
1039
|
-
async send(text, h = {}, turnDirective) {
|
|
1043
|
+
async send(text, h = {}, turnDirective, flags) {
|
|
1040
1044
|
if (this.ctrl)
|
|
1041
1045
|
throw new Error("Session.send called while a turn is in flight — serialize turns (the shell queues input)");
|
|
1046
|
+
this.wakeTurn = flags?.wake === true;
|
|
1042
1047
|
// Arm the interrupt controller BEFORE maybeRecall. The host flips status to "thinking" the instant send() is
|
|
1043
1048
|
// called, so an esc during first-turn memory recall / MCP discovery (which hit the network and can be slow)
|
|
1044
1049
|
// would otherwise no-op — this.ctrl was null until execute(). execute() reuses this same controller.
|
|
@@ -1057,6 +1062,7 @@ export class Session {
|
|
|
1057
1062
|
}
|
|
1058
1063
|
finally {
|
|
1059
1064
|
this.ctrl = null; // execute() nulls on its own path too; this also covers the maybeRecall-abort early return
|
|
1065
|
+
this.wakeTurn = false;
|
|
1060
1066
|
}
|
|
1061
1067
|
}
|
|
1062
1068
|
/** MOA turn (MOA-DESIGN.md): fan out to settings.moa's proposers in parallel, then run the
|
|
@@ -1180,6 +1186,7 @@ export class Session {
|
|
|
1180
1186
|
summarize: this.summarize,
|
|
1181
1187
|
preservedState: () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list
|
|
1182
1188
|
background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
|
|
1189
|
+
liveSubAgents: this.wakeTurn ? this.liveAgents : undefined, // a wake turn with sub-agents live yields from its first idle round
|
|
1183
1190
|
maxTokens: this.maxTokens,
|
|
1184
1191
|
maxTurnTokens: this.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
|
|
1185
1192
|
maxTurnWallClockMs: this.maxTurnWallClockMs, // opt-in per-turn TIME ceiling; the brake on hour-long crawling turns
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Pre-exec redirect for "reinvent a native tool" shell commands. A model whose image/video/vision/voice
|
|
2
|
+
// tool hit a transient worker outage used to read "work around it" as a mandate to BUILD the stack: it
|
|
3
|
+
// pip-installed comfy-cli, cloned ComfyUI and downloaded diffusion weights onto the serving box (live aurora
|
|
4
|
+
// session, 10-09) — instead of retrying the native tool it already had. This is the last line of defence at
|
|
5
|
+
// the shell: an install/download verb COMBINED WITH a media-stack token is answered with a TOOL RESULT (never
|
|
6
|
+
// a second system message — llama.cpp's chat template 400s on that, see engine/unrestricted.ts) that points
|
|
7
|
+
// at the tool the model already has. Pure and unit-tested (test/native-redirect.test.mts); shellExec and
|
|
8
|
+
// shellBackground in registry.ts hook it at the top, modeled on subAgentRedirect.
|
|
9
|
+
//
|
|
10
|
+
// A weight download (*.safetensors/.gguf/.ckpt, `hf download`) is HARD-BLOCKED every time: it pins GBs on the
|
|
11
|
+
// box that serves the model and collapses decode to ~1 tok/s. A generic install that merely mentions a media
|
|
12
|
+
// token is redirected ONCE — the identical command re-issued goes through, so a legitimate non-media install
|
|
13
|
+
// is never permanently blocked. KODE_ALLOW_TOOLING_INSTALL=1 (set by the OWNER in the engine's environment;
|
|
14
|
+
// a `export` inside the model's shell cannot reach it) lifts the guard entirely.
|
|
15
|
+
//
|
|
16
|
+
// Heuristic, not a security boundary: it catches the honest mistake (the plain command), not a model that
|
|
17
|
+
// hides the install in a script it writes and then runs. The levers that matter are the tool failure
|
|
18
|
+
// semantics and the capability map (registry.ts); this is the backstop.
|
|
19
|
+
const STACKS = [
|
|
20
|
+
{
|
|
21
|
+
name: "image",
|
|
22
|
+
tools: "`image_generate` (FLUX fast default; `quality: \"photoreal\"` or a face `reference` → RealVisXL via the identity broker) and `image_analyze`",
|
|
23
|
+
re: /\bcomfy(?:ui|[-_]cli)?\b|\bdiffusers\b|\bdiffusionkit\b|\bmflux\b|\bsdxl\b|\bstable[-_ .]?diffusion\w*|\brealvis\w*|\bjuggernaut\w*|\bflux[.\-_]?1\b|\bflux[-_](?:dev|schnell|pro)\b|\bblack-forest-labs\b|\binference\.sh\b|\binfsh\b|\binvokeai\b|\bfooocus\b|\bautomatic1111\b|\bsd-webui\b|\bip[-_]adapter\w*|\binsightface\b|\.safetensors\b|\.ckpt\b/i,
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
name: "video",
|
|
27
|
+
tools: "`video_generate` (LTX) and `video_analyze`",
|
|
28
|
+
re: /\bltx[-_]?video\b|\banimatediff\b|\bcogvideo\w*|\bstable[-_]video\b|\bwan2\S*|\bhunyuan[-_]?video\b|\bmochi\b/i,
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: "vision",
|
|
32
|
+
tools: "`image_analyze` / `video_analyze` (Qwen2-VL)",
|
|
33
|
+
re: /\bllava\b|\bqwen[\d.]*[-_]?vl\b|\bmlx[-_]vlm\b|\bmoondream\b|\bpaligemma\b|\bminicpm[-_]v\b/i,
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: "voice",
|
|
37
|
+
tools: "`voice_speak` / `voice_transcribe` (Kokoro + whisper.cpp)",
|
|
38
|
+
re: /\bwhisper\w*|\bkokoro\w*/i,
|
|
39
|
+
},
|
|
40
|
+
];
|
|
41
|
+
const GENERIC_TOOLS = "the native media tools (`image_generate`, `video_generate`, `image_analyze`, `video_analyze`, `voice_speak`, `voice_transcribe`)";
|
|
42
|
+
const WEIGHT_EXT = /\.(?:safetensors|gguf|ckpt)\b/i;
|
|
43
|
+
const HF_RESOLVE = /huggingface\.co\/\S*\/resolve\//i;
|
|
44
|
+
const HF_PY = /\b(?:snapshot_download|hf_hub_download)\b/;
|
|
45
|
+
// Install/launch verbs, anchored at the START of a command segment (after wrappers are stripped) — so
|
|
46
|
+
// `grep "pip install whisper" docs/` and `echo "brew install llava"` (verb not at command position) pass.
|
|
47
|
+
const INSTALL_VERBS = [
|
|
48
|
+
/^(?:pip3?|python3?(?:\.\d+)?\s+-m\s+pip|uv\s+pip|conda|mamba|micromamba)\s+(?:-\S+\s+)*install\b/,
|
|
49
|
+
/^pipx\s+(?:-\S+\s+)*(?:install|run)\b/,
|
|
50
|
+
/^uv\s+(?:add|tool\s+(?:install|run))\b/,
|
|
51
|
+
/^(?:uvx|npx|poetry\s+add)\b/,
|
|
52
|
+
/^(?:brew|port|apt(?:-get)?|dnf|yum|apk)\s+(?:-\S+\s+)*(?:install|reinstall)\b/,
|
|
53
|
+
/^(?:npm|pnpm|bun)\s+(?:-\S+\s+)*(?:i|install|add)\b/,
|
|
54
|
+
/^yarn\s+(?:global\s+)?add\b/,
|
|
55
|
+
/^(?:cargo|go)\s+install\b/,
|
|
56
|
+
/^git\s+clone\b/,
|
|
57
|
+
/^docker\s+(?:pull|run)\b/,
|
|
58
|
+
/^ollama\s+pull\b/,
|
|
59
|
+
/^(?:comfy(?:-cli)?|infsh)\b/,
|
|
60
|
+
];
|
|
61
|
+
// Leading wrappers that do not change what actually runs: sudo/nohup/time/env FOO=x, a subshell paren, a
|
|
62
|
+
// VAR=val prefix, `bash -c '`, an opening quote.
|
|
63
|
+
const WRAPPER = /^(?:[({!]\s*|(?:sudo|nohup|time|exec|command|builtin|caffeinate|env|xargs)\s+(?:-\S+\s+)*|\w+=\S*\s+|(?:ba|z)?sh\s+-\w*c\s+|eval\s+|["'`]\s*)/;
|
|
64
|
+
function segments(command) {
|
|
65
|
+
const flat = command.replace(/\d*>&\d*/g, " ").replace(/&>>?/g, " ");
|
|
66
|
+
return flat.split(/&&|\|\||;|\n|&(?=\s|$)/).map((s) => s.trim()).filter(Boolean);
|
|
67
|
+
}
|
|
68
|
+
function unwrap(seg) {
|
|
69
|
+
let s = seg;
|
|
70
|
+
for (let i = 0; i < 8; i++) {
|
|
71
|
+
const m = WRAPPER.exec(s);
|
|
72
|
+
if (!m?.[0])
|
|
73
|
+
break;
|
|
74
|
+
s = s.slice(m[0].length);
|
|
75
|
+
}
|
|
76
|
+
return s;
|
|
77
|
+
}
|
|
78
|
+
const curlDownloads = (s) => /(?:^|\s)(?:-[A-Za-z]*[oO][A-Za-z]*|--output(?:-dir)?|--remote-name(?:-all)?)(?=\s|=|$)/.test(s) || />\s*\S/.test(s) || /\|\s*(?:sudo\s+)?(?:ba|z)?sh\b/.test(s);
|
|
79
|
+
function stackOf(text) {
|
|
80
|
+
return STACKS.find((st) => st.re.test(text));
|
|
81
|
+
}
|
|
82
|
+
const blockMsg = (tools) => `error: not run — downloading model weights onto this box is blocked. It pins GBs on the machine that serves ` +
|
|
83
|
+
`your own model (decode collapses to ~1 tok/s) and rebuilds a capability you ALREADY HAVE: ${tools}. Use ` +
|
|
84
|
+
`that. If it errors, the worker is DOWN (an outage): retry once, then TELL THE OWNER — never install ` +
|
|
85
|
+
`tooling or fetch weights to substitute. Only the owner can lift this block.`;
|
|
86
|
+
const redirectMsg = (tools) => `error: not run — you already have ${tools} for this — use it. A worker being down is an outage to ` +
|
|
87
|
+
`retry/report to the owner, not something to install or rebuild. If this install is genuinely unrelated ` +
|
|
88
|
+
`to image/video/vision/voice, re-issue the identical command once and it will run.`;
|
|
89
|
+
/** Classify one shell command. Pure: no env, no state. null = nothing to say. */
|
|
90
|
+
export function classifyToolingCommand(command) {
|
|
91
|
+
// An inline python snippet (-c, or a heredoc whose lines are not command-position) that calls the HF
|
|
92
|
+
// weight downloaders is a weight download however it is split.
|
|
93
|
+
if (/^\s*python3?\b/.test(command) && HF_PY.test(command)) {
|
|
94
|
+
const stack = stackOf(command);
|
|
95
|
+
return { kind: "block", capability: stack?.name ?? "media", message: blockMsg(stack?.tools ?? GENERIC_TOOLS) };
|
|
96
|
+
}
|
|
97
|
+
let redirect = null;
|
|
98
|
+
for (const raw of segments(command)) {
|
|
99
|
+
const seg = unwrap(raw);
|
|
100
|
+
const stack = stackOf(seg);
|
|
101
|
+
const hfDownload = /^(?:hf|huggingface-cli)\s+(?:-\S+\s+)*download\b/.test(seg) && !/--repo-type[=\s]+(?:dataset|space)\b/.test(seg);
|
|
102
|
+
const fetcher = /^(?:wget|aria2c|axel)\b/.test(seg) || (/^curl\b/.test(seg) && curlDownloads(seg)) || /^git\s+lfs\s+(?:pull|clone)\b/.test(seg);
|
|
103
|
+
if (hfDownload || (fetcher && (WEIGHT_EXT.test(seg) || HF_RESOLVE.test(seg)))) {
|
|
104
|
+
const tools = stack?.tools ?? GENERIC_TOOLS;
|
|
105
|
+
return { kind: "block", capability: stack?.name ?? "media", message: blockMsg(tools) };
|
|
106
|
+
}
|
|
107
|
+
if (!redirect && stack && (fetcher || INSTALL_VERBS.some((re) => re.test(seg)))) {
|
|
108
|
+
redirect = { kind: "redirect", capability: stack.name, message: redirectMsg(stack.tools) };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return redirect;
|
|
112
|
+
}
|
|
113
|
+
// Flag- and pip-spelling-insensitive identity of a command: `pip install -U comfy-cli`, `pip3 install comfy-cli
|
|
114
|
+
// --break-system-packages` and `python3 -m pip install comfy-cli` are the same attempt, so the second is the
|
|
115
|
+
// "identical" one that passes.
|
|
116
|
+
function attemptKey(command) {
|
|
117
|
+
return command.toLowerCase().replace(/\s+/g, " ")
|
|
118
|
+
.replace(/\b(?:python3?(?:\.\d+)? -m pip3?|uv pip|pip3)\b/g, "pip")
|
|
119
|
+
.replace(/(?:^| )--?[a-z][\w-]*(?:=\S+)?(?= |$)/g, "").trim();
|
|
120
|
+
}
|
|
121
|
+
const SEEN_MAX = 200;
|
|
122
|
+
/** The shell hook. Returns the tool-result string to answer with INSTEAD of running the command, or null to
|
|
123
|
+
* run it. `seen` carries the redirect-once memory (the caller owns it, module-level in registry.ts). */
|
|
124
|
+
export function nativeToolRedirect(command, seen, env = process.env) {
|
|
125
|
+
const allow = env.KODE_ALLOW_TOOLING_INSTALL;
|
|
126
|
+
if (allow === "1" || allow === "true")
|
|
127
|
+
return null;
|
|
128
|
+
const v = classifyToolingCommand(command);
|
|
129
|
+
if (!v)
|
|
130
|
+
return null;
|
|
131
|
+
if (v.kind === "block")
|
|
132
|
+
return v.message;
|
|
133
|
+
const key = attemptKey(command);
|
|
134
|
+
if (seen.has(key))
|
|
135
|
+
return null; // the identical attempt, re-issued after the redirect: let it through
|
|
136
|
+
if (seen.size >= SEEN_MAX)
|
|
137
|
+
seen.clear();
|
|
138
|
+
seen.add(key);
|
|
139
|
+
return v.message;
|
|
140
|
+
}
|