@0perator/operator 0.1.49 → 0.1.50

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
@@ -26,6 +26,29 @@ npm + both git remotes (memjar/kode, axetechnologies/kode). Test counts are the
26
26
  local HTTP servers incl. a failing proposer, `Session.setModel`/MOA dispatch, `activeModel`
27
27
  persistence round-trip, `RemoteHost` ask_user frame shape + response routing). Suite 317/317.
28
28
 
29
+ ## 0.1.50 — 2026-09-21
30
+ - Hardening from a Carmack/Karpathy/Boris/Hinton master review of the 0.1.49 bash tool + anti-loop:
31
+ - **Fixed (blocker):** enterprise-tier allowlist denied the new `bash` tool (only `shell_exec` was listed),
32
+ so every enterprise seat broke on the first shell command. `bash` added to `ENTERPRISE_ALLOW`.
33
+ - **Fixed (blocker):** the process-wide `ShellSession` had no serialization — a foreground turn and a
34
+ background sub-agent both calling `bash` could stomp each other's buffer and cross-deliver output/exit
35
+ codes. Added a FIFO promise-queue so overlapping calls run one-at-a-time; sentinel regex anchored to
36
+ start-of-line; fast-fail when the shell dies mid-command; bounded buffer so a runaway (`yes`) can't OOM.
37
+ - **Fixed (would false-stop real work):** the narration-loop guard now gates on PROGRESS — repeated prose
38
+ only counts as a loop when the prior tool batch returned nothing new, so a model using a fixed template
39
+ over productive, varying work is never wrongly halted. Fingerprint is Unicode-aware (non-Latin narration
40
+ no longer exempt) and strips embedded tool-call JSON (text-recovered calls fingerprint the prose).
41
+ - Carmack shell-systems pass: spawn the persistent shell **detached** and kill by process GROUP so a
42
+ timed-out command's backgrounded grandchildren (`&` jobs) don't orphan (#6); wire `disposeShellSession()`
43
+ into the CLI exit/SIGTERM handlers so the shell never orphans on normal exit (#5, previously dead code);
44
+ add a `stdin` error handler so an EPIPE from a kill/write race can't crash the whole CLI (#7). The
45
+ `exit`-kills-bash fast-fail (#3) and buffer bound (#8 memory) already landed above.
46
+ - Known follow-ups (flagged by the review, not in this release): the permissions-layer `executeParallel`
47
+ fans unsafe tools through parallel `execute()` instead of the executor's sequential path (#1 — bash is
48
+ already covered by the queue above; other unsafe tools get a focused fix); backgrounded-child output can
49
+ bleed into the next command's buffer (#4 — needs per-job fds, a design change).
50
+ - Tests: +1 concurrency (overlapping run() serialize cleanly). Suite 332/332.
51
+
29
52
  ## 0.1.49 — 2026-09-21
30
53
  - Added: **frontier `bash` tool** — a PERSISTENT shell session. `cd`, exported env vars, activated
31
54
  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.50";
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).
@@ -390,8 +391,8 @@ function Root() {
390
391
  // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
391
392
  // spawned stdio MCP subprocesses (session.shutdown), or they orphan. exit runs sync; SIGTERM exits after.
392
393
  useEffect(() => {
393
- const onExit = () => session.shutdown();
394
- const onTerm = () => { session.shutdown(); process.exit(0); };
394
+ const onExit = () => { session.shutdown(); disposeShellSession(); };
395
+ const onTerm = () => { session.shutdown(); disposeShellSession(); process.exit(0); };
395
396
  process.once("exit", onExit);
396
397
  process.once("SIGTERM", onTerm);
397
398
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
@@ -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);
@@ -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",
@@ -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.50",
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": {