@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
@@ -5,18 +5,35 @@
5
5
  // JSCore engine for tool SCHEMAS (toSchemas), but the run() bodies below never execute there — the
6
6
  // mobile app runs tools natively in Swift. nodeImport() keeps esbuild from statically resolving them.
7
7
  const nodeImport = (m) => import(m);
8
- import { MemoryStore } from "../memory/index.js";
8
+ import { buildMemory } from "../memory/providers.js";
9
9
  import { indexSessions, readSession, searchSessions } from "../memory/session-index.js";
10
+ import { formatHits, indexCatalog, readCatalogSession, searchCatalog, sessionSearchConfig, SESSION_SCOPES } from "../memory/session-catalog.js";
10
11
  import { listLocalSkills, localSkillsDir as profileSkillsDir, resolveSkillFile } from "../config/skills-index.js";
11
12
  import { operatorPath } from "../config/home.js";
12
13
  import { ownChild } from "../util/owned-children.js";
14
+ import { BG_MAX_RUNNING, createJob, finishJob, newJobId, pruneShellJobs, runningJobCount, shellJobs, stopShellJob, trackJobOutput } from "./shell-jobs.js";
13
15
  import { pexecFile } from "./exec.js";
16
+ import { WAVE_TOOLS } from "./wave-tools.js";
17
+ import { WAVE2_TOOLS } from "./wave2-tools.js";
18
+ import { GIT_PR_TOOLS } from "./git-pr.js";
19
+ import { INCIDENT_TOOLS } from "./incident-tools.js";
20
+ import { MONITORING_TOOLS } from "./monitoring-tools.js";
21
+ import { desktopScreenshot, desktopClick, desktopRead, appInteract, capturePermalink, liveDrive } from "./chauffeur-native.js";
22
+ import { findFiles, FIND_FILES_DEFAULT_LIMIT, FIND_FILES_MAX_LIMIT, KINDS } from "./find-files.js";
14
23
  import { formatGitStatus } from "./git-status.js";
15
- import { expandPath } from "./paths.js";
24
+ import { expandPath, assertContentSearchScope, assertShellHomeWideSearch, assertShellBlindDownload } from "./paths.js";
16
25
  import { runMemoryTool } from "./memory.js";
17
26
  import { documentGenerate } from "./document.js";
18
27
  import { runCronTool } from "../autonomy/cron.js";
19
28
  import { runDelegateTask } from "../autonomy/delegate.js";
29
+ import { runDelegateToAgent, agentCliToolDescription } from "../autonomy/agent-cli.js";
30
+ import { runSpawnCloudAgent, runListCloudAgents, runCloudAgentStatus, runStopCloudAgent } from "../autonomy/cloud-agent.js";
31
+ import { isFeatureEnabled } from "../config/features.js";
32
+ import { BYO_PRESETS } from "../router/models.js";
33
+ // BYO cloud provider ids delegate_task can target once the owner has stored that provider's key (the preset
34
+ // table; a custom provider registered via `operator auth byo-model` works the same). Surfaced in the tool
35
+ // description so the model KNOWS the option exists — without it, it never delegates to a connected cloud.
36
+ const BYO_DELEGATE_PROVIDERS = Object.keys(BYO_PRESETS).join(", ");
20
37
  import { runSessionRewind } from "../memory/session-rewind.js";
21
38
  import { runSkillCatalog } from "../skills/catalogue.js";
22
39
  import { runBrowser, runBrowserRead } from "../browser/session.js";
@@ -47,7 +64,24 @@ async function getShellSession() {
47
64
  sess = new ShellSession();
48
65
  _shells.set(key, sess);
49
66
  }
50
- return sess;
67
+ return { sess, key };
68
+ }
69
+ /** ctrl+b: hand the foreground session's running shell command to a background job. The tool call resolves
70
+ * right away (shellExec returns the "moved to background" result); returns false when nothing is running. */
71
+ export function requestShellDetach(key) {
72
+ return _shells.get(key)?.requestDetach() ?? false;
73
+ }
74
+ /** Take over a command that was just detached: it becomes job `id`, and the session gets a fresh shell that
75
+ * starts where the old one was (cwd only — exported variables, functions and aliases stay with the old shell). */
76
+ function adoptDetached(key, run, id, ShellSession, processCwd) {
77
+ const job = createJob(id, run.command, { kill: (sig) => run.kill(sig), pid: run.pid }, "moved");
78
+ job.started = run.startedAt;
79
+ trackJobOutput(job, run.partial);
80
+ run.setTap((chunk) => trackJobOutput(job, chunk));
81
+ void run.finished.then((r) => finishJob(job, r.exitCode));
82
+ const fresh = new ShellSession();
83
+ fresh.seedCwd(processCwd(run.pid));
84
+ _shells.set(key, fresh);
51
85
  }
52
86
  /** Kill EVERY persistent shell (and their process groups) on process shutdown so none orphan.
53
87
  * Wired into the CLI's exit/SIGTERM handlers — no-op if no shell was ever started. */
@@ -65,22 +99,63 @@ export function disposeShellSessionKey(key) {
65
99
  _shells.delete(key);
66
100
  }
67
101
  }
102
+ // Commands that routinely outlive a foreground timeout. ssh is deliberately absent: what runs on the remote host is unknown.
103
+ const LONG_CMD_RE = /(?:^|[;&|(]\s*|&&\s*)(?:(?:sudo\s+)?(?:npm|pnpm|yarn|bun)\s+(?:install|i|ci|add|test|run\s+(?:build|test)|build)\b|pip3?\s+install\b|(?:python3?\s+-m\s+)?pytest\b|cargo\s+(?:build|test|install)\b|go\s+(?:build|test)\b|(?:g?make|cmake|gradle|\.\/gradlew|mvn)\b|docker\s+(?:build|pull)\b|brew\s+(?:install|upgrade)\b|apt(?:-get)?\s+(?:install|upgrade)\b|wget\b|curl\b[^|;&]*\s(?:-[a-zA-Z]*[OL]\b|--output\b|-o\s))/;
104
+ export function isLongRunningCommand(command) {
105
+ return LONG_CMD_RE.test(command.trim()) && !/\bssh\b/.test(command);
106
+ }
68
107
  async function shellExec(args) {
69
108
  const command = str(args.command);
70
109
  if (!command)
71
110
  return "error: no command given";
111
+ const homeWide = assertShellHomeWideSearch(command);
112
+ if (homeWide)
113
+ return homeWide;
114
+ const blind = assertShellBlindDownload(command);
115
+ if (blind)
116
+ return blind;
117
+ // An explicit timeout_ms is the model's own choice and is honored; otherwise a known-long command goes straight to a job.
118
+ if (args.timeout_ms === undefined && isLongRunningCommand(command)) {
119
+ const started = await shellBackground(args);
120
+ if (started.startsWith("started background job"))
121
+ return `[auto-backgrounded: this command is expected to run long, so it was NOT run in the foreground shell]\n${started}`;
122
+ return started;
123
+ }
72
124
  const timeout = Number(args.timeout_ms ?? 120_000);
73
125
  // A `cwd` arg is scoped to this one call (subshell) so it doesn't silently move the persistent
74
126
  // session's directory; an explicit `cd` INSIDE the command persists, exactly like a terminal.
75
127
  const cwd = args.cwd ? expandPath(str(args.cwd)) : undefined;
76
128
  const toRun = cwd ? `( cd ${JSON.stringify(cwd)} && { ${command}; } )` : command;
77
129
  try {
78
- const sess = await getShellSession();
79
- const r = await sess.run(toRun, timeout);
130
+ const { shellExecMode } = (await nodeImport("./shell-context.js"));
131
+ const mod = (await nodeImport("./shell-session.js"));
132
+ const mode = shellExecMode.getStore() ?? "persistent";
133
+ // Multi-shell rounds (Executor.executeParallel sets mode=ephemeral) must NOT share the persistent
134
+ // FIFO — concurrent stdin/sentinel framing would cross-wire output. One-shot bash overlaps for real.
135
+ // Lone bash stays persistent (cwd/env + ctrl+b detach).
136
+ let r;
137
+ let movedId = "";
138
+ if (mode === "ephemeral") {
139
+ r = await mod.runEphemeralShell(toRun, timeout);
140
+ }
141
+ else {
142
+ const { sess, key } = await getShellSession();
143
+ r = await sess.run(toRun, timeout, { onDetach: (run) => { movedId = newJobId(); adoptDetached(key, run, movedId, mod.ShellSession, mod.processCwd); } });
144
+ }
80
145
  let out = r.output || "";
81
- const { shellResultNotes } = await import("./shell-session.js");
146
+ if (r.detached) {
147
+ const sofar = out ? `\nOutput so far:\n${out.split("\n").slice(-20).join("\n")}` : "";
148
+ return `moved to background as ${movedId}: ${command}\nIt keeps running. You will be notified when it finishes, so do not poll. bash_output {"id":"${movedId}"} reads its output, bash_kill {"id":"${movedId}"} stops it.\nThe shell restarted in the same directory (environment variables, functions and aliases from the old shell are not carried over). It is free for your next command.${sofar}`;
149
+ }
150
+ const { shellResultNotes } = mod;
82
151
  if (r.timedOut) {
83
- return (out ? out + "\n" : "") + `[timed out after ${timeout}ms — the shell was reset (cwd/env cleared); narrow the command or pass a larger timeout_ms]`;
152
+ const resetNote = mode === "ephemeral"
153
+ ? `[timed out after ${timeout}ms — ephemeral shell killed; run long commands with shell_background instead]`
154
+ : r.reset
155
+ ? `[timed out after ${timeout}ms — the command was killed and the shell had to be reset (cwd/env cleared); run long commands with shell_background instead]`
156
+ : `[timed out after ${timeout}ms — the command was killed; the shell is still alive (cwd/env kept). Run long commands with shell_background instead of raising timeout_ms]`;
157
+ const stdinHint = out && mode !== "ephemeral" ? "\n[output arrived but the command never finished: it may be waiting on stdin — interactive input is not supported (stdin is /dev/null); use non-interactive flags, e.g. ssh -n or -o BatchMode=yes]" : "";
158
+ return (out ? out + "\n" : "") + resetNote + stdinHint;
84
159
  }
85
160
  if (r.truncated)
86
161
  out += `\n[output truncated at 8MB — narrow it: add a path, pipe to \`head\`, or use \`grep -l\`/\`grep -c\`]`;
@@ -266,11 +341,17 @@ async function sessionHandoff(args) {
266
341
  return `error: ${e.message}`;
267
342
  }
268
343
  }
344
+ // Content-search wall clock. Was 300s — a home-wide path looked "hung" for ~5 minutes in the TUI.
345
+ // Narrow scopes finish in well under this; broad scopes are refused by assertContentSearchScope.
346
+ const CONTENT_SEARCH_TIMEOUT_MS = 20_000;
269
347
  async function grepSearch(args) {
270
348
  const pattern = str(args.pattern);
271
349
  const path = expandPath(str(args.path, "."));
272
350
  if (!pattern)
273
351
  return "error: no pattern given";
352
+ const scopeErr = assertContentSearchScope(path);
353
+ if (scopeErr)
354
+ return scopeErr;
274
355
  // -s suppresses errors for unreadable/special files (sockets, FIFOs, permission-denied) that a
275
356
  // recursive grep over a real dir (e.g. /private/tmp, full of IPC sockets) inevitably hits; without it
276
357
  // grep exits 2 and the tool used to report a hard failure even when it HAD found matches.
@@ -282,7 +363,7 @@ async function grepSearch(args) {
282
363
  // errors immediately, but a FIFO with no writer hangs grep on open forever. Killed grep still leaves
283
364
  // whatever it matched in stdout (handled in the catch), so a real dir with a stray pipe can't wedge
284
365
  // the agent.
285
- const { stdout } = await pexecFile("grep", [...flags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: 300_000, killSignal: "SIGKILL" });
366
+ const { stdout } = await pexecFile("grep", [...flags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: CONTENT_SEARCH_TIMEOUT_MS, killSignal: "SIGKILL" });
286
367
  return capMatches(stdout);
287
368
  }
288
369
  catch (e) {
@@ -343,6 +424,9 @@ async function ripgrepSearch(args) {
343
424
  const path = expandPath(str(args.path, "."));
344
425
  if (!pattern)
345
426
  return "error: no pattern given";
427
+ const scopeErr = assertContentSearchScope(path);
428
+ if (scopeErr)
429
+ return scopeErr;
346
430
  const filesOnly = !!args.files_with_matches;
347
431
  const glob = args.glob ? str(args.glob) : "";
348
432
  // Belt-and-suspenders over rg -g / grep --include: always JS-filter the output by the glob too.
@@ -355,7 +439,7 @@ async function ripgrepSearch(args) {
355
439
  if (glob)
356
440
  gflags.push(`--include=${glob}`);
357
441
  try {
358
- const { stdout } = await pexecFile("grep", [...gflags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: 300_000, killSignal: "SIGKILL" });
442
+ const { stdout } = await pexecFile("grep", [...gflags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: CONTENT_SEARCH_TIMEOUT_MS, killSignal: "SIGKILL" });
359
443
  return capG(stdout);
360
444
  }
361
445
  catch (ge) {
@@ -374,7 +458,7 @@ async function ripgrepSearch(args) {
374
458
  rgArgs.push("-g", glob);
375
459
  rgArgs.push("-e", pattern, path);
376
460
  try {
377
- const { stdout } = await pexecFile("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024, timeout: 300_000, killSignal: "SIGKILL" });
461
+ const { stdout } = await pexecFile("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024, timeout: CONTENT_SEARCH_TIMEOUT_MS, killSignal: "SIGKILL" });
378
462
  return capG(stdout);
379
463
  }
380
464
  catch (e) {
@@ -440,21 +524,37 @@ async function gitStatus(args) {
440
524
  // isolation default — is honored however late it is set; an eager `new MemoryStore()` resolved the prod
441
525
  // path before any test could redirect it.
442
526
  let _memoryStore;
443
- const memory = () => (_memoryStore ??= new MemoryStore());
527
+ /** The tools' shared memory surface. Settings load lazily (node-only) so this stays out of the neutral
528
+ * browser graph; a node-free host — or no `memory.providers` configured — gets the bare MemoryStore,
529
+ * byte-identical to the pre-provider engine. Built once, like the old singleton. */
530
+ const memory = async () => {
531
+ if (_memoryStore)
532
+ return _memoryStore;
533
+ let cfg;
534
+ try {
535
+ const { loadSettings } = await nodeImport("../config/settings.js"); // variable-specifier load keeps settings out of the browser graph
536
+ cfg = loadSettings().memory;
537
+ }
538
+ catch { /* node-free host — local store only */ }
539
+ return (_memoryStore = buildMemory(cfg));
540
+ };
444
541
  async function memoryStore(args) {
445
542
  const text = str(args.text);
446
543
  if (!text)
447
544
  return "error: no text given";
448
545
  const tags = Array.isArray(args.tags) ? args.tags.map(String) : [];
449
- const ok = await memory().capture(text, tags);
450
- return ok ? `stored memory (${tags.join(",") || "no tags"})` : "error: could not store memory";
546
+ const supersedes = str(args.supersedes) || undefined;
547
+ const ok = await (await memory()).capture(text, tags, supersedes);
548
+ if (!ok)
549
+ return "error: could not store memory";
550
+ return `stored memory (${tags.join(",") || "no tags"})` + (supersedes ? `, superseding ${supersedes}` : "");
451
551
  }
452
552
  async function memorySearch(args) {
453
553
  const query = str(args.query);
454
554
  const limit = Number(args.limit ?? 10);
455
- const hits = await memory().recall(query || undefined, limit);
555
+ const hits = await (await memory()).recall(query || undefined, limit);
456
556
  return hits.length
457
- ? hits.map(h => `[${new Date(h.ts).toISOString()}] ${h.text}`).join("\n")
557
+ ? hits.map(h => `[${h.id ?? "no-id"}] [${new Date(h.ts).toISOString()}] ${h.text}`).join("\n")
458
558
  : "(no matches)";
459
559
  }
460
560
  // Git run for checkpoints, HARDENED so a checkpoint can never freeze the session (the "checkpoint… spins
@@ -539,7 +639,7 @@ async function checkpoint(args) {
539
639
  const { stdout: sha } = await checkpointGit(["rev-parse", "--short", "HEAD"], workspace, 10_000);
540
640
  if (push)
541
641
  await checkpointGit(["push"], workspace, 120_000);
542
- await memory().capture(summary, ["checkpoint", workspace]);
642
+ await (await memory()).capture(summary, ["checkpoint", workspace]);
543
643
  return `checkpoint ${sha.trim()} — ${summary}${initialized ? " (new git repo initialized here)" : ""}${push ? " (pushed)" : ""}`;
544
644
  }
545
645
  catch (e) {
@@ -629,6 +729,45 @@ async function webSearch(args) {
629
729
  clearTimeout(timer);
630
730
  }
631
731
  }
732
+ // Knowledge search — queries the vector knowledge base for semantic retrieval. safe/read-only.
733
+ // The wire client, config-resolution chain (env → operator-home kb.json → operator-named dotenv →
734
+ // unconfigured; decision 2026-10-21-config-resolution) and error taxonomy live in
735
+ // memory/skylark.ts — the ONE Skylark client, shared with the `skylark` memory provider
736
+ // (PV2-34 branch 2) so the tree never grows a second drifting implementation. This wrapper only
737
+ // maps the typed result onto the tool's user-facing strings.
738
+ async function knowledgeSearch(args) {
739
+ const q = str(args.query ?? args.q);
740
+ if (!q)
741
+ return "error: knowledge_search needs a query";
742
+ const n = Math.min(Math.max(Number(args.n ?? args.count ?? 5), 1), 20);
743
+ const { skylarkSearch } = await import("../memory/skylark.js");
744
+ const r = await skylarkSearch(q, n, Number(args.timeout_ms ?? 15_000));
745
+ if (!r.ok) {
746
+ switch (r.error) {
747
+ case "unconfigured":
748
+ // Branding boundary: actionable WITHOUT leaking internal env names or absolute paths — the
749
+ // full resolution chain (env overrides included) is documented in the README's Knowledge
750
+ // base section; the error points at the zero-knowledge-needed option only.
751
+ return 'error: knowledge_search — no access token configured. Add {"token": "…"} to kb.json ' +
752
+ "in the Operator home (chmod 600) — the README's Knowledge base section covers every option.";
753
+ case "unauthorized":
754
+ return "error: knowledge_search — knowledge base access token rejected (401)";
755
+ case "http":
756
+ return `error: knowledge_search — KB returned ${r.detail}. Is Skylark running?`;
757
+ case "timeout":
758
+ return "error searching knowledge base: timed out";
759
+ default:
760
+ return `error searching knowledge base: ${r.detail ?? "network failure"}`;
761
+ }
762
+ }
763
+ if (!r.hits.length)
764
+ return "(no results in knowledge base)";
765
+ const out = r.hits.slice(0, n).map((h, i) => {
766
+ const snippet = String(h.text ?? "").replace(/\s+/g, " ").slice(0, 300);
767
+ return `${i + 1}. ${h.source}\n distance: ${h.distance.toFixed(4)}\n ${snippet}`;
768
+ }).join("\n\n");
769
+ return out || "(no results)";
770
+ }
632
771
  // Retry a bot-blocked fetch through the AXE autopilot's real-browser /markdown route — same
633
772
  // KODE_AUTOPILOT_URL backend web_search's /serp uses. Returns rendered markdown, or null if no
634
773
  // backend is configured, the request fails, or the response has no usable body.
@@ -956,44 +1095,175 @@ async function fileUpload(args) {
956
1095
  clearTimeout(timer);
957
1096
  }
958
1097
  }
959
- const bgJobs = new Map();
960
- let bgSeq = 0;
961
- const BG_MAX_RUNNING = 8; // cap concurrent live jobs — a background tool must never let the agent fork-bomb the host
962
- const BG_KEEP_FINISHED = 16; // retain a bounded history of finished jobs so bash_output can still report an exit
963
- const BG_BUF_CAP = 200_000; // per-job ring: keep the last ~200KB so a chatty job can't grow memory without bound
964
- // Drop the oldest finished jobs once we exceed the retention budget — keeps `bgJobs` from growing across a
965
- // long session. Running jobs are never pruned; insertion order (Map) makes "oldest finished" cheap.
966
- function pruneBgJobs() {
967
- const finished = [...bgJobs.entries()].filter(([, j]) => j.done);
968
- for (let i = 0; i < finished.length - BG_KEEP_FINISHED; i++)
969
- bgJobs.delete(finished[i][0]);
1098
+ // download_file (tools/download.ts): the one supported way to fetch a file to disk — fails loudly, resumes, verifies, never leaves a
1099
+ // half file at the final name. Runs as a tracked background job by default (same ids, bash_output, bash_kill, /jobs, completion
1100
+ // notice as shell_background) because real downloads outlast a turn; background:false waits (bounded) and returns the result.
1101
+ async function downloadFileTool(args) {
1102
+ // Node-only module: loaded through the opaque nodeImport so it never enters the neutral (mobile/JSCore) bundle graph.
1103
+ const { downloadFile } = (await nodeImport("./download.js"));
1104
+ const url = str(args.url);
1105
+ const dest = str(args.dest);
1106
+ if (!url)
1107
+ return "error: no url given";
1108
+ if (!dest)
1109
+ return "error: no dest given (a file path, or a directory ending in /)";
1110
+ const opts = {
1111
+ url, dest: expandPath(dest), overwrite: args.overwrite === true,
1112
+ sha256: args.sha256 ? str(args.sha256) : undefined,
1113
+ expectedBytes: typeof args.expected_bytes === "number" ? args.expected_bytes : undefined,
1114
+ headers: args.headers && typeof args.headers === "object" ? args.headers : undefined,
1115
+ };
1116
+ if (args.background === false) {
1117
+ const ac = new AbortController();
1118
+ const cap = typeof args.timeout_ms === "number" ? args.timeout_ms : 120_000;
1119
+ const timer = setTimeout(() => ac.abort(), cap);
1120
+ try {
1121
+ const r = await downloadFile({ ...opts, signal: ac.signal });
1122
+ return r.message === "cancelled" ? `stopped after ${Math.round(cap / 1000)}s — a partial file is kept; call download_file again (background:true) to continue it` : r.message;
1123
+ }
1124
+ finally {
1125
+ clearTimeout(timer);
1126
+ }
1127
+ }
1128
+ pruneShellJobs();
1129
+ if (runningJobCount() >= BG_MAX_RUNNING)
1130
+ return `error: ${BG_MAX_RUNNING} background jobs already running — bash_kill one before starting another`;
1131
+ const id = newJobId();
1132
+ const ac = new AbortController();
1133
+ const job = createJob(id, `download_file ${url} -> ${opts.dest}`, { kill: () => ac.abort() }, "background");
1134
+ let last = 0;
1135
+ void downloadFile({
1136
+ ...opts, signal: ac.signal,
1137
+ onProgress: (p) => {
1138
+ const now = Date.now();
1139
+ if (now - last < 5000)
1140
+ return;
1141
+ last = now;
1142
+ trackJobOutput(job, `${p.total ? `${Math.round((p.bytes / p.total) * 100)}% ` : ""}${(p.bytes / 1e6).toFixed(1)} MB${p.total ? ` of ${(p.total / 1e6).toFixed(1)} MB` : ""} · ${(p.bytesPerSec / 1e6).toFixed(1)} MB/s\n`);
1143
+ },
1144
+ }).then((r) => { trackJobOutput(job, `${r.message}\n`); finishJob(job, r.ok ? 0 : 1); }, (e) => { trackJobOutput(job, `error: ${e.message}\n`); finishJob(job, 1); });
1145
+ return `started download job ${id}: ${url} -> ${opts.dest}\nYou will be notified when it finishes (the notice carries the final size and sha256, or the error), so do not poll. Progress: bash_output {"id":"${id}"}; stop: bash_kill {"id":"${id}"}. Do NOT claim it is downloaded until the notice says so.`;
970
1146
  }
1147
+ // --- Background / detached shell (checklist gap: shell_exec is synchronous with a timeout only). For a
1148
+ // long-running command, shell_background spawns it detached, buffers output, and returns a job id to poll
1149
+ // with bash_output or stop with bash_kill (the BashOutput/KillShell analog). Runs under the same OS
1150
+ // sandbox wrap as shell_exec. child_process loads lazily (neutral bundle).
971
1151
  async function shellBackground(args) {
972
1152
  const command = str(args.command);
973
1153
  if (!command)
974
1154
  return "error: no command given";
975
- pruneBgJobs();
976
- const running = [...bgJobs.values()].filter((j) => !j.done).length;
977
- if (running >= BG_MAX_RUNNING)
1155
+ const homeWide = assertShellHomeWideSearch(command);
1156
+ if (homeWide)
1157
+ return homeWide;
1158
+ const blind = assertShellBlindDownload(command);
1159
+ if (blind)
1160
+ return blind;
1161
+ pruneShellJobs();
1162
+ if (runningJobCount() >= BG_MAX_RUNNING)
978
1163
  return `error: ${BG_MAX_RUNNING} background jobs already running — bash_kill one before starting another`;
979
1164
  const cwd = args.cwd ? expandPath(str(args.cwd)) : undefined;
980
1165
  const { spawn } = await nodeImport("node:child_process");
981
1166
  const { file, args: argv } = await wrapShell(command); // same OS sandbox wrap as shell_exec
982
- const id = `sh${++bgSeq}`;
1167
+ const id = newJobId();
983
1168
  // Its own process group, so the WHOLE job tree (`npm run dev` → node → …) can be stopped, not just the top shell. It used to be
984
1169
  // "not detached: the job dies with Operator" — it did not: a running job outlived /exit, held the event loop open (Operator froze
985
1170
  // after /exit) and was orphaned. Owned now: killed at exit, reaped by the next Operator if this one crashes.
986
1171
  const p = spawn(file, argv, { cwd, detached: true });
987
1172
  ownChild(p, `background job ${id}`, { cmd: `${file} ${argv.join(" ")}`, group: true });
988
- const job = { proc: p, buf: "", done: false, code: null, started: Date.now(), cmd: command };
989
- const cap = (d) => { job.buf += d.toString("utf8"); if (job.buf.length > BG_BUF_CAP)
990
- job.buf = job.buf.slice(-BG_BUF_CAP); };
1173
+ const job = createJob(id, command, p, "background");
1174
+ if (typeof args.description === "string" && args.description)
1175
+ job.description = args.description;
1176
+ const cap = (d) => trackJobOutput(job, d.toString("utf8"));
991
1177
  p.stdout?.on("data", cap);
992
1178
  p.stderr?.on("data", cap);
993
- p.on("close", (c) => { job.done = true; job.code = c; });
994
- p.on("error", (e) => { job.buf += `\n[spawn error: ${e.message}]`; job.done = true; job.code = -1; });
995
- bgJobs.set(id, job);
996
- return `started background job ${id}: ${command}\nPoll it with bash_output {"id":"${id}"}; stop it with bash_kill {"id":"${id}"}.`;
1179
+ p.on("close", (c) => finishJob(job, c));
1180
+ p.on("error", (e) => { trackJobOutput(job, `\n[spawn error: ${e.message}]`); finishJob(job, -1); });
1181
+ const label = job.description ? ` (${job.description})` : "";
1182
+ return `started background job ${id}${label}: ${command}\nYou will be notified when it finishes, so do not poll. Read output with bash_output {"id":"${id}"}; stop it with bash_kill {"id":"${id}"}.`;
1183
+ }
1184
+ async function verifyPipeline(args) {
1185
+ const stages = args.stages;
1186
+ if (!Array.isArray(stages) || !stages.length)
1187
+ return "error: stages must be a non-empty array";
1188
+ const parts = [];
1189
+ let passed = 0;
1190
+ const total = stages.length;
1191
+ for (const stage of stages) {
1192
+ const label = str(stage.label) || "unnamed";
1193
+ const command = str(stage.command);
1194
+ if (!command) {
1195
+ parts.push(`\n=== ${label.toUpperCase()} SKIPPED (no command) ===`);
1196
+ continue;
1197
+ }
1198
+ const timeout = Number(stage.timeout_ms ?? 120_000);
1199
+ const expect = str(stage.expect) || "zero";
1200
+ parts.push(`\n=== ${label.toUpperCase()} ===`);
1201
+ const result = await shellExec({ command, timeout_ms: timeout });
1202
+ const exitMatch = result.match(/\[exit (\d+)\]$/);
1203
+ const exitCode = exitMatch ? parseInt(exitMatch[1], 10) : (result.includes("(no output)") ? 0 : 0);
1204
+ const failed = expect === "zero"
1205
+ ? result.includes("[exit ") && exitCode !== 0
1206
+ : !result || result === "(no output)";
1207
+ if (result.length > 2000) {
1208
+ const head = result.slice(0, 800);
1209
+ const tail = result.slice(-800);
1210
+ parts.push(head + `\n... (${result.length - 1600} chars omitted) ...\n` + tail);
1211
+ }
1212
+ else {
1213
+ parts.push(result);
1214
+ }
1215
+ if (failed) {
1216
+ parts.push(`\n=== ${label.toUpperCase()} FAILED ===`);
1217
+ parts.push(`\nPipeline aborted at stage ${passed + 1}/${total}. ${passed} passed, ${total - passed - 1} skipped.`);
1218
+ return parts.join("\n");
1219
+ }
1220
+ passed++;
1221
+ parts.push(`=== ${label.toUpperCase()} PASSED ===`);
1222
+ }
1223
+ parts.push(`\n=== ALL ${total} STAGES PASSED ===`);
1224
+ return parts.join("\n");
1225
+ }
1226
+ async function briefUpdate(args) {
1227
+ const filePath = expandPath(str(args.path));
1228
+ if (!filePath)
1229
+ return "error: no path given";
1230
+ const section = str(args.section);
1231
+ if (!section)
1232
+ return "error: no section given";
1233
+ const content = str(args.content);
1234
+ if (!content)
1235
+ return "error: no content given";
1236
+ const mode = str(args.mode) || "replace";
1237
+ const { readFile, writeFile, mkdir } = await nodeImport("node:fs/promises");
1238
+ const { dirname } = await nodeImport("node:path");
1239
+ const heading = `## ${section}`;
1240
+ let body;
1241
+ try {
1242
+ body = await readFile(filePath, "utf8");
1243
+ }
1244
+ catch {
1245
+ await mkdir(dirname(filePath), { recursive: true });
1246
+ const ts = new Date().toISOString().slice(0, 10);
1247
+ body = `# Brief\n\n_Created ${ts}_\n\n`;
1248
+ }
1249
+ const headingIdx = body.indexOf(heading);
1250
+ if (headingIdx >= 0) {
1251
+ const afterHeading = headingIdx + heading.length;
1252
+ const nextH2 = body.indexOf("\n## ", afterHeading);
1253
+ const sectionEnd = nextH2 >= 0 ? nextH2 : body.length;
1254
+ if (mode === "append") {
1255
+ const existing = body.slice(afterHeading, sectionEnd);
1256
+ body = body.slice(0, sectionEnd) + "\n" + content + "\n" + body.slice(sectionEnd);
1257
+ }
1258
+ else {
1259
+ body = body.slice(0, afterHeading) + "\n\n" + content + "\n" + body.slice(sectionEnd);
1260
+ }
1261
+ }
1262
+ else {
1263
+ body = body.trimEnd() + "\n\n" + heading + "\n\n" + content + "\n";
1264
+ }
1265
+ await writeFile(filePath, body);
1266
+ return `updated section "${section}" in ${filePath} (${mode})`;
997
1267
  }
998
1268
  // A spawn_agent sub-agent id ("agent-1", "agent-2", …) is a DIFFERENT registry than shell_background's
999
1269
  // own job ids ("sh1", "sh2", …) — bash_output/bash_kill only ever know the latter. A model that spawned a
@@ -1014,7 +1284,7 @@ async function bashOutput(args) {
1014
1284
  const redirect = subAgentRedirect(id);
1015
1285
  if (redirect)
1016
1286
  return redirect;
1017
- const job = bgJobs.get(id);
1287
+ const job = shellJobs.get(id);
1018
1288
  if (!job)
1019
1289
  return `error: no background job "${id}" (list ids from shell_background's return)`;
1020
1290
  const out = job.buf;
@@ -1027,28 +1297,7 @@ async function bashKill(args) {
1027
1297
  const redirect = subAgentRedirect(id);
1028
1298
  if (redirect)
1029
1299
  return redirect;
1030
- const job = bgJobs.get(id);
1031
- if (!job)
1032
- return `error: no background job "${id}"`;
1033
- if (job.done)
1034
- return `job ${id} already finished (exit ${job.code})`;
1035
- try {
1036
- const pid = job.proc.pid;
1037
- if (pid) {
1038
- try {
1039
- process.kill(-pid, "SIGTERM");
1040
- }
1041
- catch {
1042
- job.proc.kill("SIGTERM");
1043
- }
1044
- } // the whole job group, falling back to the top process
1045
- else
1046
- job.proc.kill("SIGTERM");
1047
- return `sent SIGTERM to background job ${id}`;
1048
- }
1049
- catch (e) {
1050
- return `error killing ${id}: ${e?.message ?? e}`;
1051
- }
1300
+ return stopShellJob(id);
1052
1301
  }
1053
1302
  const agentTasks = [];
1054
1303
  let taskSeq = 0;
@@ -1359,7 +1608,7 @@ async function videoGenerate(args) {
1359
1608
  // image_analyze — real vision. Calls the fleet VL model (Qwen2-VL, OpenAI-vision /v1/chat/completions) so
1360
1609
  // Operator can SEE an image (a reference, screenshot, or generated output) instead of guessing from file
1361
1610
  // size / numpy brightness. A served model on a dedicated node — never loads a VL model inline on this box.
1362
- // Enterprise-grade vision plumbing (mirrors Hermes' vision_tools.py strategy, adapted for a single-threaded
1611
+ // Enterprise-grade vision plumbing (mirrors the Python core's vision_tools.py strategy, adapted for a single-threaded
1363
1612
  // local 7B). Three parts: (1) proactive downscale — a VL model's cost scales with pixels, and full-res
1364
1613
  // (3680x2392 ~78s) stalls the worker past the timeout, which also blocks its /health and cascades retries
1365
1614
  // into "no vision service reachable"; downscaling the long edge to 1568px is a measured ~10x speedup with no
@@ -1371,22 +1620,30 @@ const VISION_COOLDOWN_MS = Math.max(10_000, Number(process.env.KODE_VISION_COOLD
1371
1620
  const visionUnhealthy = new Map(); // base url -> epoch ms it may be retried after
1372
1621
  /** Vision endpoints in priority order: KODE_VISION_URL, the fleet Qwen2-VL worker (JL1), then an optional
1373
1622
  * cloud fallback. Each carries its own auth + model; local targets get a /health gate, cloud targets don't. */
1374
- function visionTargets() {
1623
+ function visionTargets(settings) {
1375
1624
  const seen = new Set();
1376
1625
  const out = [];
1377
1626
  const add = (u, auth, model, label) => {
1378
1627
  if (!u)
1379
1628
  return;
1380
- const url = u.replace(/\/$/, "");
1381
- if (seen.has(url))
1629
+ const url = u.trim().replace(/\/$/, "");
1630
+ if (!url || seen.has(url))
1382
1631
  return;
1383
1632
  seen.add(url);
1384
1633
  const local = /\/\/(127\.0\.0\.1|localhost|192\.168\.|10\.|\[?::1)/.test(url) || /\.local(:|\/|$)/.test(url);
1385
1634
  out.push({ url, auth, model, local, label });
1386
1635
  };
1387
- add(process.env.KODE_VISION_URL, mediaAuth(), undefined, "vision-url");
1388
- add("http://192.168.1.103:8095", mediaAuth(), undefined, "fleet-jl1"); // Qwen2-VL-7B-Instruct-4bit (mlx_vlm.server) on JL1
1389
- add(process.env.KODE_VISION_FALLBACK_URL, process.env.KODE_VISION_FALLBACK_KEY ? { Authorization: `Bearer ${process.env.KODE_VISION_FALLBACK_KEY}` } : {}, process.env.KODE_VISION_FALLBACK_MODEL || undefined, "cloud-fallback");
1636
+ // Priority order, every source explicit — no baked endpoints. A loopback target gets a /health gate + the
1637
+ // point-of-need auto-on; a remote one is tried as-is. settings carries the real URLs (services.vision.*),
1638
+ // so a different box/deploy is one config edit, not a code change. The local worker is tried BEFORE the
1639
+ // remote fleet node: it's on THIS box (zero LAN cost, revivable), and omitting it was the bug that sent
1640
+ // image_analyze straight to a possibly-down remote node with no local fallback.
1641
+ const v = settings.services?.vision;
1642
+ add(process.env.KODE_VISION_URL, mediaAuth(), undefined, "env-override"); // explicit hard override
1643
+ add(v?.url, mediaAuth(), undefined, "local"); // this box's managed worker (loopback → auto-on)
1644
+ add(v?.remoteUrl, mediaAuth(), undefined, "remote"); // LAN fallback (another fleet node)
1645
+ add(process.env.KODE_VISION_FALLBACK_URL, // cloud fallback (never health-gated)
1646
+ process.env.KODE_VISION_FALLBACK_KEY ? { Authorization: `Bearer ${process.env.KODE_VISION_FALLBACK_KEY}` } : {}, process.env.KODE_VISION_FALLBACK_MODEL || undefined, "cloud-fallback");
1390
1647
  return out;
1391
1648
  }
1392
1649
  /** Read a local image, downscaling its long edge to VISION_MAX_EDGE first (macOS `sips`, then `ffmpeg`, then
@@ -1480,7 +1737,8 @@ async function visionImageDataUrl(image) {
1480
1737
  * each independently, retry once on an empty body, and on timeout / 402 / 429 / auth-error mark the target
1481
1738
  * unhealthy for a TTL and fall through to the next. Throws with the last error only when all are exhausted. */
1482
1739
  async function visionComplete(parts, args, defaultTimeoutMs) {
1483
- const targets = visionTargets();
1740
+ const { loadSettings } = await nodeImport("../config/settings.js"); // variable-specifier load keeps settings out of the browser graph
1741
+ const targets = visionTargets(loadSettings());
1484
1742
  const timeout = Math.max(5_000, Number(args.timeout_ms ?? defaultTimeoutMs));
1485
1743
  const now = () => Date.now();
1486
1744
  let lastErr = `no vision service reachable (tried ${targets.map((t) => t.url).join(", ")})`;
@@ -1490,9 +1748,17 @@ async function visionComplete(parts, args, defaultTimeoutMs) {
1490
1748
  continue;
1491
1749
  }
1492
1750
  if (t.local && !(await imageHealthy(t.url))) {
1493
- visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
1494
- lastErr = `${t.label} health check failed at ${t.url}`;
1495
- continue;
1751
+ // Media pipeline is off BY DEFAULT (ADR 2026-10-19 — GPU stays with Aurora), so a dead LOCAL vision
1752
+ // worker is the EXPECTED state, not an outage: bring it up at point of need (single-flight; repairs a
1753
+ // launchd-disabled job too) and re-probe before condemning the target. Loopback only — a remote LAN
1754
+ // worker (JL1) isn't served by this box's launchd job.
1755
+ const loopback = /\/\/(127\.0\.0\.1|localhost|\[?::1)/.test(t.url);
1756
+ const revived = loopback && await import("../services/preflight.js").then((m) => m.ensureVisionUp(t.url)).catch(() => false);
1757
+ if (!(revived && await imageHealthy(t.url))) {
1758
+ visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
1759
+ lastErr = `${t.label} health check failed at ${t.url}`;
1760
+ continue;
1761
+ }
1496
1762
  }
1497
1763
  const model = str(args.model) || t.model || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
1498
1764
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -1871,15 +2137,19 @@ const TOOLS = [
1871
2137
  "in one call is still in effect on the next. So set things up ONCE and reuse them — do NOT " +
1872
2138
  "re-run `source .../activate && ...` or re-`cd` on every call; activate/enter once, then just " +
1873
2139
  "run the command. stdout and stderr come back merged (like a terminal) with the exit code. " +
1874
- "Optional `cwd` runs that one command in a subshell without moving the session. For a " +
1875
- "long-running server/build/watcher use shell_background instead so this shell isn't blocked. " +
2140
+ "Optional `cwd` runs that one command in a subshell without moving the session. For anything " +
2141
+ "that can run more than ~2 minutes -- a server/build/watcher, but ALSO a full test suite or any " +
2142
+ "other verification run -- use shell_background instead of guessing a bigger timeout_ms; a timeout " +
2143
+ "here kills the command (and resets this shell's cwd/env only if bash itself wedges). Known-long commands (installs, builds, test suites, downloads) are auto-started as background jobs. " +
2144
+ "If the user presses ctrl+b while this runs, it moves to the background (shN) and you are told when it finishes; do not poll. " +
1876
2145
  "Pipelines run with `set -o pipefail`: if ANY stage fails the pipeline fails and you see [exit N] — a check hidden behind `| tail` can never fake success. " +
1877
2146
  "Prefer SINGLE quotes for patterns and paths (grep -l '^x', not grep -l \"^x\"): a raw double-quote " +
1878
2147
  "inside the command can break tool-call serialization on the local model and make the call fail.",
1879
2148
  parameters: { type: "object", properties: {
1880
2149
  command: { type: "string", description: "the bash command to run in the persistent shell" },
2150
+ description: { type: "string", description: "plain-English label for what this command does (shown in the UI as a summary tag)" },
1881
2151
  cwd: { type: "string", description: "optional: run this one command from here (scoped; does not move the session)" },
1882
- timeout_ms: { type: "number", description: "optional per-command timeout (default 120000); on timeout the shell is reset" },
2152
+ timeout_ms: { type: "number", description: "optional per-command timeout (default 120000); on timeout the command is killed (the shell is kept unless it wedges) -- for a command that may legitimately run long (a full test suite, a build), use shell_background instead of raising this" },
1883
2153
  }, required: ["command"] },
1884
2154
  run: shellExec,
1885
2155
  },
@@ -1888,28 +2158,76 @@ const TOOLS = [
1888
2158
  name: "shell_exec", safe: false,
1889
2159
  description: "Alias of `bash` — runs a command in the same persistent shell session (state persists across calls).",
1890
2160
  parameters: { type: "object", properties: {
1891
- command: { type: "string" }, cwd: { type: "string" }, timeout_ms: { type: "number" },
2161
+ command: { type: "string" }, description: { type: "string" }, cwd: { type: "string" }, timeout_ms: { type: "number" },
1892
2162
  }, required: ["command"] },
1893
2163
  run: shellExec,
1894
2164
  },
1895
2165
  {
1896
2166
  name: "shell_background", safe: false,
1897
- description: "Start a long-running shell command DETACHED and return a job id immediately (does not block). Poll it with bash_output, stop it with bash_kill. Use for servers, builds, watchers.",
1898
- parameters: { type: "object", properties: { command: { type: "string" }, cwd: { type: "string" } }, required: ["command"] },
2167
+ description: "Start a long-running shell command DETACHED and return a job id immediately (does not block). Use it from the start for servers, builds, watchers, and for a full test suite or any verification run expected to take more than ~2 minutes -- bash's foreground timeout would otherwise kill it AND reset the shell's cwd/env. You are notified when it finishes, so do not poll in a loop; read output with bash_output, stop it with bash_kill.",
2168
+ parameters: { type: "object", properties: { command: { type: "string" }, description: { type: "string" }, cwd: { type: "string" } }, required: ["command"] },
1899
2169
  run: shellBackground,
1900
2170
  },
2171
+ {
2172
+ name: "download_file", safe: false,
2173
+ description: "Download a URL to disk, correctly. USE THIS instead of curl/wget in bash: it fails loudly on any HTTP error (404/403/5xx), resumes a partial file, retries network drops and stalls, refuses an HTML page that is standing in for the file (the classic silent failure), checks the size and, when you pass sha256, the hash, and only then renames onto dest, so a half download never sits at the final name. Runs in the BACKGROUND by default (job id like shell_background; you are notified on completion with the final size + sha256, or the exact error) — start downloads one at a time and never report one as done until that notice arrives. `dest` is a file path, or a directory ending in `/` (the name comes from the URL). Pass `sha256` / `expected_bytes` whenever a trustworthy value exists. background:false waits up to timeout_ms (default 120000) — only for small files.",
2174
+ parameters: { type: "object", properties: {
2175
+ url: { type: "string", description: "http(s) URL" },
2176
+ dest: { type: "string", description: "file path, or a directory ending in /" },
2177
+ sha256: { type: "string", description: "expected SHA-256 (64 hex); a mismatch deletes the download" },
2178
+ expected_bytes: { type: "number" },
2179
+ overwrite: { type: "boolean", description: "replace an existing dest (default false: refuse)" },
2180
+ background: { type: "boolean", description: "default true; false waits for the result" },
2181
+ timeout_ms: { type: "number", description: "only with background:false" },
2182
+ headers: { type: "object", description: "extra request headers, e.g. {\"authorization\": \"Bearer …\"}" },
2183
+ }, required: ["url", "dest"] },
2184
+ run: downloadFileTool,
2185
+ },
1901
2186
  {
1902
2187
  name: "bash_output", safe: true,
1903
- description: "Read new stdout/stderr from a background job started by shell_background (drains what's arrived since the last poll) and whether it's still running. NOT for a spawn_agent sub-agent id — use agent_status for those instead.",
2188
+ description: "Read new stdout/stderr from a background shell job (shell_background, or a command moved to the background with ctrl+b; drains what's arrived since the last read) and whether it's still running. A finished job is announced to you, so do not poll. NOT for a spawn_agent sub-agent id — use agent_status for those instead.",
1904
2189
  parameters: { type: "object", properties: { id: { type: "string", description: "the job id from shell_background" } }, required: ["id"] },
1905
2190
  run: bashOutput,
1906
2191
  },
1907
2192
  {
1908
2193
  name: "bash_kill", safe: false,
1909
- description: "Stop a running background job (SIGTERM) started by shell_background.",
2194
+ description: "Stop a running background shell job (SIGTERM): one from shell_background or one moved to the background with ctrl+b.",
1910
2195
  parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
1911
2196
  run: bashKill,
1912
2197
  },
2198
+ {
2199
+ name: "verify_pipeline", safe: false,
2200
+ description: "Run a multi-stage verification pipeline: build → serve → test → screenshot in labeled stages. " +
2201
+ "Each stage runs its command sequentially; if a stage fails the pipeline aborts with the failure. " +
2202
+ "Output is formatted with === STAGE === markers for readability. Use this for end-to-end verification " +
2203
+ "chains where you need structured pass/fail per step.",
2204
+ parameters: { type: "object", properties: {
2205
+ stages: {
2206
+ type: "array",
2207
+ items: { type: "object", properties: {
2208
+ label: { type: "string", description: "human-readable stage name (e.g. 'Type Check', 'Build', 'Test')" },
2209
+ command: { type: "string", description: "bash command to run" },
2210
+ timeout_ms: { type: "number", description: "per-stage timeout (default 120000)" },
2211
+ expect: { type: "string", enum: ["zero", "output"], description: "zero = exit 0 required (default); output = any output is success" },
2212
+ }, required: ["label", "command"] },
2213
+ description: "ordered list of verification stages",
2214
+ },
2215
+ }, required: ["stages"] },
2216
+ run: verifyPipeline,
2217
+ },
2218
+ {
2219
+ name: "brief_update", safe: false,
2220
+ description: "Update a structured _ai-docs brief during verification — write or append to a named section. " +
2221
+ "Creates the file with a standard header if absent. Use this to maintain a living verification " +
2222
+ "document as stages complete.",
2223
+ parameters: { type: "object", properties: {
2224
+ path: { type: "string", description: "path to the _ai-docs brief (e.g. _ai-docs/briefs/my-feature.md)" },
2225
+ section: { type: "string", description: "section heading (e.g. 'Verification', 'Results')" },
2226
+ content: { type: "string", description: "markdown content to write in the section" },
2227
+ mode: { type: "string", enum: ["replace", "append"], description: "replace = overwrite section; append = add below existing content (default: replace)" },
2228
+ }, required: ["path", "section", "content"] },
2229
+ run: briefUpdate,
2230
+ },
1913
2231
  {
1914
2232
  name: "task_add", safe: false,
1915
2233
  description: "Add one or more tasks to the session TODO list (multi-step work tracking the user can see). Give `text` for one or `tasks` (array) for several.",
@@ -2004,15 +2322,36 @@ const TOOLS = [
2004
2322
  },
2005
2323
  {
2006
2324
  name: "search", safe: true,
2007
- description: "Fast code/text search (ripgrep: parallel, .gitignore-aware, skips binaries). ALWAYS prefer this over `find … | grep` for locating things. Scope it to a directory with `path` (default: current dir) — never search the whole home directory. `glob` filters filenames (e.g. \"*.ts\"). Set `files_with_matches` to get just the matching file paths (cheap — locate before you read).",
2325
+ description: "Fast code/text search (ripgrep: parallel, .gitignore-aware, skips binaries). ALWAYS prefer this over `find … | grep` for locating things. Scope it to a directory with `path` (default: current dir). HARD REFUSAL: path may not be $HOME, /, /Users, or other machine-wide roots — those hang for minutes; use find_files for names, or a narrow subtree for content. `glob` filters filenames (e.g. \"*.ts\"). Set `files_with_matches` to get just the matching file paths (cheap — locate before you read).",
2008
2326
  parameters: { type: "object", properties: {
2009
2327
  pattern: { type: "string", description: "regex to search for" },
2010
- path: { type: "string", description: "directory to scope the search to; default is the current dir" },
2328
+ path: { type: "string", description: "directory to scope the search to; default is the current dir. Must NOT be $HOME or /" },
2011
2329
  glob: { type: "string", description: "filename glob filter, e.g. \"*.ts\"" },
2012
2330
  files_with_matches: { type: "boolean", description: "return only the paths of files that match" },
2013
2331
  }, required: ["pattern"] },
2014
2332
  run: ripgrepSearch,
2015
2333
  },
2334
+ {
2335
+ name: "find_files", safe: true,
2336
+ description: "Find files anywhere on the machine by NAME or METADATA (kind, date, size, extension, author, Finder tags) — reads the OS search index (Spotlight / Windows Search / locate), so it is instant and covers the whole home directory by default. Use this for \"where is the file\" questions; use `search` for exact content/regex within a scoped directory. Results are absolute paths, newest first. Pass `path` to scope. `content: true` also matches the index's full-text content. `where` appends a raw backend predicate for power use — Spotlight: `kMDItemPixelHeight > 2000`; Windows Search SQL: `System.ItemType = '.docx'`. If the index is unavailable the tool falls back to scanning ONE directory (`path`, else the current dir) and says so on its first line. `details: true` returns `<path>\\t<size>\\t<modified ISO>\\t<kind>` per hit.",
2337
+ parameters: { type: "object", properties: {
2338
+ query: { type: "string", description: "words or a filename fragment (matches names; with content:true also full-text content)" },
2339
+ name: { type: "string", description: "filename fragment matched on the file name only" },
2340
+ path: { type: "string", description: "scope directory; default: the whole home dir (index) or the current dir (fallback)" },
2341
+ kind: { type: "string", enum: [...KINDS], description: "file kind filter" },
2342
+ modified_within: { type: "string", description: "only files changed within this window, e.g. 30m, 24h, 7d" },
2343
+ limit: { type: "number", description: `max results (default ${FIND_FILES_DEFAULT_LIMIT}, max ${FIND_FILES_MAX_LIMIT})` },
2344
+ content: { type: "boolean", description: "match the index's full-text content too, not only names" },
2345
+ min_size: { type: "string", description: "minimum size, e.g. 500KB, 10MB" },
2346
+ max_size: { type: "string", description: "maximum size, e.g. 1.5GB" },
2347
+ author: { type: "string", description: "document author (index metadata; ignored by the fallback)" },
2348
+ tags: { type: "array", items: { type: "string" }, description: "Finder tags / keywords (index metadata; ignored by the fallback)" },
2349
+ extension: { type: "string", description: "file extension, e.g. pdf" },
2350
+ where: { type: "string", description: "raw backend predicate appended verbatim (Spotlight query syntax or Windows Search SQL WHERE fragment); refused by the fallback" },
2351
+ details: { type: "boolean", description: "one line per hit: path, size, modified ISO, kind" },
2352
+ }, required: ["query"] },
2353
+ run: findFiles,
2354
+ },
2016
2355
  {
2017
2356
  name: "list_directory", safe: true,
2018
2357
  description: "List entries in a directory.",
@@ -2044,7 +2383,7 @@ const TOOLS = [
2044
2383
  },
2045
2384
  {
2046
2385
  name: "memory_search", safe: true,
2047
- description: "Search stored memory notes by substring/tag match, most recent first.",
2386
+ description: "Search stored memory notes by substring/tag match, most recent first. Each result's leading [id] is what you pass to memory_store's `supersedes` to retract/correct it.",
2048
2387
  parameters: { type: "object", properties: {
2049
2388
  query: { type: "string" }, limit: { type: "number" },
2050
2389
  } },
@@ -2052,9 +2391,10 @@ const TOOLS = [
2052
2391
  },
2053
2392
  {
2054
2393
  name: "memory_store", safe: false,
2055
- description: "Store a durable memory note with optional tags.",
2394
+ description: "Store a durable memory note with optional tags. If a stored note turns out to be wrong or outdated, don't just add a corrected note beside it -- pass `supersedes` (the [id] from memory_search) so the old one stops surfacing in future recall. Nothing is deleted (the old note stays on disk for history), it's just excluded going forward.",
2056
2395
  parameters: { type: "object", properties: {
2057
2396
  text: { type: "string" }, tags: { type: "array", items: { type: "string" } },
2397
+ supersedes: { type: "string", description: "id (from memory_search's [id]) of an earlier note this one corrects or retracts" },
2058
2398
  }, required: ["text"] },
2059
2399
  run: memoryStore,
2060
2400
  },
@@ -2107,6 +2447,16 @@ const TOOLS = [
2107
2447
  }, required: ["query"] },
2108
2448
  run: webSearch,
2109
2449
  },
2450
+ {
2451
+ name: "knowledge_search", safe: true,
2452
+ description: "Search the local Skylark knowledge base (vector KB) for semantic retrieval. Returns top hits with source, distance, and snippet. Use for retrieving past work, project context, and stored facts.",
2453
+ parameters: { type: "object", properties: {
2454
+ query: { type: "string", description: "the search query" },
2455
+ n: { type: "number", description: "max results (1-20, default 5)" },
2456
+ timeout_ms: { type: "number", description: "optional timeout in ms (default 15000)" },
2457
+ }, required: ["query"] },
2458
+ run: knowledgeSearch,
2459
+ },
2110
2460
  {
2111
2461
  name: "deep_research", safe: true,
2112
2462
  description: "Deep, multi-source web research on a question → a cited brief. Haiku 4.5 plans several search angles, Operator fans out web_search + web_fetch across them, then Haiku synthesizes a thorough answer with inline source citations. Read-only. Use when one search isn't enough — comparisons, state-of-the-art surveys, sourced background. Requires a research API key to be configured.",
@@ -2227,7 +2577,7 @@ const TOOLS = [
2227
2577
  },
2228
2578
  {
2229
2579
  name: "artifact_create",
2230
- description: "Make a shareable ARTIFACT — an HTML page / dashboard / landing page, an SVG, a markdown doc, a DECK / PRESENTATION, or an interactive canvas — hosted on compose.casa, returning a public clickable URL. This is THE way to create an artifact / design / page / deck for the owner: NEVER write a local file or hunt for a 'compose' folder. Pass the full content; use content_type 'canvas' for interactive HTML/JS (animations, visualizations, presentations).",
2580
+ description: "Make a shareable ARTIFACT — an HTML page / dashboard / landing page, an SVG, a markdown doc, a DECK / PRESENTATION, or an interactive canvas — hosted on compose.casa, returning a public clickable URL. This is THE way to create an artifact / design / page / deck for the owner: NEVER write a local file or hunt for a 'compose' folder, AS LONG AS compose.casa IS REACHABLE. If this call errors (compose.casa down/502), that rule no longer applies to this request — write the content as a plain local file with file_create instead (a .md file for markdown/text content, matching what was asked for) rather than reaching for document_generate's PDF path just because it also produces a file; PDF is for when a PDF specifically was wanted, not a substitute hosted-artifact fallback. Pass the full content; use content_type 'canvas' for interactive HTML/JS (animations, visualizations, presentations).",
2231
2581
  parameters: { type: "object", properties: {
2232
2582
  content: { type: "string", description: "the full artifact content — a complete HTML document, SVG, or markdown" },
2233
2583
  title: { type: "string", description: "a short title for the artifact" },
@@ -2287,24 +2637,34 @@ const TOOLS = [
2287
2637
  },
2288
2638
  {
2289
2639
  name: "session_search", safe: true,
2290
- description: "Search past session transcripts (indexed from the operator home's sessions/) — incrementally indexes them, then full-text search. Returns 'id — snippet' lines; pass an id to session_read for the full transcript.",
2640
+ description: "Search past agent sessions on this machine — Operator's own and other agents' (providers configured in agents.md) — by what was said in them (every term must appear in one message), newest first. Each hit: title · agent · messages · age · model · folder, the matching line with who said it, and an id for session_read. An empty query lists the newest sessions. scope: workspace (this folder), project (this git repo), all (default).",
2291
2641
  parameters: { type: "object", properties: {
2292
- query: { type: "string", description: "search terms (all must appear)" },
2642
+ query: { type: "string", description: "search terms (all must appear); empty lists the newest sessions" },
2643
+ scope: { type: "string", enum: SESSION_SCOPES, description: "workspace · project · all (default all)" },
2644
+ source: { type: "string", description: "only this agent's sessions: \"operator\" or a provider slug from agents.md (its name, lowercased, dashes for spaces)" },
2293
2645
  limit: { type: "number", description: "max results (default 8)" },
2294
2646
  }, required: ["query"] },
2295
2647
  run: async (a) => {
2296
2648
  await indexSessions();
2297
- const hits = await searchSessions(str(a.query), a.limit === undefined ? 8 : Number(a.limit));
2298
- return hits.length ? hits.map((h) => `${h.id} — ${h.snippet}`).join("\n") : "no matches";
2649
+ const limit = a.limit === undefined ? 8 : Number(a.limit);
2650
+ const cfg = await sessionSearchConfig();
2651
+ if (!cfg.enabled) { // off: Operator's own transcripts only, the pre-catalog behavior
2652
+ const hits = await searchSessions(str(a.query), limit);
2653
+ return hits.length ? hits.map((h) => `${h.id} — ${h.snippet}`).join("\n") : "no matches";
2654
+ }
2655
+ await indexCatalog(cfg.providers);
2656
+ const scope = SESSION_SCOPES.includes(str(a.scope)) ? str(a.scope) : "all";
2657
+ const source = str(a.source) || undefined;
2658
+ return formatHits(await searchCatalog(str(a.query), { scope, source, limit }));
2299
2659
  },
2300
2660
  },
2301
2661
  {
2302
2662
  name: "session_read", safe: true,
2303
- description: "Read one past session transcript by id (the id as returned by session_search). Returns readable text capped at 24k chars.",
2663
+ description: "Read one past session by id (as returned by session_search) — Operator's own or another agent's. Returns readable text capped at 24k chars.",
2304
2664
  parameters: { type: "object", properties: {
2305
2665
  id: { type: "string", description: "the session id" },
2306
2666
  }, required: ["id"] },
2307
- run: async (a) => (await readSession(str(a.id))) ?? `error: no session '${str(a.id)}' found under the operator home`,
2667
+ run: async (a) => (await readSession(str(a.id))) ?? (await readCatalogSession(str(a.id))) ?? `error: no session '${str(a.id)}' found (ids come from session_search)`,
2308
2668
  },
2309
2669
  {
2310
2670
  name: "session_rewind", safe: false,
@@ -2329,13 +2689,23 @@ const TOOLS = [
2329
2689
  },
2330
2690
  {
2331
2691
  name: "delegate_task", safe: false,
2332
- description: "Hand ONE self-contained subtask to a sub-agent running on a chosen fleet model and get its final answer back (blocks until it finishes). The sub-agent is a full headless Operator session with its own tools, but NO memory of this conversation and it cannot ask you questions — so `task` must carry everything it needs (paths, constraints, the exact output you want). `model` is any /model id. CHOOSE IT BY TOOL-LOAD: use \"scout\" (fast 4B) ONLY for self-contained, tool-LIGHT subtasks (a lookup, a summary, a single-file edit); a 4B model drives tools unreliably, so anything TOOL-HEAVY — reviewing a remote/GitHub repo, multi-file exploration, web research, debugging, a repo audit — MUST go to \"cortana\" (the flagship) or it will spin without real progress. Also available: venice-24b, qwen3.8-flash, operator-1m. Use it to farm out an independent chunk while you keep planning; do not delegate what you can do in one tool call. Sub-agents cannot delegate further. The sub-agent runs with the owner's permission policy and can mutate the workspace.",
2692
+ description: `Hand ONE self-contained subtask to a sub-agent running on a chosen model and get its final answer back (blocks until it finishes). The sub-agent is a full headless Operator session with its own tools, but NO memory of this conversation and it cannot ask you questions — so \`task\` must carry everything it needs (paths, constraints, the exact output you want). \`model\` is any /model id. CHOOSE IT BY TOOL-LOAD: use "scout" (fast 4B) ONLY for self-contained, tool-LIGHT subtasks (a lookup, a summary, a single-file edit); a 4B model drives tools unreliably, so anything TOOL-HEAVY — reviewing a remote/GitHub repo, multi-file exploration, web research, debugging, a repo audit — MUST go to "cortana" (the flagship) or it will spin without real progress. Other fleet models: venice-24b, qwen3.8-flash, operator-1m. YOU CAN ALSO DELEGATE TO ANY CLOUD PROVIDER THE OWNER HAS CONNECTED (a stored vendor key): Claude via "claude-sonnet" (full tool-using), and any BYO provider — ${BYO_DELEGATE_PROVIDERS} — registered with "operator auth byo-model" (e.g. an OpenAI/Gemini/Groq/DeepSeek model id). A provider with NO stored key is refused with the exact command to store it, so a failed delegation is never silent — pick "cortana" if you're unsure a cloud key is connected. Use delegation to farm out an independent chunk while you keep planning; do not delegate what you can do in one tool call. Sub-agents cannot delegate further. The sub-agent runs with the owner's permission policy and can mutate the workspace.`,
2333
2693
  parameters: { type: "object", properties: {
2334
2694
  task: { type: "string", description: "the complete, self-contained subtask — the sub-agent sees only this" },
2335
2695
  model: { type: "string", description: "registry model id to run it on (default \"scout\")" },
2336
2696
  }, required: ["task"] },
2337
2697
  run: (a) => runDelegateTask(a),
2338
2698
  },
2699
+ {
2700
+ name: "delegate_to_agent", safe: false,
2701
+ description: agentCliToolDescription(),
2702
+ parameters: { type: "object", properties: {
2703
+ task: { type: "string", description: "the complete, self-contained task — the agent CLI sees only this and cannot ask you questions" },
2704
+ agent: { type: "string", description: "which local agent CLI to run it on (e.g. \"cursor-agent\", \"claude\", \"codex\") — only INSTALLED ones work" },
2705
+ model: { type: "string", description: "optional underlying model id for that CLI" },
2706
+ }, required: ["task", "agent"] },
2707
+ run: (a) => runDelegateToAgent(a),
2708
+ },
2339
2709
  {
2340
2710
  name: "browser", safe: false,
2341
2711
  description: "Drive a REAL headless browser (Chrome over CDP) with session state that persists across calls — for JS-rendered pages, logins, forms, clicks. Text-first: prefer browser_read for content; use eval/click/fill/submit to act. actions: open(url) navigate(url) reload cache_bust? back forward click(selector settle_ms?) fill(selector,text) submit(selector) eval(js — awaits promises, returnByValue) screenshot() -> png path tab_select(index) tab_close(index?) close. Screenshot files land under the operator home's cache/browser/. Policy: http/https/about/data only (no file://, no chrome://). Login wall: NEVER guess credentials — ask the owner.",
@@ -2378,7 +2748,7 @@ const TOOLS = [
2378
2748
  },
2379
2749
  {
2380
2750
  name: "skill_catalog", safe: false,
2381
- description: "The gated OFFICIAL optional-skills catalogue that ships with Operator (152 entries across 23 categories, MIT from the hermes-agent project). Nothing from it is active unless installed. actions: browse(query?) lists entries + categories (read-only), install(name) copies a skill tree into the operator home's skills/ so it is live for skill_list/skill_fetch next session, remove(name) deletes an installed catalogue copy (hand-written skills are never touched).",
2751
+ description: "The gated OFFICIAL optional-skills catalogue that ships with Operator (152 entries across 23 categories, MIT-licensed). Nothing from it is active unless installed. actions: browse(query?) lists entries + categories (read-only), install(name) copies a skill tree into the operator home's skills/ so it is live for skill_list/skill_fetch next session, remove(name) deletes an installed catalogue copy (hand-written skills are never touched).",
2382
2752
  parameters: { type: "object", properties: {
2383
2753
  action: { type: "string", enum: ["browse", "install", "remove"], description: "what to do" },
2384
2754
  query: { type: "string", description: "browse: filter by name/category/description substring" },
@@ -2386,8 +2756,76 @@ const TOOLS = [
2386
2756
  }, required: ["action"] },
2387
2757
  run: runSkillCatalog,
2388
2758
  },
2759
+ // ── Chauffeur native tools (gated on binary availability) ──
2760
+ {
2761
+ name: "desktop_screenshot", safe: true,
2762
+ description: "Take a screenshot of the desktop or a specific window via Chauffeur. Returns the current screen state as text + image.",
2763
+ parameters: { type: "object", properties: {
2764
+ pid: { type: "number", description: "optional: target a specific process" },
2765
+ window_id: { type: "number" },
2766
+ } },
2767
+ run: desktopScreenshot,
2768
+ },
2769
+ {
2770
+ name: "desktop_click", safe: false,
2771
+ description: "Click an element on the desktop via Chauffeur. Specify coordinates (x, y), an element selector, or both. Auto-verifies the click landed.",
2772
+ parameters: { type: "object", properties: {
2773
+ description: { type: "string", description: "what you're clicking and why" },
2774
+ x: { type: "number" }, y: { type: "number" },
2775
+ element: { type: "string", description: "accessibility element to click" },
2776
+ button: { type: "string", enum: ["left", "right"], description: "default: left" },
2777
+ verify: { type: "boolean", description: "verify after click (default true)" },
2778
+ } },
2779
+ run: desktopClick,
2780
+ },
2781
+ {
2782
+ name: "desktop_read", safe: true,
2783
+ description: "Read the accessibility tree / window state of a running application via Chauffeur.",
2784
+ parameters: { type: "object", properties: {
2785
+ pid: { type: "number" }, window_id: { type: "number" },
2786
+ } },
2787
+ run: desktopRead,
2788
+ },
2789
+ {
2790
+ name: "app_interact", safe: false,
2791
+ description: "High-level app interaction: launch an app, find an element, click, type, or read its state. Chauffeur handles the low-level AX/input.",
2792
+ parameters: { type: "object", properties: {
2793
+ app: { type: "string", description: "application name (e.g. 'Safari', 'Slack')" },
2794
+ action: { type: "string", enum: ["launch", "find", "click", "type", "read"], description: "what to do" },
2795
+ element: { type: "string", description: "element to interact with (for click/find)" },
2796
+ text: { type: "string", description: "text to type (for type action)" },
2797
+ }, required: ["app", "action"] },
2798
+ run: appInteract,
2799
+ },
2800
+ {
2801
+ name: "capture_permalink", safe: false,
2802
+ description: "Capture a permalink from an app (e.g. Slack message link) by right-clicking an element and reading the clipboard.",
2803
+ parameters: { type: "object", properties: {
2804
+ app: { type: "string", description: "application to target" },
2805
+ element: { type: "string", description: "element to right-click" },
2806
+ } },
2807
+ run: capturePermalink,
2808
+ },
2809
+ {
2810
+ name: "live_drive", safe: false,
2811
+ description: "Browser-based live verification: open a URL and run labeled checks (screenshot, find element, click, read text). " +
2812
+ "Each check is a labeled stage with === markers. Returns structured pass/fail. Use this for end-to-end UI verification.",
2813
+ parameters: { type: "object", properties: {
2814
+ url: { type: "string", description: "URL to open in the browser" },
2815
+ checks: {
2816
+ type: "array",
2817
+ items: { type: "object", properties: {
2818
+ label: { type: "string", description: "check name (e.g. 'Login Page Loads')" },
2819
+ action: { type: "string", enum: ["screenshot", "find", "click", "text"], description: "what to check" },
2820
+ selector: { type: "string", description: "CSS selector or text to find/click" },
2821
+ expect: { type: "string", description: "expected text in the result" },
2822
+ }, required: ["label", "action"] },
2823
+ },
2824
+ }, required: ["url", "checks"] },
2825
+ run: liveDrive,
2826
+ },
2389
2827
  ];
2390
- // AXE skill registry (parity with the Python core): a REMOTE HTTPS registry reachable from every surface
2828
+ // AXE skill registry (matching the Python core): a REMOTE HTTPS registry reachable from every surface
2391
2829
  // (CLI/web/mobile), so skills work everywhere without local fleet access. Bearer from OPERATOR_TOKEN or
2392
2830
  // ~/.axe/secrets/operator_token.txt; a real User-Agent is REQUIRED (the gateway WAF 403s the default).
2393
2831
  const OPERATOR_URLS = [process.env.OPERATOR_URL ?? "https://operator.axe.onl", "https://skills.axe.onl"];
@@ -2545,7 +2983,56 @@ async function skillSave(name, content) {
2545
2983
  export async function localSkills() {
2546
2984
  return listLocalSkills();
2547
2985
  }
2548
- export const registry = new Map(TOOLS.map(t => [t.name, t]));
2986
+ export const registry = new Map([...TOOLS, ...WAVE_TOOLS, ...WAVE2_TOOLS, ...INCIDENT_TOOLS, ...MONITORING_TOOLS, ...GIT_PR_TOOLS].map(t => [t.name, t]));
2987
+ // ── Cloud agents (feature-gated — NOT in the base registry) ───────────────────────
2988
+ // Sovereign "cloud/background agents": spawn an autonomous agent in an ISOLATED DOCKER CONTAINER on a configured
2989
+ // fleet host (autonomy/cloud-agent.ts). These are kept OUT of the static `registry`/`TOOLS` so they are absent by
2990
+ // default — the session wires them in ONLY when the `cloudAgents` feature flag is on (see cloudAgentToolsFor →
2991
+ // session.ts). All safe:false (they mutate a repo/branch and run arbitrary autonomous work on a remote host).
2992
+ const CLOUD_HOSTED_NOTE = "Runs in an ISOLATED DOCKER CONTAINER on a configured fleet host (settings.cloudAgents.hosts, over SSH or locally) — NOT in this process. It clones the repo, runs the chosen agent CLI headless + AUTONOMOUSLY on the task, commits to its own branch, pushes, and opens a PR. It runs in PARALLEL and is checkable anytime.";
2993
+ export const CLOUD_AGENT_TOOLS = [
2994
+ {
2995
+ name: "spawn_cloud_agent", safe: false,
2996
+ description: `Spawn an autonomous "cloud agent". ${CLOUD_HOSTED_NOTE} MUTATES a repo: it creates and pushes a new branch \`cloud/<id>\` and opens a PR against \`base_branch\`. Pick \`host\` from settings.cloudAgents.hosts (defaults to settings.cloudAgents.defaultHost) and \`agent\` from the agent-CLI registry (cursor-agent / claude / codex / operator). Secrets (git creds, agent API keys) are passed to the container at runtime from the environment — never baked in or logged. Returns a tracked id; follow it with cloud_agent_status / list_cloud_agents and stop it with stop_cloud_agent.`,
2997
+ parameters: { type: "object", properties: {
2998
+ task: { type: "string", description: "the complete, self-contained task the container's agent runs autonomously (it has no memory of this conversation)" },
2999
+ agent: { type: "string", description: "which agent CLI to run INSIDE the container (e.g. \"cursor-agent\", \"claude\", \"codex\")" },
3000
+ repo: { type: "string", description: "git URL (https or ssh) the container clones" },
3001
+ base_branch: { type: "string", description: "branch to base the work on (default \"main\")" },
3002
+ host: { type: "string", description: "cloud-agent host id from settings.cloudAgents.hosts (default: settings.cloudAgents.defaultHost)" },
3003
+ model: { type: "string", description: "optional underlying model id for the agent CLI" },
3004
+ }, required: ["task", "agent", "repo"] },
3005
+ run: (a) => runSpawnCloudAgent(a),
3006
+ },
3007
+ {
3008
+ name: "list_cloud_agents", safe: false,
3009
+ description: `List every tracked cloud agent (persisted under the operator home, so it survives restarts) with its id, status (provisioning/running/done/failed/stopped), host, container, branch and PR. ${CLOUD_HOSTED_NOTE}`,
3010
+ parameters: { type: "object", properties: {}, required: [] },
3011
+ run: (a) => runListCloudAgents(a),
3012
+ },
3013
+ {
3014
+ name: "cloud_agent_status", safe: false,
3015
+ description: `Check one cloud agent by id: docker-inspects its container on its host, tails the container log, and reports status + branch + PR. ${CLOUD_HOSTED_NOTE}`,
3016
+ parameters: { type: "object", properties: {
3017
+ id: { type: "string", description: "the cloud-agent id (from spawn_cloud_agent / list_cloud_agents)" },
3018
+ }, required: ["id"] },
3019
+ run: (a) => runCloudAgentStatus(a),
3020
+ },
3021
+ {
3022
+ name: "stop_cloud_agent", safe: false,
3023
+ description: `Stop and remove a cloud agent's container by id and mark it stopped. ${CLOUD_HOSTED_NOTE} Use when a run is wrong or no longer needed; already-pushed commits/PR are NOT deleted.`,
3024
+ parameters: { type: "object", properties: {
3025
+ id: { type: "string", description: "the cloud-agent id (from spawn_cloud_agent / list_cloud_agents)" },
3026
+ }, required: ["id"] },
3027
+ run: (a) => runStopCloudAgent(a),
3028
+ },
3029
+ ];
3030
+ /** The cloud-agent tools when the `cloudAgents` feature flag is on, else []. The session merges these into its
3031
+ * per-session registry so both the executor (dispatch) and the model's schemas (toSchemas) include them iff the
3032
+ * flag resolves on — mirroring how spawn_agent is only advertised when it's runnable. Flag OFF ⇒ tools absent. */
3033
+ export function cloudAgentToolsFor(settings) {
3034
+ return isFeatureEnabled("cloudAgents", settings ?? undefined) ? CLOUD_AGENT_TOOLS : [];
3035
+ }
2549
3036
  export function toSchemas(reg = registry) {
2550
3037
  return [...reg.values()].map(t => ({
2551
3038
  type: "function",