@0perator/operator 0.2.4 → 0.2.5

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.
@@ -371,6 +371,8 @@ export function basePersona(_cwd = process.cwd(), opts = {}) {
371
371
  `\nScratch dir (also \`$OPERATOR_SCRATCH\` in every shell) — temporary scripts, probe ` +
372
372
  `output, downloads to inspect, intermediate files: ALWAYS here, never /tmp and never the repo root. It is ` +
373
373
  `git-ignored and swept after a week, so nothing you keep belongs in it; name files \`<subject>-<thing>\`.` +
374
+ (typeof process !== "undefined" && process.platform === "darwin"
375
+ ? `\nmacOS: BSD tools (no \`grep -P\`); Mac ssh is zsh: quote globs.` : "") +
374
376
  ctxLine +
375
377
  `\n## Talking about yourself\nYou are Operator, AXE's agent, whichever model is serving you — the model underneath can change between sessions (or mid-session with /model) and you are still Operator. Asked what you are, say you are Operator; give ` +
376
378
  `the context window above if asked. What you may say about the model underneath is set by the "Active model" section at the end ` +
@@ -440,14 +442,14 @@ export function basePersona(_cwd = process.cwd(), opts = {}) {
440
442
  `intent; a failed step is cancelled and replaced by a revised one. The owner watches the list live, so never ` +
441
443
  `restate the numbered plan in prose round after round — narrate only what you are doing now.`) +
442
444
  `\n## Parallel tool calls\nWhen the next few steps are INDEPENDENT, issue them as multiple tool calls in a ` +
443
- `SINGLE message so they run in parallel — independent bash commands included (they overlap for real). ` +
445
+ `SINGLE message so they run together — independent bash commands included. ` +
444
446
  `Serialize only when one call's output feeds the next. Read several files with ONE read_files call.` +
445
447
  `\n## Long-running commands\nBuilds, servers, watchers, test suites and batches go to shell_background from ` +
446
448
  `the start; a finished job announces itself at your next turn, so do NOT poll bash_output in a loop.` +
447
449
  `\n## Downloading files\nUse download_file (on demand), never curl/wget, and NEVER say a file is downloaded until its ` +
448
450
  `completion notice says so; a 0-byte file, an HTML page with an .iso/.zip name or a failed hash is a FAILURE ` +
449
451
  `to report and fix, not to retry blindly.` +
450
- `\n## Finding things\nContent: the search tool scoped to a directory — never bash \`grep -r\` / \`rg\` / ` +
452
+ `\n## Finding things\nContent: the search tool scoped to a directory, then file_read, not cat/sed. Never bash \`grep -r\` / \`rg\` / ` +
451
453
  `\`find ~/ | grep\` over $HOME or / (it refuses those roots because they wedge the TUI for minutes). Check the ` +
452
454
  `2-3 most likely directories first, batched in ONE message.\nA FLEET HOST / server name (acropolis, jl1, jla, …): ` +
453
455
  `\`~/.ssh/config\` + \`ssh <name> 'hostname; uptime'\`, then \`gh repo view axetechnologies/<name>\`, then fleet ` +
@@ -496,7 +498,8 @@ export function harnessRules(cwd = process.cwd(), opts = {}) {
496
498
  // (10/31: on JL2 Cortana never saw the rule). Static per session — cache-safe.
497
499
  function subagentsSection(opts) {
498
500
  return opts.interactive
499
- ? `\n## Sub-agents — you stay the lead\nWhen work splits into independent parts, call spawn_agent in the SAME round ` +
501
+ ? `\n## Sub-agents — you stay the lead\nDelegate to finish sooner: when work splits into independent parts, ` +
502
+ `call spawn_agent in the SAME round ` +
500
503
  `you decide to (never announce it without the call; its description carries the brief format and rules) and ` +
501
504
  `tell the owner who you are sending and why. While they run, do what does not depend on them and never redo a ` +
502
505
  `step an agent is still working on. When a report or a STUCK notice arrives, check what the agent produced ` +
@@ -36,6 +36,7 @@ import { FILE_WRITE as MUTATING_TOOLS, POLLERS as LOOP_GUARD_EXEMPT, STATUS_TOOL
36
36
  /** The executor's identical-call refusal, exactly (tools/executor.ts): a tool's own output that merely starts with
37
37
  * "loop guard:" (a log, a grep of this source) is real output, not a refusal to be counted and replaced. */
38
38
  export const EXECUTOR_REPEAT_REFUSAL = /^loop guard: "[^"]+" called \d+x with identical args this turn/;
39
+ import { batchHints } from "./batch-hints.js";
39
40
  import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, needsDeliverFindings, DELIVER_FINDINGS_NUDGE, EMPTY_REPLY_NUDGE, fallbackLine, noAnswer, closeStopNote, stopQuestion, stripEngineEcho } from "./continuation.js";
40
41
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
41
42
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
@@ -795,6 +796,7 @@ export async function runTurn(userInput, conversation, opts) {
795
796
  // Delegation-by-prose guard applies only where spawn_agent is actually offered (interactive foreground; a bg
796
797
  // sub-agent has no spawn tool and must not be told to call one).
797
798
  const hasSpawnTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "spawn_agent");
799
+ const widen = opts.batchHints ? batchHints(hasSpawnTool) : undefined;
798
800
  let announceNudges = 0;
799
801
  let selfDialogueNudges = 0; // owner-facing: replies that react to a speaker who did not speak (continuation.ts)
800
802
  let closingNudged = false; // owner-facing: one nudge to close with status + a steering question instead of a bare stop
@@ -1831,6 +1833,9 @@ export async function runTurn(userInput, conversation, opts) {
1831
1833
  }
1832
1834
  if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
1833
1835
  return stopTurn(notConvergingNote(response.toolCalls), "stopped", rounds + 1);
1836
+ const hint = widen?.(response.toolCalls);
1837
+ if (hint)
1838
+ engineUser(hint);
1834
1839
  continue;
1835
1840
  }
1836
1841
  // No structured tool_calls — check for text-encoded ones before treating this as final.
@@ -0,0 +1,45 @@
1
+ // Two short engine notes that suggest wider rounds: reads sent one at a time, and a plan whose parts do not depend on
2
+ // each other. Each at most once per turn; they ride the conversation's tail, never the system prompt or the tools.
3
+ import { BATCHABLE_READ, DELEGATION, SHELL_FOREGROUND } from "../tools/classes.js";
4
+ import { isReadOnlyCommand } from "../tools/readonly-shell.js";
5
+ export const SINGLE_READ_ROUNDS = 4;
6
+ export const BATCH_HINT = `The last ${SINGLE_READ_ROUNDS} rounds each made one read-only call. When calls do not depend on each other, send them together in one message.`;
7
+ export const FANOUT_HINT = "The plan has independent parts. spawn_agent can run them in parallel, one `tasks` entry each, if that is faster than doing them yourself.";
8
+ const argsOf = (c) => { try {
9
+ return JSON.parse(c.function.arguments || "{}") ?? {};
10
+ }
11
+ catch {
12
+ return {};
13
+ } };
14
+ const readOnly = (c) => BATCHABLE_READ.has(c.function.name) || (SHELL_FOREGROUND.has(c.function.name) && isReadOnlyCommand(argsOf(c).command));
15
+ const PATH = /(?:[\w.~-]*\/[\w./~-]+|\b[\w-]+\.[a-z]{1,5}\b)/i;
16
+ const DEPENDS = /\b(then|after|once|based on|using|verify|test|check|review|combine|merge|summar\w+|report|commit)\b/i;
17
+ /** Three or more new steps, each on its own file or folder, none worded as following another. */
18
+ function independentPlan(c) {
19
+ if (c.function.name !== "task_add")
20
+ return false;
21
+ const tasks = argsOf(c).tasks;
22
+ if (!Array.isArray(tasks))
23
+ return false;
24
+ const targets = tasks.map((t) => (typeof t === "string" && !DEPENDS.test(t) ? PATH.exec(t)?.[0] : undefined)).filter(Boolean);
25
+ return targets.length >= 3 && targets.length === tasks.length && new Set(targets).size === targets.length;
26
+ }
27
+ export function batchHints(canSpawn) {
28
+ let singles = 0;
29
+ let batched = false;
30
+ let fannedOut = false;
31
+ return (calls) => {
32
+ if (calls.some((c) => DELEGATION.has(c.function.name)))
33
+ fannedOut = true;
34
+ singles = calls.length === 1 && readOnly(calls[0]) ? singles + 1 : 0;
35
+ if (canSpawn && !fannedOut && calls.some(independentPlan)) {
36
+ fannedOut = true;
37
+ return FANOUT_HINT;
38
+ }
39
+ if (!batched && singles >= SINGLE_READ_ROUNDS) {
40
+ batched = true;
41
+ return BATCH_HINT;
42
+ }
43
+ return undefined;
44
+ };
45
+ }
@@ -15,6 +15,7 @@
15
15
  // resource (web_search, memory_search…) never holds a writer back.
16
16
  // • Barrier tools (git_command/checkpoint/computer_*/browser*/delegate_*/…) can touch ANYTHING and
17
17
  // share a device — they run alone, in input order.
18
+ // • A plainly read-only shell ("look") overlaps reads and other looks; writes, shells and barriers keep their order.
18
19
  // • Shell tools (bash/shell_exec) can also touch anything, but INDEPENDENT shells in one round run
19
20
  // concurrently (matches Cursor). A shell waits for every prior non-shell; later non-shells wait for
20
21
  // the whole shell wave. Shells do NOT wait for each other. (Ephemeral one-shot processes when a
@@ -23,6 +24,7 @@
23
24
  // failure never strands its dependents — the chain advances regardless.
24
25
  // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
25
26
  import { SCHED_BARRIER, SHELL_FOREGROUND } from "../tools/classes.js";
27
+ import { isReadOnlyCommand } from "../tools/readonly-shell.js";
26
28
  /** The report runBatch hands each runOne — and a hand-rolled batch loop builds the same way: `started` fires `onStart`
27
29
  * once, `why` holds the refusal. */
28
30
  export function callReport(onStart, signal) {
@@ -47,9 +49,9 @@ const BARRIER_PREFIX = ["computer_", "browser", "shell", "mcp__"]; // browser_va
47
49
  // NOTE: "shell" prefix still matches shell_background / shell_*; SHELL_FOREGROUND is checked FIRST so
48
50
  // bash/shell_exec become "shell" (parallelizable) instead of falling through to barrier.
49
51
  export function defaultClassify(_unused, isSafe) {
50
- return (n) => {
52
+ return (n, args) => {
51
53
  if (SHELL_FOREGROUND.has(n))
52
- return "shell";
54
+ return isReadOnlyCommand(args?.command) ? "look" : "shell";
53
55
  if (SCHED_BARRIER.has(n))
54
56
  return "barrier";
55
57
  for (const p of BARRIER_PREFIX)
@@ -107,6 +109,8 @@ export function runBatch(calls, opts) {
107
109
  const keyedReads = []; // prior reads that named a resource (a later conflicting write waits for them)
108
110
  const inflight = new Set(); // everything not yet settled (barrier gate)
109
111
  const shellInflight = new Set(); // shells currently running — other shells skip these
112
+ const looks = new Set(); // read-only shells: later writes wait, other reads do not
113
+ const namedReads = new Set(); // reads that named a resource: a read-only shell need not wait
110
114
  let afterBarrier = Promise.resolve(); // every op must clear the last hard barrier / shell wave
111
115
  // Cancellation: `aborted` settles when the turn is interrupted so queued calls stop waiting on their
112
116
  // predecessors and are cancelled, not run late. The listener is removed when the batch ends — a long turn
@@ -130,11 +134,11 @@ export function runBatch(calls, opts) {
130
134
  };
131
135
  for (let i = 0; i < calls.length; i++) {
132
136
  const c = calls[i];
133
- const kind = opts.classify(c.name);
137
+ const kind = opts.classify(c.name, c.args);
134
138
  // Flush before scheduling a non-shell so it observes the whole prior shell wave.
135
139
  if (kind !== "shell")
136
140
  flushShellWave();
137
- let keys = (kind === "barrier" || kind === "shell") ? [] : opts.keys(c.name, c.args);
141
+ let keys = (kind === "barrier" || kind === "shell" || kind === "look") ? [] : opts.keys(c.name, c.args);
138
142
  // no-path MUTATIONS (memory_store, task_add, cron create…): serialize per tool-name lock.
139
143
  // Reads never take the lock — a path-less read pairs with nothing and is safe to overlap.
140
144
  if (kind === "write" && keys.length === 0)
@@ -153,11 +157,19 @@ export function runBatch(calls, opts) {
153
157
  if (!shellInflight.has(p))
154
158
  gate.push(p);
155
159
  }
160
+ else if (kind === "look") {
161
+ // Waits like a shell, except on work that changes nothing: named reads and other read-only shells.
162
+ gate.push(afterBarrier);
163
+ for (const p of inflight)
164
+ if (!looks.has(p) && !namedReads.has(p))
165
+ gate.push(p);
166
+ }
156
167
  else if (kind === "read") {
157
168
  gate.push(afterBarrier); // barriers/shells can change anything a read observes
158
169
  if (!keys.length) {
159
170
  for (const t2 of writeTails.values())
160
171
  gate.push(t2); // path-less read: any prior write may target it
172
+ gate.push(...looks); // it may write (scratchpad), which an earlier look must not see
161
173
  }
162
174
  for (const k of keys) {
163
175
  // A read waits only for PRIOR WRITES on overlapping resources; prior reads never block it.
@@ -167,7 +179,7 @@ export function runBatch(calls, opts) {
167
179
  }
168
180
  }
169
181
  else {
170
- gate.push(afterBarrier);
182
+ gate.push(afterBarrier, ...looks);
171
183
  for (const k of keys) {
172
184
  for (const [wk, wt] of writeTails)
173
185
  if (conflicts(k, wk))
@@ -212,10 +224,14 @@ export function runBatch(calls, opts) {
212
224
  else if (kind === "write")
213
225
  for (const k of keys)
214
226
  writeTails.set(k, run);
215
- else if (keys.length)
227
+ else if (kind === "look")
228
+ looks.add(run);
229
+ else if (keys.length) {
216
230
  keyedReads.push({ keys, run });
231
+ namedReads.add(run);
232
+ }
217
233
  inflight.add(run);
218
- run.then(() => { inflight.delete(run); shellInflight.delete(run); });
234
+ run.then(() => { inflight.delete(run); shellInflight.delete(run); looks.delete(run); namedReads.delete(run); });
219
235
  done.push(run);
220
236
  }
221
237
  return Promise.all(done).then(() => { detach(); return results; });
package/dist/mcp/index.js CHANGED
@@ -143,11 +143,11 @@ export function withMcp(local, hub) {
143
143
  // through the full composition; finding C: hub tools serialize PER SERVER (mcp:<server> key)
144
144
  // instead of a global barrier — same-server calls keep input order, independent servers overlap.
145
145
  sched: {
146
- classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
146
+ classify: (n, a) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n, a) : "write"),
147
147
  keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
148
148
  },
149
149
  executeParallel: (calls, onSettle, signal, onStart) => runBatch(calls, {
150
- classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
150
+ classify: (n, a) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n, a) : "write"),
151
151
  keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
152
152
  runOne: (c, report) => {
153
153
  const sc = c;
package/dist/session.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Headless session controller — owns the conversation + engine wiring for ONE interactive session,
2
2
  // with no UI dependency, so it is testable end-to-end without a TTY. cli.tsx is a thin Ink shell
3
3
  // that maps these callbacks onto React state; a test can drive the same `send()` directly.
4
+ import { DELEGATION } from "./tools/classes.js";
4
5
  import { runTurn, TurnAbortedError } from "./engine/agent.js";
5
6
  import { recordTruncation } from "./observability/blackbox.js";
6
7
  import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE, SESSION_CONTEXT_REQUEST_LINE } from "./engine/messages.js";
@@ -1489,11 +1490,13 @@ export class Session {
1489
1490
  rollBudget() {
1490
1491
  return rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS, this.compactionSpeedTargetTokens);
1491
1492
  }
1492
- /** Where compaction.summaryModel may take a background pass: its first leg on a private address that is proven to
1493
+ /** Where compaction.summaryModel may take a background pass: its first leg, on a server other than the
1494
+ * conversation's own, at a private address that is proven to
1493
1495
  * stay there — a llama-server answering `/props` itself, or a router route marked `fleet_only` — with room for a
1494
1496
  * pass. A provider-key row, the Anthropic wire, a retired row and a gateway host never qualify: the pass carries
1495
1497
  * conversation text. Asked before every pass (a router's table reloads live). Undefined = the live endpoint. */
1496
1498
  async summaryLeg(b) {
1499
+ const live = { base: this.lastBase ?? this.inner.base, model: this.lastModel ?? this.inner.model };
1497
1500
  const id = this.compactionSummaryModel;
1498
1501
  if (!id)
1499
1502
  return undefined;
@@ -1509,9 +1512,12 @@ export class Session {
1509
1512
  const s = await probeServed(leg.base, { timeoutMs: 1500, model: leg.model });
1510
1513
  if ((!s.direct && !s.fleetOnly) || (s.ctx ?? p.ctx ?? 0) < need)
1511
1514
  continue;
1515
+ // One llama-server answers every model name; a router tells its servers apart only by route.
1516
+ if (new URL(leg.base).origin === new URL(live.base).origin && (s.direct || leg.model === live.model))
1517
+ continue;
1512
1518
  return { leg, ...(s.direct && s.slots && s.slots > 1 ? { slots: s.slots } : {}) };
1513
1519
  }
1514
- return this.summaryRefused("no leg proven to stay on your own machines with room for a pass");
1520
+ return this.summaryRefused("no leg on another server, proven to stay on your own machines, with room for a pass");
1515
1521
  }
1516
1522
  summaryRefused(reason) {
1517
1523
  if (!this.summaryModelTold)
@@ -1532,7 +1538,9 @@ export class Session {
1532
1538
  return { ...own, slot };
1533
1539
  }
1534
1540
  /** One rolling pass, a lean request (no system prompt, no tools) so what it reads is its own prompt whatever the
1535
- * server has cached. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
1541
+ * server has cached. It shares no prefix with the conversation, so on a llama.cpp leg it would replace the cache the
1542
+ * next turn needs (a hybrid model cannot rewind, and a long session is too big to keep aside): a background pass
1543
+ * runs there only on a separate summary model, and otherwise waits for compaction. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
1536
1544
  * compaction, the owner waiting) takes the whole uncovered tail at once. Once the notes are over their cap the pass
1537
1545
  * folds their older half into one summary instead. False when nothing advanced: nothing left, an empty answer, or
1538
1546
  * the conversation was replaced meanwhile. */
@@ -1575,7 +1583,8 @@ export class Session {
1575
1583
  });
1576
1584
  let r;
1577
1585
  const side = live ? undefined : await this.summaryLeg(b);
1578
- if (signal?.aborted)
1586
+ const keepsOurCache = !live && shipsLlamaCacheKnobs(base, leg?.transport);
1587
+ if (signal?.aborted || (keepsOurCache && !side))
1579
1588
  return false;
1580
1589
  if (side) {
1581
1590
  try {
@@ -1589,6 +1598,8 @@ export class Session {
1589
1598
  }
1590
1599
  if (!r)
1591
1600
  this.summaryRefused("its request failed or came back empty");
1601
+ if (!r && keepsOurCache)
1602
+ return false;
1592
1603
  }
1593
1604
  const via = r ? this.compactionSummaryModel : undefined;
1594
1605
  r ??= await ask(leg, { base, model }, this.affinity({ base, model, transport: leg?.transport })); // the live turn's slot or session: the span is cached there
@@ -1603,7 +1614,7 @@ export class Session {
1603
1614
  return true;
1604
1615
  }
1605
1616
  /** After a settled turn: while half a chunk or more is uncovered (or the notes are over their cap), summarize it in
1606
- * the background, one bounded pass at a time. send() aborts the pass in flight, so the owner's next message never
1617
+ * the background, where a pass may run at all (rollingPass), one bounded pass at a time. send() aborts the pass in flight, so the owner's next message never
1607
1618
  * waits for it; what a pass had not finished is picked up after the next turn, or read live at compaction. Never
1608
1619
  * for a sub-agent: its session ends with its turn, and nothing would abort its pass when the owner's turn wants
1609
1620
  * the model. */
@@ -2104,6 +2115,7 @@ export class Session {
2104
2115
  const turn = { text, task, convoStart, t0: _t0 };
2105
2116
  this.inflight = turn;
2106
2117
  const turnModelId = routeLabel ?? this.modelId; // the MoA specialist's own id, else the /model pick
2118
+ const shape = { toolRounds: 0, multiCallRounds: 0, subAgentCalls: 0 }; // for the turn's telemetry record
2107
2119
  try {
2108
2120
  const res = await runTurn(text, this.convo, {
2109
2121
  ownerText,
@@ -2150,7 +2162,14 @@ export class Session {
2150
2162
  onToolResult: h.onToolResult,
2151
2163
  onToolCallStart: h.onToolCallStart,
2152
2164
  onToolDraft: h.onToolDraft,
2153
- onToolBatch: h.onToolBatch,
2165
+ onToolBatch: (events, durationMs) => {
2166
+ shape.toolRounds++;
2167
+ if (events.length > 1)
2168
+ shape.multiCallRounds++;
2169
+ shape.subAgentCalls += events.filter((e) => DELEGATION.has(e.name)).length;
2170
+ h.onToolBatch?.(events, durationMs);
2171
+ },
2172
+ batchHints: !this.background,
2154
2173
  onAutoContinue: h.onAutoContinue,
2155
2174
  onCacheStats: h.onCacheStats,
2156
2175
  onServed: h.onServed,
@@ -2205,7 +2224,7 @@ export class Session {
2205
2224
  // The conversation knows the mode only once the carried note is in it (a fast-start rewrite sends the raw text).
2206
2225
  if (mode.note && this.convo.all.slice(convoStart).some((m) => m.role === "user" && typeof m.content === "string" && m.content.includes(mode.note)))
2207
2226
  this.planReviewTold = mode.on;
2208
- this.telemetry.record({ type: "turn", rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
2227
+ this.telemetry.record({ type: "turn", ...shape, model: turnModelId, rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
2209
2228
  // MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): OPT-IN with KODE_MOA_SHADOW=1 (was on
2210
2229
  // by default until 0.1.334). Its classifier call goes to the SAME endpoint as the turn, and on a single-slot
2211
2230
  // llama-server (Cortana, --parallel 1) that 8-token call evicted the session's cached prompt after every turn:
@@ -2275,7 +2294,7 @@ export class Session {
2275
2294
  }
2276
2295
  catch (e) {
2277
2296
  if (e instanceof TurnAbortedError) {
2278
- this.telemetry.record({ type: "turn", rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
2297
+ this.telemetry.record({ type: "turn", ...shape, rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
2279
2298
  const r = this.interruptedRecord(turn); // an esc is how the owner usually ends a loop: the loop still teaches
2280
2299
  const cfg = this.selfImproveCfg();
2281
2300
  if (r)
@@ -29,6 +29,8 @@ export const WEB_SEARCH = set("web_search", "deep_research");
29
29
  export const WEB_FETCH = set("web_fetch", "browser", "browser_read", "http_request");
30
30
  /** Everything that only looks something up: the "reads" a sub-agent's activity counters add up. */
31
31
  export const LOOKUP = set(FILE_READ, "list_directory", LOCAL_SEARCH, WEB_SEARCH, WEB_FETCH);
32
+ /** Reads worth sending together: one of these alone, round after round, draws the batching note (engine/batch-hints.ts). */
33
+ export const BATCHABLE_READ = set(FILE_READ, "list_directory", LOCAL_SEARCH, WEB_SEARCH, "web_fetch", "git_status");
32
34
  /** Read-only tools: the same call returning the same result again is no new information. */
33
35
  export const IDEMPOTENT = set("file_read", "read_files", "search", "grep_search", "list_directory", "find_files", "locate", "web_search", "web_fetch", "git_status", "memory_search", "session_search", "session_read", "skill_catalog", "skill_fetch", "skill_list");
34
36
  // ── Plan, agents, polling ─────────────────────────────────────────────────────────────────────────────────
@@ -94,10 +94,13 @@ export function withDeferred(base, st) {
94
94
  // Promise.all barrier made base calls wait for every meta first. Now: search/describe classify
95
95
  // read, tool_call is an exclusive barrier (it can invoke ANYTHING downstream), pass-through
96
96
  // keeps the chain's truth. sched is exposed so any outer wrapper propagates it.
97
+ // No meta call: the chain below owns the whole round (its batch ids, its gates).
98
+ if (!calls.some((c) => DEFERRED_META_NAMES.includes(c.name)))
99
+ return base.executeParallel(calls, onSettle, signal, onStart);
97
100
  return runBatch(calls, {
98
- classify: (n) => (n === "tool_call" ? "barrier"
101
+ classify: (n, a) => (n === "tool_call" ? "barrier"
99
102
  : n === "tool_search" || n === "tool_describe" ? "read"
100
- : base.sched ? base.sched.classify(n) : "write"),
103
+ : base.sched ? base.sched.classify(n, a) : "write"),
101
104
  keys: (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a)),
102
105
  runOne: (c, report) => (DEFERRED_META_NAMES.includes(c.name)
103
106
  ? runMeta(c.name, c.args, report) : base.execute(c.name, c.args, report)),
@@ -108,9 +111,9 @@ export function withDeferred(base, st) {
108
111
  });
109
112
  },
110
113
  sched: {
111
- classify: (n) => (n === "tool_call" ? "barrier"
114
+ classify: (n, a) => (n === "tool_call" ? "barrier"
112
115
  : n === "tool_search" || n === "tool_describe" ? "read"
113
- : base.sched ? base.sched.classify(n) : "write"),
116
+ : base.sched ? base.sched.classify(n, a) : "write"),
114
117
  keys: (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a)),
115
118
  },
116
119
  };
@@ -281,15 +284,17 @@ export function withNativeDeferred(base, cat) {
281
284
  return base.execute(target, toolArgs, report);
282
285
  };
283
286
  const isMeta = (n) => NATIVE_META_NAMES.includes(n);
284
- const classify = (n) => (n === "tool_call" ? "barrier"
287
+ const classify = (n, a) => (n === "tool_call" ? "barrier"
285
288
  : n === "tool_search" ? "read"
286
- : base.sched ? base.sched.classify(n) : "write");
289
+ : base.sched ? base.sched.classify(n, a) : "write");
287
290
  const keys = (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a));
288
291
  return {
289
292
  async execute(name, args, report) {
290
293
  return isMeta(name) ? runMeta(name, args, report) : base.execute(name, args, report);
291
294
  },
292
295
  async executeParallel(calls, onSettle, signal, onStart) {
296
+ if (!calls.some((c) => isMeta(c.name)))
297
+ return base.executeParallel(calls, onSettle, signal, onStart);
293
298
  return runBatch(calls, {
294
299
  classify, keys,
295
300
  runOne: (c, report) => (isMeta(c.name) ? runMeta(c.name, c.args, report) : base.execute(c.name, c.args, report)),
@@ -0,0 +1,92 @@
1
+ // Is a shell command plainly read-only? Only scheduling asks (engine/batch-scheduler.ts): a yes lets the call overlap
2
+ // other reads. Permissions and approvals never read this. Any doubt is a no, which keeps the call serial.
3
+ // Refused anywhere, quoted or not: expansion, substitution, escapes, redirects, background/and/or, sequencing, newlines.
4
+ const NEVER = /[$`\\\n\r;&<>]/;
5
+ const UNQUOTED_NEVER = /[(){}#]/;
6
+ const GLOB = /[*?[]/;
7
+ // A file name that expands into a flag could change what these two do; the others have no flag that writes or runs.
8
+ const GLOB_OK = new Set(["ls", "cat", "head", "tail", "grep"]);
9
+ function pipeline(command) {
10
+ const stages = [[]];
11
+ let word;
12
+ const end = () => { if (word)
13
+ stages[stages.length - 1].push(word); word = undefined; };
14
+ for (let i = 0; i < command.length; i++) {
15
+ const ch = command[i];
16
+ if (ch === "'" || ch === '"') {
17
+ const close = command.indexOf(ch, i + 1);
18
+ if (close < 0)
19
+ return undefined;
20
+ word ??= { text: "", glob: false, quoted: false };
21
+ word.text += command.slice(i + 1, close);
22
+ word.quoted = true;
23
+ i = close;
24
+ }
25
+ else if (ch === " " || ch === "\t")
26
+ end();
27
+ else if (ch === "|") {
28
+ end();
29
+ stages.push([]);
30
+ }
31
+ else if (UNQUOTED_NEVER.test(ch))
32
+ return undefined;
33
+ else {
34
+ word ??= { text: "", glob: false, quoted: false };
35
+ word.text += ch;
36
+ if (GLOB.test(ch))
37
+ word.glob = true;
38
+ }
39
+ }
40
+ end();
41
+ return stages.every((s) => s.length > 0) ? stages : undefined;
42
+ }
43
+ const FIND_BARE = new Set(["-print", "-print0", "-prune", "-empty", "-not", "-o", "-a", "-and", "-or"]);
44
+ const FIND_VALUE = new Set(["-name", "-iname", "-path", "-ipath", "-regex", "-iregex", "-type", "-maxdepth", "-mindepth", "-mtime", "-mmin", "-newer", "-size"]);
45
+ function findReads(args) {
46
+ for (let i = 0; i < args.length; i++) {
47
+ const a = args[i];
48
+ if (!a.startsWith("-") || FIND_BARE.has(a))
49
+ continue;
50
+ if (!FIND_VALUE.has(a))
51
+ return false;
52
+ i++;
53
+ }
54
+ return true;
55
+ }
56
+ // git takes abbreviated long options, so a prefix of one of these counts as it.
57
+ const GIT_REFUSED = ["--output", "--ext-diff", "--textconv"];
58
+ function gitReads(args) {
59
+ let i = 0;
60
+ while (args[i] === "--no-pager" || args[i] === "-C")
61
+ i += args[i] === "-C" ? 2 : 1;
62
+ if (!["status", "log", "diff", "show"].includes(args[i] ?? ""))
63
+ return false;
64
+ return args.slice(i + 1).every((a) => {
65
+ const flag = a.split("=")[0];
66
+ return !flag.startsWith("--") || flag.length < 4 || !GIT_REFUSED.some((r) => r.startsWith(flag) || flag.startsWith(r));
67
+ });
68
+ }
69
+ function stageReads([head, ...rest]) {
70
+ if (!head || head.quoted || head.glob)
71
+ return false;
72
+ const cmd = head.text;
73
+ if (!GLOB_OK.has(cmd) && rest.some((w) => w.glob))
74
+ return false;
75
+ const args = rest.map((w) => w.text);
76
+ switch (cmd) {
77
+ case "ls":
78
+ case "cat":
79
+ case "head":
80
+ case "grep": return true;
81
+ case "tail": return !args.some((a) => /^-[^-]*[fF]|^--f|^--retry/.test(a)); // following never ends
82
+ case "rg": return !args.some((a) => /^--(pre|hostname-bin|search-zip)|^-[^-]*z/.test(a)); // these start programs
83
+ case "find": return findReads(args);
84
+ case "git": return gitReads(args);
85
+ default: return false;
86
+ }
87
+ }
88
+ export function isReadOnlyCommand(command) {
89
+ if (typeof command !== "string" || !command.trim() || NEVER.test(command))
90
+ return false;
91
+ return pipeline(command.trim())?.every(stageReads) === true;
92
+ }
@@ -2395,7 +2395,7 @@ const TOOLS = [
2395
2395
  {
2396
2396
  name: "bash", safe: false,
2397
2397
  contract: { v: 1, effects: ["exec"], bins: ["bash", "sandbox-exec", "bwrap", "ps", "lsof"] },
2398
- description: "Run a command in a PERSISTENT bash session: `cd`, exported variables, an activated venv and functions carry over — set up once, don't re-`cd` or re-activate every call. stdout+stderr merged, with the exit code; pipelines run with `set -o pipefail`. Anything that may run over ~2 minutes (server, build, watcher, full test suite) goes to shell_background, not a bigger timeout_ms; ctrl+b moves a running command to the background and you are told when it ends — don't poll. Prefer SINGLE quotes for patterns and paths: a raw double-quote can break tool-call serialization.",
2398
+ description: "Run a command in a PERSISTENT bash session: `cd`, variables, venvs and functions carry over. To search, read or list files use search / file_read / list_directory, not grep/cat/sed/ls. stdout+stderr merged, with the exit code; pipelines run with `set -o pipefail`. Anything that may run over ~2 minutes (server, build, watcher, full test suite) goes to shell_background, not a bigger timeout_ms. Prefer SINGLE quotes for patterns and paths: a raw double-quote can break tool-call serialization.",
2399
2399
  parameters: { type: "object", properties: {
2400
2400
  command: { type: "string", description: "the command to run" },
2401
2401
  description: { type: "string", description: "short label for the UI" },
@@ -2505,7 +2505,7 @@ const TOOLS = [
2505
2505
  {
2506
2506
  name: "file_read", safe: true,
2507
2507
  contract: { v: 3, effects: ["read"], bins: ["osascript", "textutil", "unzip"] },
2508
- description: "Read a file, optionally a line range, with line numbers. Without offset/limit, only the first 2000 lines are returned — pass offset/limit to page through a larger file. For very long lines (minified code, one-line JSON or logs) page by character instead: start_char (and max_chars, up to 38000) returns the exact raw text with no line numbers.",
2508
+ description: "Read a file (not cat/sed), optionally a line range, with line numbers. Without offset/limit, only the first 2000 lines are returned — pass offset/limit to page through a larger file. For very long lines (minified code, one-line JSON or logs) page by character instead: start_char (and max_chars, up to 38000) returns the exact raw text with no line numbers.",
2509
2509
  parameters: { type: "object", properties: {
2510
2510
  path: { type: "string" }, offset: { type: "number" }, limit: { type: "number" }, force: { type: "boolean" },
2511
2511
  start_char: { type: "number", description: "raw mode: character offset to start at (0-based); the reply names the next start_char" },
@@ -2578,7 +2578,7 @@ const TOOLS = [
2578
2578
  {
2579
2579
  name: "search", safe: true,
2580
2580
  contract: { v: 1, effects: ["read"], bins: ["rg", "grep"] },
2581
- description: "Fast content search (ripgrep: parallel, .gitignore-aware, skips binaries) — prefer it over `find … | grep`. Scope with `path` (default: current dir). HARD REFUSAL: path may not be $HOME, /, /Users or another machine-wide root (they hang for minutes) — use find_files (on demand) for names, a narrow subtree for content. `glob` filters filenames; files_with_matches returns just the paths (locate before you read).",
2581
+ description: "Fast content search (ripgrep: parallel, .gitignore-aware, skips binaries) — use it, not shell grep/rg. Scope with `path` (default: current dir). HARD REFUSAL: path may not be $HOME, /, /Users or another machine-wide root (they hang for minutes) — use find_files (on demand) for names, a narrow subtree for content. `glob` filters filenames; files_with_matches returns just the paths (locate before you read).",
2582
2582
  parameters: { type: "object", properties: {
2583
2583
  pattern: { type: "string", description: "regex" },
2584
2584
  path: { type: "string", description: "directory scope (default current dir; not $HOME or /)" },
@@ -443,6 +443,54 @@ const MISSING_MANIFEST = [
443
443
  export function missingManifest(lowerOutput) {
444
444
  return MISSING_MANIFEST.find(([re]) => re.test(lowerOutput))?.[1];
445
445
  }
446
+ /** The words of a command that is one plain call, optionally piped into `head`. null for anything else: chains,
447
+ * redirects, expansions and unquoted globs mean the shell is doing real work. */
448
+ function plainWords(command) {
449
+ const body = command.trim().replace(/^cd\s+[^;&|<>$`\n]+?\s*(?:&&|;|\n)\s*/, "").replace(/\s2>(?:\/dev\/null|&1)(?=\s|$)/g, "")
450
+ .replace(/\s*\|\s*head(?:\s+-(?:n\s*)?\d+)?\s*$/, "");
451
+ if (body.includes("\n"))
452
+ return null;
453
+ const words = [];
454
+ const token = /\s*(?:((?:'[^']*'|"(?:\\.|[^"\\$`])*"|[^\s'"\x5c;&|<>$`(){}*?[\]])+)|$)/y;
455
+ while (token.lastIndex < body.length) {
456
+ const m = token.exec(body);
457
+ if (!m)
458
+ return null;
459
+ if (m[1])
460
+ words.push(m[1]);
461
+ }
462
+ return words;
463
+ }
464
+ /** One line naming the native tool when it does the same job as this command; undefined when in doubt (a hint the
465
+ * tool cannot honour teaches the model to ignore them all). */
466
+ export function nativeToolHint(command) {
467
+ const [bin, ...rest] = plainWords(command) ?? [];
468
+ const flags = rest.filter((w) => w.startsWith("-"));
469
+ const args = rest.filter((w) => !w.startsWith("-"));
470
+ const hint = (tool, how) => `[native tool: ${tool} ${how}; pass the full path]`;
471
+ const read = () => hint("file_read", "reads this (offset/limit for a range), instead of cat/sed/head");
472
+ if (bin === "grep" || bin === "rg") {
473
+ const known = flags.every((f) => (bin === "grep" ? /^-[nrREHIsl]+$/ : /^-[nHl]+$/).test(f));
474
+ const recursive = bin === "rg" || flags.some((f) => /[rR]/.test(f));
475
+ if (known && (args.length === 2 || (args.length === 1 && recursive)))
476
+ return hint("search", "does this search (files_with_matches for -l), instead of shell grep/rg");
477
+ }
478
+ else if (bin === "cat" && !flags.length && args.length) {
479
+ return args.length === 1 ? read() : hint("read_files", "reads these in one call, instead of cat");
480
+ }
481
+ else if (bin === "head") {
482
+ if (/^(?:-\d+ |-n ?\d+ )?[^- ]\S*$/.test(rest.join(" ")))
483
+ return read();
484
+ }
485
+ else if (bin === "sed") {
486
+ if (rest.length === 3 && rest[0] === "-n" && /^(['"]?)\d+(?:,\d+)?p\1$/.test(rest[1]))
487
+ return read();
488
+ }
489
+ else if (bin === "ls" && flags.every((f) => /^-[a1]+$/.test(f)) && args.length <= 1) {
490
+ return hint("list_directory", "lists this, instead of ls");
491
+ }
492
+ return undefined;
493
+ }
446
494
  export function shellResultNotes(command, exitCode, output) {
447
495
  const notes = [];
448
496
  let code = exitCode;
@@ -455,7 +503,7 @@ export function shellResultNotes(command, exitCode, output) {
455
503
  if (code) {
456
504
  const out = output.toLowerCase();
457
505
  if (/invalid option|illegal option|unrecognized option|invalid command code|usage: sed|usage: grep|gnu_/.test(out)) {
458
- notes.push("[hint: macOS ships BSD sed/grep/awk — GNU-isms fail here: `sed -n 'X,+Np'` (use a computed 'X,Yp' range or `awk 'NR>=X&&NR<X+N'`), `grep -P` (use grep -E), `date -d` (use date -j -f). Rewrite and retry.]");
506
+ notes.push("[hint: macOS ships BSD sed/grep/awk — GNU-isms fail here: `sed -n 'X,+Np'` (use a computed 'X,Yp' range or `awk 'NR>=X&&NR<X+N'`), `grep -P` (use grep -E, or `rg -P` if rg is installed), `cat -A` (use cat -vet), `date -d` (use date -j -f). Rewrite and retry.]");
459
507
  }
460
508
  if (out.includes("command not found") && /\btimeout\b|\bsed -i\b|\brealpath\b|\breadlink -f\b/.test(command)) {
461
509
  notes.push("[hint: not installed on macOS by default — use `gtimeout` (brew coreutils), `sed -i ''`, or a python one-liner.]");
@@ -471,5 +519,12 @@ export function shellResultNotes(command, exitCode, output) {
471
519
  notes.push("[hint: git can't resolve that ref HERE — either the name shadows a path (disambiguate: `git <cmd> <rev> -- <path>`), or the branch doesn't exist in THIS checkout (worktrees/other clones hold their own local branches). Check first with `git rev-parse --verify <ref>` or `git branch -a`; don't retry variants blind.]");
472
520
  }
473
521
  }
522
+ if (/zsh:(?:\d+:)? no matches found/.test(output)) {
523
+ notes.push("[hint: zsh (a Mac's login shell, e.g. over ssh) fails a command on an unmatched glob: quote the glob, or use `find`.]");
524
+ }
525
+ // Success with output only: a failed run's exit trailer has to stay last (engine/loop-guard.ts).
526
+ const native = code === 0 && output ? nativeToolHint(command) : undefined;
527
+ if (native)
528
+ notes.push(native);
474
529
  return { exitForTrailer: code, notes };
475
530
  }
@@ -7,7 +7,7 @@ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
7
7
  // • OrbitSpinner — a background sub-agent is working (rotating arc, violet)
8
8
  import { useEffect, useRef } from "react";
9
9
  import { Text } from "ink";
10
- import { theme } from "./theme.js";
10
+ import { theme, secondary } from "./theme.js";
11
11
  import { useTick } from "./tick.js";
12
12
  import { renderSweepBar } from "./progressbar.js";
13
13
  import { fmtElapsed } from "./format.js";
@@ -60,5 +60,5 @@ export function RecoverSpinner({ active, label, cols = termCols() }) {
60
60
  const room = cols - 1 - cellWidth(glyph) - 1 - 2 - cellWidth(time);
61
61
  const text = `${label ?? "adjusting"}…`;
62
62
  const withBar = cellWidth(text) + 2 + cellWidth(bar) <= room;
63
- return (_jsxs(Text, { color: theme.compactProgress, children: [glyph, " ", withBar ? text : truncateToWidth(text, Math.max(1, room)), withBar ? _jsxs(Text, { color: theme.compactProgress, children: [" ", bar] }) : null, " ", _jsx(Text, { dimColor: true, children: time })] }));
63
+ return (_jsxs(Text, { color: theme.compactProgress, children: [glyph, " ", withBar ? text : truncateToWidth(text, Math.max(1, room)), withBar ? _jsxs(Text, { color: theme.compactProgress, children: [" ", bar] }) : null, " ", _jsx(Text, { ...secondary, children: time })] }));
64
64
  }