@0perator/operator 0.1.165 → 0.1.167

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,37 @@ Operator is AXE's terminal coding agent (npm `@0perator/operator`), running on A
4
4
  Newest first. Every release bumps `src/cli.tsx` VERSION + `package.json`, adds an entry here, and ships to
5
5
  npm + both git remotes (memjar/kode, axetechnologies/kode). Test counts are the full suite at that release.
6
6
 
7
+ ## 0.1.167 — 2026-10-01 — Sub-agent watchdog: stall-detector, not an absolute wall-clock cap
8
+ - **A slow-but-progressing sub-agent is no longer killed.** The background watchdog was an *absolute* 20-minute
9
+ timer: a child token-starved behind the foreground on the single shared endpoint (seen live: 11 rounds, real
10
+ file writes, ~2.6k tokens in 20 min) got reaped mid-progress and marked "errored." It's now a true **stall
11
+ detector** — the clock resets on every real progress signal (a token via `onTokens`, a completed tool round
12
+ via `onToolBatch`), so only an agent that has made **no** progress for the window (a genuinely hung request —
13
+ connection open, no chunks, the case the watchdog exists for) is stopped. The stop reason is now the accurate
14
+ "no progress for Nm" instead of "exceeded Nm wall-clock limit". `KODE_BG_TIMEOUT_MS` still overrides the 20m
15
+ default. `src/background/index.ts`; `test/background-hardening.test.mts` +1 (a progressing agent survives 4×
16
+ the window). Full suite 791 passed, 0 failed.
17
+
18
+ ## 0.1.166 — 2026-10-01 — Grandmaster wave: cache-stable prefix, flywheel anti-poison, lossless tool results, sub-agent economics
19
+ - **GW-04 — deterministic tool-schema prefix.** `McpHub.schemas()` now sorts by namespaced name so the
20
+ `[system+tools]` prefix is byte-identical across sessions/restarts — KV prefix-cache reuse is strictly
21
+ prefix-positional, so any reorder zeroed every downstream hit. Pairs with slot-save/restore reuse. (Audit also
22
+ confirmed the prefix is already stable *within* a session: MCP discovery is first-turn-only.) +3 parity tests.
23
+ - **GW-18 (client) — flywheel anti-poisoning.** `hasLeakedToolCall()` flags tool-call markup that leaked into
24
+ assistant text (the `--jinja`-off Qwen failure); the flywheel sink excludes those turns from the promotable
25
+ training corpus and tags every row `parse_fallback` — so Aurora can't be trained to emit tool markup as prose.
26
+ +14-fixture parser canary. (Server `--jinja` half is fleet-serving side.)
27
+ - **GW-10 — lossless tool-result eviction.** A >40K tool result no longer discards its middle forever: the FULL
28
+ output spills to `~/.axe/operator/tool-outputs/<id>.txt` and the model gets a pointer to re-read the omitted
29
+ middle via `file_read(offset/limit)`. `capToolResult` stays node-free (spill sink injected → web bundle safe);
30
+ wired for all local tools (the dominant token sink). Fewer tokens/turn → slower approach to the depth ceiling.
31
+ +4 tests.
32
+ - **GW-14 — sub-agent economics.** The `spawn_agent` description + sub-agent brief now state a RETURN CONTRACT
33
+ (report ~1-2k tokens, file:line pointers not pasted output — a bloated child report forces the parent to
34
+ compact), a SINGLE-WRITER rule, and effort-matching.
35
+ - **`/rc`** alias for `/remotecontrol`.
36
+ - Full suite: 790 passed, 0 failed (105 files). `tsc --noEmit` clean.
37
+
7
38
  ## 0.1.165 — 2026-10-01 — Robustness: deep-context swap-thrash guard + ESC-abort hardening
8
39
  - **Swap-thrash guard (track · fix · prevent).** A long session could grow the live context past the box's RAM,
9
40
  so model weights + KV cache spilled into swap and decode collapsed to ~0 tok/s (measured 2026-10-01: context
@@ -129,20 +129,44 @@ export class BackgroundAgents {
129
129
  void this.run(id, entry.info, entry.brief, entry.type);
130
130
  }
131
131
  }
132
- /** Watchdog for a hung child: if it's still "working" after STALL_TIMEOUT_MS, stop() it (interrupt +
133
- * free its slot, same as an owner-initiated stop) and — unlike a deliberate stop, which the owner already
134
- * knows about — post an explicit, unmissable reason, since nobody asked for this one. A no-op if the
135
- * agent already finished by the time the timer fires (checked by id, so it can never fire on a reused
136
- * slot — ids are sequential and never recycled). */
132
+ /** Watchdog for a HUNG child — a STALL detector, NOT an absolute cap. The clock resets on every real
133
+ * progress signal (a token or a completed tool round, via touchProgress), so a slow-but-advancing agent —
134
+ * e.g. one token-starved behind the foreground on the single shared endpoint — is NEVER killed. Only an
135
+ * agent that has made NO progress for stallTimeoutMs (a genuinely hung request: connection open, no chunks)
136
+ * is stopped and its slot freed, with an explicit unmissable reason. A no-op once the agent leaves
137
+ * "working" (checked by id, which is never recycled). (Before this, the timer was absolute, so a correct
138
+ * agent crawling behind a busy foreground — 11 rounds, real file writes — was reaped mid-progress.) */
137
139
  scheduleStallTimeout(id) {
140
+ const a = this.agents.get(id);
141
+ if (a)
142
+ a.lastProgressAt = Date.now(); // start the stall clock from now
143
+ this.armStallCheck(id, this.stallTimeoutMs);
144
+ }
145
+ /** Reset the stall clock — called on each real progress signal so a working agent can't be reaped for
146
+ * being SLOW (only for being SILENT). Cheap: a timestamp write the armed check reads when it fires. */
147
+ touchProgress(id) {
148
+ const a = this.agents.get(id);
149
+ if (a)
150
+ a.lastProgressAt = Date.now();
151
+ }
152
+ /** Arm (or re-arm) the one-shot stall check `delay` ms out. When it fires: if the agent progressed within
153
+ * the window, re-arm for the remaining time instead of killing it; only genuine silence for the full
154
+ * stallTimeoutMs stops it. */
155
+ armStallCheck(id, delay) {
156
+ this.clearStallTimer(id);
138
157
  const timer = setTimeout(() => {
139
158
  const a = this.agents.get(id);
140
159
  if (!a || a.info.status !== "working")
141
160
  return; // finished/stopped already — nothing to do
161
+ const idle = Date.now() - (a.lastProgressAt ?? Date.now());
162
+ if (idle < this.stallTimeoutMs) {
163
+ this.armStallCheck(id, this.stallTimeoutMs - idle);
164
+ return;
165
+ } // progressed → not stalled
142
166
  const mins = Math.round(this.stallTimeoutMs / 60_000);
143
167
  this.stop(id);
144
- this.onDone(a.info, `[${id} stopped: exceeded ${mins}m wall-clock limit (stalled or a hung request) — any result above may be incomplete]`);
145
- }, this.stallTimeoutMs);
168
+ this.onDone(a.info, `[${id} stopped: no progress for ${mins}m (stalled or a hung request) — any partial result above may be incomplete]`);
169
+ }, Math.max(100, delay));
146
170
  timer.unref?.();
147
171
  const entry = this.agents.get(id);
148
172
  if (entry)
@@ -200,7 +224,7 @@ export class BackgroundAgents {
200
224
  // to what prior sends already counted. Replaces the old ≈1-per-content-delta tally, which missed
201
225
  // every token generated as a tool-call argument or reasoning (most of a skill-writer's output — so
202
226
  // a sub-agent that wrote thousands of tokens read as "53 tok").
203
- onTokens: (t) => { info.tokens = total + t; this.onChange(); },
227
+ onTokens: (t) => { info.tokens = total + t; this.touchProgress(id); this.onChange(); },
204
228
  // Reasoning stream → the "thinking" line. Coalesce (keep the tail) and throttle re-renders:
205
229
  // a long think can emit hundreds of chunks, but the panel only needs to refresh ~1/sec.
206
230
  onReasoning: (chunk) => {
@@ -225,6 +249,7 @@ export class BackgroundAgents {
225
249
  const settled = events.map((e) => ({ name: e.name, arg: shortArg(e.args), running: false }));
226
250
  info.steps = [...(info.steps ?? []).filter((s) => !s.running), ...settled].slice(-RECENT_STEPS);
227
251
  info.thought = undefined;
252
+ this.touchProgress(id); // a completed round is unambiguous progress — reset the stall clock
228
253
  this.onChange();
229
254
  // This child can mutate the same session-wide task list the foreground plan pane reads (a single
230
255
  // module-level store in registry.ts) — refresh the pane live instead of leaving it frozen until the
package/dist/cli.js CHANGED
@@ -1386,7 +1386,8 @@ function Root() {
1386
1386
  }
1387
1387
  break;
1388
1388
  case "remotecontrol":
1389
- case "remote": {
1389
+ case "remote":
1390
+ case "rc": {
1390
1391
  if (remoteRef.current) {
1391
1392
  remoteRef.current.stop();
1392
1393
  remoteRef.current = null;
@@ -69,6 +69,9 @@ export function buildBrief(input, cwd) {
69
69
  schemaHintFor(type),
70
70
  "```",
71
71
  "Use null for any field you genuinely cannot fill.",
72
+ "Keep it COMPACT (aim ≤1-2k tokens): prefer file:line pointers and short summaries over pasting large file",
73
+ "contents, logs, or full command output — the parent re-reads sources itself, and a bloated answer lands in",
74
+ "its context and can force a compaction.",
72
75
  ].join("\n");
73
76
  }
74
77
  // Pull the last JSON object out of the child's output — prefer a fenced ```json block, else the last
package/dist/mcp/index.js CHANGED
@@ -66,9 +66,18 @@ export class McpHub {
66
66
  has(name) {
67
67
  return this.tools.has(name);
68
68
  }
69
- /** OpenAI-format function schemas for every discovered remote tool (namespaced names). */
69
+ /** OpenAI-format function schemas for every discovered remote tool (namespaced names), SORTED by name.
70
+ * KV prefix-cache reuse is strictly prefix-positional, so any reorder of the tools array zeroes every
71
+ * downstream cache hit. discover() may populate `this.tools` in nondeterministic (concurrent) order, so we
72
+ * sort here — making the serialized [tools] blob byte-identical across sessions and restarts (GW-04), which
73
+ * is what lets slot-save/restore reuse survive a reconnect instead of re-prefilling from scratch. */
70
74
  schemas() {
71
- return [...this.tools.values()].map((t) => ({
75
+ return [...this.tools.values()]
76
+ .sort((a, b) => {
77
+ const an = `${a.server}${SEP}${a.def.name}`, bn = `${b.server}${SEP}${b.def.name}`;
78
+ return an < bn ? -1 : an > bn ? 1 : 0;
79
+ })
80
+ .map((t) => ({
72
81
  type: "function",
73
82
  function: {
74
83
  name: `${t.server}${SEP}${t.def.name}`,
@@ -4,6 +4,20 @@
4
4
  // REFLECTION. All sinks are best-effort and MUST never block or throw into a turn. Node imports are lazy
5
5
  // (same mobile/JSCore-bundle discipline as services/preflight.ts) so the neutral bundle carries none of it.
6
6
  const nodeImport = (m) => import(/* @vite-ignore */ m);
7
+ // GW-18 (flywheel gate): markers of a STRUCTURED tool call that leaked into the assistant's plain text instead
8
+ // of being parsed into tool_calls — the documented Qwen3 failure when the server runs without `--jinja` (the
9
+ // heuristic parser passes the XML through as content with finish_reason:"stop"). A turn like this is the worst
10
+ // possible training row: it's recorded as a "completed" turn, but the assistant text IS raw tool markup, so
11
+ // training on it teaches the model to EMIT the markup as prose — the agent self-poisons on its own parser bug.
12
+ // Also catches leaked think delimiters (reasoning that wasn't stripped). Err toward detection: a false positive
13
+ // only drops ONE turn from the corpus; a false negative poisons the model.
14
+ const TOOLCALL_LEAK = /<tool_call>|<\/tool_call>|<\|tool_call\|>|<function\s*=|<\/function>|<\/?think>/i;
15
+ /** True when assistant `content` contains leaked tool-call / think markup — i.e. the model's structured output
16
+ * was NOT parsed and bled into the text (a `--jinja`-off / template-mismatch parse fallback). Pure; exported
17
+ * for the parser canary. Such a turn must never be graded into the training corpus (GW-18). */
18
+ export function hasLeakedToolCall(content) {
19
+ return TOOLCALL_LEAK.test(content);
20
+ }
7
21
  /** FLYWHEEL sink — append the turn as one JSONL row to a daily capture the fleet's training pipeline reads.
8
22
  * A turn that produced content, ran ≥1 round, and wasn't cut for repetition/abort is marked graded:true,
9
23
  * so downstream can filter to promotable trajectories without re-judging every row. */
@@ -19,8 +33,12 @@ async function captureFlywheel(r) {
19
33
  // graded = a promotable trajectory. A turn that changed files but never ran a passing check
20
34
  // (unverified, per the verify-before-done gate) is NOT promotable — that is precisely the hollow
21
35
  // "done" this whole loop exists to stop the fleet from training on.
22
- const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified;
23
- const row = JSON.stringify({ ts: Date.now(), graded, ...r }) + "\n";
36
+ // A leaked/garbled tool call recorded as a "completed" turn would train the model to emit tool markup as
37
+ // prose (self-poisoning) — exclude it from promotable rows AND tag it so the pipeline can audit leak rate
38
+ // and the serving side (GW-01/GW-18 `--jinja`) can be verified by the trend going to ~0.
39
+ const parseFallback = hasLeakedToolCall(r.content);
40
+ const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !parseFallback;
41
+ const row = JSON.stringify({ ts: Date.now(), graded, parse_fallback: parseFallback, ...r }) + "\n";
24
42
  await appendFile(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), row);
25
43
  }
26
44
  catch { /* best-effort — capture never blocks or fails a turn */ }
package/dist/session.js CHANGED
@@ -48,7 +48,14 @@ function makeSpawnTool(handler) {
48
48
  "still working; call agent_status (no args) to see every sub-agent's real state before concluding " +
49
49
  "otherwise. A sub-agent id is NOT a shell_background job id — never poll it with bash_output/bash_kill " +
50
50
  "(those are for shell_background only and will just error); use agent_status to check on it, " +
51
- "message_agent to nudge it, and stop_agent to actually halt it if the user asks you to stop/cancel it.",
51
+ "message_agent to nudge it, and stop_agent to actually halt it if the user asks you to stop/cancel it. " +
52
+ "RETURN CONTRACT: in the task, tell the sub-agent to report back CONCISELY — a short findings list plus " +
53
+ "file:line pointers, NOT pasted large output (it can re-read files itself). Its report posts back into " +
54
+ "THIS conversation, so a bloated report bloats your own context and can trigger a compaction — scope the " +
55
+ "ask so ~1-2k tokens of findings is enough. SINGLE WRITER: keep file EDITS on one agent in sequence (you); " +
56
+ "spawn sub-agents for READ / SEARCH / REVIEW intelligence, not for parallel writes to the same files — two " +
57
+ "writers on one working tree corrupt each other. Match effort to the task: a lookup is one agent (or just " +
58
+ "do it inline); only genuinely independent, multi-step work is worth a spawn.",
52
59
  parameters: {
53
60
  type: "object",
54
61
  properties: {
@@ -14,6 +14,7 @@ import { shellKeyStore } from "./shell-context.js";
14
14
  // Re-exported for back-compat (existing importers reach it via executor.js) — moved to its own
15
15
  // file since it's a pure helper with no node deps; see result-cap.ts for why that separation matters.
16
16
  import { capToolResult } from "./result-cap.js";
17
+ import { spillToolOutput } from "./tool-output-spill.js"; // GW-10: lossless eviction — spill big outputs, hand back a re-readable pointer
17
18
  export { TOOL_RESULT_MAX_CHARS, capToolResult } from "./result-cap.js";
18
19
  // Command tools whose working directory should default to the executor root (they take an optional `cwd`).
19
20
  const CWD_TOOLS = new Set(["bash", "shell_exec", "shell_background", "git", "git_command", "git_status"]);
@@ -79,7 +80,7 @@ export class Executor {
79
80
  try {
80
81
  // Run the tool inside THIS session's shell-key context so a persistent-shell tool (bash) picks
81
82
  // this session's own ShellSession, not a process-wide singleton shared with other sub-agents.
82
- const out = capToolResult(await shellKeyStore.run(this.shellKey, () => tool.run(args)));
83
+ const out = capToolResult(await shellKeyStore.run(this.shellKey, () => tool.run(args)), spillToolOutput);
83
84
  // A file edit changed the workspace, so prior identical-call counts are stale — re-running the same
84
85
  // test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
85
86
  if (MUTATING_TOOLS.has(name))
@@ -13,11 +13,14 @@
13
13
  export const TOOL_RESULT_MAX_CHARS = 40_000; // ~40KB
14
14
  const TOOL_RESULT_TAIL_CHARS = 2_000;
15
15
  const TOOL_RESULT_HEAD_CHARS = TOOL_RESULT_MAX_CHARS - TOOL_RESULT_TAIL_CHARS;
16
- export function capToolResult(result) {
16
+ export function capToolResult(result, spill) {
17
17
  if (result.length <= TOOL_RESULT_MAX_CHARS)
18
18
  return result;
19
19
  const head = result.slice(0, TOOL_RESULT_HEAD_CHARS);
20
20
  const tail = result.slice(-TOOL_RESULT_TAIL_CHARS);
21
- const marker = `\n…[result truncated: ${TOOL_RESULT_MAX_CHARS} of ${result.length} chars — narrow your query]\n`;
21
+ const path = spill ? spill(result) : null;
22
+ const marker = path
23
+ ? `\n…[${result.length} chars total; showing head+tail — FULL output saved to ${path} · re-read the omitted middle with file_read(path, offset, limit)]\n`
24
+ : `\n…[result truncated: ${TOOL_RESULT_MAX_CHARS} of ${result.length} chars — narrow your query]\n`;
22
25
  return head + marker + tail;
23
26
  }
@@ -0,0 +1,26 @@
1
+ // GW-10 spill sink (NODE-ONLY — never import from the browser barrel; it uses node:fs). When a tool result
2
+ // exceeds capToolResult's cap, the FULL output is written here so nothing is lost: the model receives a pointer
3
+ // (the saved path) in place of the discarded middle and re-reads it on demand with file_read(offset/limit).
4
+ // Injected into capToolResult so that module stays node-free for kode-web. Best-effort: a failed write returns
5
+ // null and capToolResult falls back to the plain head+tail truncation — a spill must never fail a tool call.
6
+ import { mkdirSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { homedir } from "node:os";
9
+ /** Where spilled tool outputs live. A flat dir under the operator home; the model is handed absolute paths. */
10
+ export function toolOutputDir() {
11
+ return join(homedir(), ".axe", "operator", "tool-outputs");
12
+ }
13
+ let _seq = 0; // process-local tiebreaker so two spills in the same ms don't collide
14
+ /** Persist `full` and return its absolute path, or null on any failure (caller degrades to head+tail). */
15
+ export function spillToolOutput(full) {
16
+ try {
17
+ const dir = toolOutputDir();
18
+ mkdirSync(dir, { recursive: true });
19
+ const path = join(dir, `${Date.now().toString(36)}-${(_seq++).toString(36)}.txt`);
20
+ writeFileSync(path, full);
21
+ return path;
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
@@ -4,7 +4,7 @@
4
4
  const KNOWN = new Set([
5
5
  "help", "model", "route", "endpoints", "services", "audit", "dashboard", "plan", "mode",
6
6
  "think", "ultrathink", "compact", "remember", "memory", "mcp", "whoami", "agents", "monitor",
7
- "bg", "new", "clear", "exit", "quit", "stats", "login", "logout", "remote", "remotecontrol",
7
+ "bg", "new", "clear", "exit", "quit", "stats", "login", "logout", "remote", "remotecontrol", "rc",
8
8
  ]);
9
9
  export function isSlashCommand(text) {
10
10
  const t = text.trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.165",
3
+ "version": "0.1.167",
4
4
  "description": "Operator (KODE) — TypeScript + Ink terminal coding agent. Full-frame render, single-engine core shared across CLI/web/mobile; runs against a local Aurora model.",
5
5
  "type": "module",
6
6
  "bin": {