@0perator/operator 0.1.261 → 0.1.263

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.
@@ -144,6 +144,26 @@ function contentSignature(content) {
144
144
  .trim()
145
145
  .slice(0, 200);
146
146
  }
147
+ // A single high-fanout round (e.g. 15 parallel web_search / fetch calls) can dump more tool output than the
148
+ // whole context window holds — which overflows the server (hard 400) AND defeats compaction, since compaction
149
+ // summarizes OLD history and preserves the RECENT turn where that bloat lives. Per-result caps (tools/registry)
150
+ // bound ONE result; this bounds the ROUND's TOTAL, so autonomous multi-tool work keeps running uninterrupted.
151
+ const TOOL_ROUND_CHAR_BUDGET = 80_000; // ~20K tokens max of tool output added per round, trimmed proportionally
152
+ /** Cap a round's total tool output to TOOL_ROUND_CHAR_BUDGET, trimming the largest results proportionally with
153
+ * a truncation note. Returns new Msg objects (originals are left intact for the verify/progress ledgers, which
154
+ * need the full results). A round at or under budget is returned unchanged. */
155
+ export function capToolRound(msgs) {
156
+ const total = msgs.reduce((n, m) => n + (m.content?.length ?? 0), 0);
157
+ if (total <= TOOL_ROUND_CHAR_BUDGET)
158
+ return msgs;
159
+ return msgs.map((m) => {
160
+ const c = m.content ?? "";
161
+ const share = Math.max(1200, Math.floor(TOOL_ROUND_CHAR_BUDGET * (c.length / total)));
162
+ if (c.length <= share)
163
+ return m;
164
+ return { ...m, content: `${c.slice(0, share)}\n…[tool result truncated to fit the round's context budget — ${c.length - share} more chars dropped; narrow the query, fetch fewer items, or request one at a time]` };
165
+ });
166
+ }
147
167
  /** A tool batch "progressed" if any result shows the batch advanced the world. Gates BOTH the no-progress
148
168
  * stall streak and the narration-loop guard, so a templated narration over PRODUCTIVE work is never
149
169
  * mistaken for a loop. A result is a STALL sentinel only if it's empty, a FAILED silent command
@@ -841,8 +861,8 @@ export async function runTurn(userInput, conversation, opts) {
841
861
  // Race the batch against the abort signal so esc breaks even a hung tool (a frozen child process) —
842
862
  // the abandoned tool runs to its own timeout, but the turn is never wedged.
843
863
  const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
844
- for (const tm of toolMsgs)
845
- conversation.tool(tm.tool_call_id, tm.content);
864
+ for (const tm of capToolRound(toolMsgs))
865
+ conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
846
866
  observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
847
867
  toolCallTotal += response.toolCalls.length;
848
868
  progressed = batchProgressed(toolMsgs);
@@ -859,8 +879,8 @@ export async function runTurn(userInput, conversation, opts) {
859
879
  throwIfAborted(opts.signal);
860
880
  conversation.assistant(recovered.cleanedContent, recovered.calls);
861
881
  const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
862
- for (const tm of toolMsgs)
863
- conversation.tool(tm.tool_call_id, tm.content);
882
+ for (const tm of capToolRound(toolMsgs))
883
+ conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
864
884
  observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
865
885
  toolCallTotal += recovered.calls.length;
866
886
  progressed = batchProgressed(toolMsgs);
@@ -9,7 +9,7 @@ export const MODEL_ALIASES = {
9
9
  "spectre": "cortana", // flagship renamed Spectre -> Cortana 35B (2026-10-07); old id keeps resolving
10
10
  };
11
11
  export const BUILTIN_MODELS = [
12
- { 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-1m", label: "Operator 128K", kind: "single", desc: "131,072-token (128K) context (:8097) — matched to the server's --ctx-size so the engine compacts BEFORE the wall (no overflow/interruption on long autonomous turns)", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 128000 },
13
13
  { 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 },
14
14
  // QwenCloud Token Plan BYO connectors (SPEC/providers.md §2 "API-key connectors"). Same keychain
15
15
  // account ("qwen") serves both; the picker hides them until connected (§1 honest availability), and
@@ -36,7 +36,7 @@ export const BUILTIN_MODELS = [
36
36
  // truncated a round at token 32767 (finish=length) mid-tool-call, and that cut call poisoned the session (0.1.259).
37
37
  // 32000 sits just UNDER the real wall (margin) AND under LEAN_HARNESS_CTX so Cortana drops the heavy memory/handoff
38
38
  // (which alone was ~16K = half the window) — persona + unrestricted layer kept. Raise ONLY if the server's --ctx-size does.
39
- { id: "cortana", label: "Cortana 35B", kind: "single", desc: "flagship — abliterated Qwen3.6-35B-A3B MoE (~3B active, ~40 tok/s), uncensored + vision (JL1:8112, llama.cpp, 32K ctx)", endpoint: "http://192.168.1.103:8112/v1", model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 32000 },
39
+ { id: "cortana", label: "Cortana 35B", kind: "single", desc: "flagship — abliterated Qwen3.6-35B-A3B MoE (~3B active, ~40 tok/s), uncensored + vision (JL1:8112, llama.cpp, 128K ctx)", endpoint: "http://192.168.1.103:8112/v1", model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 128000 },
40
40
  // Qwen3-4B — fast LOCAL tier (stock qwen3-4b-mlx-q4, 2.26GB MLX 4-bit, ctx 40960) served via mlx_lm.server
41
41
  // on JL1:8110. Qwen3 vocab (151936) — the same family as ghost-32b, so it's the review-recommended quick tier
42
42
  // AND the vocab lineage for ghost spec-decode (the actual draft is Qwen3-0.6B, too small to list here). Runs
@@ -1224,11 +1224,148 @@ async function videoGenerate(args) {
1224
1224
  // image_analyze — real vision. Calls the fleet VL model (Qwen2-VL, OpenAI-vision /v1/chat/completions) so
1225
1225
  // Operator can SEE an image (a reference, screenshot, or generated output) instead of guessing from file
1226
1226
  // size / numpy brightness. A served model on a dedicated node — never loads a VL model inline on this box.
1227
- /** Candidate vision endpoints: KODE_VISION_URL first, then the fleet Qwen2-VL worker (JL1). */
1228
- function visionEndpoints() {
1229
- const envs = [process.env.KODE_VISION_URL].filter(Boolean);
1230
- const defaults = ["http://192.168.1.103:8095"]; // Qwen2-VL-7B-Instruct-4bit (mlx_vlm.server, OpenAI-vision) on JL1
1231
- return [...new Set([...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
1227
+ // Enterprise-grade vision plumbing (mirrors Hermes' vision_tools.py strategy, adapted for a single-threaded
1228
+ // local 7B). Three parts: (1) proactive downscale — a VL model's cost scales with pixels, and full-res
1229
+ // (3680x2392 ~78s) stalls the worker past the timeout, which also blocks its /health and cascades retries
1230
+ // into "no vision service reachable"; downscaling the long edge to 1568px is a measured ~10x speedup with no
1231
+ // description-quality loss. (2) An ordered endpoint chain with per-endpoint health cooldown, so a busy /
1232
+ // rate-limited / 402'd target is skipped for a TTL instead of failing the turn. (3) An optional cloud
1233
+ // fallback (KODE_VISION_FALLBACK_URL, OpenAI-vision compatible) so a cold/busy local worker never hard-fails.
1234
+ const VISION_MAX_EDGE = Math.max(256, Number(process.env.KODE_VISION_MAX_EDGE) || 1568);
1235
+ const VISION_COOLDOWN_MS = Math.max(10_000, Number(process.env.KODE_VISION_COOLDOWN_MS) || 120_000);
1236
+ const visionUnhealthy = new Map(); // base url -> epoch ms it may be retried after
1237
+ /** Vision endpoints in priority order: KODE_VISION_URL, the fleet Qwen2-VL worker (JL1), then an optional
1238
+ * cloud fallback. Each carries its own auth + model; local targets get a /health gate, cloud targets don't. */
1239
+ function visionTargets() {
1240
+ const seen = new Set();
1241
+ const out = [];
1242
+ const add = (u, auth, model, label) => {
1243
+ if (!u)
1244
+ return;
1245
+ const url = u.replace(/\/$/, "");
1246
+ if (seen.has(url))
1247
+ return;
1248
+ seen.add(url);
1249
+ const local = /\/\/(127\.0\.0\.1|localhost|192\.168\.|10\.|\[?::1)/.test(url) || /\.local(:|\/|$)/.test(url);
1250
+ out.push({ url, auth, model, local, label });
1251
+ };
1252
+ add(process.env.KODE_VISION_URL, mediaAuth(), undefined, "vision-url");
1253
+ add("http://192.168.1.103:8095", mediaAuth(), undefined, "fleet-jl1"); // Qwen2-VL-7B-Instruct-4bit (mlx_vlm.server) on JL1
1254
+ add(process.env.KODE_VISION_FALLBACK_URL, process.env.KODE_VISION_FALLBACK_KEY ? { Authorization: `Bearer ${process.env.KODE_VISION_FALLBACK_KEY}` } : {}, process.env.KODE_VISION_FALLBACK_MODEL || undefined, "cloud-fallback");
1255
+ return out;
1256
+ }
1257
+ /** Read a local image, downscaling its long edge to VISION_MAX_EDGE first (macOS `sips`, then `ffmpeg`, then
1258
+ * the original bytes — never upscales). http(s) urls pass straight through (the server fetches them). */
1259
+ async function visionImageDataUrl(image) {
1260
+ if (/^https?:\/\//.test(image))
1261
+ return image;
1262
+ const { readFile } = await nodeImport("node:fs/promises");
1263
+ const orig = await readFile(image).catch(() => null);
1264
+ if (!orig)
1265
+ throw new Error(`could not read a file at ${image}`);
1266
+ const ext = (image.split(".").pop() || "png").toLowerCase();
1267
+ let mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "webp" ? "image/webp" : ext === "gif" ? "image/gif" : "image/png";
1268
+ let buf = orig;
1269
+ try {
1270
+ const os = await nodeImport("node:os");
1271
+ const { join } = await nodeImport("node:path");
1272
+ const { mkdtemp, readFile: rf, rm } = await nodeImport("node:fs/promises");
1273
+ const { execFile } = await nodeImport("node:child_process");
1274
+ const { promisify } = await nodeImport("node:util");
1275
+ const pexec = promisify(execFile);
1276
+ const dir = await mkdtemp(join(os.tmpdir(), "axe-iv-"));
1277
+ try {
1278
+ const out = join(dir, "v.jpg");
1279
+ let shrank = false;
1280
+ try {
1281
+ const { stdout } = await pexec("sips", ["-g", "pixelWidth", "-g", "pixelHeight", image]);
1282
+ const w = Number((/pixelWidth:\s*(\d+)/.exec(stdout) || [])[1] || 0);
1283
+ const h = Number((/pixelHeight:\s*(\d+)/.exec(stdout) || [])[1] || 0);
1284
+ if (!w || !h || Math.max(w, h) <= VISION_MAX_EDGE)
1285
+ return `data:${mime};base64,${buf.toString("base64")}`; // already small enough
1286
+ await pexec("sips", ["-Z", String(VISION_MAX_EDGE), "-s", "format", "jpeg", image, "--out", out]);
1287
+ shrank = true;
1288
+ }
1289
+ catch {
1290
+ try {
1291
+ // non-macOS / sips missing → ffmpeg; min() clamps the fit-box to the image so it never upscales.
1292
+ await pexec("ffmpeg", ["-nostdin", "-y", "-loglevel", "error", "-i", image, "-vf", `scale='min(iw,${VISION_MAX_EDGE})':'min(ih,${VISION_MAX_EDGE})':force_original_aspect_ratio=decrease`, out]);
1293
+ shrank = true;
1294
+ }
1295
+ catch {
1296
+ shrank = false;
1297
+ }
1298
+ }
1299
+ if (shrank) {
1300
+ const small = await rf(out).catch(() => null);
1301
+ if (small && small.length) {
1302
+ buf = small;
1303
+ mime = "image/jpeg";
1304
+ }
1305
+ }
1306
+ }
1307
+ finally {
1308
+ await rm(dir, { recursive: true, force: true }).catch(() => { });
1309
+ }
1310
+ }
1311
+ catch { /* any resize failure → original bytes (correctness over speed) */ }
1312
+ return `data:${mime};base64,${buf.toString("base64")}`;
1313
+ }
1314
+ /** POST a vision chat, walking the endpoint chain: skip any in cooldown, /health-gate local targets, time
1315
+ * each independently, retry once on an empty body, and on timeout / 402 / 429 / auth-error mark the target
1316
+ * unhealthy for a TTL and fall through to the next. Throws with the last error only when all are exhausted. */
1317
+ async function visionComplete(parts, args, defaultTimeoutMs) {
1318
+ const targets = visionTargets();
1319
+ const timeout = Math.max(5_000, Number(args.timeout_ms ?? defaultTimeoutMs));
1320
+ const now = () => Date.now();
1321
+ let lastErr = `no vision service reachable (tried ${targets.map((t) => t.url).join(", ")})`;
1322
+ for (const t of targets) {
1323
+ if ((visionUnhealthy.get(t.url) || 0) > now()) {
1324
+ lastErr = `${t.label} in cooldown`;
1325
+ continue;
1326
+ }
1327
+ if (t.local && !(await imageHealthy(t.url))) {
1328
+ visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
1329
+ lastErr = `${t.label} health check failed at ${t.url}`;
1330
+ continue;
1331
+ }
1332
+ const model = str(args.model) || t.model || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
1333
+ for (let attempt = 0; attempt < 2; attempt++) {
1334
+ const ctrl = new AbortController();
1335
+ const timer = setTimeout(() => ctrl.abort(), timeout);
1336
+ try {
1337
+ const res = await fetch(`${t.url}/v1/chat/completions`, {
1338
+ method: "POST", signal: ctrl.signal,
1339
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...t.auth },
1340
+ body: JSON.stringify({ model, messages: [{ role: "system", content: VISION_SYS }, { role: "user", content: parts }], ...(Number.isFinite(Number(args.max_tokens)) ? { max_tokens: Number(args.max_tokens) } : {}), temperature: 0 }),
1341
+ });
1342
+ if (!res.ok) {
1343
+ const body = (await res.text().catch(() => "")).slice(0, 180);
1344
+ if (res.status === 401 || res.status === 402 || res.status === 403 || res.status === 429 || /credit|insufficient|quota|billing/i.test(body))
1345
+ visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
1346
+ lastErr = `${t.label} returned ${res.status}${body ? ` — ${body}` : ""}`;
1347
+ break; // non-200 → next endpoint
1348
+ }
1349
+ const j = (await res.json().catch(() => ({})));
1350
+ const text = j.choices?.[0]?.message?.content?.trim();
1351
+ if (text)
1352
+ return text;
1353
+ lastErr = `${t.label} returned no text`; // empty → retry once, then next endpoint
1354
+ }
1355
+ catch (e) {
1356
+ const aborted = e?.name === "AbortError";
1357
+ lastErr = aborted ? `${t.label} timed out after ${Math.round(timeout / 1000)}s` : `${t.label}: ${String(e?.message ?? e)}`;
1358
+ if (aborted) {
1359
+ visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
1360
+ break;
1361
+ } // busy/slow → cooldown + next endpoint
1362
+ }
1363
+ finally {
1364
+ clearTimeout(timer);
1365
+ }
1366
+ }
1367
+ }
1368
+ throw new Error(lastErr);
1232
1369
  }
1233
1370
  // Uncensoring system prompt for the vision model (owner's private system): the engine-level unrestricted
1234
1371
  // layer only sees chat() turns, not these direct vision calls, so the analyze side gets its own one-line
@@ -1239,52 +1376,19 @@ async function imageAnalyze(args) {
1239
1376
  if (!image)
1240
1377
  return "error: image_analyze needs an image (a local path or an http(s) url)";
1241
1378
  const question = str(args.question) || "Describe this image in detail.";
1242
- const model = str(args.model) || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
1243
- // http(s) url → pass straight through; a local file → read + inline as a data: URL (the server accepts both).
1244
- let imageUrl = image;
1245
- if (!/^https?:\/\//.test(image)) {
1246
- const { readFile } = await nodeImport("node:fs/promises");
1247
- const buf = await readFile(image).catch(() => null);
1248
- if (!buf)
1249
- return `error: image_analyze could not read a file at ${image} (pass a local path or an http(s) url)`;
1250
- const ext = (image.split(".").pop() || "png").toLowerCase();
1251
- const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "webp" ? "image/webp" : ext === "gif" ? "image/gif" : "image/png";
1252
- imageUrl = `data:${mime};base64,${buf.toString("base64")}`;
1253
- }
1254
- const candidates = visionEndpoints();
1255
- let base;
1256
- for (const e of candidates) {
1257
- if (await imageHealthy(e)) {
1258
- base = e;
1259
- break;
1260
- }
1379
+ let imageUrl;
1380
+ try {
1381
+ imageUrl = await visionImageDataUrl(image); // downscales a large local image first; http(s) passes through
1261
1382
  }
1262
- if (!base)
1263
- return `error: no vision service reachable (tried ${candidates.join(", ")}). Bring up the Qwen2-VL worker (com.axe.vision-worker).`;
1264
- const ctrl = new AbortController();
1265
- const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 120_000));
1383
+ catch {
1384
+ return `error: image_analyze could not read a file at ${image} (pass a local path or an http(s) url)`;
1385
+ }
1386
+ const parts = [{ type: "text", text: question }, { type: "image_url", image_url: { url: imageUrl } }];
1266
1387
  try {
1267
- const res = await fetch(`${base}/v1/chat/completions`, {
1268
- method: "POST", signal: ctrl.signal,
1269
- headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
1270
- body: JSON.stringify({
1271
- model,
1272
- messages: [{ role: "system", content: VISION_SYS }, { role: "user", content: [{ type: "text", text: question }, { type: "image_url", image_url: { url: imageUrl } }] }],
1273
- ...(Number.isFinite(Number(args.max_tokens)) ? { max_tokens: Number(args.max_tokens) } : {}), temperature: 0,
1274
- }),
1275
- });
1276
- if (!res.ok)
1277
- return `error: vision worker returned ${res.status} — ensure the Qwen2-VL worker is up`;
1278
- const j = (await res.json().catch(() => ({})));
1279
- const text = j.choices?.[0]?.message?.content?.trim();
1280
- return text || "error: vision worker returned no text";
1388
+ return await visionComplete(parts, args, 120_000);
1281
1389
  }
1282
1390
  catch (e) {
1283
- const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
1284
- return `error: vision worker unreachable at ${base} (${msg}) — start the Qwen2-VL worker (com.axe.vision-worker)`;
1285
- }
1286
- finally {
1287
- clearTimeout(timer);
1391
+ return `error: vision — ${String(e?.message ?? e)}. The vision model is busy or unavailable; retry shortly, or configure a fallback vision endpoint.`;
1288
1392
  }
1289
1393
  }
1290
1394
  // video_analyze — real video understanding: ffmpeg samples frames evenly across the clip, then the VL model
@@ -1296,7 +1400,6 @@ async function videoAnalyze(args) {
1296
1400
  return "error: video_analyze needs a video (a local path or an http(s) url)";
1297
1401
  const question = str(args.question) || "These frames are sampled in order across a video. Describe what happens across the video.";
1298
1402
  const nFrames = Math.max(2, Math.min(Number(args.frames) || 8, 16));
1299
- const model = str(args.model) || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
1300
1403
  const { mkdtemp, readFile, rm, writeFile, readdir } = await nodeImport("node:fs/promises");
1301
1404
  const os = await nodeImport("node:os");
1302
1405
  const { join } = await nodeImport("node:path");
@@ -1337,33 +1440,8 @@ async function videoAnalyze(args) {
1337
1440
  const b = await readFile(join(dir, f));
1338
1441
  parts.push({ type: "image_url", image_url: { url: `data:image/png;base64,${b.toString("base64")}` } });
1339
1442
  }
1340
- const candidates = visionEndpoints();
1341
- let base;
1342
- for (const e of candidates) {
1343
- if (await imageHealthy(e)) {
1344
- base = e;
1345
- break;
1346
- }
1347
- }
1348
- if (!base)
1349
- return `error: no vision service reachable (tried ${candidates.join(", ")}). Bring up the Qwen2-VL worker.`;
1350
- const ctrl = new AbortController();
1351
- const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 180_000));
1352
- try {
1353
- const res = await fetch(`${base}/v1/chat/completions`, {
1354
- method: "POST", signal: ctrl.signal,
1355
- headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...mediaAuth() },
1356
- body: JSON.stringify({ model, messages: [{ role: "system", content: VISION_SYS }, { role: "user", content: parts }], ...(Number.isFinite(Number(args.max_tokens)) ? { max_tokens: Number(args.max_tokens) } : {}), temperature: 0 }),
1357
- });
1358
- if (!res.ok)
1359
- return `error: vision worker returned ${res.status} — ensure the Qwen2-VL worker is up`;
1360
- const j = (await res.json().catch(() => ({})));
1361
- const text = j.choices?.[0]?.message?.content?.trim();
1362
- return text ? `video analysis (${picked.length} frames) → ${text}` : "error: vision worker returned no text";
1363
- }
1364
- finally {
1365
- clearTimeout(timer);
1366
- }
1443
+ const text = await visionComplete(parts, args, 180_000); // shared endpoint failover + cloud fallback
1444
+ return `video analysis (${picked.length} frames) → ${text}`;
1367
1445
  }
1368
1446
  catch (e) {
1369
1447
  const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.261",
3
+ "version": "0.1.263",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",