@0perator/operator 0.1.49 → 0.1.51

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,34 @@ Operator is AXE's terminal coding agent (npm `@0perator/operator`), running on t
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.51 — 2026-09-21
8
+ - Landed: **remote-control "rich head"** host side (SPEC/remote-session.md §11, PROPOSED — not part of
9
+ the v1 FROZEN envelope) — `RemoteHost` gains `RemoteCapabilities` (commands/skills/mcpServers/models/
10
+ mode/cwd/model) sent in the `snapshot` and re-sent as a `capabilities` state frame only when it
11
+ changes, plus a `command` drive frame (follower → host, `{name, args?}`) dispatched through the SAME
12
+ path a local `/name args` line takes. Client side (web command drawer, kode-mobile CommandSurface,
13
+ SPEC addendum) shipped separately in 0.1.50; this lands the host emit + dispatch handler.
14
+ - Owner decision: a follower may drive **every slash command except** `exit`/`quit` (kills the host
15
+ process), `login`/`logout` (mutates stored credentials), and `remotecontrol`/`remote` (a follower
16
+ could disconnect every other follower) — six hard-excluded case-labels. `bg`, `services`, and
17
+ `dashboard` are explicitly INCLUDED: `isOwnFrame()` (sessionId + ownerSub match) plus OPERATOR-token
18
+ relay auth means a follower is the authenticated owner on another device, not a third party.
19
+ `REMOTE_SAFE_COMMANDS` (`cli.tsx`) is the single allowlist for both what's advertised in
20
+ `capabilities.commands` and what `onCommand` will actually dispatch.
21
+ - Fixed (blocker, found in adversarial self-review — see `REMOTE_RICH_HEAD_AUDIT.md`): a
22
+ `capabilities.mcpServers` full tool enumeration at this fleet's real scale (600+ MCP tools across a
23
+ handful of servers) could exceed the SPEC §8 256 KB per-frame cap. `capCapabilities()` now sends each
24
+ server's name + true `toolCount` with `tools[]` capped to a 20-entry preview. Paired with the
25
+ pre-existing, previously-unenforced SPEC §8 snapshot cap: `capTranscript()` trims the snapshot to the
26
+ last 200 entries, then shrinks oldest-first until under 512 KB, marking `truncated: true` +
27
+ `omittedBefore: <seq>` when either bound bites.
28
+ - Tests: +15 vs 0.1.50 (10 from the host-side reference patch itself — `command` own/wrong-session/
29
+ mismatched-ownerSub/missing-name, capabilities in snapshot before/after connect, delta on change,
30
+ no-op on identical re-set; +5 from the blocker fix above — 600+ tool capabilities payload stays under
31
+ the 256 KB frame cap, toolCount survives the trim, small server lists pass through untrimmed,
32
+ 200-entry snapshot truncation + `omittedBefore`, no false-positive truncation on a short transcript).
33
+ Suite 347/347; `tsc --noEmit` clean.
34
+
7
35
  ## 0.1.48 — 2026-09-21
8
36
  - Added: `/model` command — pick between `aurora-1m` (default, :8097), `aurora-128k` (:8096, lighter
9
37
  RAM), or `moa` (Mixture of Agents) via an interactive picker (`/model`) or directly (`/model <id>`).
@@ -26,6 +54,29 @@ npm + both git remotes (memjar/kode, axetechnologies/kode). Test counts are the
26
54
  local HTTP servers incl. a failing proposer, `Session.setModel`/MOA dispatch, `activeModel`
27
55
  persistence round-trip, `RemoteHost` ask_user frame shape + response routing). Suite 317/317.
28
56
 
57
+ ## 0.1.50 — 2026-09-21
58
+ - Hardening from a Carmack/Karpathy/Boris/Hinton master review of the 0.1.49 bash tool + anti-loop:
59
+ - **Fixed (blocker):** enterprise-tier allowlist denied the new `bash` tool (only `shell_exec` was listed),
60
+ so every enterprise seat broke on the first shell command. `bash` added to `ENTERPRISE_ALLOW`.
61
+ - **Fixed (blocker):** the process-wide `ShellSession` had no serialization — a foreground turn and a
62
+ background sub-agent both calling `bash` could stomp each other's buffer and cross-deliver output/exit
63
+ codes. Added a FIFO promise-queue so overlapping calls run one-at-a-time; sentinel regex anchored to
64
+ start-of-line; fast-fail when the shell dies mid-command; bounded buffer so a runaway (`yes`) can't OOM.
65
+ - **Fixed (would false-stop real work):** the narration-loop guard now gates on PROGRESS — repeated prose
66
+ only counts as a loop when the prior tool batch returned nothing new, so a model using a fixed template
67
+ over productive, varying work is never wrongly halted. Fingerprint is Unicode-aware (non-Latin narration
68
+ no longer exempt) and strips embedded tool-call JSON (text-recovered calls fingerprint the prose).
69
+ - Carmack shell-systems pass: spawn the persistent shell **detached** and kill by process GROUP so a
70
+ timed-out command's backgrounded grandchildren (`&` jobs) don't orphan (#6); wire `disposeShellSession()`
71
+ into the CLI exit/SIGTERM handlers so the shell never orphans on normal exit (#5, previously dead code);
72
+ add a `stdin` error handler so an EPIPE from a kill/write race can't crash the whole CLI (#7). The
73
+ `exit`-kills-bash fast-fail (#3) and buffer bound (#8 memory) already landed above.
74
+ - Known follow-ups (flagged by the review, not in this release): the permissions-layer `executeParallel`
75
+ fans unsafe tools through parallel `execute()` instead of the executor's sequential path (#1 — bash is
76
+ already covered by the queue above; other unsafe tools get a focused fix); backgrounded-child output can
77
+ bleed into the next command's buffer (#4 — needs per-job fds, a design change).
78
+ - Tests: +1 concurrency (overlapping run() serialize cleanly). Suite 332/332.
79
+
29
80
  ## 0.1.49 — 2026-09-21
30
81
  - Added: **frontier `bash` tool** — a PERSISTENT shell session. `cd`, exported env vars, activated
31
82
  venvs and shell functions now survive across bash calls like a real terminal, so the model sets
package/dist/cli.js CHANGED
@@ -13,6 +13,7 @@ import { Session } from "./session.js";
13
13
  import { AuroraRouter } from "./router/router.js";
14
14
  import { BackgroundAgents } from "./background/index.js";
15
15
  import { loadSettings, saveSettings } from "./config/settings.js";
16
+ import { disposeShellSession } from "./tools/registry.js";
16
17
  import { EventSink } from "./telemetry/events.js";
17
18
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
18
19
  import { expandFileMentions } from "./util/mentions.js";
@@ -21,7 +22,7 @@ import { homedir, hostname } from "node:os";
21
22
  import { createHash } from "node:crypto";
22
23
  // RELEASE CHECKLIST (every bump): update this + package.json "version", ADD A CHANGELOG.md ENTRY
23
24
  // (improvements / fixes / tests), run the suite, then publish to npm + push both remotes.
24
- const VERSION = "0.1.49";
25
+ const VERSION = "0.1.51";
25
26
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
26
27
  const settings = loadSettings();
27
28
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
@@ -240,6 +241,36 @@ const HELP = [
240
241
  " /exit /quit leave operator",
241
242
  "esc — interrupt a running turn (or quit when idle)",
242
243
  ].join("\n");
244
+ // Slash commands a remote-control FOLLOWER is allowed to drive (RemoteHost `command` frame →
245
+ // SPEC/remote-session.md extension; see REMOTE_RICH_HEAD_AUDIT.md). This is BOTH the allowlist enforced
246
+ // in the "remotecontrol" case's onCommand below AND what's advertised in RemoteCapabilities.commands —
247
+ // one list, so a follower's command palette never offers something the host will actually refuse.
248
+ // Deliberately excludes: exit/quit (kills the host process), login/logout (mutates the owner's stored
249
+ // AXE credentials), and remotecontrol/remote (a follower must never be able to kick every other
250
+ // follower off the session it's attached to). Those four are the only slash commands that act OUTSIDE
251
+ // the tool/permission system (direct switch-case side effects, ungated whether local or remote) —
252
+ // everything below still runs with the same local privilege a `prompt` frame already has today.
253
+ const REMOTE_SAFE_COMMANDS = [
254
+ { name: "help", description: "list available commands" },
255
+ { name: "model", description: "pick a model: aurora-1m · aurora-128k · moa (mixture-of-agents)", args: "[id]" },
256
+ { name: "route", description: "pin routing to an endpoint, or auto (by size)", args: "[endpoint|auto]" },
257
+ { name: "endpoints", description: "show the aurora endpoint + live health" },
258
+ { name: "services", description: "ensure/inspect the service lever (aurora+autopilot+searxng); stop searxng", args: "[stop]" },
259
+ { name: "audit", description: "recent tool + control-plane events from the audit trail", args: "[n]" },
260
+ { name: "dashboard", description: "launch the live swarm console" },
261
+ { name: "plan", description: "toggle plan mode (read-only research + propose a plan)" },
262
+ { name: "think", description: "toggle extended reasoning" },
263
+ { name: "ultrathink", description: "toggle deep, exhaustive reasoning" },
264
+ { name: "compact", description: "force-compact the conversation now" },
265
+ { name: "remember", description: "store a note to recall in future sessions", args: "<note>" },
266
+ { name: "memory", description: "show remembered notes", args: "[query]" },
267
+ { name: "mcp", description: "count of fleet MCP tools this session" },
268
+ { name: "whoami", description: "show signed-in identity" },
269
+ { name: "bg", description: "spawn a background sub-agent, list, or stop one", args: "<task|stop id>" },
270
+ { name: "new", description: "start a fresh conversation" },
271
+ { name: "clear", description: "clear the screen (keeps the conversation)" },
272
+ ];
273
+ const REMOTE_SAFE_COMMAND_NAMES = new Set(REMOTE_SAFE_COMMANDS.map((c) => c.name));
243
274
  let ID = 0;
244
275
  const nextId = () => `e${++ID}`;
245
276
  const firstLine = (s) => (s.split("\n")[0] ?? "").slice(0, 100);
@@ -387,11 +418,36 @@ function Root() {
387
418
  const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); };
388
419
  const push = (e) => setEntries((prev) => [...prev, e]);
389
420
  const submitRef = useRef(() => { });
421
+ // AXE skills fetched/saved THIS session (name -> a best-effort description) — there's no persistent
422
+ // skill-loader/registry in this codebase to read from (skills are hub-fetched on demand by the
423
+ // skill_fetch/skill_save tools, see tools/registry.ts), so this is the closest real signal for
424
+ // RemoteCapabilities.skills: "what has this session actually pulled in," tracked from onToolBatch
425
+ // below. Session-scoped by design — a fresh session starts with an empty list, matching /model's own
426
+ // lack of persistence across sessions.
427
+ const skillsRef = useRef(new Map());
428
+ // Assembles RemoteCapabilities from the real registries at call time — commands (the remote-safe
429
+ // allowlist above), skills (skillsRef), MCP servers (session.mcpServers() — empty until first-turn
430
+ // discovery has run, see session.ts maybeRecall), models (session.modelRegistry()), permission mode,
431
+ // cwd, and the active model. Cheap to call liberally: RemoteHost.setCapabilities() only touches the
432
+ // wire when the result actually differs from what's already been sent.
433
+ // mcpServers reports the REAL per-server tool count here (toolCount) alongside the full tools[] —
434
+ // RemoteHost.setCapabilities() is what trims tools[] to a wire-safe preview (REMOTE_RICH_HEAD_AUDIT.md
435
+ // §4 BLOCKER: this fleet's own MCP surface is 600+ tools, comfortably over the SPEC §8 256 KB frame
436
+ // cap if enumerated in full); building it honestly here means toolCount survives that trim intact.
437
+ const buildCapabilities = () => ({
438
+ commands: REMOTE_SAFE_COMMANDS,
439
+ skills: [...skillsRef.current.entries()].map(([name, description]) => ({ name, description })),
440
+ mcpServers: session.mcpServers().map((s) => ({ name: s.name, toolCount: s.tools.length, tools: s.tools })),
441
+ models: session.modelRegistry().map((m) => ({ id: m.id, label: m.label, ctx: m.ctx ?? 0, kind: m.kind })),
442
+ mode: settings.permissions.mode === "gated" ? "gated" : "auto", // "bypass"/"audit" both drive with no approval gate from a follower's POV
443
+ cwd: process.cwd(),
444
+ model: session.currentModel(),
445
+ });
390
446
  // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
391
447
  // spawned stdio MCP subprocesses (session.shutdown), or they orphan. exit runs sync; SIGTERM exits after.
392
448
  useEffect(() => {
393
- const onExit = () => session.shutdown();
394
- const onTerm = () => { session.shutdown(); process.exit(0); };
449
+ const onExit = () => { session.shutdown(); disposeShellSession(); };
450
+ const onTerm = () => { session.shutdown(); disposeShellSession(); process.exit(0); };
395
451
  process.once("exit", onExit);
396
452
  process.once("SIGTERM", onTerm);
397
453
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
@@ -516,6 +572,21 @@ function Root() {
516
572
  };
517
573
  push({ kind: "tool", step });
518
574
  remoteRef.current?.toolStep(step);
575
+ // Track skills this session has actually pulled in, for RemoteCapabilities.skills (see
576
+ // skillsRef above) — the description is synthetic (this codebase has no skill metadata to
577
+ // read a real one from), not sourced from the fetched skillmd content.
578
+ if (!isErrorResult(ev.result)) {
579
+ if (ev.name === "skill_fetch") {
580
+ const slug = String(ev.args?.slug ?? "").trim();
581
+ if (slug)
582
+ skillsRef.current.set(slug, "loaded this session via skill_fetch");
583
+ }
584
+ else if (ev.name === "skill_save") {
585
+ const nm = String(ev.args?.name ?? "").trim();
586
+ if (nm)
587
+ skillsRef.current.set(nm, "saved to profile this session via skill_save");
588
+ }
589
+ }
519
590
  }
520
591
  liveText.current = "";
521
592
  liveReasoning.current = "";
@@ -571,6 +642,9 @@ function Root() {
571
642
  writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()));
572
643
  }
573
644
  catch { /* auto-save is best-effort */ }
645
+ // Re-check capabilities after every turn: MCP discovery (first-turn only) may have just landed,
646
+ // and any skill_fetch/skill_save this turn updated skillsRef above. A no-op diff never hits the wire.
647
+ remoteRef.current?.setCapabilities(buildCapabilities());
574
648
  const q = queued.current;
575
649
  queued.current = "";
576
650
  if (q)
@@ -618,6 +692,7 @@ function Root() {
618
692
  setRoute(s.currentModel());
619
693
  saveSettings({ activeModel: s.currentModel() });
620
694
  sys(`model → ${s.currentModel()} · ctx ${s.ctxPct()}% · turns ${s.turnCount()}`);
695
+ remoteRef.current?.setCapabilities(buildCapabilities()); // active model changed — re-sync attached followers
621
696
  };
622
697
  if (arg) {
623
698
  apply(arg);
@@ -837,6 +912,19 @@ function Root() {
837
912
  onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
838
913
  onAskUserResponse: (id, answer) => settleQuestion(id, answer), // first-wins with local
839
914
  onInterrupt: () => s.interrupt(), // follower cancels the turn
915
+ // A follower drove a slash command. Reuse the EXACT same path a local `/name args` line
916
+ // takes (submitRef → onSubmit → handleSlash) — never a second implementation of the
917
+ // switch — but only for names on the remote-safe allowlist; anything else is refused
918
+ // locally-visibly (sys + an audit event) rather than silently dropped or silently run.
919
+ onCommand: (name, args) => {
920
+ if (!REMOTE_SAFE_COMMAND_NAMES.has(name)) {
921
+ sys(`remote control: blocked "/${name}" from a follower — not exposed for remote dispatch`);
922
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command_blocked", detail: name } });
923
+ return;
924
+ }
925
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command", detail: args ? `${name} ${args}` : name } });
926
+ submitRef.current(`/${name}${args ? " " + args : ""}`);
927
+ },
840
928
  onState: (st, detail) => {
841
929
  if (st === "live")
842
930
  sys(`✷ remote control LIVE — session ${rh.id}\n Continue on your phone or at https://0perator.co/session/${rh.id}\n /remotecontrol again to stop.`);
@@ -852,6 +940,7 @@ function Root() {
852
940
  },
853
941
  });
854
942
  remoteRef.current = rh;
943
+ rh.setCapabilities(buildCapabilities()); // cached now, so the very first attach's snapshot already carries it
855
944
  rh.connect();
856
945
  sys(`connecting remote control → ${url} …`);
857
946
  break;
@@ -9,7 +9,34 @@ import { compact, needsCompaction, clampMaxTokens } from "./compaction.js";
9
9
  import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
10
10
  const MAX_SELF_HEAL_PER_TURN = 3;
11
11
  const LOOP_GUARD_LIMIT = 3;
12
+ const CONTENT_LOOP_LIMIT = 3; // same substantial assistant narration this many rounds ⇒ stuck, even if tool args vary
12
13
  const MAX_EMPTY_RETRIES = 1; // one nudge on an empty "dud" round before finalizing
14
+ /** Fingerprint of an assistant round's PROSE, for catching a model narrating in circles while its
15
+ * tools make no progress (the "12× Empty outputs" burn). Strips embedded tool-call JSON / code fences
16
+ * so the fingerprint is the PROSE, stable even when the (varying) call args live inside the content
17
+ * (text-recovered calls). Unicode-aware (\p{L}\p{N}) so non-Latin narration isn't normalized to "" and
18
+ * silently exempted. */
19
+ function contentSignature(content) {
20
+ return (content || "")
21
+ .replace(/```[\s\S]*?```/g, " ") // fenced code / tool blocks
22
+ .replace(/\{[\s\S]*?\}/g, " ") // inline JSON (text-encoded tool calls)
23
+ .toLowerCase()
24
+ .normalize("NFKC")
25
+ .replace(/[^\p{L}\p{N} ]+/gu, " ")
26
+ .replace(/\s+/g, " ")
27
+ .trim()
28
+ .slice(0, 200);
29
+ }
30
+ /** A tool batch "progressed" if any result carried real content (not empty, not a (no output)/error/
31
+ * loop-guard sentinel). Gates the narration-loop guard: repeated prose is only a loop when the tools it
32
+ * reacts to aren't advancing — so templated narration over PRODUCTIVE, varying work is never mistaken
33
+ * for a loop. */
34
+ function batchProgressed(toolMsgs) {
35
+ return toolMsgs.some((tm) => {
36
+ const c = (tm.content || "").trim();
37
+ return c.length > 0 && !/^\(no output|^error[:\s]|^loop guard/i.test(c);
38
+ });
39
+ }
13
40
  /** Thrown by runTurn when the turn is interrupted via AgentOpts.signal (SPEC §9). One type for hosts to catch. */
14
41
  export class TurnAbortedError extends Error {
15
42
  constructor() {
@@ -106,6 +133,8 @@ export async function runTurn(userInput, conversation, opts) {
106
133
  const softRounds = opts.maxRounds ?? 10;
107
134
  const hardCap = opts.maxRoundsHard ?? Math.max(40, softRounds * 4);
108
135
  const callCounts = new Map();
136
+ const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
137
+ let progressed = true; // did the PREVIOUS tool batch advance? gates the guard (progress clears it)
109
138
  let selfHealBudget = MAX_SELF_HEAL_PER_TURN;
110
139
  conversation.user(userInput);
111
140
  let rounds = 0;
@@ -199,6 +228,28 @@ export async function runTurn(userInput, conversation, opts) {
199
228
  continue;
200
229
  }
201
230
  }
231
+ // Narration loop guard: a spinning model emits the SAME prose across rounds while its tools return
232
+ // nothing new (the "12× Empty outputs…" burn). Gate on PROGRESS so templated narration over
233
+ // productive, varying work is never mistaken for a loop — a batch that advanced clears the counter;
234
+ // gate on RAW length so non-Latin narration still qualifies. Fires only when prose repeats AND the
235
+ // prior batch didn't advance.
236
+ if (progressed) {
237
+ contentSigs.clear();
238
+ }
239
+ else if (response.content.trim().length >= 40) {
240
+ const csig = contentSignature(response.content);
241
+ if (csig) {
242
+ const seen = (contentSigs.get(csig) ?? 0) + 1;
243
+ contentSigs.set(csig, seen);
244
+ if (seen >= CONTENT_LOOP_LIMIT) {
245
+ const gist = response.content.trim().split("\n", 1)[0].slice(0, 200);
246
+ const stuck = `[stopped — I repeated the same step ${seen}× while the tools returned nothing new, ` +
247
+ `which usually means a tool isn't doing what I expect. Where I'm stuck: ${gist}\nTell me how you'd like to proceed.]`;
248
+ conversation.assistant(stuck);
249
+ return { content: stuck, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
250
+ }
251
+ }
252
+ }
202
253
  if (response.toolCalls.length > 0) {
203
254
  throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
204
255
  conversation.assistant(response.content, response.toolCalls);
@@ -206,6 +257,7 @@ export async function runTurn(userInput, conversation, opts) {
206
257
  for (const tm of toolMsgs)
207
258
  conversation.tool(tm.tool_call_id, tm.content);
208
259
  toolCallTotal += response.toolCalls.length;
260
+ progressed = batchProgressed(toolMsgs);
209
261
  continue;
210
262
  }
211
263
  // No structured tool_calls — check for text-encoded ones before treating this as final.
@@ -217,6 +269,7 @@ export async function runTurn(userInput, conversation, opts) {
217
269
  for (const tm of toolMsgs)
218
270
  conversation.tool(tm.tool_call_id, tm.content);
219
271
  toolCallTotal += recovered.calls.length;
272
+ progressed = batchProgressed(toolMsgs);
220
273
  continue;
221
274
  }
222
275
  const final = stripScratchpad(recovered.cleanedContent);
package/dist/mcp/index.js CHANGED
@@ -86,6 +86,19 @@ export class McpHub {
86
86
  toolCount() {
87
87
  return this.tools.size;
88
88
  }
89
+ /** Per-server tool inventory (unnamespaced names) — for capability advertising (e.g. the
90
+ * remote-control snapshot's `capabilities.mcpServers`), not for dispatch. Empty until discover()
91
+ * has run (or if it hasn't found anything yet). Server order follows first-discovered-tool order;
92
+ * not sorted, since callers so far only render or diff it, never rely on a stable ordering. */
93
+ serversWithTools() {
94
+ const bySrv = new Map();
95
+ for (const t of this.tools.values()) {
96
+ const list = bySrv.get(t.server) ?? [];
97
+ list.push({ name: t.def.name, description: t.def.description });
98
+ bySrv.set(t.server, list);
99
+ }
100
+ return [...bySrv.entries()].map(([name, tools]) => ({ name, tools }));
101
+ }
89
102
  }
90
103
  /** Compose the local executor with the MCP hub: local tools win, a namespaced name routes to MCP.
91
104
  * With no hub (or an inert one) this is the local executor plus empty schemas — zero behavior change. */
@@ -2,7 +2,7 @@
2
2
  // tools mcp__*, computer_* control, future privileged tools) is denied, so new tools are safe-by-default.
3
3
  const ENTERPRISE_ALLOW = new Set([
4
4
  "file_read", "file_write", "file_edit", "grep_search", "list_directory",
5
- "shell_exec", "shell_background", "bash_output", "bash_kill",
5
+ "bash", "shell_exec", "shell_background", "bash_output", "bash_kill",
6
6
  "git_command", "checkpoint", "task_add", "task_list", "task_update",
7
7
  "memory_search", "memory_store", "web_fetch", "web_search",
8
8
  "skill_list", "skill_fetch", "skill_save",
@@ -1,4 +1,29 @@
1
1
  const V = 1;
2
+ // SPEC §8 limits (relay-enforced per spec, but host.ts didn't honor either one — REMOTE_RICH_HEAD_AUDIT.md
3
+ // §1/§4 BLOCKER: this repo's own MCP surface is 600+ tools across a handful of servers, which put
4
+ // `capabilities.mcpServers` alone at 70-100+ KB before this fix, on top of an already-uncapped transcript.
5
+ // Enforced host-side as defense-in-depth (the relay may also cap/drop/error an oversized frame, but a
6
+ // follower deserves a `truncated` signal rather than a silently broken snapshot).
7
+ const SNAPSHOT_MAX_ENTRIES = 200; // SPEC §8: last 200 message-entries + their tool steps, whichever binds first
8
+ const SNAPSHOT_MAX_BYTES = 512 * 1024; // SPEC §8 snapshot cap
9
+ const MCP_TOOL_PREVIEW = 20; // per-server tool NAMES kept when a server's inventory is large — see capCapabilities
10
+ const byteLen = (v) => Buffer.byteLength(JSON.stringify(v), "utf8");
11
+ // BLOCKER fix (REMOTE_RICH_HEAD_AUDIT.md §4, "summarize, don't enumerate"): a server's `tools[]` is
12
+ // prefixed to MCP_TOOL_PREVIEW entries — `toolCount` still carries the real total, so a follower's UI
13
+ // can render "webhook (37 tools)" instead of either silently truncating names with no signal or paying
14
+ // ~150 bytes/tool for a 600+ tool fleet surface on every snapshot/capabilities delta. Called once from
15
+ // setCapabilities() (not per-send) so the stored `this.capabilities` used for change-detection and every
16
+ // later sendSnapshot() is already the capped shape.
17
+ function capCapabilities(caps) {
18
+ return {
19
+ ...caps,
20
+ mcpServers: caps.mcpServers.map((s) => ({
21
+ name: s.name,
22
+ toolCount: s.tools.length,
23
+ tools: s.tools.length > MCP_TOOL_PREVIEW ? s.tools.slice(0, MCP_TOOL_PREVIEW) : s.tools,
24
+ })),
25
+ };
26
+ }
2
27
  export class RemoteHost {
3
28
  url;
4
29
  token;
@@ -18,6 +43,7 @@ export class RemoteHost {
18
43
  liveTimer = null;
19
44
  livePending = null;
20
45
  turnN = 0;
46
+ capabilities = null;
21
47
  constructor(url, token, meta, cb) {
22
48
  this.url = url;
23
49
  this.token = token;
@@ -97,6 +123,15 @@ export class RemoteHost {
97
123
  if (this.isOwnFrame(f))
98
124
  this.cb.onInterrupt();
99
125
  break;
126
+ // A follower driving a slash command (e.g. /model, /new) through the SAME router a local owner
127
+ // types into. Same guard as every other drive frame; the SHELL is additionally responsible for
128
+ // allowlisting which command names it will actually dispatch (this class has no opinion on
129
+ // that — it just forwards a well-formed request through). `args` is the raw trailing string,
130
+ // exactly as typed after the command name locally.
131
+ case "command":
132
+ if (this.isOwnFrame(f) && typeof f.payload?.name === "string" && f.payload.name)
133
+ this.cb.onCommand(String(f.payload.name), typeof f.payload?.args === "string" ? f.payload.args : undefined);
134
+ break;
100
135
  case "error":
101
136
  this.cb.onState?.("error", f.payload?.message ?? f.payload?.code);
102
137
  break;
@@ -125,7 +160,43 @@ export class RemoteHost {
125
160
  state(type, payload) { this.send(type, this.sessionId, payload, ++this.seq); }
126
161
  sendSnapshot() {
127
162
  this.flushLive();
128
- this.send("snapshot", this.sessionId, { transcript: this.entries, activity: this.activity, status: { ctxPct: this.ctxPct, route: this.route } }, this.seq);
163
+ const { transcript, truncated, omittedBefore } = this.capTranscript(this.entries);
164
+ this.send("snapshot", this.sessionId, {
165
+ transcript, activity: this.activity, status: { ctxPct: this.ctxPct, route: this.route },
166
+ ...(truncated ? { truncated: true, omittedBefore } : {}),
167
+ ...(this.capabilities ? { capabilities: this.capabilities } : {}), // absent until the shell's first setCapabilities() call; already capped by capCapabilities() in setCapabilities()
168
+ }, this.seq);
169
+ }
170
+ /** SPEC §8 snapshot cap: last 200 message/tool entries, then shrink further (oldest-first) until the
171
+ * serialized transcript fits 512 KB — `capabilities` gets its own budget (capCapabilities), so this
172
+ * only accounts for the transcript half. `omittedBefore` is this host's CURRENT seq at truncation
173
+ * time (entries carry no seq of their own): enough for a follower to know only scrollback before
174
+ * "now" was cut, not that live driving is affected. Cheap to call on every attach — at most O(200)
175
+ * serializations of a shrinking slice, and attach is not a hot path. */
176
+ capTranscript(entries) {
177
+ let out = entries;
178
+ let truncated = false;
179
+ if (out.length > SNAPSHOT_MAX_ENTRIES) {
180
+ out = out.slice(-SNAPSHOT_MAX_ENTRIES);
181
+ truncated = true;
182
+ }
183
+ while (out.length > 1 && byteLen(out) > SNAPSHOT_MAX_BYTES) {
184
+ out = out.slice(1);
185
+ truncated = true;
186
+ }
187
+ return truncated ? { transcript: out, truncated, omittedBefore: this.seq } : { transcript: out, truncated };
188
+ }
189
+ /** Store the host's current capabilities and, if a session is already live and they actually
190
+ * changed, re-send them as a `capabilities` state frame so already-attached followers stay in
191
+ * sync (e.g. after a /model switch or a skill load — see RemoteCapabilities). Safe to call before
192
+ * "welcome"/connect(): the value is just cached for the next sendSnapshot(), nothing is sent. Safe
193
+ * to call on every turn: a no-op change never touches the wire (seq stays put). */
194
+ setCapabilities(caps) {
195
+ const capped = capCapabilities(caps);
196
+ const changed = JSON.stringify(capped) !== JSON.stringify(this.capabilities);
197
+ this.capabilities = capped;
198
+ if (changed && this.sessionId)
199
+ this.state("capabilities", capped);
129
200
  }
130
201
  // ── mirror upserts ────────────────────────────────────────────────────────
131
202
  upsertMessage(id, role, content, reasoning) {
package/dist/session.js CHANGED
@@ -340,6 +340,11 @@ export class Session {
340
340
  mcpToolCount() {
341
341
  return this.hub?.toolCount() ?? 0;
342
342
  }
343
+ /** Per-server MCP tool inventory (0 servers until first turn / if MCP is off) — for capability
344
+ * advertising (RemoteHost.setCapabilities), not for dispatch. */
345
+ mcpServers() {
346
+ return this.hub?.serversWithTools() ?? [];
347
+ }
343
348
  /** Tear down session resources (kills any spawned stdio MCP servers). Call on shell exit. */
344
349
  shutdown() {
345
350
  this.hub?.shutdown();
@@ -25,6 +25,12 @@ async function getShellSession() {
25
25
  }
26
26
  return _shellSession;
27
27
  }
28
+ /** Kill the persistent shell (and its process group) on process shutdown so it never orphans.
29
+ * Wired into the CLI's exit/SIGTERM handlers — no-op if a shell was never started. */
30
+ export function disposeShellSession() {
31
+ _shellSession?.dispose();
32
+ _shellSession = null;
33
+ }
28
34
  async function shellExec(args) {
29
35
  const command = str(args.command);
30
36
  if (!command)
@@ -34,6 +34,7 @@ export class ShellSession {
34
34
  cwd: this.cwd,
35
35
  env: { ...process.env, PS1: "", PROMPT_COMMAND: "", TERM: "dumb" },
36
36
  stdio: ["pipe", "pipe", "pipe"],
37
+ detached: true, // own process group, so killShell() can reap grandchildren (`&` jobs), not just bash
37
38
  });
38
39
  p.stdout.setEncoding("utf8");
39
40
  p.stderr.setEncoding("utf8");
@@ -42,6 +43,9 @@ export class ShellSession {
42
43
  p.stderr.on("data", onData); // merge stderr into the same stream, like a real terminal
43
44
  p.on("exit", () => { this.proc = null; });
44
45
  p.on("error", () => { this.proc = null; });
46
+ // A write to a closed pipe (e.g. a timeout-kill racing an in-flight write) emits 'error' on stdin;
47
+ // unhandled, Node throws and takes down the whole CLI. Swallow it — the run loop already fails safe.
48
+ p.stdin.on("error", () => { });
45
49
  this.proc = p;
46
50
  // Don't let the long-lived shell (or its pipes) keep the process alive at exit — a tool's
47
51
  // background shell must never block Operator (or a test runner) from exiting cleanly.
@@ -66,52 +70,75 @@ export class ShellSession {
66
70
  this.starting = null;
67
71
  }
68
72
  }
69
- /** Run one command in the persistent shell and return its merged output + exit code. */
70
- async run(command, timeoutMs = 120_000) {
73
+ // One FIFO for ALL run() calls. Background sub-agents share this process-wide shell, so without
74
+ // serialization two concurrent calls would stomp each other's buffer/sentinel and cross-deliver
75
+ // output + exit codes. The queue makes overlapping calls wait their turn on the one real shell.
76
+ queue = Promise.resolve();
77
+ /** Run one command in the persistent shell and return its merged output + exit code.
78
+ * Serialized: concurrent callers execute one-at-a-time in arrival order. */
79
+ run(command, timeoutMs = 120_000) {
80
+ const prev = this.queue;
81
+ let release;
82
+ this.queue = new Promise((r) => (release = r));
83
+ return prev.catch(() => { }).then(() => this.runLocked(command, timeoutMs)).finally(() => release());
84
+ }
85
+ async runLocked(command, timeoutMs = 120_000) {
71
86
  await this.ensure();
72
87
  const p = this.proc;
73
88
  if (!p)
74
89
  return { output: "error: shell failed to start", exitCode: null, timedOut: false, truncated: false };
75
90
  const nonce = Math.random().toString(36).slice(2, 10);
76
91
  const marker = `${SENTINEL}${nonce}`;
77
- // A trailing newline before the command guards against a previous no-newline write; the
78
- // sentinel prints on its own line regardless of whether `command` ended in a newline.
79
92
  this.buf = "";
80
93
  p.stdin.write(`${command}\nprintf '\\n%s:%s\\n' '${marker}' "$?"\n`);
81
- const re = new RegExp(`\\n?${marker}:(-?\\d+)\\r?\\n`);
94
+ // Require the leading newline printf always emits, so the marker only matches at start-of-line —
95
+ // a command's own output can't spoof "<random-nonce marker>:<digits>" as the last chars of a line.
96
+ const re = new RegExp(`\\n${marker}:(-?\\d+)\\r?\\n`);
97
+ const HARD_BUF = OUTPUT_CAP * 4; // bound memory even if the sentinel never arrives (e.g. `yes`)
82
98
  const deadline = Date.now() + Math.max(1000, timeoutMs);
99
+ const finish = (out, exitCode, timedOut, truncated) => {
100
+ if (timedOut || exitCode === null) {
101
+ this.killShell(p);
102
+ this.proc = null;
103
+ }
104
+ this.buf = "";
105
+ return { output: out.replace(/\r/g, "").replace(/\n+$/, ""), exitCode, timedOut, truncated };
106
+ };
83
107
  while (true) {
84
108
  const m = this.buf.match(re);
85
109
  if (m) {
86
- let output = this.buf.slice(0, m.index).replace(/\r/g, "");
87
- let truncated = false;
88
- if (output.length > OUTPUT_CAP) {
89
- output = output.slice(0, OUTPUT_CAP);
90
- truncated = true;
91
- }
92
- this.buf = "";
93
- return { output: output.replace(/\n+$/, ""), exitCode: Number(m[1]), timedOut: false, truncated };
94
- }
95
- if (Date.now() > deadline) {
96
- // Non-interactive bash won't job-control a SIGINT to the foreground child, so the only
97
- // reliable stop is to kill the shell and respawn on the next call. cwd/env reset only here.
98
- const partial = this.buf.replace(/\r/g, "").slice(0, OUTPUT_CAP);
99
- try {
100
- p.kill("SIGKILL");
101
- }
102
- catch { /* */ }
103
- this.proc = null;
104
- this.buf = "";
105
- return { output: partial.replace(/\n+$/, ""), exitCode: null, timedOut: true, truncated: false };
110
+ const raw = this.buf.slice(0, m.index);
111
+ return finish(raw.length > OUTPUT_CAP ? raw.slice(0, OUTPUT_CAP) : raw, Number(m[1]), false, raw.length > OUTPUT_CAP);
106
112
  }
113
+ // Shell died mid-command (crash / `exit` / OOM-kill): fail fast instead of spinning to the deadline.
114
+ if (p.exitCode !== null || this.proc !== p)
115
+ return finish(this.buf.slice(0, OUTPUT_CAP), null, false, false);
116
+ // Runaway output that never reaches the sentinel: stop before it balloons memory.
117
+ if (this.buf.length > HARD_BUF)
118
+ return finish(this.buf.slice(0, OUTPUT_CAP), null, false, true);
119
+ if (Date.now() > deadline)
120
+ return finish(this.buf.slice(0, OUTPUT_CAP), null, true, false);
107
121
  await new Promise((r) => setTimeout(r, 15));
108
122
  }
109
123
  }
110
- dispose() {
124
+ /** SIGKILL the shell AND its process group (spawned detached), so backgrounded grandchildren (`&` jobs)
125
+ * don't survive as orphans. Falls back to a plain kill if the group signal fails. */
126
+ killShell(p) {
111
127
  try {
112
- this.proc?.kill("SIGKILL");
128
+ if (p?.pid)
129
+ process.kill(-p.pid, "SIGKILL");
130
+ else
131
+ p?.kill("SIGKILL");
132
+ }
133
+ catch {
134
+ try {
135
+ p?.kill("SIGKILL");
136
+ }
137
+ catch { /* already gone */ }
113
138
  }
114
- catch { /* */ }
139
+ }
140
+ dispose() {
141
+ this.killShell(this.proc);
115
142
  this.proc = null;
116
143
  this.buf = "";
117
144
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.49",
3
+ "version": "0.1.51",
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": {