@0perator/operator 0.1.263 → 0.1.274

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.
@@ -6,7 +6,7 @@ import { readFileSync, appendFileSync, mkdirSync } from "node:fs";
6
6
  import { join, dirname } from "node:path";
7
7
  import { operatorPath } from "./home.js";
8
8
  import { renderHarnessContext } from "./operator-harness.js";
9
- import { renderToolCatalogue } from "../tools/registry.js";
9
+ import { renderToolCatalogue, visibleRegistry } from "../tools/registry.js";
10
10
  import { renderSkillsIndex } from "./skills-index.js";
11
11
  // Project context: auto-load a per-repo instructions file from `cwd` and append it to the system prompt, so
12
12
  // Operator picks up house rules, conventions and build commands the way modern coding agents do. First match
@@ -224,25 +224,43 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
224
224
  `OPEN it for them yourself (bash \`open <url-or-local-path>\`) and put the clickable link in your reply — ` +
225
225
  `never leave them to ask "open it for me". Skip the auto-open inside a media-robot / headless batch.` +
226
226
  `\n## The media pipeline — what you ACTUALLY have (don't invent tools)\nYour media stack is three ` +
227
- `scale-to-zero fleet workers, nothing else — do NOT offer ComfyUI, SDXL, Juggernaut/RealVis/EpicRealism, ` +
227
+ `scale-to-zero fleet workers, nothing else — do NOT offer ComfyUI, standalone SDXL, Juggernaut/EpicRealism, ` +
228
228
  `FLUX.1-dev/pro, Midjourney, or a cloud image API as if available; they are not wired in, and suggesting ` +
229
229
  `them is a hallucinated capability. (a) IMAGES — \`image_generate\` → FLUX.1-schnell (4-bit MLX) on the ` +
230
- `image broker. schnell is speed-tuned: strong but not a dev/pro-tier photoreal ceiling. When the owner ` +
231
- `wants higher quality, pass \`expand: true\` — the broker rewrites your prompt through the Aurora expander ` +
232
- `into a richer, more cinematic prompt (the expanded text comes back in the result and is logged); combine ` +
233
- `with a larger \`size\`. That is your real quality lever — reach for it instead of claiming you need a ` +
234
- `model you don't have. It also accepts \`reference\`+\`strength\`, passed through to the broker. (b) VIDEO ` +
230
+ `image broker by default. schnell is speed-tuned: strong but not a photoreal ceiling. For PHOTOREAL from ` +
231
+ `text alone, pass \`quality: "photoreal"\`: it routes to the identity broker, where RealVisXL IS wired ` +
232
+ `(SDXL text-to-image, ~1024px, slower, no face needed) — that is your photoreal path, so you never need to ` +
233
+ `build one. To enrich the prompt, pass \`expand: true\` — the broker rewrites your prompt through the Aurora ` +
234
+ `expander into a richer, more cinematic prompt (the expanded text comes back in the result and is logged); ` +
235
+ `combine with a larger \`size\`. Those are your real quality levers — reach for them instead of claiming ` +
236
+ `you need a model you don't have. It also accepts \`reference\`+\`strength\`, passed through to the broker. (b) VIDEO ` +
235
237
  `— \`video_generate\` → LTX-Video-0.9.5 on the video broker, with \`expand\` and \`reference_image\` ` +
236
238
  `(IMAGE-TO-VIDEO): pass an image and LTX conditions on it as the FIRST FRAME, so the subject in the clip ` +
237
- `IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` → Qwen2-VL-7B on the fleet.` +
239
+ `IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` → a Qwen2-VL worker on the ` +
240
+ `fleet (REAL vision, not guessing from a filename). It walks an ordered endpoint chain with per-endpoint ` +
241
+ `health-cooldown + an optional cloud fallback, so a cold/busy worker never hard-fails; large images are ` +
242
+ `auto-downscaled before the model sees them. To match a reference, \`image_analyze\` it FIRST, then write ` +
243
+ `your generate prompt from what you actually SAW.` +
238
244
  `\n**Likeness is LIVE — this is how you "generate HER".** To make a SPECIFIC person, pass their FACE photo ` +
239
- `as \`reference\` to \`image_generate\`: it routes to the identity broker (RealVisXL + IP-Adapter-FaceID) ` +
245
+ `as \`reference\` to \`image_generate\`: it routes to the identity broker (the same RealVisXL wired above, plus IP-Adapter-FaceID) ` +
240
246
  `which preserves that exact face (arcface-verified) in whatever new scene/pose your prompt describes — you ` +
241
247
  `do NOT build your own pipeline for this, the tool does it. The result carries an honest \`axe_identity\` ` +
242
248
  `block — if \`identity_applied\` is false or \`fidelity_note\` is weak/none, SAY so; never pass a look-alike ` +
243
249
  `off as an exact match. A VIDEO of that person from a shared image works too (its first frame IS the real ` +
244
250
  `photo) via \`reference_image\` on \`video_generate\`. Every generation is logged to a provenance flywheel, ` +
245
251
  `so the pipeline compounds with use.` +
252
+ `\n**A media tool that errors is an OUTAGE, not a missing capability.** If \`image_generate\` / \`video_generate\` / ` +
253
+ `\`image_analyze\` / \`voice_*\` returns an error (worker down, 5xx, timeout): retry once, and if it is still down ` +
254
+ `TELL THE OWNER. NEVER install ComfyUI, diffusers, comfy-cli, inference.sh or any CLI, and NEVER download ` +
255
+ `diffusion/vision/voice weights, to substitute for it on your own initiative — the shell will redirect it ` +
256
+ `anyway, and the capability already exists as the tool. Only when the OWNER explicitly asks for that install: ` +
257
+ `say the native tool already covers it, and if they still want it, run it (the shell redirects once — re-issue ` +
258
+ `the same command to proceed; a weight download stays blocked until the owner lifts it).` +
259
+ `\n## Deep research — \`deep_research\` (cited, multi-source)\nWhen a question needs more than one search — a ` +
260
+ `comparison, a state-of-the-art survey, sourced background — reach for \`deep_research\`: it plans several ` +
261
+ `search angles, fans out \`web_search\` + \`web_fetch\` across them, and returns a brief with inline source ` +
262
+ `citations. A single lookup is faster with plain \`web_search\`; use \`deep_research\` when depth and ` +
263
+ `citations matter. It never invents sources — if the search backend is down it says so rather than guessing.` +
246
264
  `\n## Running scripts — never inline a multi-line script\nFor anything more than a ONE-LINE snippet, write ` +
247
265
  `the script to a file with file_write and run the file (\`python3 /tmp/probe.py\`). Do NOT embed a ` +
248
266
  `multi-line program inside \`python3 -c "…"\` or \`bash -c "…"\`: the newlines, \`#\` comments and quotes ` +
@@ -330,11 +348,19 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
330
348
  `when you're running low on context, call session_handoff to record what you did, the state, and the ` +
331
349
  `next steps: your next session in this directory loads it automatically, so write it for your future self.` +
332
350
  (opts.interactive
333
- ? `\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
334
- `build) call spawn_agent with a fully self-contained instruction — it runs on another session ` +
335
- `in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
336
- `live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
337
- `spawn many at once — they all share this one model.`
351
+ ? `\n## Sub-agents\nUse them to cover more ground and finish faster. You have spawn_agent and delegate_task: ` +
352
+ `farm a self-contained subtask to a parallel session that posts its result back while you keep working. ` +
353
+ `Reach for them PROACTIVELY — run the work like a staff engineer directing a team, not a solo grind:\n` +
354
+ `- COVERAGE: fan out independent pieces at once — search several subsystems, draft multiple files, audit N ` +
355
+ `things in parallel. Each sub-agent's noise stays OUT of your context, so you cover far more ground without ` +
356
+ `bloating this thread.\n` +
357
+ `- SPEED: parallelize what isn't bottlenecked on this one model — tool/IO-bound subtasks, or subtasks you ` +
358
+ `route to a DIFFERENT backend (delegate_task with model: e.g. cortana or a cloud tier) so they genuinely run ` +
359
+ `alongside you. N sub-agents on this ONE local model SERIALIZE at the model, so spawn several only when they ` +
360
+ `run on different endpoints OR the win is coverage / context-isolation rather than wall-clock.\n` +
361
+ `- Give each a FULLY self-contained instruction (it can't see this chat and can't ask questions). Skip ` +
362
+ `trivial inline work. The user watches each sub-agent live — its own colour, tokens, and time — in the ` +
363
+ `background panel.`
338
364
  : ""));
339
365
  }
340
366
  const LEAN_NOTE = "\n\n(Lean harness: long-term memory + handoff omitted to fit this model's smaller context — answer from the live conversation; do not recite stored notes.)";
@@ -391,6 +417,6 @@ export function composeSystemPrompt(o) {
391
417
  renderHarnessContext(cwd) +
392
418
  (lean ? LEAN_NOTE : loadHandoff()) +
393
419
  (skillsIdx ? `\n\n## Skills installed locally (skill_fetch <name> loads one; skill_fetch <name> <file_path> reads its references/templates/scripts)\n${skillsIdx}` : "") +
394
- renderToolCatalogue(undefined, { lean }) +
420
+ renderToolCatalogue(visibleRegistry(o.settings.powerTools), { lean }) +
395
421
  (interactive ? renderEmbodimentGuide(!!o.settings.computer?.enabled, o.chauffeurReady ?? !!o.settings.mcp) : ""));
396
422
  }
@@ -8,6 +8,7 @@ import { dirname } from "node:path";
8
8
  import { operatorPath } from "./home.js";
9
9
  import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
10
10
  import { DEFAULT_MODEL_ID } from "../router/models.js";
11
+ import { DEFAULT_POWER_TOOLS } from "../tools/power-tools.js";
11
12
  // The sole endpoint: Aurora on :8097 at its REAL served context — 307,200 tokens (300K; the llama-server
12
13
  // runs --ctx-size 307200 with q8_0 KV cache, standardized on JL1+JL2 2026-09-27). ctxWindow MUST match the
13
14
  // server's real --ctx-size: an inflated value (it was 1048576/"1M") makes compaction fire far too late — the
@@ -23,10 +24,15 @@ const DEFAULTS = {
23
24
  },
24
25
  modelMode: "local", // default: this node uses its own local model (endpoints.aurora); set "aurora" to use the shared fleet
25
26
  fleet: { auroraNodes: ["http://192.168.1.103:8097", "http://192.168.1.146:8097"] }, // JL1, JL2 — the live Aurora serving nodes (priority order)
26
- maxTokens: 32768, // generous per-reply output cap — 1M ctx has ample room; clampMaxTokens still trims
27
- // to the space left after the prompt so a reply never overflows. A small cap (was
28
- // 2048) forced the model to truncate + work around; this lets full files/answers land.
27
+ maxTokens: 64000, // per-reply output ceiling at the frontier bar (Claude Code/Sonnet allow up to 64k output;
28
+ // Codex/Gemini similar). clampMaxTokens still fits it to the space left after the prompt, so a
29
+ // reply never overflows — this is a CEILING the model rarely reaches, not a target. Max output
30
+ // so a big file/answer lands whole in one reply instead of truncating + working around.
29
31
  temperature: 0.7,
32
+ compaction: { threshold: 0.9 }, // compact only NEAR the window (frontier posture: Claude Code/Gemini use the
33
+ // full context + compact near the limit), not at a conservative fraction. The
34
+ // absolute RAM-safe ceiling (compactionCeilingTokens) still binds first on a
35
+ // local big-window model; this governs fast/cloud models with ample decode.
30
36
  mcp: false,
31
37
  memory: { recall: true },
32
38
  selfImprove: { flywheel: true, memory: false, skills: false, reflect: false }, // trajectory capture ON; memory/skills/reflect sinks staged
@@ -38,6 +44,7 @@ const DEFAULTS = {
38
44
  telemetry: { enabled: true }, // local-only metrics (silent JSONL); remote sink opt-in via KODE_TELEMETRY_URL
39
45
  sandbox: { mode: "off" }, // no isolation by default — enterprise turns it on (KODE_SANDBOX / settings)
40
46
  computer: { enabled: false }, // computer control OFF by default; enable with KODE_COMPUTER=1 or settings.json
47
+ powerTools: DEFAULT_POWER_TOOLS, // agnostic logWatch ON; fleet-coupled groups OFF (KODE_POWERTOOLS_* / settings.json)
41
48
  search: {}, // web_search backend unset by default; set search.searxngUrl / search.autopilotUrl or the env vars
42
49
  // Service lever — JL1 defaults. On a machine without these launchd agents every start step just fails
43
50
  // harmlessly and the boot screen falls back to the manual hint (autostart is best-effort by design).
@@ -92,7 +99,7 @@ function readSettingsFile(path) {
92
99
  /** Fold env vars over the file+default merge — the top layer of the precedence stack. Only an env
93
100
  * var that's actually set overrides; an unset one leaves the file/default value alone. */
94
101
  function applyEnv(s) {
95
- const out = { ...s, endpoints: { ...s.endpoints }, memory: { ...s.memory }, selfImprove: { ...s.selfImprove }, verifyGate: { ...s.verifyGate }, background: { ...s.background }, ui: { ...s.ui }, permissions: { ...s.permissions }, telemetry: { ...s.telemetry }, sandbox: { ...s.sandbox }, computer: { ...s.computer }, search: { ...s.search }, services: s.services ? structuredClone(s.services) : undefined, compaction: s.compaction ? { ...s.compaction } : undefined };
102
+ const out = { ...s, endpoints: { ...s.endpoints }, memory: { ...s.memory }, selfImprove: { ...s.selfImprove }, verifyGate: { ...s.verifyGate }, background: { ...s.background }, ui: { ...s.ui }, permissions: { ...s.permissions }, telemetry: { ...s.telemetry }, sandbox: { ...s.sandbox }, computer: { ...s.computer }, powerTools: { ...s.powerTools }, search: { ...s.search }, services: s.services ? structuredClone(s.services) : undefined, compaction: s.compaction ? { ...s.compaction } : undefined };
96
103
  if (process.env.KODE_MODEL)
97
104
  out.endpoints = { ...out.endpoints, aurora: { ...out.endpoints.aurora, model: process.env.KODE_MODEL } }; // AI-agnostic quick-swap (keeps failover)
98
105
  const mm = process.env.KODE_MODEL_MODE; // local | aurora — env override of the node's model source
@@ -135,6 +142,27 @@ function applyEnv(s) {
135
142
  out.sandbox = { mode: sb };
136
143
  if (process.env.KODE_COMPUTER === "1")
137
144
  out.computer = { enabled: true };
145
+ // Power-tools feature flags — each KODE_POWERTOOLS_* (1/0) overrides its group; agnostic logWatch defaults
146
+ // ON, the fleet-coupled groups OFF. A disabled group's tools are absent from schemas/catalogue/executor.
147
+ const ptFlag = (name) => {
148
+ const v = process.env[name];
149
+ return v === "1" ? true : v === "0" ? false : undefined;
150
+ };
151
+ const ptLog = ptFlag("KODE_POWERTOOLS_LOGWATCH");
152
+ const ptFleet = ptFlag("KODE_POWERTOOLS_FLEET");
153
+ const ptMem = ptFlag("KODE_POWERTOOLS_FLEETMEM");
154
+ const ptHydra = ptFlag("KODE_POWERTOOLS_HYDRA");
155
+ const ptHf = ptFlag("KODE_POWERTOOLS_HFUPLOAD");
156
+ if (ptLog !== undefined)
157
+ out.powerTools = { ...out.powerTools, logWatch: ptLog };
158
+ if (ptFleet !== undefined)
159
+ out.powerTools = { ...out.powerTools, fleetOps: ptFleet };
160
+ if (ptMem !== undefined)
161
+ out.powerTools = { ...out.powerTools, fleetMemory: ptMem };
162
+ if (ptHydra !== undefined)
163
+ out.powerTools = { ...out.powerTools, trainingCapture: ptHydra };
164
+ if (ptHf !== undefined)
165
+ out.powerTools = { ...out.powerTools, hfUpload: ptHf };
138
166
  // Service lever: KODE_SERVICES_AUTOSTART=0 disables autostart of BOTH launchd services (Operator then
139
167
  // only probes + reports); KODE_STOP_SEARXNG_ON_EXIT=0 keeps the SearXNG container running after exit.
140
168
  if (out.services) {
@@ -149,6 +177,11 @@ function applyEnv(s) {
149
177
  out.services = { ...out.services, stopOnExit: { ...out.services.stopOnExit, searxng: false } };
150
178
  }
151
179
  }
180
+ // Auto-detect boot: KODE_AUTODETECT=0 probes only the active endpoint; KODE_AUTODETECT_CLOUD=0 never falls back to a BYO vendor.
181
+ if (process.env.KODE_AUTODETECT === "0")
182
+ out.autodetect = { ...out.autodetect, enabled: false };
183
+ if (process.env.KODE_AUTODETECT_CLOUD === "0")
184
+ out.autodetect = { ...out.autodetect, cloud: false };
152
185
  // Autonomy env overrides. KODE_KEEP_AWAKE=1 forces keep-awake for the run; KODE_AUTONOMY_DREAM=0/1
153
186
  // is the hard dream off/on switch that overrides the file. Both only act when actually set.
154
187
  if (out.autonomy) {
@@ -197,8 +230,16 @@ export function defaultCompactionCeiling(totalBytes, windowTokens) {
197
230
  // a small live context keeps every owner-facing reply fast; retrieval reclaims what compaction summarizes out.
198
231
  // Autonomy rides high — just under the 64GB swap cliff (~126k) — because an unattended run isn't waiting on
199
232
  // decode and fewer compactions means it holds the thread across a long multi-step mission instead of thrashing.
200
- const INTERACTIVE_DEFAULT_CEILING = 24_000;
201
- const AUTONOMY_DEFAULT_CEILING = 100_000;
233
+ // Owner directive (James 2026-10-10): max every software limit — hold as much context as the hardware safely
234
+ // allows, compact only near the real limit (the frontier posture: Claude Code / Codex / Gemini use the full
235
+ // window and compact near it, not at an artificial low ceiling). Both modes now ride the RAM-aware safe ceiling
236
+ // (defaultCompactionCeiling clamps 1_000_000 down to what fits without swapping — ~126k on a 64GB box, higher on
237
+ // more RAM, 0.85·window on a huge-RAM box). The clamp is NOT a policy limit: crossing it swaps the KV cache and
238
+ // decode collapses to ~0 tok/s (a freeze, not a slowdown), so it stays as crash-prevention. NOTE the tradeoff
239
+ // the owner accepts: a larger live context = slower per-reply DECODE on a bandwidth-bound local model; the ceiling
240
+ // never limited token SPEND, it protected decode speed. An explicit settings/env override still wins either way.
241
+ const INTERACTIVE_DEFAULT_CEILING = 1_000_000;
242
+ const AUTONOMY_DEFAULT_CEILING = 1_000_000;
202
243
  /** The absolute-token proactive-compaction ceiling to hand runTurn, resolved PER SESSION MODE — the one knob
203
244
  * that stops us trading reign for speed. Interactive and autonomy each have their own explicit override
204
245
  * (`compaction.ceilingTokens` / `compaction.autonomyCeilingTokens`, env-overridden in loadSettings) validated
@@ -72,6 +72,25 @@ const NO_EDIT_NUDGE = 15; // tool rounds that change NO file ⇒ ONE soft "conve
72
72
  const THINK_SPIRAL_ROUNDS = 5; // consecutive heavy-reasoning, no-file-edit rounds (while /think on) ⇒ latch think OFF
73
73
  const THINK_SPIRAL_MIN_REASON_CHARS = 400; // a round counts as "heavy reasoning" only past this much reasoning_content
74
74
  const REHYDRATE_MAX_FILES = 5; // after a compaction, name up to this many recently-touched files for the model to re-read
75
+ // Decode-speed floor — the latency guarantee (James 2026-10-10, AXE-WARDEN: "a field user's life is on the line,
76
+ // Operator cannot crawl"). A bandwidth-bound local model's DECODE rate falls as the live context grows (measured
77
+ // ~45→9→5 tok/s on a 64GB box; a 300k-ctx model at ~89k was 7 tok/s → 7-min turns). When the last round's measured
78
+ // decode rate drops below the floor, the compaction ceiling is tightened to SPEED_PROTECT_CEILING so the NEXT round
79
+ // compacts hard — Operator shrinks its own context to restore speed instead of sitting at a few tok/s for minutes.
80
+ // ADAPTIVE: it only tightens WHEN decode is actually suffering, so a fast model (cloud / spec-decode / small local)
81
+ // keeps its full context ceiling — speed AND context, not one fixed slider. Env KODE_DECODE_FLOOR_TPS overrides.
82
+ const DECODE_SPEED_FLOOR_TPS = (() => { const v = Number(process.env.KODE_DECODE_FLOOR_TPS); return Number.isFinite(v) && v >= 0 ? v : 12; })();
83
+ const SPEED_PROTECT_CEILING = (() => { const v = Number(process.env.KODE_SPEED_PROTECT_CEILING); return Number.isFinite(v) && v >= 8000 ? v : 32_000; })();
84
+ /** The effective compaction ceiling after the decode-speed floor. When the model decoded BELOW the floor last
85
+ * round (a big context on bandwidth-bound HW), cap the ceiling at SPEED_PROTECT_CEILING so the proactive-compaction
86
+ * gate fires and the context shrinks; above the floor (or no measurement yet) the configured ceiling stands, so
87
+ * context is traded for speed ONLY while speed is actually suffering. Pure + exported for tests. */
88
+ export function speedProtectedCeiling(ceiling, decodeTokPerSec) {
89
+ if (decodeTokPerSec != null && decodeTokPerSec > 0 && decodeTokPerSec < DECODE_SPEED_FLOOR_TPS) {
90
+ return Math.min(ceiling ?? SPEED_PROTECT_CEILING, SPEED_PROTECT_CEILING);
91
+ }
92
+ return ceiling;
93
+ }
75
94
  const COMPACTION_FAIL_LIMIT = 3; // rounds still OVER the window after compaction ran ⇒ it can't free space (summarizer failing / un-evictable bulk); stop spinning into the same wall
76
95
  const MAX_TRUNC_RETRIES = 3; // chunk-write nudges before a repeatedly-truncated tool call surfaces honestly — a
77
96
  // genuinely large body (docstring, generated file) can need one extra round past the quote-fix case: first
@@ -257,7 +276,7 @@ function parseArgs(raw) {
257
276
  * guard (SPEC §2: identical (name,args) ≥3× this turn is short-circuited) and reporting the
258
277
  * batch via onToolBatch with a real (unrounded) duration.
259
278
  */
260
- async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolStart, onToolResult) {
279
+ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolStart, onToolResult, signal) {
261
280
  // One id for this whole round (SPEC parallel-tool-batch) — every call made here, however it
262
281
  // resolves (executed, parse error, loop-guarded), shares it, so a host can box "N tools in
263
282
  // parallel" together even for the calls that never reached the executor. Same id-shape idiom as
@@ -310,7 +329,7 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
310
329
  onToolStart?.(pending);
311
330
  const started = performance.now();
312
331
  const executed = pending.length
313
- ? await tools.executeParallel(pending, onToolResult ? (i, r) => onToolResult(pending[i].id, r, batchId) : undefined)
332
+ ? await tools.executeParallel(pending, onToolResult ? (i, r) => onToolResult(pending[i].id, r, batchId) : undefined, signal)
314
333
  : [];
315
334
  const durationMs = performance.now() - started;
316
335
  const resultById = new Map(preResolved);
@@ -458,6 +477,7 @@ export async function runTurn(userInput, conversation, opts) {
458
477
  let tokensTotal = 0; // output tokens summed across rounds (from llama.cpp timings)
459
478
  let genMsTotal = 0; // server-side generation ms summed across rounds
460
479
  let promptTokensTotal = 0; // prompt tokens PREFILLED, summed across rounds
480
+ let lastDecodeTokPerSec; // last round's measured decode rate (tok/s) — drives the speed-floor on the NEXT round's compaction gate
461
481
  let promptMsTotal = 0; // prefill ms summed across rounds
462
482
  let emptyRetries = 0; // reasoning models sometimes return a "dud" round (no content, no tool calls)
463
483
  let truncRetries = 0; // chunk-write nudges spent recovering a truncated-tool-call 500 (truncatedToolNudge)
@@ -516,7 +536,7 @@ export async function runTurn(userInput, conversation, opts) {
516
536
  tools: opts.toolSchemas,
517
537
  summarize: opts.summarize,
518
538
  threshold: opts.compactionThreshold,
519
- ceilingTokens: opts.compactionCeilingTokens,
539
+ ceilingTokens: speedProtectedCeiling(opts.compactionCeilingTokens, lastDecodeTokPerSec), // latency guarantee: tighten when decode is below the floor
520
540
  minKeepTurns: opts.minKeepTurns,
521
541
  meter: globalTokenMeter, // SPEC §5: size to THIS endpoint's learned ratio, not chars/4
522
542
  meterKey: endpointKey(ep.base, ep.model),
@@ -580,6 +600,12 @@ export async function runTurn(userInput, conversation, opts) {
580
600
  });
581
601
  tokensTotal += response.tokens ?? 0;
582
602
  genMsTotal += response.genMs ?? 0; // accumulate real gen metrics across rounds
603
+ // Measure THIS round's decode rate (tok/s) from the server's own gen timing — feeds the speed-floor
604
+ // (speedProtectedCeiling) on the next round's compaction gate. Needs a real sample (enough tokens over
605
+ // enough time) so a tiny/instant round can't spuriously trip or clear the floor.
606
+ if ((response.tokens ?? 0) >= 16 && (response.genMs ?? 0) >= 250) {
607
+ lastDecodeTokPerSec = response.tokens / (response.genMs / 1000);
608
+ }
583
609
  promptTokensTotal += response.promptTokens ?? 0;
584
610
  promptMsTotal += response.promptMs ?? 0; // and prefill (the invisible wall-time cost)
585
611
  // Token meter (SPEC §5): teach the endpoint its real chars/token from the server's EXACT
@@ -766,7 +792,9 @@ export async function runTurn(userInput, conversation, opts) {
766
792
  opts.onSelfHeal?.("server_error", seen - CONTENT_LOOP_LIMIT + 1); // footer ↻ — breaking a stall
767
793
  conversation.user(`You've repeated the same step ${seen}× with the same result — that approach is not working. Do NOT ` +
768
794
  `end the turn or ask me how to proceed. STOP repeating it and try a genuinely DIFFERENT approach: a ` +
769
- `different command, tool, path, or angle; if a tool seems broken, work around it. If you already ` +
795
+ `different command, tool, path, or angle; if a tool seems broken, work around it — but NEVER replace ` +
796
+ `a native tool (image/video/vision/voice, search, delegate) by installing tooling or downloading ` +
797
+ `models: a tool that errors is an outage, so retry it once and report it. If you already ` +
770
798
  `know the fix (you often do — you just described one), do it now.`);
771
799
  continue;
772
800
  }
@@ -789,7 +817,8 @@ export async function runTurn(userInput, conversation, opts) {
789
817
  ` (a) BREAK IT DOWN — split the stuck step into a smaller, concrete sub-action and do just that ` +
790
818
  `one thing now; or\n` +
791
819
  ` (b) SWITCH APPROACH — a genuinely different tool, command, path, or order of operations; if a ` +
792
- `tool or command seems broken, work around it.\n` +
820
+ `tool or command seems broken, work around it — but NEVER replace a native tool by installing ` +
821
+ `tooling or downloading models (a failing tool is an outage: retry once, then report it).\n` +
793
822
  `Do NOT reproduce your previous output, do NOT end the turn, and do NOT ask me how to proceed — ` +
794
823
  `decide and act on the smallest next concrete step.`);
795
824
  continue;
@@ -860,7 +889,7 @@ export async function runTurn(userInput, conversation, opts) {
860
889
  conversation.assistant(response.content, response.toolCalls);
861
890
  // Race the batch against the abort signal so esc breaks even a hung tool (a frozen child process) —
862
891
  // the abandoned tool runs to its own timeout, but the turn is never wedged.
863
- const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
892
+ const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal), opts.signal);
864
893
  for (const tm of capToolRound(toolMsgs))
865
894
  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
866
895
  observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
@@ -878,7 +907,7 @@ export async function runTurn(userInput, conversation, opts) {
878
907
  if (recovered.calls.length > 0) {
879
908
  throwIfAborted(opts.signal);
880
909
  conversation.assistant(recovered.cleanedContent, recovered.calls);
881
- const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
910
+ const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal), opts.signal);
882
911
  for (const tm of capToolRound(toolMsgs))
883
912
  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
884
913
  observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
@@ -0,0 +1,48 @@
1
+ // Anthropic Messages API client — the one cloud model Operator calls DIRECTLY (outside the OpenAI-shaped
2
+ // router), used by the deep_research tool. Anthropic's wire format differs from OpenAI: `x-api-key` auth
3
+ // (not Bearer), an `anthropic-version` header, a top-level `system`, and a `content[]` array in the reply.
4
+ // Key resolution: KODE_ANTHROPIC_KEY, then ANTHROPIC_API_KEY. Model: KODE_RESEARCH_MODEL, else Haiku 4.5.
5
+ const DEFAULT_MODEL = process.env.KODE_RESEARCH_MODEL || "claude-haiku-4-5-20251001";
6
+ export function anthropicKey() {
7
+ return process.env.KODE_ANTHROPIC_KEY || process.env.ANTHROPIC_API_KEY || undefined;
8
+ }
9
+ /** POST one Anthropic Messages turn and return the concatenated text of the reply. Throws on a missing
10
+ * key, a non-200, or a timeout — the caller surfaces that to the model as a tool error. */
11
+ export async function anthropicComplete(system, user, opts = {}) {
12
+ const key = anthropicKey();
13
+ if (!key)
14
+ throw new Error("no Anthropic API key configured"); // key env vars documented in AGENTS.md
15
+ const ctrl = new AbortController();
16
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 120_000);
17
+ try {
18
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
19
+ method: "POST",
20
+ signal: ctrl.signal,
21
+ headers: {
22
+ "Content-Type": "application/json",
23
+ "x-api-key": key,
24
+ "anthropic-version": "2023-06-01",
25
+ "User-Agent": "operator/kode-tsi",
26
+ },
27
+ body: JSON.stringify({
28
+ model: opts.model || DEFAULT_MODEL,
29
+ max_tokens: opts.maxTokens ?? 4096,
30
+ temperature: opts.temperature ?? 0.3,
31
+ system,
32
+ messages: [{ role: "user", content: user }],
33
+ }),
34
+ });
35
+ if (!res.ok) {
36
+ const body = (await res.text().catch(() => "")).slice(0, 300);
37
+ throw new Error(`Anthropic ${res.status}${body ? ` — ${body}` : ""}`);
38
+ }
39
+ const j = (await res.json());
40
+ const text = (j.content ?? []).filter((b) => b.type === "text").map((b) => b.text ?? "").join("").trim();
41
+ if (!text)
42
+ throw new Error("Anthropic returned no text");
43
+ return text;
44
+ }
45
+ finally {
46
+ clearTimeout(timer);
47
+ }
48
+ }
@@ -9,14 +9,16 @@
9
9
  // key equals or is a path prefix of the other (dir vs child), when either is a device barrier, or
10
10
  // both are unknown-name writes with no keys (conservative: no keys + mutating = device-class).
11
11
  // • READS (pure ops) run alongside anything that cannot change what they observe: they wait only for
12
- // prior WRITES on conflicting keys. WRITES wait for everything conflicting (read-after-write is a
13
- // read's concern; write-after-write and write-after-read are this write's concern) — serialized
14
- // per-resource in INPUT ORDER via the resource's tail promise.
12
+ // prior WRITES on conflicting keys. WRITES wait for everything conflicting — prior writes AND prior
13
+ // reads that named an overlapping resource (RAW, WAW and WAR) — so a batch is observably equivalent to
14
+ // running it one call at a time in input order, on every resource it shares. A read that named no
15
+ // resource (web_search, memory_search…) never holds a writer back.
15
16
  // • Barrier tools (bash/shell_exec/git_command/checkpoint/computer_*/browser*/browser_vault/…) can
16
17
  // touch ANYTHING and share one persistent shell — they run alone, in input order.
17
18
  // • A rejected/denied run resolves as a string (executor contract: resolve-not-reject); one call's
18
19
  // failure never strands its dependents — the chain advances regardless.
19
20
  // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
21
+ export const cancelledResult = (name) => `cancelled: ${name} did not start — the turn was interrupted before it ran`;
20
22
  const BARRIER_EXACT = new Set([
21
23
  "bash", "shell_exec", "shell_background", "bash_kill",
22
24
  "git_command", "checkpoint", "tool_call",
@@ -34,17 +36,35 @@ export function defaultClassify(name, isSafe) {
34
36
  return isSafe(n) ? "read" : "write";
35
37
  };
36
38
  }
37
- /** Path-ish arg keys: any string value under a path-named arg, normalized to a comparable key.
38
- * A MUTATING call with no path keys gets a per-name lock — injected by runBatch (which knows the
39
- * class), never here: reads must not acquire locks or they could never pair with their writes. */
40
- export function defaultKeys(_name, args) {
39
+ const KEY_ARG = /path|dir|file|cwd|target|token|handle|^(out|output|dest|destination)$/i; // output-path args name a file the call WRITES
40
+ const KEY_DEPTH = 4;
41
+ /** Resource keys of a call: every string under a path-named arg — directly, as an array element (read_files
42
+ * `paths`), or inside a nested object (`edits:[{path}]`; a name set at the nearest object key) — normalized to a
43
+ * comparable key. `resolve` lets the node-side executor turn a spelling into the absolute path the tool will
44
+ * touch (cwd/root/~ are not the scheduler's to know). A MUTATING call with no keys gets a per-name lock —
45
+ * injected by runBatch (which knows the class), never here: reads must not acquire locks or they could never
46
+ * pair with their writes. */
47
+ export function defaultKeys(_name, args, resolve) {
41
48
  const out = [];
42
- for (const [k, v] of Object.entries(args ?? {})) {
43
- if (typeof v === "string" && v && /path|dir|file|cwd|target|token|handle/i.test(k))
44
- out.push(normKey(v));
45
- }
49
+ collectKeys(args ?? {}, "", false, 0, out, resolve);
46
50
  return out;
47
51
  }
52
+ function collectKeys(v, argName, named, depth, out, resolve) {
53
+ if (typeof v === "string") {
54
+ if (named && v)
55
+ out.push(normKey(resolve ? resolve(v, argName) : v));
56
+ return;
57
+ }
58
+ if (depth >= KEY_DEPTH || v === null || typeof v !== "object")
59
+ return;
60
+ if (Array.isArray(v)) {
61
+ for (const e of v)
62
+ collectKeys(e, argName, named, depth + 1, out, resolve);
63
+ return;
64
+ }
65
+ for (const [k, e] of Object.entries(v))
66
+ collectKeys(e, k, KEY_ARG.test(k), depth + 1, out, resolve);
67
+ }
48
68
  function normKey(p) {
49
69
  const t = p.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
50
70
  const trimmed = t.replace(/\/+$/, "");
@@ -62,8 +82,23 @@ export function runBatch(calls, opts) {
62
82
  const results = new Array(calls.length);
63
83
  const done = [];
64
84
  const writeTails = new Map(); // resource key -> last WRITE on it
85
+ const keyedReads = []; // prior reads that named a resource (a later conflicting write waits for them)
65
86
  const inflight = new Set(); // everything not yet settled (barrier gate)
66
87
  let afterBarrier = Promise.resolve(); // every op must clear the last barrier
88
+ // Cancellation: `aborted` settles when the turn is interrupted so queued calls stop waiting on their
89
+ // predecessors and are cancelled, not run late. The listener is removed when the batch ends — a long turn
90
+ // runs hundreds of batches on ONE signal and an unremoved listener per batch trips the EventTarget leak warning.
91
+ const signal = opts.signal;
92
+ let detach = () => { };
93
+ const aborted = signal && new Promise((resolve) => {
94
+ if (signal.aborted) {
95
+ resolve();
96
+ return;
97
+ }
98
+ const onAbort = () => resolve();
99
+ signal.addEventListener("abort", onAbort, { once: true });
100
+ detach = () => signal.removeEventListener("abort", onAbort);
101
+ });
67
102
  for (let i = 0; i < calls.length; i++) {
68
103
  const c = calls[i];
69
104
  const kind = opts.classify(c.name);
@@ -85,9 +120,7 @@ export function runBatch(calls, opts) {
85
120
  gate.push(t2); // path-less read: any prior write may target it
86
121
  }
87
122
  for (const k of keys) {
88
- // A read waits only for PRIOR WRITES on overlapping resources. Prior READS never matter
89
- // (nothing to serialize), and a write after a read must NOT wait for the read: the model
90
- // consumes results next turn; any pre/post read value is a valid serialization.
123
+ // A read waits only for PRIOR WRITES on overlapping resources; prior reads never block it.
91
124
  for (const [wk, wt] of writeTails)
92
125
  if (conflicts(k, wk))
93
126
  gate.push(wt);
@@ -99,15 +132,27 @@ export function runBatch(calls, opts) {
99
132
  for (const [wk, wt] of writeTails)
100
133
  if (conflicts(k, wk))
101
134
  gate.push(wt);
135
+ // WAR: a write must not overlap an EARLIER read of the same resource. A read racing a write is not
136
+ // "either old or new": file writes truncate-then-fill, so the read can observe an empty/partial file
137
+ // (measured: 10 of 40 [file_read f, file_write f] batches returned an empty read), and a delete
138
+ // can pull the file out from under it. Sequential order would always give the old content.
139
+ for (const r of keyedReads)
140
+ if (r.keys.some((rk) => conflicts(k, rk)))
141
+ gate.push(r.run);
102
142
  }
103
143
  }
104
- const run = Promise.all(gate).then(async () => {
144
+ const ready = Promise.all(gate);
145
+ const run = (aborted ? Promise.race([ready, aborted]) : ready).then(async () => {
105
146
  let r;
106
- try {
107
- r = await opts.runOne(c);
108
- }
109
- catch (e) {
110
- r = `error running ${c.name}: ${e?.message ?? String(e)}`;
147
+ if (signal?.aborted)
148
+ r = cancelledResult(c.name);
149
+ else {
150
+ try {
151
+ r = await opts.runOne(c);
152
+ }
153
+ catch (e) {
154
+ r = `error running ${c.name}: ${e?.message ?? String(e)}`;
155
+ }
111
156
  }
112
157
  results[i] = r;
113
158
  try {
@@ -120,9 +165,11 @@ export function runBatch(calls, opts) {
120
165
  else if (kind === "write")
121
166
  for (const k of keys)
122
167
  writeTails.set(k, run);
168
+ else if (keys.length)
169
+ keyedReads.push({ keys, run });
123
170
  inflight.add(run);
124
171
  run.then(() => inflight.delete(run));
125
172
  done.push(run);
126
173
  }
127
- return Promise.all(done).then(() => results);
174
+ return Promise.all(done).then(() => { detach(); return results; });
128
175
  }
package/dist/mcp/index.js CHANGED
@@ -139,7 +139,7 @@ export function withMcp(local, hub) {
139
139
  classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
140
140
  keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
141
141
  },
142
- executeParallel: (calls, onSettle) => runBatch(calls, {
142
+ executeParallel: (calls, onSettle, signal) => runBatch(calls, {
143
143
  classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
144
144
  keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
145
145
  runOne: (c) => {
@@ -147,6 +147,7 @@ export function withMcp(local, hub) {
147
147
  return hub?.has(sc.name) ? hub.call(sc.name, sc.args) : local.execute(sc.name, sc.args);
148
148
  },
149
149
  onSettle,
150
+ signal,
150
151
  }),
151
152
  };
152
153
  }
@@ -1,6 +1,6 @@
1
1
  import { digestArgs } from "./audit.js";
2
2
  import { EventSink } from "../telemetry/events.js";
3
- import { runBatch, defaultClassify, defaultKeys } from "../engine/batch-scheduler.js";
3
+ import { runBatch, defaultClassify, defaultKeys, cancelledResult } from "../engine/batch-scheduler.js";
4
4
  import { registrySafeTools } from "./tier.js";
5
5
  export { PermissionPolicy } from "./policy.js";
6
6
  const DENIED = (name) => `Permission denied: "${name}" was refused by the operator permission policy. ` +
@@ -17,7 +17,7 @@ export function withPermissions(inner, policy, opts = {}) {
17
17
  // `batch` carries the round identity a PendingToolCall was stamped with (engine/agent.ts's
18
18
  // runToolCalls) onto every ToolEvent this call emits — absent for the single-call execute() path,
19
19
  // which has no round context.
20
- async function gate(name, args, exec, batch) {
20
+ async function gate(name, args, exec, batch, signal) {
21
21
  const digest = digestArgs(name, args);
22
22
  const decision = policy.decide(name, args);
23
23
  const t0 = performance.now();
@@ -44,6 +44,12 @@ export function withPermissions(inner, policy, opts = {}) {
44
44
  return DENIED(name);
45
45
  }
46
46
  }
47
+ // An esc during the (human) approval wait: the approval may land AFTER the interrupt, and an approved edit
48
+ // must not then execute. Recorded as an error (the wire outcome enum is frozen; nothing was refused by policy).
49
+ if (signal?.aborted) {
50
+ tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0, ...batch });
51
+ return cancelledResult(name);
52
+ }
47
53
  let result;
48
54
  try {
49
55
  result = await exec();
@@ -64,7 +70,7 @@ export function withPermissions(inner, policy, opts = {}) {
64
70
  // but conflicting resources serialize in input order through the shared DAG scheduler. The old
65
71
  // Promise.all-over-execute() dropped the 0.1.225 walk at this layer: a gated batch of
66
72
  // [write f, read f] raced, the read deterministically observing pre-write state on slow writes.
67
- executeParallel: (calls, onSettle) => {
73
+ executeParallel: (calls, onSettle, signal) => {
68
74
  const safe = new Set(registrySafeTools());
69
75
  return runBatch(calls, {
70
76
  // prefer the INNER executor's classification truth (per-session toolset); fall back to the
@@ -76,9 +82,10 @@ export function withPermissions(inner, policy, opts = {}) {
76
82
  const batch = sc.batchId !== undefined
77
83
  ? { batchId: sc.batchId, batchSize: sc.batchSize ?? calls.length, batchIndex: sc.batchIndex ?? calls.findIndex((x) => x.id === sc.id) }
78
84
  : undefined;
79
- return gate(sc.name, sc.args, () => inner.execute(sc.name, sc.args), batch);
85
+ return gate(sc.name, sc.args, () => inner.execute(sc.name, sc.args), batch, signal);
80
86
  },
81
87
  onSettle,
88
+ signal,
82
89
  });
83
90
  },
84
91
  };