@0perator/operator 0.1.285 → 0.1.321

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 (118) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +2 -1
  3. package/dist/acp/config-options.js +3 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +308 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +217 -44
  11. package/dist/autonomy/delegate.js +34 -5
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/index.js +22 -0
  14. package/dist/autonomy/profile.js +1 -1
  15. package/dist/autonomy/session-factory.js +25 -16
  16. package/dist/background/index.js +40 -0
  17. package/dist/browser/cdp.js +1 -1
  18. package/dist/bus/inbox.js +20 -0
  19. package/dist/classifier/config.js +47 -0
  20. package/dist/classifier/modes.js +41 -0
  21. package/dist/classifier/types.js +1 -0
  22. package/dist/cli.js +645 -93
  23. package/dist/config/features.js +69 -0
  24. package/dist/config/persona.js +143 -107
  25. package/dist/config/scaffold.js +15 -0
  26. package/dist/config/settings.js +107 -12
  27. package/dist/consolidation/sleep.js +73 -11
  28. package/dist/engine/agent.js +279 -20
  29. package/dist/engine/anthropic-chat.js +343 -0
  30. package/dist/engine/aurora.js +109 -16
  31. package/dist/engine/batch-scheduler.js +41 -9
  32. package/dist/engine/classifier.js +85 -0
  33. package/dist/engine/compaction.js +25 -6
  34. package/dist/engine/fast-start.js +25 -0
  35. package/dist/engine/loop-guard.js +448 -0
  36. package/dist/engine/net-error.js +24 -0
  37. package/dist/engine/repetition-guard.js +180 -0
  38. package/dist/engine/router-adapter.js +1 -0
  39. package/dist/engine/selfheal.js +8 -0
  40. package/dist/engine/toolcalls.js +51 -1
  41. package/dist/engine/verify-gate.js +2 -0
  42. package/dist/flywheel/processor.js +78 -31
  43. package/dist/flywheel/srft.js +13 -0
  44. package/dist/hooks/index.js +196 -0
  45. package/dist/idle/activity.js +20 -0
  46. package/dist/idle/index.js +5 -0
  47. package/dist/idle/monitor.js +71 -0
  48. package/dist/idle/policy.js +66 -0
  49. package/dist/idle/proc.js +22 -0
  50. package/dist/idle/reaper.js +69 -0
  51. package/dist/idle/session-record.js +59 -0
  52. package/dist/index.js +1 -1
  53. package/dist/mcp/config.js +93 -15
  54. package/dist/mcp/index.js +9 -2
  55. package/dist/memory/index.js +0 -0
  56. package/dist/memory/providers.js +210 -0
  57. package/dist/memory/session-catalog.js +422 -0
  58. package/dist/memory/session-providers.js +121 -0
  59. package/dist/memory/session-sources.js +335 -0
  60. package/dist/memory/skylark.js +131 -0
  61. package/dist/models/bench.js +103 -0
  62. package/dist/models/registry.js +144 -0
  63. package/dist/models/switch.js +69 -0
  64. package/dist/observability/blackbox.js +37 -0
  65. package/dist/permissions/index.js +22 -7
  66. package/dist/permissions/policy.js +31 -6
  67. package/dist/permissions/tier.js +1 -1
  68. package/dist/remote/host.js +20 -2
  69. package/dist/remote/safe-commands.js +38 -0
  70. package/dist/router/discovery.js +127 -0
  71. package/dist/router/models.js +107 -16
  72. package/dist/router/portal.js +100 -0
  73. package/dist/router/router.js +1 -1
  74. package/dist/services/preflight.js +108 -8
  75. package/dist/services/store-sync.js +111 -0
  76. package/dist/session-teardown.js +10 -1
  77. package/dist/session.js +338 -46
  78. package/dist/skills/catalogue.js +1 -1
  79. package/dist/tools/chauffeur-native.js +155 -0
  80. package/dist/tools/chauffeur.js +26 -3
  81. package/dist/tools/download.js +229 -0
  82. package/dist/tools/executor.js +19 -9
  83. package/dist/tools/find-files.js +483 -0
  84. package/dist/tools/git-pr.js +94 -0
  85. package/dist/tools/incident-tools.js +82 -0
  86. package/dist/tools/memory.js +12 -2
  87. package/dist/tools/monitoring-tools.js +312 -0
  88. package/dist/tools/paths.js +154 -0
  89. package/dist/tools/registry.js +582 -95
  90. package/dist/tools/semantic-compress.js +124 -0
  91. package/dist/tools/shell-context.js +1 -0
  92. package/dist/tools/shell-jobs.js +163 -0
  93. package/dist/tools/shell-session.js +174 -6
  94. package/dist/tools/tool-output-spill.js +1 -1
  95. package/dist/tools/wave-tools.js +609 -0
  96. package/dist/tools/wave2-tools.js +411 -0
  97. package/dist/ui/App.js +15 -4
  98. package/dist/ui/BgPanel.js +30 -6
  99. package/dist/ui/Composer.js +15 -2
  100. package/dist/ui/QuestionPrompt.js +32 -12
  101. package/dist/ui/SessionPicker.js +86 -0
  102. package/dist/ui/StatusRule.js +5 -5
  103. package/dist/ui/ToolStep.js +17 -1
  104. package/dist/ui/Transcript.js +17 -1
  105. package/dist/ui/index.js +1 -1
  106. package/dist/ui/liveTools.js +21 -3
  107. package/dist/ui/slashCommands.js +2 -0
  108. package/dist/util/mentions.js +1 -1
  109. package/dist/util/screenshots.js +74 -8
  110. package/dist/util/slash.js +2 -2
  111. package/dist/vault/store.js +1 -1
  112. package/mcp/README.md +88 -0
  113. package/mcp/ocr-macos.swift +45 -0
  114. package/mcp/powertools-media.mjs +464 -0
  115. package/mcp/powertools-toolbox.mjs +1114 -0
  116. package/mcp/powertools.md +210 -0
  117. package/mcp/powertools.mjs +861 -0
  118. package/package.json +9 -2
@@ -0,0 +1,155 @@
1
+ // Native Chauffeur tool wrappers for the Operator engine. These wrap key Chauffeur MCP tools as
2
+ // first-class engine tools so any model dropped into Operator gets desktop automation and live-drive
3
+ // verification without needing to know about MCP at all. The hub is memoized per process.
4
+ import { buildChauffeurHub } from "./chauffeur.js";
5
+ let hubPromise = null;
6
+ function getHub() {
7
+ return (hubPromise ??= buildChauffeurHub());
8
+ }
9
+ export async function chauffeurReady() {
10
+ const hub = await getHub();
11
+ return hub !== null;
12
+ }
13
+ async function callChauffeur(tool, args) {
14
+ const hub = await getHub();
15
+ // Graceful degradation when the desktop driver is not available on this host.
16
+ // No install path in user prose: the install path is operator-runtime's responsibility
17
+ // (setup-services.sh), not something to ask the end-user to resolve by name or env var.
18
+ if (!hub)
19
+ return "error: desktop automation unavailable on this host";
20
+ try {
21
+ const result = await hub.call(`chauffeur:${tool}`, args);
22
+ if (typeof result === "string")
23
+ return result;
24
+ return JSON.stringify(result, null, 2);
25
+ }
26
+ catch (e) {
27
+ return `error calling chauffeur:${tool}: ${e?.message ?? e}`;
28
+ }
29
+ }
30
+ export async function desktopScreenshot(args) {
31
+ return callChauffeur("get_desktop_state", {
32
+ include_screenshot: true,
33
+ ...args,
34
+ });
35
+ }
36
+ export async function desktopClick(args) {
37
+ const description = args.description;
38
+ const x = args.x ?? args.coordinate_x;
39
+ const y = args.y ?? args.coordinate_y;
40
+ const element = args.element;
41
+ const clickArgs = {};
42
+ if (x != null && y != null) {
43
+ clickArgs.x = x;
44
+ clickArgs.y = y;
45
+ }
46
+ if (element)
47
+ clickArgs.element = element;
48
+ if (args.button)
49
+ clickArgs.button = args.button;
50
+ const result = await callChauffeur("click", clickArgs);
51
+ if (args.verify !== false) {
52
+ const verify = await callChauffeur("verify_state", { expect: typeof description === "string" ? description : "click landed" });
53
+ return result + "\n--- verify ---\n" + verify;
54
+ }
55
+ return result;
56
+ }
57
+ export async function desktopRead(args) {
58
+ const pid = args.pid;
59
+ const windowId = args.window_id;
60
+ const readArgs = {};
61
+ if (pid != null)
62
+ readArgs.pid = pid;
63
+ if (windowId != null)
64
+ readArgs.window_id = windowId;
65
+ return callChauffeur("get_window_state", readArgs);
66
+ }
67
+ export async function appInteract(args) {
68
+ const app = args.app;
69
+ const action = args.action;
70
+ if (typeof app !== "string")
71
+ return "error: app name required";
72
+ if (typeof action !== "string")
73
+ return "error: action required (launch, find, click, type, read)";
74
+ const parts = [];
75
+ if (action === "launch" || action === "find" || action === "click" || action === "type") {
76
+ const launch = await callChauffeur("launch_app", { name: app });
77
+ parts.push("=== LAUNCH ===\n" + launch);
78
+ }
79
+ if (action === "read" || action === "find") {
80
+ const state = await callChauffeur("get_window_state", { app_name: app });
81
+ parts.push("=== READ ===\n" + state);
82
+ }
83
+ if (action === "click" && args.element) {
84
+ const click = await callChauffeur("click", { element: args.element });
85
+ parts.push("=== CLICK ===\n" + click);
86
+ }
87
+ if (action === "type" && args.text) {
88
+ const type = await callChauffeur("type_text", { text: args.text });
89
+ parts.push("=== TYPE ===\n" + type);
90
+ }
91
+ return parts.join("\n\n") || `completed ${action} on ${app}`;
92
+ }
93
+ export async function capturePermalink(args) {
94
+ const parts = [];
95
+ if (args.app) {
96
+ const launch = await callChauffeur("launch_app", { name: args.app });
97
+ parts.push(launch);
98
+ }
99
+ if (args.element) {
100
+ const click = await callChauffeur("right_click", { element: args.element });
101
+ parts.push(click);
102
+ }
103
+ const clipboard = await callChauffeur("clipboard_read", {});
104
+ parts.push("clipboard: " + clipboard);
105
+ return parts.join("\n");
106
+ }
107
+ export async function liveDrive(args) {
108
+ const url = args.url;
109
+ if (typeof url !== "string")
110
+ return "error: url required";
111
+ const checks = args.checks;
112
+ if (!Array.isArray(checks) || !checks.length)
113
+ return "error: checks must be a non-empty array";
114
+ const parts = [];
115
+ // Prepare browser
116
+ parts.push("=== BROWSER PREPARE ===");
117
+ const prep = await callChauffeur("browser_prepare", {});
118
+ parts.push(prep);
119
+ parts.push("\n=== NAVIGATE ===");
120
+ const nav = await callChauffeur("browser_navigate", { url });
121
+ parts.push(nav);
122
+ let passed = 0;
123
+ for (const check of checks) {
124
+ const label = check.label || "check";
125
+ const action = check.action || "screenshot";
126
+ parts.push(`\n=== ${String(label).toUpperCase()} ===`);
127
+ let result;
128
+ switch (action) {
129
+ case "screenshot":
130
+ result = await callChauffeur("get_browser_state", { include_screenshot: true });
131
+ break;
132
+ case "find":
133
+ result = await callChauffeur("find", { text: check.selector || check.expect });
134
+ break;
135
+ case "click":
136
+ result = await callChauffeur("browser_click", { selector: check.selector });
137
+ break;
138
+ case "text":
139
+ result = await callChauffeur("get_page_text", {});
140
+ break;
141
+ default:
142
+ result = `unknown action: ${action}`;
143
+ }
144
+ parts.push(result);
145
+ if (check.expect && typeof result === "string" && !result.toLowerCase().includes(String(check.expect).toLowerCase())) {
146
+ parts.push(`=== ${String(label).toUpperCase()} FAILED (expected "${check.expect}" not found) ===`);
147
+ }
148
+ else {
149
+ passed++;
150
+ parts.push(`=== ${String(label).toUpperCase()} PASSED ===`);
151
+ }
152
+ }
153
+ parts.push(`\n=== LIVE DRIVE COMPLETE: ${passed}/${checks.length} checks passed ===`);
154
+ return parts.join("\n");
155
+ }
@@ -22,11 +22,23 @@ export const CHAUFFEUR_READ_TOOLS = [
22
22
  // Bounded post-condition check (read-only verification, not an input event) — lets the model confirm an
23
23
  // action landed instead of guessing from the next screenshot.
24
24
  "verify_state",
25
+ // Browser READS (web front-end testing/driving — non-mutating inspection, unprompted). get_browser_state
26
+ // = the live page's DOM/a11y as text; get_page_text = its rendered text; find = locate an element by
27
+ // text/role; get_accessibility_tree = the AX tree. gif_creator records a short clip of what just happened
28
+ // for the owner to review (a capture, not an input event). This is Operator's browser surface for FE
29
+ // testing — pair get_browser_state + verify_state around each step (see the fe-testing skill).
30
+ "get_browser_state", "get_page_text", "find", "get_accessibility_tree", "gif_creator",
25
31
  ];
26
32
  export const CHAUFFEUR_ACTION_TOOLS = [
27
33
  "launch_app", "bring_to_front", // window/app management
28
34
  "click", "double_click", "right_click", "type_text", "press_key", "hotkey", // input
29
35
  "scroll", "move_cursor", "drag", "invoke_menu", "set_value", "clipboard_write",
36
+ // Browser ACTIONS (web front-end testing/driving — navigation + input, gated "ask" fg / "deny" bg).
37
+ // browser_prepare opens/attaches a tab; browser_navigate loads a URL; browser_click/type/pointer drive
38
+ // the page; browser_set_input_files uploads; browser_dialog handles a native dialog (never trigger one
39
+ // blindly — it blocks events); browser_download pulls a file.
40
+ "browser_prepare", "browser_navigate", "browser_click", "browser_type", "browser_pointer",
41
+ "browser_set_input_files", "browser_dialog", "browser_download",
30
42
  ];
31
43
  export const CHAUFFEUR_TOOLS = [...CHAUFFEUR_READ_TOOLS, ...CHAUFFEUR_ACTION_TOOLS];
32
44
  // Namespaced names (server:tool) the hub exposes. ACTION names are what cli.tsx forces to "ask" (fg);
@@ -50,14 +62,21 @@ async function resolveBinaryFresh() {
50
62
  const override = process.env.KODE_CHAUFFEUR_BIN;
51
63
  if (override)
52
64
  return override;
53
- const { existsSync } = await import("node:fs");
54
- const { homedir } = await import("node:os");
65
+ // Variable-specifier dynamic imports — matches the mcp/config.ts + mcp/stdio.ts convention
66
+ // so esbuild cannot statically resolve "node:*" into a browser/JSCore graph. Required for
67
+ // test/neutral-graph.test.mts to pass when any chain (registry.ts → chauffeur-native.ts →
68
+ // chauffeur.ts) reaches this module from the shared engine bundle.
69
+ const nodeFs = "node:fs";
70
+ const nodeOs = "node:os";
71
+ const nodeChild = "node:child_process";
72
+ const { existsSync } = await import(nodeFs);
73
+ const { homedir } = await import(nodeOs);
55
74
  const local = `${homedir()}/.local/bin/chauffeur-local`;
56
75
  if (existsSync(local))
57
76
  return local;
58
77
  // Fall back to PATH resolution; if `chauffeur` isn't there either, give up (no dead hub, no failed spawn).
59
78
  try {
60
- const { execFile } = await import("node:child_process");
79
+ const { execFile } = await import(nodeChild);
61
80
  const p = await new Promise((resolve, reject) => {
62
81
  execFile("/bin/sh", ["-c", "command -v chauffeur"], { timeout: 3000, encoding: "utf8" }, (err, stdout) => (err ? reject(err) : resolve(stdout)));
63
82
  });
@@ -83,7 +102,11 @@ export async function buildChauffeurServer() {
83
102
  tools: [...CHAUFFEUR_TOOLS], // curated allowlist (the McpHub filters discovery to these)
84
103
  };
85
104
  }
105
+ let _hubPromise = null;
86
106
  export async function buildChauffeurHub() {
107
+ return (_hubPromise ??= buildChauffeurHubFresh());
108
+ }
109
+ async function buildChauffeurHubFresh() {
87
110
  const server = await buildChauffeurServer();
88
111
  return server ? new McpHub([server]) : null;
89
112
  }
@@ -0,0 +1,229 @@
1
+ // download_file: fetch a URL to disk the way a download is supposed to work, and say plainly when it did not.
2
+ // The failure this exists for: `curl -s … &` + `wait`, 0-byte files, then "Already downloaded" because nothing read the result back.
3
+ // So: fail loudly on any HTTP error, resume a partial file (`<dest>.part`), retry network drops and stalls, refuse an HTML page that
4
+ // is standing in for the file, verify length (and sha256 when the caller has one), and only then rename onto `dest` — a half
5
+ // download never sits at the final name. Node-only (no child process), so there is nothing to own or orphan.
6
+ import { createHash } from "node:crypto";
7
+ import { createReadStream } from "node:fs";
8
+ import { mkdir, open, rename, rm, stat } from "node:fs/promises";
9
+ import { basename, dirname, extname, join } from "node:path";
10
+ /** A page that is fine to save as text; anything else arriving as HTML is almost certainly an error or landing page. */
11
+ const TEXT_EXT = new Set([".html", ".htm", ".xhtml", ".php", ".asp", ".aspx", ".txt", ".md", ".json", ".xml", ".csv", ".svg", ".js", ".css", ".log", ".yaml", ".yml", ".toml", ".ini", ".sh", ".py"]);
12
+ const HTML_START = /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>]|<body[\s>])/i;
13
+ class Fatal extends Error {
14
+ }
15
+ class Retryable extends Error {
16
+ }
17
+ const human = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(2)} GB` : n >= 1e6 ? `${(n / 1e6).toFixed(1)} MB` : n >= 1e3 ? `${(n / 1e3).toFixed(1)} KB` : `${n} B`);
18
+ const sleep = (ms, signal) => new Promise((res) => { const t = setTimeout(res, ms); signal?.addEventListener("abort", () => { clearTimeout(t); res(); }, { once: true }); });
19
+ async function sizeOf(path) {
20
+ try {
21
+ return (await stat(path)).size;
22
+ }
23
+ catch {
24
+ return 0;
25
+ }
26
+ }
27
+ async function exists(path) {
28
+ try {
29
+ await stat(path);
30
+ return true;
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ async function sha256OfFile(path) {
37
+ const h = createHash("sha256");
38
+ await new Promise((res, rej) => { const s = createReadStream(path); s.on("data", (c) => h.update(c)); s.on("end", () => res()); s.on("error", rej); });
39
+ return h;
40
+ }
41
+ function fileNameFromUrl(url) {
42
+ try {
43
+ const last = decodeURIComponent(basename(new URL(url).pathname));
44
+ return last && last !== "/" ? last.replace(/[\\/:*?"<>|\0]/g, "_") : "download";
45
+ }
46
+ catch {
47
+ return "download";
48
+ }
49
+ }
50
+ async function resolveDest(dest, url) {
51
+ let isDir = dest.endsWith("/");
52
+ if (!isDir) {
53
+ try {
54
+ isDir = (await stat(dest)).isDirectory();
55
+ }
56
+ catch { /* not there yet */ }
57
+ }
58
+ return isDir ? join(dest, fileNameFromUrl(url)) : dest;
59
+ }
60
+ export async function downloadFile(o) {
61
+ const t0 = Date.now();
62
+ const done = (r) => ({ ...r, seconds: Math.round((Date.now() - t0) / 100) / 10 });
63
+ let attempts = 0;
64
+ let url;
65
+ try {
66
+ url = new URL(o.url);
67
+ }
68
+ catch {
69
+ return done({ ok: false, attempts, message: `error: "${o.url}" is not a valid URL` });
70
+ }
71
+ if (url.protocol !== "http:" && url.protocol !== "https:")
72
+ return done({ ok: false, attempts, message: `error: only http(s) URLs can be downloaded, got ${url.protocol}` });
73
+ const finalPath = await resolveDest(o.dest, o.url);
74
+ const part = `${finalPath}.part`;
75
+ const doFetch = o.fetchImpl ?? fetch;
76
+ const retries = o.retries ?? 5;
77
+ const stallMs = o.stallMs ?? 30_000;
78
+ const wantSha = o.sha256?.trim().toLowerCase();
79
+ if (wantSha && !/^[0-9a-f]{64}$/.test(wantSha))
80
+ return done({ ok: false, attempts, message: "error: sha256 must be 64 hex characters" });
81
+ if (!o.overwrite && (await exists(finalPath))) {
82
+ return done({ ok: false, attempts, path: finalPath, message: `error: ${finalPath} already exists — pass overwrite:true to replace it, or choose another dest` });
83
+ }
84
+ await mkdir(dirname(finalPath), { recursive: true });
85
+ let resumedFrom;
86
+ let lastError = "";
87
+ let progressAt = 0;
88
+ for (let attempt = 0; attempt <= retries; attempt++) {
89
+ attempts = attempt + 1;
90
+ if (o.signal?.aborted)
91
+ return done({ ok: false, attempts, message: "cancelled", resumedFrom });
92
+ if (attempt > 0)
93
+ await sleep(Math.min((o.retryDelayMs ?? 1000) * 2 ** (attempt - 1), 30_000), o.signal);
94
+ if (o.signal?.aborted)
95
+ return done({ ok: false, attempts, message: "cancelled", resumedFrom });
96
+ const have = await sizeOf(part);
97
+ const ac = new AbortController();
98
+ const onAbort = () => ac.abort();
99
+ o.signal?.addEventListener("abort", onAbort, { once: true });
100
+ let stalled = false;
101
+ let discardPart = false; // set when what is on disk is known to be garbage (an HTML page), so it is not offered for resume
102
+ let stallTimer;
103
+ const kick = () => { if (stallTimer)
104
+ clearTimeout(stallTimer); stallTimer = setTimeout(() => { stalled = true; ac.abort(); }, stallMs); };
105
+ try {
106
+ kick();
107
+ const headers = { ...(o.headers ?? {}) };
108
+ if (have > 0)
109
+ headers.range = `bytes=${have}-`;
110
+ const res = await doFetch(url, { headers, redirect: "follow", signal: ac.signal });
111
+ const ctype = res.headers.get("content-type") ?? undefined;
112
+ if (res.status === 416) { // the .part is not a prefix of what the server has (or is already complete)
113
+ const m = /\/(\d+)\s*$/.exec(res.headers.get("content-range") ?? "");
114
+ if (m && Number(m[1]) === have) { /* complete already: fall through to verification below with no body */ }
115
+ else {
116
+ await rm(part, { force: true });
117
+ throw new Retryable("server rejected the resume range (HTTP 416) — restarting from zero");
118
+ }
119
+ }
120
+ else if (!res.ok) {
121
+ const msg = `HTTP ${res.status} ${res.statusText}`.trim();
122
+ if (res.status >= 500 || res.status === 408 || res.status === 429)
123
+ throw new Retryable(msg);
124
+ throw new Fatal(`${msg} for ${res.url || o.url} — nothing was saved`);
125
+ }
126
+ let start = have;
127
+ if (res.status === 200 && have > 0) {
128
+ start = 0;
129
+ await rm(part, { force: true });
130
+ } // server ignored Range: restart cleanly
131
+ if (res.status === 206) {
132
+ const m = /bytes\s+(\d+)-/.exec(res.headers.get("content-range") ?? "");
133
+ if (m && Number(m[1]) !== have) {
134
+ await rm(part, { force: true });
135
+ throw new Retryable("server resumed from the wrong offset — restarting from zero");
136
+ }
137
+ }
138
+ if (start > 0 && resumedFrom === undefined)
139
+ resumedFrom = start;
140
+ const len = Number(res.headers.get("content-length") ?? NaN);
141
+ const crTotal = /\/(\d+)\s*$/.exec(res.headers.get("content-range") ?? "");
142
+ const total = res.status === 416 ? have : crTotal ? Number(crTotal[1]) : Number.isFinite(len) ? len + (res.status === 206 ? start : 0) : undefined;
143
+ if (ctype && /^text\/html/i.test(ctype) && !TEXT_EXT.has(extname(finalPath).toLowerCase()) && res.status !== 416) {
144
+ throw new Fatal(`the server answered with an HTML page (${ctype}), not a "${extname(finalPath) || "file"}" — a landing/error/login page standing in for the download. Nothing was saved. Check the URL.`);
145
+ }
146
+ if (o.expectedBytes !== undefined && total !== undefined && total !== o.expectedBytes) {
147
+ throw new Fatal(`size mismatch before download: the server reports ${total} bytes, you expected ${o.expectedBytes}. Nothing was saved.`);
148
+ }
149
+ const hash = start > 0 ? await sha256OfFile(part) : createHash("sha256");
150
+ let got = start;
151
+ if (res.status !== 416) {
152
+ const fh = await open(part, start > 0 ? "a" : "w");
153
+ try {
154
+ let first = true;
155
+ const reader = res.body?.getReader();
156
+ if (!reader)
157
+ throw new Retryable("empty response body");
158
+ for (;;) {
159
+ const { done: eof, value } = await reader.read();
160
+ if (eof)
161
+ break;
162
+ kick();
163
+ if (first) {
164
+ first = false;
165
+ if (start === 0 && !TEXT_EXT.has(extname(finalPath).toLowerCase()) && HTML_START.test(Buffer.from(value.subarray(0, 512)).toString("utf8"))) {
166
+ await reader.cancel().catch(() => { });
167
+ discardPart = true;
168
+ throw new Fatal("the response body is an HTML page, not the file — a landing/error/login page standing in for the download. Nothing was saved. Check the URL.");
169
+ }
170
+ }
171
+ await fh.write(value);
172
+ hash.update(value);
173
+ got += value.byteLength;
174
+ const now = Date.now();
175
+ if (o.onProgress && now - progressAt >= 1000) {
176
+ progressAt = now;
177
+ o.onProgress({ bytes: got, total, bytesPerSec: (got - start) / Math.max(0.001, (now - t0) / 1000) });
178
+ }
179
+ }
180
+ }
181
+ finally {
182
+ await fh.close();
183
+ }
184
+ }
185
+ if (total !== undefined && got !== total)
186
+ throw new Retryable(`connection closed early: received ${got} of ${total} bytes`);
187
+ const digest = hash.digest("hex");
188
+ if (o.expectedBytes !== undefined && got !== o.expectedBytes) {
189
+ await rm(part, { force: true });
190
+ throw new Fatal(`size mismatch: got ${got} bytes, expected ${o.expectedBytes}. The partial file was deleted.`);
191
+ }
192
+ if (wantSha && digest !== wantSha) {
193
+ await rm(part, { force: true });
194
+ throw new Fatal(`sha256 mismatch: got ${digest}, expected ${wantSha}. The file was NOT kept — it is not the file you asked for.`);
195
+ }
196
+ if (got === 0) {
197
+ await rm(part, { force: true });
198
+ throw new Fatal("the server sent 0 bytes — nothing was saved.");
199
+ }
200
+ await rename(part, finalPath);
201
+ return done({
202
+ ok: true, attempts, path: finalPath, bytes: got, sha256: digest, contentType: ctype, finalUrl: res.url || o.url, resumedFrom,
203
+ message: `downloaded ${human(got)} to ${finalPath} (sha256 ${digest}${wantSha ? ", matches the one you gave" : ", not checked against a published hash"})` +
204
+ `${resumedFrom ? `; resumed from ${human(resumedFrom)}` : ""}${attempts > 1 ? `; ${attempts} attempts` : ""}.`,
205
+ });
206
+ }
207
+ catch (e) {
208
+ const err = e;
209
+ if (o.signal?.aborted)
210
+ return done({ ok: false, attempts, message: "cancelled", resumedFrom });
211
+ if (err instanceof Fatal) {
212
+ if (discardPart)
213
+ await rm(part, { force: true });
214
+ return done({ ok: false, attempts, path: finalPath, message: `error: ${err.message}`, resumedFrom });
215
+ }
216
+ lastError = stalled ? `stalled: no data for ${Math.round(stallMs / 1000)}s` : err.message || String(err);
217
+ }
218
+ finally {
219
+ if (stallTimer)
220
+ clearTimeout(stallTimer);
221
+ o.signal?.removeEventListener("abort", onAbort);
222
+ }
223
+ }
224
+ const kept = await sizeOf(part);
225
+ return done({
226
+ ok: false, attempts, path: finalPath, resumedFrom,
227
+ message: `error: gave up after ${attempts} attempts (${lastError}).${kept ? ` ${human(kept)} are kept at ${part} — call download_file again with the same dest to resume.` : ""}`,
228
+ });
229
+ }
@@ -2,9 +2,8 @@
2
2
  // Interface consumed by the engine (Karpathy's lane):
3
3
  // execute(name, args) -> Promise<string> one call; never throws, always resolves
4
4
  // executeParallel(calls) -> Promise<string[]> one round's tool_calls, in input order;
5
- // executed in input order: a contiguous run of safe
6
- // (read-only) tools runs concurrently, every other
7
- // call runs alone, awaited in place
5
+ // BTX DAG: reads overlap, writes conflict-order,
6
+ // barriers alone, independent bash/shell_exec overlap
8
7
  // resetTurn() -> void clear loop-guard history; call once per
9
8
  // new user turn (not required by SPEC §3's
10
9
  // round loop itself, but needed so the guard
@@ -12,11 +11,12 @@
12
11
  import { isAbsolute, join, resolve } from "node:path";
13
12
  import { registry } from "./registry.js";
14
13
  import { expandPath } from "./paths.js";
15
- import { shellKeyStore } from "./shell-context.js";
14
+ import { shellKeyStore, shellExecMode } from "./shell-context.js";
16
15
  // Re-exported for back-compat (existing importers reach it via executor.js) — moved to its own
17
16
  // file since it's a pure helper with no node deps; see result-cap.ts for why that separation matters.
18
17
  import { capToolResult } from "./result-cap.js";
19
18
  import { spillToolOutput } from "./tool-output-spill.js"; // GW-10: lossless eviction — spill big outputs, hand back a re-readable pointer
19
+ import { semanticCompress } from "./semantic-compress.js";
20
20
  export { TOOL_RESULT_MAX_CHARS, capToolResult } from "./result-cap.js";
21
21
  import { runBatch, defaultClassify, defaultKeys } from "../engine/batch-scheduler.js";
22
22
  // Command tools whose working directory should default to the executor root (they take an optional `cwd`).
@@ -94,7 +94,10 @@ export class Executor {
94
94
  try {
95
95
  // Run the tool inside THIS session's shell-key context so a persistent-shell tool (bash) picks
96
96
  // this session's own ShellSession, not a process-wide singleton shared with other sub-agents.
97
- const out = capToolResult(await shellKeyStore.run(this.shellKey, () => tool.run(args)), spillToolOutput);
97
+ const raw = await shellKeyStore.run(this.shellKey, () => tool.run(args));
98
+ // Semantic compression first (per-tool-type, keeps errors/head/tail), then the hard cap+spill.
99
+ const compressed = semanticCompress(raw, { toolName: name, toolArgs: args });
100
+ const out = capToolResult(compressed, spillToolOutput);
98
101
  // A file edit that LANDED changed the workspace, so prior identical-call counts are stale — re-running the
99
102
  // same test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
100
103
  // A FAILING edit ("error: old_string not found") changed nothing, so it must not reset the count.
@@ -116,14 +119,21 @@ export class Executor {
116
119
  }
117
120
  async executeParallel(calls, onSettle, signal) {
118
121
  // BTX: one shared DAG scheduler (engine/batch-scheduler.ts) — per-resource write chains,
119
- // reads wait only for conflicting prior writes, device tools barrier-serialize. This replaces
120
- // the 0.1.225 contiguous walk: same guarantees, strictly more overlap.
121
- return runBatch(calls, {
122
+ // reads wait only for conflicting prior writes, device tools barrier-serialize, independent
123
+ // bash/shell_exec overlap (shell kind). This replaces the 0.1.225 contiguous walk.
124
+ //
125
+ // Matching Cursor for shells: when this round has ≥2 bash/shell_exec calls, run them as ephemeral
126
+ // one-shots so the persistent ShellSession FIFO cannot serialize wall-clock. A lone bash still
127
+ // uses the persistent session (cwd/env + ctrl+b detach stick). See shellExecMode.
128
+ const SHELL_TOOLS = new Set(["bash", "shell_exec"]);
129
+ const shellCount = calls.reduce((n, c) => n + (SHELL_TOOLS.has(c.name) ? 1 : 0), 0);
130
+ const mode = shellCount >= 2 ? "ephemeral" : "persistent";
131
+ return shellExecMode.run(mode, () => runBatch(calls, {
122
132
  classify: this.sched.classify,
123
133
  keys: (n, a) => this.sched.keys(n, a),
124
134
  runOne: (c) => this.execute(c.name, c.args),
125
135
  onSettle,
126
136
  signal,
127
- });
137
+ }));
128
138
  }
129
139
  }