@0perator/operator 0.1.359 → 0.1.360-next.1

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.
Files changed (66) hide show
  1. package/dashboard/index.html +2 -2
  2. package/dist/autonomy/cloud-agent.js +2 -2
  3. package/dist/autonomy/headless.js +15 -6
  4. package/dist/autonomy/session-factory.js +2 -1
  5. package/dist/background/notices.js +1 -1
  6. package/dist/browser/session.js +7 -0
  7. package/dist/cli.js +94 -52
  8. package/dist/config/features.js +6 -5
  9. package/dist/config/persona.js +57 -40
  10. package/dist/config/settings.js +39 -55
  11. package/dist/config/toolchain.js +14 -1
  12. package/dist/engine/agent.js +72 -33
  13. package/dist/engine/aurora.js +24 -2
  14. package/dist/engine/compaction.js +27 -7
  15. package/dist/engine/decision-points.js +16 -4
  16. package/dist/engine/kv-slot.js +87 -0
  17. package/dist/engine/loop-guard.js +49 -18
  18. package/dist/engine/messages.js +8 -1
  19. package/dist/engine/progress-deadline.js +37 -0
  20. package/dist/engine/verify-gate.js +134 -9
  21. package/dist/enterprise/cli.js +13 -1
  22. package/dist/mcp/craft-server.js +5 -3
  23. package/dist/memory/live-progress.js +35 -6
  24. package/dist/permissions/policy.js +8 -0
  25. package/dist/permissions/signature.js +9 -0
  26. package/dist/products/artifact-library.js +47 -0
  27. package/dist/products/craft.js +58 -94
  28. package/dist/products/temple.js +230 -0
  29. package/dist/remote/host.js +28 -1
  30. package/dist/router/discovery.js +23 -6
  31. package/dist/router/models.js +29 -70
  32. package/dist/services/preflight.js +3 -41
  33. package/dist/session.js +121 -38
  34. package/dist/skills/catalogue.js +2 -0
  35. package/dist/skills/finder.js +1 -1
  36. package/dist/toolchain/toolchain.py +20 -3
  37. package/dist/tools/background-result.js +26 -0
  38. package/dist/tools/chauffeur-native.js +6 -0
  39. package/dist/tools/craft.js +17 -6
  40. package/dist/tools/deferred.js +64 -30
  41. package/dist/tools/executor.js +4 -2
  42. package/dist/tools/paths.js +3 -3
  43. package/dist/tools/read-ledger.js +44 -0
  44. package/dist/tools/registry.js +218 -264
  45. package/dist/tools/sandbox.js +52 -39
  46. package/dist/tools/shell-context.js +5 -0
  47. package/dist/tools/shell-session.js +61 -29
  48. package/dist/tools/vision-gateway.js +79 -34
  49. package/dist/tools/wave-tools.js +2 -2
  50. package/dist/tools/wave2-tools.js +6 -6
  51. package/dist/ui/ArtifactPicker.js +2 -2
  52. package/dist/ui/Composer.js +9 -2
  53. package/dist/ui/StatusRule.js +1 -1
  54. package/dist/ui/modelPicker.js +1 -1
  55. package/dist/ui/nextStep.js +1 -0
  56. package/dist/ui/pending.js +10 -0
  57. package/dist/update.js +87 -9
  58. package/dist/util/retry.js +34 -0
  59. package/dist/util/slash.js +2 -1
  60. package/dist/vault/tool.js +3 -1
  61. package/mcp/powertools-toolbox.mjs +166 -1
  62. package/package.json +9 -13
  63. package/dashboard/README.md +0 -62
  64. package/dist/compose/client.js +0 -56
  65. package/mcp/README.md +0 -88
  66. package/mcp/powertools.md +0 -210
@@ -27,7 +27,7 @@ One stdlib file for /usr/bin/python3 -I (3.9.6 on both boxes): -I drops the scri
27
27
  """
28
28
  from __future__ import annotations
29
29
 
30
- import argparse, contextlib, datetime as dt, fcntl, hashlib, http.client, json, os, pathlib, platform, plistlib, pwd, re, shutil, signal, socket, stat, struct, subprocess, sys, tarfile, tempfile, time, urllib.error, urllib.parse, urllib.request, zipfile
30
+ import argparse, contextlib, datetime as dt, errno, fcntl, hashlib, http.client, json, os, pathlib, platform, plistlib, pwd, re, shutil, signal, socket, stat, struct, subprocess, sys, tarfile, tempfile, time, urllib.error, urllib.parse, urllib.request, zipfile
31
31
 
32
32
  HERE = pathlib.Path(__file__).resolve().parent
33
33
  SCHEMA = "operator.toolchain/1"
@@ -1727,14 +1727,31 @@ def cmd_rollback(args) -> int:
1727
1727
  return EX_OK
1728
1728
 
1729
1729
 
1730
+ def link_target(p):
1731
+ """realpath of the consumer link, which another process flips (rename(2) over it). On macOS 26 a readlink racing
1732
+ that rename can fail with EINVAL for an instant, and realpath then returns the link itself; that case is retried,
1733
+ every other failure fails closed (None)."""
1734
+ for _ in range(5):
1735
+ try:
1736
+ os.stat(p)
1737
+ except OSError as e:
1738
+ if e.errno != errno.EINVAL:
1739
+ return None
1740
+ continue
1741
+ real = os.path.realpath(p)
1742
+ if not os.path.islink(real):
1743
+ return real
1744
+ return None
1745
+
1746
+
1730
1747
  def resolve_bin(root: pathlib.Path, consumer: str, binary: str) -> tuple:
1731
1748
  for n in (consumer, binary):
1732
1749
  if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", n):
1733
1750
  raise Refused(f"invalid name {n!r}")
1734
1751
  link, cdir = root / "consumers" / consumer / "bin" / binary, root / "consumers" / consumer
1735
- if not os.path.exists(cdir):
1752
+ gen = link_target(cdir)
1753
+ if gen is None:
1736
1754
  raise Refused(f"consumer {consumer} is not activated in {root} ({cdir} is missing or dangling)")
1737
- gen = os.path.realpath(cdir)
1738
1755
  if not re.fullmatch(r"\d+", os.path.basename(gen)) or os.path.dirname(gen) != os.path.realpath(root / "generations"):
1739
1756
  raise Refused(f"{cdir} points at {gen}, not a generation")
1740
1757
  # through the generation just resolved, as the gateway and engine do: back through the consumer link, a flip in between would pair generation N with another build
@@ -0,0 +1,26 @@
1
+ // How a shell result says its command went to a background job, and how bash_output says that job ended. One definition
2
+ // for the tool layer that writes the text (registry.ts) and the engine that reads it (verify-gate.ts): on 11/24 the gate
3
+ // knew only the first prefix, so an auto-backgrounded `npm test` counted as a passed check. Dependency-free leaf, like mutating.ts.
4
+ export const MOVED_TO_BACKGROUND = "moved to background as ";
5
+ export const AUTO_BACKGROUNDED = "[auto-backgrounded: ";
6
+ export const STARTED_BACKGROUND_JOB = "started background job ";
7
+ /** True when the command is still running as a background job: it has produced no result yet. */
8
+ export const stillInBackground = (result) => {
9
+ const r = result.trimStart();
10
+ return r.startsWith(MOVED_TO_BACKGROUND) || r.startsWith(AUTO_BACKGROUNDED);
11
+ };
12
+ /** The id of the job a backgrounded command's result names. */
13
+ export const backgroundJobId = (result) => {
14
+ const r = result.trimStart();
15
+ const rest = r.startsWith(MOVED_TO_BACKGROUND) ? r.slice(MOVED_TO_BACKGROUND.length)
16
+ : r.startsWith(STARTED_BACKGROUND_JOB) ? r.slice(STARTED_BACKGROUND_JOB.length)
17
+ : r.startsWith(AUTO_BACKGROUNDED) ? r.slice(r.indexOf("\n" + STARTED_BACKGROUND_JOB) + 1 + STARTED_BACKGROUND_JOB.length) : "";
18
+ return rest.match(/^sh\d+/)?.[0];
19
+ };
20
+ /** bash_output's first line for a job that has ended. `code` is null when it was killed or its shell died. */
21
+ export const jobFinishedLine = (id, code) => `[job ${id} finished — exit ${code}]`;
22
+ /** The job and exit code a bash_output result reports, once the job has ended (-1: it ended without an exit code). */
23
+ export const finishedJob = (result) => {
24
+ const m = result.match(/^\[job (sh\d+) finished — exit (-?\d+|null)\]/);
25
+ return m ? { id: m[1], exit: m[2] === "null" ? -1 : Number(m[2]) } : undefined;
26
+ };
@@ -47,6 +47,8 @@ export async function desktopClick(args) {
47
47
  clickArgs.element = element;
48
48
  if (args.button)
49
49
  clickArgs.button = args.button;
50
+ if (clickArgs.x == null && !clickArgs.element)
51
+ return "error: desktop_click needs `x` and `y` (e.g. x: 640, y: 360) or `element` (a name from desktop_read)";
50
52
  const result = await callChauffeur("click", clickArgs);
51
53
  if (args.verify !== false) {
52
54
  const verify = await callChauffeur("verify_state", { expect: typeof description === "string" ? description : "click landed" });
@@ -71,6 +73,10 @@ export async function appInteract(args) {
71
73
  return "error: app name required";
72
74
  if (typeof action !== "string")
73
75
  return "error: action required (launch, find, click, type, read)";
76
+ if (action === "click" && !args.element)
77
+ return "error: app_interact click needs `element` — e.g. element: \"Send\"";
78
+ if (action === "type" && !args.text)
79
+ return "error: app_interact type needs `text` — the characters to type";
74
80
  const parts = [];
75
81
  if (action === "launch" || action === "find" || action === "click" || action === "type") {
76
82
  const launch = await callChauffeur("launch_app", { name: app });
@@ -5,22 +5,25 @@ async function craft() {
5
5
  export const CRAFT_TOOLS = [
6
6
  {
7
7
  name: "craft_create",
8
- description: "Make a first-class CRAFT — a hosted, shareable, ACCOUNT-OWNED page / deck / doc / board / dashboard / app — and get a stable id + a public URL. Unlike artifact_create (ephemeral), a craft is owned by your account, versioned, and can be updated / listed / fetched later by id. Use for work you'll keep, revise, or share for review.",
9
- parameters: { type: "object", additionalProperties: false, required: ["content"], properties: {
10
- content: { type: "string", description: "the page/deck/doc body — HTML, SVG, or markdown" },
8
+ description: "Make a first-class CRAFT — a hosted, shareable, ACCOUNT-OWNED page / deck / doc / board / dashboard / app / image / video — and get a stable id + its 0perator.co share link. Versioned; update / list / fetch / delete it later by id. Use for work you'll keep, revise, or share for review.",
9
+ parameters: { type: "object", additionalProperties: false, properties: {
10
+ content: { type: "string", description: "the body — HTML, markdown, SVG, or text" },
11
11
  title: { type: "string", description: "short title" },
12
- type: { type: "string", description: "page (default) | deck | doc | board | dashboard | app | svg | markdown | canvas" },
12
+ type: { type: "string", description: "page (default) | deck | doc | board | dashboard | app | image | video" },
13
+ content_type: { type: "string", description: "html | markdown | svg | text | canvas (inferred when omitted)" },
14
+ paths: { type: "array", items: { type: "string" }, description: "local files to include (images, video, assets the HTML references)" },
15
+ visibility: { type: "string", description: "link (default) | private | public" },
13
16
  } },
14
17
  async run(args) { return (await craft()).craftCreate(args); },
15
18
  },
16
19
  {
17
20
  name: "craft_update",
18
- description: "Update a craft you own by id — new content, title, or visibility (private | link | people | workspace | public). Optimistic concurrency: pass expected_version (from craft_get) to avoid clobbering a change made since you read it.",
21
+ description: "Update a craft you own by id — new content, title, or visibility (private | link | public). Optimistic concurrency: pass expected_version (from craft_get) to avoid clobbering a change made since you read it.",
19
22
  parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
20
23
  id: { type: "string", description: "the craft id (from craft_create / craft_list)" },
21
24
  content: { type: "string", description: "replacement body" },
22
25
  title: { type: "string", description: "new title" },
23
- visibility: { type: "string", description: "private | link | people | workspace | public" },
26
+ visibility: { type: "string", description: "private | link | public" },
24
27
  expected_version: { type: "string", description: "the version you last read (optimistic concurrency)" },
25
28
  } },
26
29
  async run(args) { return (await craft()).craftUpdate(args); },
@@ -41,4 +44,12 @@ export const CRAFT_TOOLS = [
41
44
  } },
42
45
  async run(args) { return (await craft()).craftGet(args); },
43
46
  },
47
+ {
48
+ name: "craft_delete",
49
+ description: "Delete a craft you own by id. Its share link stops working.",
50
+ parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
51
+ id: { type: "string", description: "the craft id" },
52
+ } },
53
+ async run(args) { return (await craft()).craftDelete(args); },
54
+ },
44
55
  ];
@@ -122,23 +122,26 @@ export function deferredEnabled(mcpToolCount, env) {
122
122
  return mcpToolCount > 0;
123
123
  return mcpToolCount >= DEFERRED_THRESHOLD;
124
124
  }
125
- // ── Native deferral (feature flag `deferredTools`, default OFF) ───────────────────────────────────────────────────
125
+ // ── Native deferral (feature flag `deferredTools`, default ON since 2026-11-24) ───────────────────────────────────
126
126
  // The main session's own long tail behind two FIXED meta-tools. Unlike the MCP layer above, nothing ever joins the
127
127
  // request: the tools array is [core schemas + tool_search + tool_call] for the whole session, byte-identical every
128
128
  // turn, so the cached prefix survives (design 2026-10-30-subagent-experts-and-capability-catalog.md, cache rule).
129
- // Schemas reach the model only as tool RESULTS (tool_search's signatures, tool_call's validation errors). Dispatch
129
+ // Schemas reach the model only as tool RESULTS (tool_search's top hit, tool_call's validation errors). Dispatch
130
130
  // goes through the wrapped executor, so permissions, plan mode and hooks apply to the real tool name.
131
- /** Always advertised in full under native deferral: the shell/file/search/plan/web/delegation loop plus the media
132
- * and doc tools the persona names. Everything else in the session's registry (and every MCP tool) is deferred. */
131
+ /** Attached to every request. Chosen from the audit trail (45,208 tool calls, 493 sessions, 09/25–11/24): the 14 most
132
+ * called tools once `shell_exec` and `grep_search` are counted as what they are (aliases of `bash` and `search`),
133
+ * plus `task_add`, without which `task_update` has nothing to update. 86.5% of all calls land on these directly,
134
+ * 93.8% with the two aliases. Ranking: _ai-docs/decisions/2026-11-24-small-core-tool-loading.md. */
133
135
  export const NATIVE_CORE_TOOLS = [
134
- "bash", "shell_exec", "shell_background", "bash_output", "bash_kill", "download_file",
135
- "file_read", "read_files", "file_write", "file_edit", "file_create", "list_directory", "glob", "search", "find_files",
136
- "git_status", "git_command", "task_add", "task_list", "task_update", "task_clear", "scratchpad", "session_handoff",
137
- "web_search", "web_fetch", "http_request", "deep_research", "browser", "browser_read",
138
- "image_generate", "image_analyze", "video_generate", "video_analyze", "artifact_create", "document_generate",
139
- "memory_search", "memory_store", "skill_list", "skill_fetch", "delegate_task",
140
- "spawn_agent", "message_agent", "agent_status", "stop_agent", "ask_user", "self_status",
136
+ "bash", "file_read", "read_files", "file_write", "file_edit", "search", "list_directory",
137
+ "git_status", "git_command", "task_add", "task_update", "web_search", "web_fetch", "image_analyze", "image_generate",
141
138
  ];
139
+ /** Attached whenever the session has them, whatever their call count — the harness leans on them by name: the engine
140
+ * turns the decision-point gate and the delegation-by-prose guard on by finding `ask_user` / `spawn_agent` in the
141
+ * request (engine/agent.ts), and the MoA planner brief hands every step to `delegate_task` (engine/moa.ts). The bash
142
+ * timeout and auto-background results send the model to `shell_background` / `bash_output`, and the verify gate
143
+ * counts a finished background check by seeing a call named `bash_output` (engine/verify-gate.ts). */
144
+ export const NATIVE_HARNESS_TOOLS = ["ask_user", "spawn_agent", "delegate_task", "shell_background", "bash_output"];
142
145
  export const NATIVE_META_NAMES = ["tool_search", "tool_call"];
143
146
  const byName = (schemas) => {
144
147
  const m = new Map();
@@ -151,11 +154,11 @@ const byName = (schemas) => {
151
154
  };
152
155
  export function nativeMetaSchemas() {
153
156
  return [
154
- metaSchema("tool_search", "Find a deferred tool (the capability map lists their names): returns up to 8 matches as name(arguments) — description, '*' = required. Then run one with tool_call.", { query: { type: "string", description: "words matched against tool names and descriptions; empty lists them all" } }, []),
155
- metaSchema("tool_call", "Run a deferred tool by exact name. `args` is checked against its schema first (a mismatch returns the schema); permissions apply exactly as for a direct call.", { name: { type: "string", description: "exact tool name" }, args: { type: "object", description: "the tool's arguments" } }, ["name"]),
157
+ metaSchema("tool_search", "Find a tool that is not attached: describe what you need in plain words. Returns the best match with its full argument schema, then up to 4 more as name(arguments) — description, '*' = required. Run one with tool_call.", { query: { type: "string", description: "what the tool should do, e.g. \"take a screenshot\"; empty lists every name" } }, []),
158
+ metaSchema("tool_call", "Run a tool that is not attached, by exact name. `args` is checked against its schema first (a mismatch returns the schema); permissions apply exactly as for a direct call.", { name: { type: "string", description: "exact tool name" }, args: { type: "object", description: "the tool's arguments" } }, ["name"]),
156
159
  ];
157
160
  }
158
- export function nativeCatalog(localSchemas, core = NATIVE_CORE_TOOLS) {
161
+ export function nativeCatalog(localSchemas, core = [...NATIVE_CORE_TOOLS, ...NATIVE_HARNESS_TOOLS]) {
159
162
  const coreSet = new Set(core);
160
163
  const all = byName(localSchemas);
161
164
  const request = [...all.values()].filter((s) => coreSet.has(s.function.name));
@@ -182,24 +185,55 @@ function signature(s) {
182
185
  const args = Object.entries(p.properties ?? {}).map(([k, v]) => `${k}${req.has(k) ? "*" : ""}: ${Array.isArray(v?.enum) ? v.enum.map((e) => JSON.stringify(e)).join("|") : v?.type ?? "any"}`);
183
186
  return `${s.function?.name}(${args.join(", ")})`;
184
187
  }
188
+ // tool_search ranking: deterministic, no model. A query word scores on a tool's NAME parts first, then on the opening
189
+ // words of its description, then on the rest — weighted by how rare the word is across the catalogue, so "notification"
190
+ // outweighs "send". A few synonyms bridge how people ask ("picture", "say", "db") to how the tools are written; one
191
+ // with an underscore names a tool outright.
192
+ const STOP = new Set("a an the of to for in on at and or with my me this that it is are be from into some do i want need please can you how what which use using tool tools".split(" "));
193
+ const stem = (w) => (w.length <= 3 ? w : /(?:[sxz]|ch|sh)es$/.test(w) ? w.slice(0, -2) : /[^su]s$/.test(w) ? w.slice(0, -1) : w.replace(/(?:ing|ed)$/, ""));
194
+ const words = (text) => text.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).map(stem);
195
+ const SYNONYMS = new Map(Object.entries({
196
+ picture: "image", photo: "image", screen: "screenshot desktop", capture: "screenshot", say: "speak", aloud: "speak", tts: "speak",
197
+ audio: "voice transcribe", recording: "transcribe", db: "sql", database: "sql", query: "sql", mail: "email",
198
+ schedule: "cronjob routine", nightly: "cronjob", remove: "delete", uninstall: "remove", npm: "pkg", package: "pkg", dependency: "pkg",
199
+ pr: "git_pr", pull: "git_pr", api: "http_request", rest: "http_request", lint: "lsp", compiler: "lsp", typescript: "lsp",
200
+ secret: "security", leaked: "security", notification: "notify_local", notify: "notify_local", remember: "memory_store",
201
+ recall: "memory_search", pdf: "document", share: "artifact", shareable: "artifact", page: "artifact browser", website: "browser",
202
+ login: "browser", log: "log_tail", click: "desktop browser", window: "desktop", server: "background", daemon: "background",
203
+ subagent: "agent", conversation: "session", chat: "session", movie: "video", clip: "video", healthy: "health", uptime: "health",
204
+ kanban: "board", outage: "incident", playbook: "skill", cron: "cronjob", commit: "checkpoint", test: "validate verify",
205
+ }).map(([k, v]) => [stem(k), v.split(" ").map((x) => (x.includes("_") ? x : stem(x)))]));
185
206
  function nativeSearch(cat, query) {
186
- const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
187
- const scored = [];
188
- for (const s of [...cat.native.values(), ...cat.mcp.values()]) {
189
- const name = (s.function?.name ?? "").toLowerCase();
190
- const text = `${name} ${(s.function?.description ?? "").toLowerCase()}`;
191
- const score = terms.reduce((n, t) => n + (name.includes(t) ? 3 : text.includes(t) ? 1 : 0), 0);
192
- if (!terms.length || score > 0)
193
- scored.push([score, s]);
194
- }
195
- if (!scored.length)
196
- return "tool_search: no deferred tool matches — try other words, or use a tool you already have";
197
- scored.sort((a, b) => b[0] - a[0]);
198
- const lines = scored.slice(0, terms.length ? 8 : 200).map(([, s]) => {
207
+ const all = [...cat.native.values(), ...cat.mcp.values()];
208
+ const terms = words(query).filter((w) => !STOP.has(w));
209
+ if (!terms.length)
210
+ return all.map((s) => s.function?.name).join(" ");
211
+ const index = (s) => {
212
+ const desc = words(s.function?.description ?? "");
213
+ return { s, id: s.function?.name ?? "", name: new Set(words(s.function?.name ?? "")), head: new Set(desc.slice(0, 12)), body: new Set(desc) };
214
+ };
215
+ const catalogue = all.map(index);
216
+ const rare = (t) => 1 + Math.log(catalogue.length / (1 + catalogue.filter((e) => e.name.has(t) || e.body.has(t)).length));
217
+ const one = (e, t) => (e.id === t ? 6 : e.name.has(t) ? 4 : e.head.has(t) ? 2 : e.body.has(t) ? 1 : 0);
218
+ // The word itself counts in full, a synonym for a little less — "screenshot" beats a tool that only says "desktop".
219
+ const weighted = terms.map((t) => ({ t, w: Math.max(rare(t), 1), syn: SYNONYMS.get(t) ?? [] }));
220
+ // A query that spells out a tool's whole name ("browser read") is asking for that tool, not a neighbour ("browser").
221
+ const named = (e) => ([...e.name].every((n) => terms.includes(n)) ? e.name.size * 2 : 0);
222
+ const score = (e) => weighted.reduce((n, { t, w, syn }) => n + Math.max(one(e, t) * w, ...syn.map((x) => one(e, x) * 0.75 * w)), named(e));
223
+ const rank = (list) => list.map((e, i) => [score(e), i, e.s]).filter(([n]) => n > 0).sort((a, b) => b[0] - a[0] || a[1] - b[1]);
224
+ const hits = rank(catalogue);
225
+ // A request the attached tools already answer: say so instead of sending the model to a lesser match.
226
+ const have = rank(cat.request.filter((s) => cat.core.has(s.function?.name ?? "")).map(index))[0];
227
+ const direct = have && (!hits.length || have[0] > hits[0][0]) ? `Already attached — call it directly: ${have[2].function?.name}\n` : "";
228
+ if (!hits.length)
229
+ return direct || "tool_search: no tool matches — try other words, or use a tool you already have";
230
+ const line = (s) => {
199
231
  const d = (s.function?.description ?? "").replace(/\s+/g, " ");
200
- return `${signature(s)} — ${d.length > 220 ? d.slice(0, 220) + "…" : d}`;
201
- });
202
- return lines.join("\n");
232
+ return `${signature(s)} — ${d.length > 160 ? d.slice(0, 160) + "…" : d}`;
233
+ };
234
+ const [[, , top], ...rest] = hits;
235
+ return `${direct}Best match — run it with tool_call {"name": "${top.function?.name}", "args": {…}}:\n${JSON.stringify(top.function)}` +
236
+ (rest.length ? `\nAlso:\n${rest.slice(0, 4).map(([, , s]) => line(s)).join("\n")}` : "");
203
237
  }
204
238
  const typeOk = (t, v) => !t ? true : t === "array" ? Array.isArray(v) : t === "object" ? !!v && typeof v === "object" && !Array.isArray(v)
205
239
  : t === "integer" ? Number.isInteger(v) : typeof v === t;
@@ -12,7 +12,7 @@ import { IDEMPOTENT_TOOLS } from "../engine/loop-guard.js";
12
12
  import { isAbsolute, join, resolve } from "node:path";
13
13
  import { registry } from "./registry.js";
14
14
  import { expandPath } from "./paths.js";
15
- import { shellKeyStore, shellExecMode } from "./shell-context.js";
15
+ import { shellKeyStore, shellExecMode, shellSignalStore } from "./shell-context.js";
16
16
  // Re-exported for back-compat (existing importers reach it via executor.js) — moved to its own
17
17
  // file since it's a pure helper with no node deps; see result-cap.ts for why that separation matters.
18
18
  import { capToolResult } from "./result-cap.js";
@@ -97,7 +97,9 @@ export class Executor {
97
97
  try {
98
98
  // Run the tool inside THIS session's shell-key context so a persistent-shell tool (bash) picks
99
99
  // this session's own ShellSession, not a process-wide singleton shared with other sub-agents.
100
- const raw = await shellKeyStore.run(this.shellKey, () => tool.run(args));
100
+ // Carry the batch's abort signal (FIX 5) through a side-channel so an in-flight bash command is killed
101
+ // on esc — a store, not a Tool.run param, so tools that use their 2nd param for test DI keep it.
102
+ const raw = await shellKeyStore.run(this.shellKey, () => shellSignalStore.run(report?.signal, () => tool.run(args)));
101
103
  // Semantic compression first (per-tool-type, keeps errors/head/tail), then the hard cap+spill.
102
104
  const compressed = semanticCompress(raw, { toolName: name, toolArgs: args });
103
105
  const out = capToolResult(compressed, spillToolOutput);
@@ -76,14 +76,14 @@ export function assertContentSearchScope(rawPath, cwd) {
76
76
  if (BROAD.has(abs) || (home && abs === home)) {
77
77
  return (`error: content search refused at "${rawPath || "."}" (resolves to ${abs}) — that scope is ` +
78
78
  `home/machine-wide and will hang for minutes. For a FILE/PROJECT NAME use find_files ` +
79
- `{"query":"…"}. For CONTENT, pass a narrow path (cwd subtree, ~/work/<repo>, ~/.axe/repos/<name>). ` +
79
+ `{"query":"…"} (on demand). For CONTENT, pass a narrow path (cwd subtree, ~/work/<repo>, ~/.axe/repos/<name>). ` +
80
80
  `For a fleet host/box (e.g. acropolis): read ~/.ssh/config, \`gh repo view\`, AGENTS.md — ` +
81
81
  `do not ripgrep $HOME.`);
82
82
  }
83
83
  return null;
84
84
  }
85
85
  const SHELL_REFUSE_MSG = "error: shell content search refused — recursive grep/rg/find over $HOME (or /, /Users, /tmp) " +
86
- "hangs for minutes. Use the `search` tool with a narrow path, or find_files for names. " +
86
+ "hangs for minutes. Use the `search` tool with a narrow path, or find_files (on demand) for names. " +
87
87
  "For a fleet host/box: ~/.ssh/config → gh repo view → AGENTS.md. Do not bypass with bash.";
88
88
  /**
89
89
  * Heuristic gate for bash / shell_exec / shell_background: catch the common bypass where the model
@@ -126,7 +126,7 @@ export function assertShellHomeWideSearch(command) {
126
126
  }
127
127
  export const BLIND_DOWNLOAD_MSG = "refused: `curl … -o/-O <file>` without `-f` / `--fail` (or `--fail-with-body`) saves an HTTP error page as if it were the file, and " +
128
128
  "a silent `-s` hides that it happened — the 0-byte / HTML-instead-of-ISO failure. Use the `download_file` tool " +
129
- "(fails loudly, resumes, retries, verifies size/sha256, never leaves a half file), or add `-f` (and `--retry 5 -C -`) " +
129
+ "(on demand; fails loudly, resumes, retries, verifies size/sha256, never leaves a half file), or add `-f` (and `--retry 5 -C -`) " +
130
130
  "and check the size afterwards. Run long transfers with shell_background or download_file, one at a time.";
131
131
  /**
132
132
  * Hard gate for bash / shell_exec / shell_background: a `curl` that writes to a FILE without failing on HTTP errors.
@@ -0,0 +1,44 @@
1
+ // sessionKey -> (resolved path -> last observed read state + the views of it already in the conversation).
2
+ const ledgers = new Map();
3
+ function forSession(sessionKey) {
4
+ let m = ledgers.get(sessionKey);
5
+ if (!m)
6
+ ledgers.set(sessionKey, (m = new Map()));
7
+ return m;
8
+ }
9
+ /** Record that `path` was read (or just written) with this on-disk state — the session now "knows" it. Views carry
10
+ * over only while the content is the same: new content means nothing of it has been shown yet. */
11
+ export function recordRead(sessionKey, path, rec) {
12
+ const m = forSession(sessionKey);
13
+ const prev = m.get(path);
14
+ const same = !!prev && !!rec.hash && prev.hash === rec.hash;
15
+ m.set(path, { ...rec, views: same ? prev.views : new Set() });
16
+ }
17
+ /** The last read state the session saw for `path`, or undefined if it was never read/written here. */
18
+ export function getRead(sessionKey, path) {
19
+ return ledgers.get(sessionKey)?.get(path);
20
+ }
21
+ /** Whether this exact view (a range key) of `path`'s current content was already delivered — and remember it now.
22
+ * False for a file never recorded. */
23
+ export function seenView(sessionKey, path, view) {
24
+ const e = ledgers.get(sessionKey)?.get(path);
25
+ if (!e)
26
+ return false;
27
+ if (e.views.has(view))
28
+ return true;
29
+ e.views.add(view);
30
+ return false;
31
+ }
32
+ /** Forget which views are in the conversation (every session, or one): after a compaction the text a view pointed at
33
+ * may be gone, so the next read must return it in full. The read state itself stays. */
34
+ export function forgetViews(sessionKey) {
35
+ for (const [k, m] of ledgers)
36
+ if (sessionKey === undefined || k === sessionKey)
37
+ for (const e of m.values())
38
+ e.views.clear();
39
+ }
40
+ /** Drop a session's whole ledger — wired into the shell-session dispose so a long run spawning many
41
+ * sub-agents does not accumulate per-lane read maps forever. Also the clean reset for tests. */
42
+ export function forgetReads(sessionKey) {
43
+ ledgers.delete(sessionKey);
44
+ }