@0perator/operator 0.1.52 → 0.1.53

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,29 @@ 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.53 — 2026-09-22
8
+ - **Parallel tool calls, made visible.** System-prompt guidance now tells the model to BATCH independent
9
+ tool calls in one round (the engine already ran batches in parallel via executeParallel — the model just
10
+ wasn't asked to). A new live per-call TUI view renders each call in a batch as its own row (name · args ·
11
+ running→done · ms · result), render-safe alongside the streaming tail.
12
+ - **Token meter fixed (it was under-counting, not the model being "nerfed").** Tool-call rounds report
13
+ predicted_n≈0 from llama.cpp, so a 40-call turn showed "365 tok". chat() now falls back to a chars/4
14
+ estimate when the server omits timings on a tool round; the real count always wins when present. No spend
15
+ cap exists (clampMaxTokens is a no-op at low ctx).
16
+ - **Live sub-agent visibility.** A working background sub-agent showed only a `round N` counter — opaque on a
17
+ slow local reasoning model. The panel now streams each child's real activity: its in-flight tool calls with
18
+ their identifying arg (`↳ file_read(src/cli.tsx) …`) and a dim, throttled tail of its current reasoning
19
+ (`⋮ …`). Steps/reads/thoughts, not just counters.
20
+ - **Sub-agent lifecycle: work → idle → decommission.** A finished child (result already posted to the
21
+ transcript) now clears from the panel after a 45s grace instead of lingering the whole session.
22
+ - **Fixed: exit-while-working froze the session.** Pressing /exit (or Ctrl-C) while a sub-agent was still
23
+ running left `operator` hung — the child's in-flight request kept the Node event loop alive. Exit now
24
+ disposes all background agents (interrupt + shutdown) so the process drains and quits cleanly.
25
+ - **Remote control: legible when unsigned.** `/remotecontrol` with no Operator token silently opened the
26
+ relay socket and surfaced the rejection as "connection lost". It now refuses before the wire with a clear
27
+ "run `operator auth login` first" message + an rc_no_token control event.
28
+ - Tests: 365/365.
29
+
7
30
  ## 0.1.52 — 2026-09-21
8
31
  - Fixed: `operator update` on a source checkout failed cryptically ("git pull failed") when the tree was
9
32
  dirty — common on a shared dev tree an agent is building in. It now detects the dirty tree, names the
@@ -1,4 +1,14 @@
1
1
  import { buildBrief, inferType, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, } from "../engine/grandmaster.js";
2
+ const RECENT_STEPS = 5; // tool steps kept per agent for the live view (older ones scroll off)
3
+ const THOUGHT_MAX = 160; // chars of the latest reasoning snippet retained (tail)
4
+ const THOUGHT_EMIT_MS = 700; // min gap between reasoning-driven re-renders — bounds render load during long thinks
5
+ const IDLE_TTL_MS = 45_000; // a finished agent lingers this long (result already in the transcript) then decommissions
6
+ // Pull the one identifying argument out of a tool call for the live line (path/file it read, the
7
+ // command/query it ran) — the follower cares "read src/cli.tsx", not the full JSON args blob.
8
+ function shortArg(args) {
9
+ const v = args?.path ?? args?.file ?? args?.pattern ?? args?.query ?? args?.command ?? args?.url ?? args?.task;
10
+ return typeof v === "string" ? v.replace(/\s+/g, " ").slice(0, 48) : undefined;
11
+ }
2
12
  export class BackgroundAgents {
3
13
  makeSession;
4
14
  onChange;
@@ -35,9 +45,35 @@ export class BackgroundAgents {
35
45
  }
36
46
  async run(id, session, info, brief, type) {
37
47
  let total = 0;
48
+ let lastThoughtEmit = 0;
38
49
  const hooks = {
39
50
  onDelta: () => { info.tokens = (info.tokens ?? 0) + 1; },
40
- onToolBatch: () => { info.round = (info.round ?? 0) + 1; this.onChange(); },
51
+ // Reasoning stream → the "thinking" line. Coalesce (keep the tail) and throttle re-renders:
52
+ // a long think can emit hundreds of chunks, but the panel only needs to refresh ~1/sec.
53
+ onReasoning: (chunk) => {
54
+ const t = ((info.thought ?? "") + chunk).replace(/\s+/g, " ");
55
+ info.thought = t.length > THOUGHT_MAX ? "…" + t.slice(-(THOUGHT_MAX - 1)) : t;
56
+ const now = Date.now();
57
+ if (now - lastThoughtEmit > THOUGHT_EMIT_MS) {
58
+ lastThoughtEmit = now;
59
+ this.onChange();
60
+ }
61
+ },
62
+ // Tools about to run — show them immediately as in-flight, with their identifying arg.
63
+ onToolStart: (calls) => {
64
+ const running = calls.map((c) => ({ name: c.name, arg: shortArg(c.args), running: true }));
65
+ info.steps = [...(info.steps ?? []), ...running].slice(-RECENT_STEPS);
66
+ this.onChange();
67
+ },
68
+ // A batch finished — replace the in-flight rows with settled name+arg, bump the round, and drop
69
+ // the pre-call reasoning (it belonged to choosing THIS batch; the next think starts fresh).
70
+ onToolBatch: (events) => {
71
+ info.round = (info.round ?? 0) + 1;
72
+ const settled = events.map((e) => ({ name: e.name, arg: shortArg(e.args), running: false }));
73
+ info.steps = [...(info.steps ?? []).filter((s) => !s.running), ...settled].slice(-RECENT_STEPS);
74
+ info.thought = undefined;
75
+ this.onChange();
76
+ },
41
77
  };
42
78
  try {
43
79
  let r = await session.send(brief, hooks);
@@ -68,6 +104,10 @@ export class BackgroundAgents {
68
104
  if (total > 0)
69
105
  info.tokens = total; // authoritative llama.cpp count summed across sends
70
106
  info.durationMs = r.durationMs ?? (Date.now() - (info.startedAt ?? Date.now()));
107
+ info.thought = undefined; // no live thinking once finished
108
+ if (info.steps)
109
+ info.steps = info.steps.map((s) => ({ ...s, running: false }));
110
+ this.scheduleReap(id);
71
111
  this.onChange();
72
112
  if (r.interrupted)
73
113
  return;
@@ -84,10 +124,25 @@ export class BackgroundAgents {
84
124
  }
85
125
  catch (e) {
86
126
  info.status = "stopped";
127
+ info.thought = undefined;
128
+ if (info.steps)
129
+ info.steps = info.steps.map((s) => ({ ...s, running: false }));
130
+ this.scheduleReap(id);
87
131
  this.onChange();
88
132
  this.onDone(info, `[${id} error: ${e instanceof Error ? e.message : String(e)}]`);
89
133
  }
90
134
  }
135
+ /** A finished agent's result is already posted to the transcript, so it lingers in the panel only
136
+ * briefly (so the owner sees it complete) then decommissions — otherwise idle agents pile up for
137
+ * the life of the session. Working agents are never reaped. Timer is unref'd so it never keeps the
138
+ * process alive on its own. */
139
+ scheduleReap(id) {
140
+ const a = this.agents.get(id);
141
+ if (!a || a.reap)
142
+ return;
143
+ a.reap = setTimeout(() => { this.agents.delete(id); this.onChange(); }, IDLE_TTL_MS);
144
+ a.reap.unref?.();
145
+ }
91
146
  /** Stop a running agent (interrupts its turn). Returns false if the id is unknown. */
92
147
  stop(id) {
93
148
  const a = this.agents.get(id);
@@ -95,6 +150,7 @@ export class BackgroundAgents {
95
150
  return false;
96
151
  a.session.interrupt();
97
152
  a.info.status = "stopped";
153
+ this.scheduleReap(id);
98
154
  this.onChange();
99
155
  return true;
100
156
  }
@@ -102,4 +158,25 @@ export class BackgroundAgents {
102
158
  activeCount() {
103
159
  return [...this.agents.values()].filter((a) => a.info.status === "working").length;
104
160
  }
161
+ /** Tear every child down on foreground exit. A child still mid-send is awaiting a streaming
162
+ * request to the model; without aborting it the Node event loop never drains and `operator`
163
+ * hangs after /exit (the "pressed exit → frozen" bug). interrupt() aborts the in-flight turn;
164
+ * shutdown() kills the child's own MCP subprocesses; reap timers are cleared. */
165
+ dispose() {
166
+ for (const a of this.agents.values()) {
167
+ if (a.reap) {
168
+ clearTimeout(a.reap);
169
+ a.reap = undefined;
170
+ }
171
+ try {
172
+ a.session.interrupt();
173
+ }
174
+ catch { /* already gone */ }
175
+ try {
176
+ a.session.shutdown();
177
+ }
178
+ catch { /* already gone */ }
179
+ }
180
+ this.agents.clear();
181
+ }
105
182
  }
package/dist/cli.js CHANGED
@@ -9,6 +9,8 @@ import { render, Box, Text, useApp } from "ink";
9
9
  import { App } from "./ui/index.js";
10
10
  import { mastheadLines } from "./ui/Masthead.js";
11
11
  import { RemoteHost } from "./remote/host.js";
12
+ import { isErrorResult } from "./ui/format.js";
13
+ import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
12
14
  import { Session } from "./session.js";
13
15
  import { AuroraRouter } from "./router/router.js";
14
16
  import { BackgroundAgents } from "./background/index.js";
@@ -22,7 +24,7 @@ import { homedir, hostname } from "node:os";
22
24
  import { createHash } from "node:crypto";
23
25
  // RELEASE CHECKLIST (every bump): update this + package.json "version", ADD A CHANGELOG.md ENTRY
24
26
  // (improvements / fixes / tests), run the suite, then publish to npm + push both remotes.
25
- const VERSION = "0.1.52";
27
+ const VERSION = "0.1.53";
26
28
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
27
29
  const settings = loadSettings();
28
30
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
@@ -200,6 +202,13 @@ const SYSTEM_PROMPT = (settings.systemPrompt ??
200
202
  `workspace; prefer doing over explaining. Answer concisely.\n## This machine\nWorking dir: ${process.cwd()}` +
201
203
  `\nContext window: 1,048,576 tokens (1M) — you run on the Aurora model served locally with a full ` +
202
204
  `1M-token context. You can hold very large files and long histories; do not claim a smaller limit.` +
205
+ `\n## Parallel tool calls\nWhen the next few steps are INDEPENDENT of each other — reading several ` +
206
+ `files, running several greps/checks, inspecting multiple unrelated things — issue them as multiple ` +
207
+ `tool calls in a SINGLE message so they run in parallel, instead of one call, waiting, then the next. ` +
208
+ `Only serialize when one call's output feeds the next call's input (e.g. read a file, then edit it), ` +
209
+ `or when a call mutates something the next call depends on seeing. Batching independent reads is ` +
210
+ `almost always faster and is the default you should reach for; do not artificially serialize work ` +
211
+ `that has no real dependency.` +
203
212
  `\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
204
213
  `build) call spawn_agent with a fully self-contained instruction — it runs on another Aurora session ` +
205
214
  `in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
@@ -279,7 +288,6 @@ const firstLine = (s) => (s.split("\n")[0] ?? "").slice(0, 100);
279
288
  const fmtDuration = (sec) => (sec < 60 ? `${sec < 10 ? sec.toFixed(1) : Math.round(sec)}s` : `${Math.floor(sec / 60)}m ${Math.round(sec % 60)}s`);
280
289
  const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k tokens` : `${n} token${n === 1 ? "" : "s"}`);
281
290
  const fmtMeta = (sec, tokens) => `(${fmtDuration(sec)} · ${fmtTokens(tokens)})`;
282
- const isErrorResult = (s) => /^(error|loop guard|\[interrupted)/i.test(s.trim());
283
291
  function Root() {
284
292
  const { exit } = useApp();
285
293
  const [boot, setBoot] = useState("checking");
@@ -288,6 +296,9 @@ function Root() {
288
296
  const [live, setLive] = useState(null);
289
297
  const [status, setStatus] = useState("idle");
290
298
  const [stepLabel, setStepLabel] = useState(""); // tool(s) currently executing, for the step animation
299
+ const [liveTools, setLiveTools] = useState([]); // one row per call in the CURRENT batch,
300
+ // live: seeded "running" by onToolStart, each flips to done/error independently as onToolResult fires
301
+ // for it — see ui/liveTools.ts. Cleared once the batch settles (onToolBatch).
291
302
  const [route, setRoute] = useState("aurora");
292
303
  const [ctxPct, setCtxPct] = useState(0);
293
304
  const [metrics, setMetrics] = useState(""); // last turn's "N tok · X tok/s · Ys" for the status rule
@@ -446,8 +457,8 @@ function Root() {
446
457
  // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
447
458
  // spawned stdio MCP subprocesses (session.shutdown), or they orphan. exit runs sync; SIGTERM exits after.
448
459
  useEffect(() => {
449
- const onExit = () => { session.shutdown(); disposeShellSession(); };
450
- const onTerm = () => { session.shutdown(); disposeShellSession(); process.exit(0); };
460
+ const onExit = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); };
461
+ const onTerm = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); process.exit(0); };
451
462
  process.once("exit", onExit);
452
463
  process.once("SIGTERM", onTerm);
453
464
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
@@ -562,7 +573,14 @@ function Root() {
562
573
  setStepLabel(kind === "context_exceeded" ? "adjusting context" : kind === "unavailable" ? "reconnecting" : "recovering");
563
574
  setStat("recovering");
564
575
  },
565
- onToolStart: (names) => { setStepLabel(names.join(", ")); setStat("executing"); },
576
+ onToolStart: (calls) => {
577
+ setStepLabel(calls.map((c) => c.name).join(", "));
578
+ setStat("executing");
579
+ setLiveTools(seedLiveTools(calls));
580
+ },
581
+ onToolResult: (id, result) => {
582
+ setLiveTools((rows) => settleLiveTool(rows, id, result));
583
+ },
566
584
  onToolBatch: (events, durationMs) => {
567
585
  for (const ev of events) {
568
586
  const step = {
@@ -591,6 +609,7 @@ function Root() {
591
609
  liveText.current = "";
592
610
  liveReasoning.current = "";
593
611
  setLive(null);
612
+ setLiveTools([]); // batch settled — the per-call rows are now in the settled transcript above
594
613
  setStat("thinking");
595
614
  },
596
615
  });
@@ -636,6 +655,7 @@ function Root() {
636
655
  finally {
637
656
  liveText.current = "";
638
657
  setLive(null);
658
+ setLiveTools([]); // an interrupt/error mid-batch must not leave stale "running" rows on screen
639
659
  setCtxPct(session.ctxPct());
640
660
  setStat("idle");
641
661
  try {
@@ -665,6 +685,7 @@ function Root() {
665
685
  break;
666
686
  case "exit":
667
687
  case "quit":
688
+ bg.dispose();
668
689
  s.shutdown();
669
690
  exit();
670
691
  break;
@@ -906,6 +927,21 @@ function Root() {
906
927
  const { loadCredentials } = await import("./auth/store.js");
907
928
  const creds = await loadCredentials().catch(() => null);
908
929
  const token = process.env.KODE_OPERATOR_TOKEN || creds?.token || "";
930
+ // Preflight: with no token the host would still open the socket and send hello{token:""},
931
+ // and the relay verifies the host token then CLOSES on a non-200 — which surfaced to the
932
+ // owner only as a generic "connection lost", hiding the real cause (not signed in on THIS
933
+ // box). Refuse legibly instead: name the fix, don't touch the wire. (An expired/rejected
934
+ // token still fails at the relay and reports its own "error" frame; this catches the far
935
+ // more common absent-token case with zero false positives, since "" is unambiguous.)
936
+ if (!token) {
937
+ sys("remote control needs an Operator sign-in on THIS machine — none found.\n" +
938
+ " Sign in here first, then re-run /remotecontrol:\n" +
939
+ " • run `operator auth login` in your shell (browser sign-in), or\n" +
940
+ " • /login <token> to paste a token\n" +
941
+ " Without a token the relay rejects the host and closes the connection.");
942
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_no_token" } });
943
+ break;
944
+ }
909
945
  const url = process.env.KODE_RELAY_URL || "wss://api.axe.onl/session/ws";
910
946
  const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
911
947
  onPrompt: (text) => submitRef.current(text), // follower drives a turn
@@ -960,6 +996,7 @@ function Root() {
960
996
  const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; }, []);
961
997
  const onInterrupt = useCallback(() => {
962
998
  if (statusRef.current === "idle") {
999
+ bg.dispose();
963
1000
  session.shutdown();
964
1001
  return exit();
965
1002
  } // Ctrl-C / ESC at rest quits
@@ -996,7 +1033,7 @@ function Root() {
996
1033
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
997
1034
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
998
1035
  : metrics;
999
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, question: question, modelPicker: modelPicker, onApprovalDecide: (allow, always) => {
1036
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, question: question, modelPicker: modelPicker, onApprovalDecide: (allow, always) => {
1000
1037
  const cur = approval;
1001
1038
  if (cur)
1002
1039
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -89,7 +89,7 @@ function parseArgs(raw) {
89
89
  * guard (SPEC §2: identical (name,args) ≥3× this turn is short-circuited) and reporting the
90
90
  * batch via onToolBatch with a real (unrounded) duration.
91
91
  */
92
- async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolStart) {
92
+ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolStart, onToolResult) {
93
93
  const pending = [];
94
94
  const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
95
95
  const parsedArgs = new Map();
@@ -112,9 +112,11 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
112
112
  pending.push({ id: tc.id, name: tc.function.name, args: parsed.args });
113
113
  }
114
114
  if (pending.length)
115
- onToolStart?.(pending.map((p) => p.name));
115
+ onToolStart?.(pending);
116
116
  const started = performance.now();
117
- const executed = pending.length ? await tools.executeParallel(pending) : [];
117
+ const executed = pending.length
118
+ ? await tools.executeParallel(pending, onToolResult ? (i, r) => onToolResult(pending[i].id, r) : undefined)
119
+ : [];
118
120
  const durationMs = performance.now() - started;
119
121
  const resultById = new Map(preResolved);
120
122
  pending.forEach((p, i) => resultById.set(p.id, executed[i]));
@@ -253,7 +255,7 @@ export async function runTurn(userInput, conversation, opts) {
253
255
  if (response.toolCalls.length > 0) {
254
256
  throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
255
257
  conversation.assistant(response.content, response.toolCalls);
256
- const toolMsgs = await runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart);
258
+ const toolMsgs = await runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart, opts.onToolResult);
257
259
  for (const tm of toolMsgs)
258
260
  conversation.tool(tm.tool_call_id, tm.content);
259
261
  toolCallTotal += response.toolCalls.length;
@@ -265,7 +267,7 @@ export async function runTurn(userInput, conversation, opts) {
265
267
  if (recovered.calls.length > 0) {
266
268
  throwIfAborted(opts.signal);
267
269
  conversation.assistant(recovered.cleanedContent, recovered.calls);
268
- const toolMsgs = await runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart);
270
+ const toolMsgs = await runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart, opts.onToolResult);
269
271
  for (const tm of toolMsgs)
270
272
  conversation.tool(tm.tool_call_id, tm.content);
271
273
  toolCallTotal += recovered.calls.length;
@@ -218,7 +218,20 @@ export async function chat(messages, o) {
218
218
  // "length" isn't a truncated ANSWER, so only flag length/content_filter when NO tool calls were made.
219
219
  const apiStop = finishReason === "length" ? "length" : finishReason === "content_filter" ? "content_filter" : undefined;
220
220
  const stopReason = degenerate ? "repetition" : (acc.size === 0 ? apiStop : undefined);
221
- return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens: meta.tokens, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs };
221
+ // llama.cpp's final SSE chunk often omits `timings` (or reports predicted_n:0) on a round that ends in
222
+ // tool_calls instead of plain prose — verified live: a 40+ tool-call turn showed ~365 total tokens on
223
+ // the status rule because every tool-calling round silently contributed 0, leaving only the final
224
+ // prose round counted. When the server gives us nothing usable for THIS round despite it clearly having
225
+ // generated output (content, reasoning, or tool-call name+arguments JSON), fall back to the same chars/4
226
+ // heuristic the rest of the engine already uses (SPEC §5 — compaction.ts's estimateTokensHeuristic,
227
+ // router-adapter.ts's estimateTokens) over everything actually streamed this round, so the meter is
228
+ // never ~0 for a round that plainly did work.
229
+ const generatedChars = content.length + reasoning.length +
230
+ [...acc.values()].reduce((n, e) => n + e.name.length + e.args.length, 0);
231
+ const tokens = meta.tokens && meta.tokens > 0 ? meta.tokens
232
+ : generatedChars > 0 ? Math.max(1, Math.ceil(generatedChars / 4)) // SPEC §5 heuristic (chars/4)
233
+ : meta.tokens;
234
+ return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs };
222
235
  }
223
236
  /** GET {base}/health → true iff {"status":"ok"}. Used by Router (SPEC §4) for self-heal failover. */
224
237
  export async function health(base) {
package/dist/mcp/index.js CHANGED
@@ -107,14 +107,29 @@ export function withMcp(local, hub) {
107
107
  ready: () => hub?.discover() ?? Promise.resolve(),
108
108
  mcpSchemas: () => hub?.schemas() ?? [],
109
109
  execute: (name, args) => (hub?.has(name) ? hub.call(name, args) : local.execute(name, args)),
110
- executeParallel: async (calls) => {
110
+ executeParallel: async (calls, onSettle) => {
111
111
  // Route each call to its lane, preserving order. Local calls keep the executor's own
112
112
  // read-only/mutating parallelism; MCP calls run concurrently (they're remote & independent).
113
- const localCalls = calls.filter((c) => !hub?.has(c.name));
114
- const localResults = localCalls.length ? await local.executeParallel(localCalls) : [];
113
+ // localIdxMap translates a local-lane sub-index back to its index in the ORIGINAL `calls` array,
114
+ // so onSettle (if given) always reports against the index the caller knows about.
115
+ const localIdxMap = [];
116
+ const localCalls = [];
117
+ calls.forEach((c, i) => { if (!hub?.has(c.name)) {
118
+ localIdxMap.push(i);
119
+ localCalls.push(c);
120
+ } });
121
+ const localResults = localCalls.length
122
+ ? await local.executeParallel(localCalls, onSettle ? (li, r) => onSettle(localIdxMap[li], r) : undefined)
123
+ : [];
115
124
  const localByIdx = new Map();
116
125
  localCalls.forEach((c, i) => localByIdx.set(c.id, localResults[i]));
117
- const mcpResults = await Promise.all(calls.map((c) => (hub?.has(c.name) ? hub.call(c.name, c.args) : Promise.resolve(localByIdx.get(c.id) ?? ""))));
126
+ const mcpResults = await Promise.all(calls.map(async (c, i) => {
127
+ if (!hub?.has(c.name))
128
+ return localByIdx.get(c.id) ?? "";
129
+ const r = await hub.call(c.name, c.args);
130
+ onSettle?.(i, r);
131
+ return r;
132
+ }));
118
133
  return mcpResults;
119
134
  },
120
135
  };
@@ -54,10 +54,14 @@ export function withPermissions(inner, policy, opts = {}) {
54
54
  }
55
55
  return {
56
56
  execute: (name, args) => gate(name, args, () => inner.execute(name, args)),
57
- executeParallel: (calls) =>
57
+ executeParallel: (calls, onSettle) =>
58
58
  // Gate each call individually (its own decision + event), preserving order. We can't hand a
59
59
  // pre-denied call to inner.executeParallel, so route per-call through execute (the executor's
60
60
  // own read-only/mutating parallelism still applies to the ones that reach it via execute).
61
- Promise.all(calls.map((c) => gate(c.name, c.args, () => inner.execute(c.name, c.args)))),
61
+ Promise.all(calls.map(async (c, i) => {
62
+ const r = await gate(c.name, c.args, () => inner.execute(c.name, c.args));
63
+ onSettle?.(i, r);
64
+ return r;
65
+ })),
62
66
  };
63
67
  }
package/dist/session.js CHANGED
@@ -430,6 +430,7 @@ export class Session {
430
430
  onReasoning: h.onReasoning,
431
431
  onRoute: (ep) => h.onRoute?.(routeLabel ?? ep.label ?? "aurora", this.ctxPct()),
432
432
  onToolStart: h.onToolStart,
433
+ onToolResult: h.onToolResult,
433
434
  onToolBatch: h.onToolBatch,
434
435
  onAutoContinue: h.onAutoContinue,
435
436
  onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
@@ -52,7 +52,7 @@ export class Executor {
52
52
  return `error running ${name}: ${e?.message ?? e}`;
53
53
  }
54
54
  }
55
- async executeParallel(calls) {
55
+ async executeParallel(calls, onSettle) {
56
56
  const results = new Array(calls.length);
57
57
  const safeIdx = new Set();
58
58
  for (let i = 0; i < calls.length; i++) {
@@ -61,11 +61,13 @@ export class Executor {
61
61
  }
62
62
  await Promise.all([...safeIdx].map(async (i) => {
63
63
  results[i] = await this.execute(calls[i].name, calls[i].args);
64
+ onSettle?.(i, results[i]);
64
65
  }));
65
66
  for (let i = 0; i < calls.length; i++) {
66
67
  if (safeIdx.has(i))
67
68
  continue;
68
69
  results[i] = await this.execute(calls[i].name, calls[i].args);
70
+ onSettle?.(i, results[i]);
69
71
  }
70
72
  return results;
71
73
  }
package/dist/ui/App.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Box } from "ink";
2
+ import { Box, Text } from "ink";
3
3
  import { StatusRule } from "./StatusRule.js";
4
4
  import { InputRule } from "./InputRule.js";
5
5
  import { Transcript } from "./Transcript.js";
@@ -7,13 +7,22 @@ import { Composer } from "./Composer.js";
7
7
  import { ThinkingSpinner } from "./ThinkingSpinner.js";
8
8
  import { StepSpinner, RecoverSpinner } from "./ActivitySpinner.js";
9
9
  import { BgPanel } from "./BgPanel.js";
10
+ import { ToolStep } from "./ToolStep.js";
10
11
  import { ApprovalPrompt } from "./ApprovalPrompt.js";
11
12
  import { QuestionPrompt } from "./QuestionPrompt.js";
13
+ // Cap on live rows shown at once for a parallel tool batch — keeps the dynamic (non-Static) frame
14
+ // bounded (same render-collapse concern liveTail guards in Transcript.tsx: Ink corrupts the frame once
15
+ // the non-Static portion approaches the terminal height). A batch rarely runs more than a handful of
16
+ // calls at once; anything past the cap is summarized as a count instead of another row.
17
+ const MAX_LIVE_TOOL_ROWS = 6;
12
18
  export function App(props) {
13
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, route, ctxPct, version, build, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, onSubmit, onQueue, onInterrupt, approval = null, onApprovalDecide, question = null, modelPicker = null } = props;
19
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, onSubmit, onQueue, onInterrupt, approval = null, onApprovalDecide, question = null, modelPicker = null } = props;
14
20
  const thinking = status === "thinking" || status === "streaming";
15
- const showSpinner = status === "recovering" || status === "executing" || thinking;
21
+ // A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
22
+ // a lone call isn't worth a bordered block, the braille spinner + name already says enough.
23
+ const showParallelRows = status === "executing" && liveTools.length > 1;
24
+ const showSpinner = status === "recovering" || (status === "executing" && !showParallelRows) || thinking;
16
25
  return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), showSpinner && (_jsx(Box, { marginTop: 1, marginBottom: 1, children: status === "recovering" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
17
26
  : status === "executing" ? _jsx(StepSpinner, { active: true, label: stepLabel })
18
- : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), _jsx(BgPanel, { agents: bgAgents }), _jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker }), _jsx(InputRule, {})] }));
27
+ : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), showParallelRows && (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "gray", paddingX: 1, children: [_jsxs(Text, { dimColor: true, children: ["running ", liveTools.length, " tools in parallel"] }), liveTools.slice(0, MAX_LIVE_TOOL_ROWS).map((step) => _jsx(ToolStep, { step: step }, step.id)), liveTools.length > MAX_LIVE_TOOL_ROWS ? _jsxs(Text, { dimColor: true, children: [" +", liveTools.length - MAX_LIVE_TOOL_ROWS, " more\u2026"] }) : null] })), _jsx(BgPanel, { agents: bgAgents }), _jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker }), _jsx(InputRule, {})] }));
19
28
  }
@@ -28,8 +28,23 @@ function GrandmasterLine({ a }) {
28
28
  return null;
29
29
  return (_jsxs(Box, { paddingLeft: 2, children: [hasModel && _jsxs(Text, { dimColor: true, children: [a.model ?? "?", a.lane != null ? ` · ${a.lane}` : ""] }), hasVerify && (_jsxs(Text, { color: a.verified ? "green" : "red", children: [hasModel ? " " : "", a.verified ? "✓ verified" : `✗ unverified${a.verifyDetail ? `: ${cap(a.verifyDetail)}` : ""}`] })), a.malformed ? _jsxs(Text, { color: "yellow", children: [(hasModel || hasVerify) ? " " : "", "\u26A0 malformed"] }) : null] }));
30
30
  }
31
+ // Live activity for a WORKING child (SPEC §7 observability): the tools it is running (in-flight
32
+ // marked with …) and the tail of its current reasoning — so the owner sees thoughts / steps / reads
33
+ // instead of a bare round counter. Both lines are dim and capped so a narrow terminal never wraps.
34
+ function ActivityLines({ a }) {
35
+ if (a.status !== "working")
36
+ return null;
37
+ const steps = a.steps ?? [];
38
+ const stepLine = steps
39
+ .slice(-3)
40
+ .map((s) => s.name + (s.arg ? `(${s.arg})` : "") + (s.running ? " …" : ""))
41
+ .join(" · ");
42
+ if (!stepLine && !a.thought)
43
+ return null;
44
+ return (_jsxs(Box, { flexDirection: "column", paddingLeft: 2, children: [stepLine ? _jsxs(Text, { dimColor: true, children: ["\u21B3 ", cap(stepLine, 72)] }) : null, a.thought ? _jsxs(Text, { dimColor: true, children: ["⋮ ", cap(a.thought, 72)] }) : null] }));
45
+ }
31
46
  export function BgPanel({ agents, title = "background" }) {
32
47
  if (agents.length === 0)
33
48
  return null;
34
- return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, children: [_jsxs(Text, { dimColor: true, children: [title, " (", agents.length, ")"] }), agents.map((a) => (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { justifyContent: "space-between", children: [_jsxs(Text, { children: [a.status === "working" ? _jsx(OrbitGlyph, {}) : _jsx(Text, { color: COLOR[a.status], children: GLYPH[a.status] }), " ", a.label, a.round != null ? ` · round ${a.round}` : ""] }), _jsx(Text, { dimColor: true, children: (() => { const m = metrics(a); return m ? `${m} · ${a.status}` : a.status; })() })] }), _jsx(GrandmasterLine, { a: a })] }, a.id)))] }));
49
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, children: [_jsxs(Text, { dimColor: true, children: [title, " (", agents.length, ")"] }), agents.map((a) => (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { justifyContent: "space-between", children: [_jsxs(Text, { children: [a.status === "working" ? _jsx(OrbitGlyph, {}) : _jsx(Text, { color: COLOR[a.status], children: GLYPH[a.status] }), " ", a.label, a.round != null ? ` · round ${a.round}` : ""] }), _jsx(Text, { dimColor: true, children: (() => { const m = metrics(a); return m ? `${m} · ${a.status}` : a.status; })() })] }), _jsx(ActivityLines, { a: a }), _jsx(GrandmasterLine, { a: a })] }, a.id)))] }));
35
50
  }
package/dist/ui/format.js CHANGED
@@ -4,3 +4,9 @@ export function formatDuration(ms) {
4
4
  return `${Math.round(ms)}ms`;
5
5
  return `${(ms / 1000).toFixed(1)}s`;
6
6
  }
7
+ // A tool result reads as an error/loop-guard/interrupt sentinel rather than real output — shared by the
8
+ // settled-transcript push (cli.tsx) and the live per-call row update (ui/liveTools.ts) so both classify
9
+ // a result the same way.
10
+ export function isErrorResult(s) {
11
+ return /^(error|loop guard|\[interrupted)/i.test(s.trim());
12
+ }
package/dist/ui/index.js CHANGED
@@ -7,4 +7,5 @@ export { ThinkingSpinner } from "./ThinkingSpinner.js";
7
7
  export { ToolStep } from "./ToolStep.js";
8
8
  export { BgPanel } from "./BgPanel.js";
9
9
  export * from "./types.js";
10
- export { formatDuration } from "./format.js";
10
+ export { formatDuration, isErrorResult } from "./format.js";
11
+ export { seedLiveTools, settleLiveTool } from "./liveTools.js";
@@ -0,0 +1,24 @@
1
+ import { isErrorResult } from "./format.js";
2
+ /** Seed one live row per call, all "running" from the same instant — the batch was just dispatched
3
+ * together, so that's the honest starting state even though safe calls run concurrently and mutating
4
+ * ones run sequentially (the UI can't see that split; each row's own elapsed timer still ticks
5
+ * correctly once ToolStep renders it, per-row, independent of the others). */
6
+ export function seedLiveTools(calls, now = Date.now()) {
7
+ return calls.map((c) => ({ id: c.id, name: c.name, args: c.args, status: "running", startedAt: now }));
8
+ }
9
+ /** Flip the ONE row matching `id` to done/error with its real result, live — called from onToolResult
10
+ * as each call in the batch settles. Rows are otherwise left untouched (still running), and an id with
11
+ * no matching row is a no-op (defensive: a stale/duplicate settle should never throw). */
12
+ export function settleLiveTool(rows, id, result, now = Date.now()) {
13
+ let changed = false;
14
+ const next = rows.map((r) => {
15
+ if (r.id !== id || r.status !== "running")
16
+ return r;
17
+ changed = true;
18
+ return { ...r, status: isErrorResult(result) ? "error" : "done", endedAt: now, summary: firstLine(result) };
19
+ });
20
+ return changed ? next : rows;
21
+ }
22
+ function firstLine(s) {
23
+ return (s.split("\n")[0] ?? "").slice(0, 100);
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.52",
3
+ "version": "0.1.53",
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": {