@0perator/operator 0.1.263 → 0.1.275

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 (38) hide show
  1. package/dist/auth/store.js +36 -5
  2. package/dist/cli.js +119 -26
  3. package/dist/config/persona.js +14 -1
  4. package/dist/engine/agent.js +4 -4
  5. package/dist/engine/anthropic.js +48 -0
  6. package/dist/engine/batch-scheduler.js +68 -21
  7. package/dist/engine/cli.js +1171 -0
  8. package/dist/mcp/index.js +2 -1
  9. package/dist/permissions/index.js +11 -4
  10. package/dist/remote/host.js +46 -5
  11. package/dist/remote/pairing.js +70 -0
  12. package/dist/router/models.js +8 -1
  13. package/dist/router/models.js.bak +78 -0
  14. package/dist/router/models.js.bak-1791259923 +78 -0
  15. package/dist/router/models.js.bak-pre-gateway +78 -0
  16. package/dist/router/models.js.bak-pre-patch2 +78 -0
  17. package/dist/router/models.js.bak2 +78 -0
  18. package/dist/services/model-autodetect.js +240 -0
  19. package/dist/tools/chauffeur.js +16 -3
  20. package/dist/tools/deferred.js +2 -1
  21. package/dist/tools/executor.js +15 -3
  22. package/dist/tools/native-redirect.js +140 -0
  23. package/dist/tools/power-tools.js +627 -0
  24. package/dist/tools/registry.js +252 -5
  25. package/dist/tools/registry.js.bak-1791259948 +1914 -0
  26. package/dist/tools/registry.js.bak-pre-plugins +1914 -0
  27. package/dist/ui/App.js +5 -4
  28. package/dist/ui/BusTray.js +70 -0
  29. package/dist/ui/Composer.js +28 -1
  30. package/dist/ui/ToolStep.js +1 -1
  31. package/dist/ui/format.js +18 -0
  32. package/dist/ui/liveTools.js +2 -5
  33. package/dist/ui/qr.js +10 -0
  34. package/dist/ui/resize.js +160 -0
  35. package/dist/ui/slashCommands.js +43 -0
  36. package/dist/ui/term.js +17 -0
  37. package/dist/util/slash.js +1 -1
  38. package/package.json +3 -1
@@ -0,0 +1,78 @@
1
+ export const DEFAULT_MODEL_ID = "operator-1m";
2
+ // Back-compat aliases: the user-facing ids were renamed aurora-* -> operator-* (the outward name is
3
+ // Operator; "aurora" is the internal model, never shown). The OLD ids still resolve — a persisted
4
+ // settings.activeModel: "aurora-1m", a `/model aurora-1m`, or any muscle memory keeps working — so the
5
+ // rename loses nothing. The served model name ("aurora-code-1") + endpoints stay internal, untouched.
6
+ export const MODEL_ALIASES = {
7
+ "aurora-1m": "operator-1m",
8
+ "aurora-128k": "operator-128k",
9
+ };
10
+ export const BUILTIN_MODELS = [
11
+ { id: "operator-1m", label: "Operator 300K", kind: "single", desc: "307,200-token (300K) context (:8097)", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 307200 },
12
+ { id: "operator-128k", label: "Operator 128K", kind: "single", desc: "128K context, lighter RAM (:8096)", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072 },
13
+ // QwenCloud Token Plan BYO connectors (SPEC/providers.md §2 "API-key connectors"). Same keychain
14
+ // account ("qwen") serves both; the picker hides them until connected (§1 honest availability), and
15
+ // authHeaders NEVER sends the Operator token to this host. ctx starts conservative and self-clamps
16
+ // to the served truth (observeContext).
17
+ { id: "qwen3.8-max", label: "Qwen 3.8 Max", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
18
+ { id: "qwen3.8-flash", label: "Qwen 3.8 Flash", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
19
+ // Venice 24B — SELF-HOSTED like Aurora (NOT a third-party connector): the open uncensored weights
20
+ // (Dolphin-Mistral-24B-Venice-Edition Q4_K_M, JL1 Ai Storage) served via llama.cpp on JL1:8110, bound
21
+ // 0.0.0.0 so the engine (on JL2) reaches it over LAN. Uncensored at the weights — answers directly, no
22
+ // retry needed; complements the engine-level unrestricted layer. Runs ALONGSIDE Aurora (:8097); the
23
+ // llama.cpp router health-checks + recovers, and ctx self-clamps to the served truth (observeContext).
24
+ { id: "venice-24b", label: "Venice 24B (uncensored)", kind: "single", desc: "self-hosted uncensored Dolphin-Mistral-24B-Venice (fleet llama.cpp, JL1:8110)", endpoint: "http://192.168.1.103:8110/v1", model: "dolphin-venice-24b", ctx: 8192 },
25
+ { id: "moa", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "fan out to proposers, synthesize with an aggregator" },
26
+ ];
27
+ /** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
28
+ * built-in by id, or adding a new one) — same shape either way, so /model doesn't care which. */
29
+ export function modelRegistry(overrides) {
30
+ if (!overrides?.length)
31
+ return BUILTIN_MODELS;
32
+ const byId = new Map(BUILTIN_MODELS.map((m) => [m.id, m]));
33
+ for (const m of overrides)
34
+ byId.set(m.id, { ...byId.get(m.id), ...m });
35
+ return [...byId.values()];
36
+ }
37
+ export function findModel(registry, id) {
38
+ const canon = MODEL_ALIASES[id] ?? id; // aurora-1m -> operator-1m (old ids keep resolving)
39
+ return registry.find((m) => m.id === canon);
40
+ }
41
+ /** The configured context window (tokens) for a model id — from BUILTIN_MODELS + settings overrides — or
42
+ * Infinity if unknown. Used to pick a LEAN harness: a small-context model (e.g. a self-hosted 8K Venice)
43
+ * can't take Operator's full memory + handoff injection (sized for Aurora's 300K); it fills the window and
44
+ * the model recites the memory instead of answering. Callers drop the heavy memory/handoff below a
45
+ * threshold while keeping the base persona (incl. the Direct/unrestricted section), so it stays uncensored. */
46
+ export function modelCtxFor(id, overrides) {
47
+ if (!id)
48
+ return Number.POSITIVE_INFINITY;
49
+ return findModel(modelRegistry(overrides), id)?.ctx ?? Number.POSITIVE_INFINITY;
50
+ }
51
+ /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora/Qwen (128K+) stay
52
+ * full; a self-hosted small model (Venice 8K, or a 16K bump) goes lean. */
53
+ export const LEAN_HARNESS_CTX = 32768;
54
+ /** Pure selection reducer for /model — no I/O (no settings read/write, no router mutation), so it's
55
+ * directly testable. The moa-needs-config check lives in Session.setModel (it needs settings.moa,
56
+ * which this module intentionally doesn't import). `hasByo` (injected by the caller, see auth/byo)
57
+ * gates BYO connector profiles: honest "not connected" beats a request-time 401. */
58
+ export function selectModel(registry, id, hasByo) {
59
+ const profile = findModel(registry, id);
60
+ if (!profile)
61
+ return { error: `unknown model "${id}" — choices: ${registry.map((m) => m.id).join(", ")}` };
62
+ if (profile.kind === "single" && !profile.endpoint)
63
+ return { error: `model "${id}" has no endpoint configured` };
64
+ if (profile.byo && hasByo && !hasByo(profile.byo)) {
65
+ return { error: `"${id}" is not connected — store the ${profile.byo} key first: operator auth byo ${profile.byo}` };
66
+ }
67
+ return { profile };
68
+ }
69
+ /** The picker-truth view of a registry: drops BYO profiles whose key isn't connected (and ALL
70
+ * unresolvable ones when the resolver is absent — a picker must never offer what setModel refuses). */
71
+ export function visibleModels(registry, hasByo) {
72
+ return registry.filter((p) => !p.byo || (hasByo ? hasByo(p.byo) : false));
73
+ }
74
+ /** Strip a trailing /v1 so a ModelProfile/MoaAggregator endpoint can feed the AuroraRouter, whose
75
+ * base is bare (engine/aurora.ts's chat() appends /v1/chat/completions itself). */
76
+ export function endpointBase(endpoint) {
77
+ return endpoint.replace(/\/v1\/?$/, "");
78
+ }
@@ -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
+ }
@@ -35,7 +35,18 @@ export const CHAUFFEUR_ACTION_NAMES = CHAUFFEUR_ACTION_TOOLS.map((t) => `chauffe
35
35
  export const CHAUFFEUR_TOOL_NAMES = CHAUFFEUR_TOOLS.map((t) => `chauffeur:${t}`);
36
36
  // Resolve the chauffeur binary: explicit override, then the fleet install path, else bare `chauffeur` on
37
37
  // PATH. Returns null only when nothing is found, so cli.tsx can skip wiring a dead hub.
38
+ // SINGLE-FLIGHT + ASYNC (the boot-stall class): this runs on cli.tsx module scope when computer control
39
+ // is enabled. The old form was `execFileSync("command", ["-v", …])` — a SYNCHRONOUS child process that
40
+ // blocks the event loop, and it re-spawned for every buildChauffeurServer()/buildChauffeurHub() call
41
+ // (chauffeur + each stdio MCP server that needs it). `command -v` is normally sub-ms, but a slow/network
42
+ // PATH entry or a wedged /bin/sh turns it into the same unbounded boot stall as the keychain read. Cached
43
+ // into one promise so the process resolves the binary at most ONCE, and awaited (never sync) so a hung
44
+ // lookup can never freeze the first frame.
45
+ let chauffeurBin = null;
38
46
  async function resolveBinary() {
47
+ return (chauffeurBin ??= resolveBinaryFresh());
48
+ }
49
+ async function resolveBinaryFresh() {
39
50
  const override = process.env.KODE_CHAUFFEUR_BIN;
40
51
  if (override)
41
52
  return override;
@@ -46,9 +57,11 @@ async function resolveBinary() {
46
57
  return local;
47
58
  // Fall back to PATH resolution; if `chauffeur` isn't there either, give up (no dead hub, no failed spawn).
48
59
  try {
49
- const { execFileSync } = await import("node:child_process");
50
- const p = execFileSync("command", ["-v", "chauffeur"], { shell: "/bin/sh", encoding: "utf8" }).trim();
51
- return p || null;
60
+ const { execFile } = await import("node:child_process");
61
+ const p = await new Promise((resolve, reject) => {
62
+ execFile("/bin/sh", ["-c", "command -v chauffeur"], { timeout: 3000, encoding: "utf8" }, (err, stdout) => (err ? reject(err) : resolve(stdout)));
63
+ });
64
+ return p.trim() || null;
52
65
  }
53
66
  catch {
54
67
  return null;
@@ -84,7 +84,7 @@ export function withDeferred(base, st) {
84
84
  return runMeta(name, args);
85
85
  return base.execute(name, args);
86
86
  },
87
- async executeParallel(calls, onSettle) {
87
+ async executeParallel(calls, onSettle, signal) {
88
88
  // BTX finding B/C follow-through: meta trio and base calls share ONE scheduled batch —
89
89
  // tool_call used to runMeta-inline (racing the base batch it dispatches INTO), and the meta
90
90
  // Promise.all barrier made base calls wait for every meta first. Now: search/describe classify
@@ -98,6 +98,7 @@ export function withDeferred(base, st) {
98
98
  runOne: (c) => (DEFERRED_META_NAMES.includes(c.name)
99
99
  ? runMeta(c.name, c.args) : base.execute(c.name, c.args)),
100
100
  onSettle,
101
+ signal,
101
102
  });
102
103
  },
103
104
  sched: {
@@ -9,8 +9,9 @@
9
9
  // new user turn (not required by SPEC §3's
10
10
  // round loop itself, but needed so the guard
11
11
  // doesn't bleed across turns)
12
- import { isAbsolute, join } from "node:path";
12
+ import { isAbsolute, join, resolve } from "node:path";
13
13
  import { registry } from "./registry.js";
14
+ import { expandPath } from "./paths.js";
14
15
  import { shellKeyStore } from "./shell-context.js";
15
16
  // Re-exported for back-compat (existing importers reach it via executor.js) — moved to its own
16
17
  // file since it's a pure helper with no node deps; see result-cap.ts for why that separation matters.
@@ -25,6 +26,12 @@ const PATH_ARGS = ["path", "file", "filename", "workspace"];
25
26
  // Tools that take an optional `workspace` and otherwise fall back to process.cwd() — a rooted session must
26
27
  // default it to its own root or the call lands in whatever directory the host process happens to run in.
27
28
  const WORKSPACE_TOOLS = new Set(["checkpoint"]);
29
+ // BTX conflict keys must be the ABSOLUTE path a call will really touch, or "d.txt", "./d.txt", "/cwd/d.txt" and
30
+ // "~/d.txt" each look like a different resource and a batched write+read of one file races. Only path-named args
31
+ // are resolved (array elements and nested objects included, by the arg name they sit under); a url, or an id
32
+ // under target/handle/token, is left as-is.
33
+ const KEY_PATH_ARG = /path|dir|file|cwd|^(out|output|dest|destination)$/i;
34
+ const URL_LIKE = /^[a-z][a-z0-9+.-]*:\/\//i;
28
35
  /** Reroot a tool call's args under `root` so a session's file/shell tools all act inside its own directory
29
36
  * (e.g. a background agent's git worktree) instead of the shared process cwd. Pure: relative path args are
30
37
  * joined under root; command tools default their cwd to root; absolute and ~ paths are left untouched
@@ -101,9 +108,13 @@ export class Executor {
101
108
  }
102
109
  sched = {
103
110
  classify: defaultClassify("", (n) => this.reg.get(n)?.safe === true),
104
- keys: defaultKeys,
111
+ keys: (n, a) => defaultKeys(n, a, (p, arg) => this.resolveKey(p, arg)),
105
112
  };
106
- async executeParallel(calls, onSettle) {
113
+ /** Same resolution the tools apply (root join, ~ expansion), done lexically so a not-yet-written file still keys. */
114
+ resolveKey(p, argName) {
115
+ return KEY_PATH_ARG.test(argName) && !URL_LIKE.test(p) ? resolve(this.root ?? process.cwd(), expandPath(p)) : p;
116
+ }
117
+ async executeParallel(calls, onSettle, signal) {
107
118
  // BTX: one shared DAG scheduler (engine/batch-scheduler.ts) — per-resource write chains,
108
119
  // reads wait only for conflicting prior writes, device tools barrier-serialize. This replaces
109
120
  // the 0.1.225 contiguous walk: same guarantees, strictly more overlap.
@@ -112,6 +123,7 @@ export class Executor {
112
123
  keys: (n, a) => this.sched.keys(n, a),
113
124
  runOne: (c) => this.execute(c.name, c.args),
114
125
  onSettle,
126
+ signal,
115
127
  });
116
128
  }
117
129
  }
@@ -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
+ }