@0perator/operator 0.1.62 → 0.1.153

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 (75) hide show
  1. package/CHANGELOG.md +1023 -0
  2. package/LICENSE +19 -0
  3. package/dist/acp/agent.js +103 -0
  4. package/dist/acp/run.js +23 -0
  5. package/dist/auth/client.js +4 -1
  6. package/dist/auth/login-intent.js +12 -0
  7. package/dist/autonomy/board-run.js +65 -0
  8. package/dist/autonomy/board.js +83 -0
  9. package/dist/autonomy/dream.js +71 -0
  10. package/dist/autonomy/headless.js +70 -0
  11. package/dist/autonomy/index.js +260 -0
  12. package/dist/autonomy/keepawake.js +84 -0
  13. package/dist/autonomy/loop.js +82 -0
  14. package/dist/autonomy/reporter.js +54 -0
  15. package/dist/autonomy/routine-run.js +25 -0
  16. package/dist/autonomy/routines.js +173 -0
  17. package/dist/autonomy/session-factory.js +61 -0
  18. package/dist/background/index.js +269 -20
  19. package/dist/background/worktree.js +62 -0
  20. package/dist/cli.js +518 -95
  21. package/dist/config/brand.js +81 -0
  22. package/dist/config/operator-harness.js +86 -0
  23. package/dist/config/persona.js +174 -0
  24. package/dist/config/settings.js +98 -9
  25. package/dist/engine/agent.js +447 -51
  26. package/dist/engine/aurora.js +180 -64
  27. package/dist/engine/compaction.js +97 -5
  28. package/dist/engine/grandmaster.js +69 -10
  29. package/dist/engine/router-adapter.js +3 -0
  30. package/dist/engine/selfheal.js +35 -0
  31. package/dist/engine/verify-gate.js +81 -0
  32. package/dist/mcp/index.js +1 -1
  33. package/dist/permissions/index.js +13 -7
  34. package/dist/router/models.js +1 -1
  35. package/dist/router/router.js +46 -7
  36. package/dist/selfimprove/index.js +88 -0
  37. package/dist/services/preflight.js +42 -1
  38. package/dist/session.js +227 -20
  39. package/dist/telemetry/events.js +9 -0
  40. package/dist/tools/executor.js +48 -24
  41. package/dist/tools/git-status.js +71 -0
  42. package/dist/tools/mutating.js +9 -0
  43. package/dist/tools/registry.js +214 -11
  44. package/dist/tools/result-cap.js +23 -0
  45. package/dist/tools/searxng.js +42 -2
  46. package/dist/ui/ActivitySpinner.js +6 -5
  47. package/dist/ui/App.js +23 -5
  48. package/dist/ui/AuthScreen.js +1 -1
  49. package/dist/ui/BgPanel.js +60 -5
  50. package/dist/ui/Composer.js +135 -13
  51. package/dist/ui/Header.js +6 -4
  52. package/dist/ui/InputRule.js +2 -1
  53. package/dist/ui/Markdown.js +69 -10
  54. package/dist/ui/Masthead.js +6 -4
  55. package/dist/ui/PlanPane.js +23 -0
  56. package/dist/ui/QuestionPrompt.js +22 -8
  57. package/dist/ui/StatsCard.js +15 -0
  58. package/dist/ui/StatusRule.js +13 -4
  59. package/dist/ui/SummaryCard.js +18 -0
  60. package/dist/ui/Table.js +114 -0
  61. package/dist/ui/ThinkingSpinner.js +6 -4
  62. package/dist/ui/ToolBatch.js +12 -0
  63. package/dist/ui/ToolStep.js +12 -4
  64. package/dist/ui/Transcript.js +30 -6
  65. package/dist/ui/chart.js +34 -0
  66. package/dist/ui/editdiff.js +84 -0
  67. package/dist/ui/highlight.js +89 -0
  68. package/dist/ui/osc.js +32 -0
  69. package/dist/ui/planExit.js +26 -0
  70. package/dist/ui/term.js +16 -0
  71. package/dist/ui/theme.js +60 -0
  72. package/dist/ui/tree.js +71 -0
  73. package/dist/util/slash.js +15 -0
  74. package/dist/util/throttle.js +28 -0
  75. package/package.json +11 -2
@@ -7,6 +7,7 @@
7
7
  const nodeImport = (m) => import(m);
8
8
  import { MemoryStore } from "../memory/index.js";
9
9
  import { pexecFile } from "./exec.js";
10
+ import { formatGitStatus } from "./git-status.js";
10
11
  import { expandPath } from "./paths.js";
11
12
  import { deniedWriteAsync, deniedReadAsync, wrapShell } from "./sandbox.js";
12
13
  import { ensureSearxng, noteSearxngUsed } from "./searxng.js";
@@ -53,8 +54,11 @@ async function shellExec(args) {
53
54
  }
54
55
  if (r.truncated)
55
56
  out += `\n[output truncated at 8MB — narrow it: add a path, pipe to \`head\`, or use \`grep -l\`/\`grep -c\`]`;
57
+ // Surface a NON-ZERO exit as a trailer so a failing check is observable to the model AND the
58
+ // verify-before-done gate (engine/verify-gate.ts); exit 0 / unknown stays byte-identical so no
59
+ // existing bash-output test changes. (Previously the code was dropped whenever a command printed.)
56
60
  if (out)
57
- return out; // real output — including non-zero exits (grep no-match, diff, test)
61
+ return r.exitCode ? out + `\n[exit ${r.exitCode}]` : out;
58
62
  return r.exitCode === 0 ? "(no output)" : `(no output; exit ${r.exitCode ?? "?"})`;
59
63
  }
60
64
  catch (e) {
@@ -95,6 +99,37 @@ async function fileRead(args) {
95
99
  return `error: ${e.message}`;
96
100
  }
97
101
  }
102
+ const READ_FILES_MAX = 20;
103
+ const READ_FILES_BUDGET = 36_000; // stay under the 40KB executor cap with room for headers/truncation msg
104
+ async function readFiles(args) {
105
+ const raw = args.paths;
106
+ if (!Array.isArray(raw) || raw.length === 0)
107
+ return "error: paths must be a non-empty array";
108
+ if (raw.length > READ_FILES_MAX)
109
+ return `error: max ${READ_FILES_MAX} files per call (got ${raw.length})`;
110
+ const entries = raw.map((e) => {
111
+ if (typeof e === "string")
112
+ return { path: e };
113
+ const o = e;
114
+ return { path: str(o.path), offset: o.offset, limit: o.limit };
115
+ });
116
+ const results = await Promise.allSettled(entries.map((e) => fileRead(e)));
117
+ const parts = [];
118
+ let total = 0;
119
+ for (let i = 0; i < results.length; i++) {
120
+ const r = results[i];
121
+ const body = r.status === "fulfilled" ? r.value : `error: ${r.reason}`;
122
+ const section = `── ${entries[i].path} ──\n${body}`;
123
+ if (total + section.length > READ_FILES_BUDGET && parts.length > 0) {
124
+ const remaining = entries.slice(i).map((e) => e.path).join(", ");
125
+ parts.push(`…[budget reached — ${results.length - i} file(s) omitted: ${remaining}. Call read_files again with these paths.]`);
126
+ break;
127
+ }
128
+ parts.push(section);
129
+ total += section.length;
130
+ }
131
+ return parts.join("\n\n");
132
+ }
98
133
  async function fileWrite(args) {
99
134
  const path = expandPath(str(args.path));
100
135
  if (!path)
@@ -351,6 +386,18 @@ async function gitCommand(args) {
351
386
  return `error: ${e.stderr || e.message}`;
352
387
  }
353
388
  }
389
+ // Structured git state — ONE clean read (branch, ahead/behind, staged/unstaged/untracked, clean?) so the
390
+ // model acts on a summary instead of parsing raw porcelain and looping. See src/tools/git-status.ts.
391
+ async function gitStatus(args) {
392
+ const cwd = args.cwd ? expandPath(str(args.cwd)) : undefined;
393
+ try {
394
+ const { stdout } = await pexecFile("git", ["status", "--porcelain=v1", "--branch"], { cwd, maxBuffer: 10 * 1024 * 1024 });
395
+ return formatGitStatus(stdout);
396
+ }
397
+ catch (e) {
398
+ return `error: ${e.stderr || e.message}`;
399
+ }
400
+ }
354
401
  // ONE memory store (src/memory) backs the memory_store/memory_search/checkpoint tools AND the Session's
355
402
  // start-of-session recall — a single JSONL file, so a note stored mid-turn is what a later session recalls.
356
403
  // SPEC §8 eyes SQLite eventually; swapping the store's backing is a MemoryStore-internal change from here.
@@ -371,6 +418,19 @@ async function memorySearch(args) {
371
418
  ? hits.map(h => `[${new Date(h.ts).toISOString()}] ${h.text}`).join("\n")
372
419
  : "(no matches)";
373
420
  }
421
+ // Git run for checkpoints, HARDENED so a checkpoint can never freeze the session (the "checkpoint… spins
422
+ // forever, esc won't help" hang, 2026-09-28). Every step gets a TIMEOUT + killSignal SIGKILL — a slow or hung
423
+ // git (a pre-commit hook, a huge tree, a stuck index lock) is killed and the call rejects instead of blocking
424
+ // forever — and a NON-INTERACTIVE env: GIT_TERMINAL_PROMPT=0 (never wait on a credential prompt), GIT_EDITOR
425
+ // and GIT_SEQUENCE_EDITOR=true + GIT_PAGER=cat (never open an editor/pager that blocks on stdin),
426
+ // GIT_OPTIONAL_LOCKS=0. The commit adds --no-verify: a checkpoint is a WIP snapshot, not a reviewed commit, so
427
+ // a slow/hung pre-commit hook (the single most common freeze) must never gate it.
428
+ function checkpointGitEnv() {
429
+ return { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", GIT_PAGER: "cat", GIT_EDITOR: "true", GIT_SEQUENCE_EDITOR: "true" };
430
+ }
431
+ async function checkpointGit(gitArgs, cwd, timeout) {
432
+ return pexecFile("git", gitArgs, { cwd, timeout, killSignal: "SIGKILL", env: checkpointGitEnv(), maxBuffer: 16 * 1024 * 1024 });
433
+ }
374
434
  // checkpoint = git add+commit in workspace + a memory note, one call (SPEC §8). Never adds
375
435
  // Co-Authored-By / AI attribution — the commit message is exactly the caller's summary.
376
436
  async function checkpoint(args) {
@@ -380,15 +440,41 @@ async function checkpoint(args) {
380
440
  const workspace = args.workspace ? expandPath(str(args.workspace)) : process.cwd();
381
441
  const push = Boolean(args.push);
382
442
  try {
383
- await pexecFile("git", ["add", "-A"], { cwd: workspace });
384
- await pexecFile("git", ["commit", "-m", summary], { cwd: workspace });
385
- const { stdout: sha } = await pexecFile("git", ["rev-parse", "--short", "HEAD"], { cwd: workspace });
443
+ // A checkpoint needs a git repo. If the workspace isn't inside one, `git init` it HERE so "save my
444
+ // work" succeeds in any fresh directory instead of failing with "fatal: not a git repository". We
445
+ // init only when there is NO enclosing repo (rev-parse fails) — so this can never reach UP into a
446
+ // parent repo (the ~/.axe 2GB-monorepo trap); an existing enclosing repo is used as-is.
447
+ let initialized = false;
448
+ const top = await checkpointGit(["rev-parse", "--show-toplevel"], workspace, 10_000)
449
+ .then((r) => r.stdout.trim())
450
+ .catch(() => "");
451
+ if (!top) {
452
+ await checkpointGit(["init"], workspace, 10_000);
453
+ initialized = true;
454
+ }
455
+ await checkpointGit(["add", "-A"], workspace, 120_000);
456
+ try {
457
+ await checkpointGit(["commit", "--no-verify", "-m", summary], workspace, 60_000);
458
+ }
459
+ catch (ce) {
460
+ // A clean tree isn't an error — git exits non-zero with "nothing to commit". Report it plainly.
461
+ const msg = String(ce.stdout || ce.stderr || ce.message || "");
462
+ if (/nothing to commit|no changes added|working tree clean/i.test(msg))
463
+ return "checkpoint — nothing to commit (working tree already clean)";
464
+ throw ce;
465
+ }
466
+ const { stdout: sha } = await checkpointGit(["rev-parse", "--short", "HEAD"], workspace, 10_000);
386
467
  if (push)
387
- await pexecFile("git", ["push"], { cwd: workspace });
468
+ await checkpointGit(["push"], workspace, 120_000);
388
469
  await memory.capture(summary, ["checkpoint", workspace]);
389
- return `checkpoint ${sha.trim()} — ${summary}${push ? " (pushed)" : ""}`;
470
+ return `checkpoint ${sha.trim()} — ${summary}${initialized ? " (new git repo initialized here)" : ""}${push ? " (pushed)" : ""}`;
390
471
  }
391
472
  catch (e) {
473
+ // A killed/timed-out git step (SIGKILL from the timeout, or ETIMEDOUT) surfaces as a clear, actionable
474
+ // message instead of a raw error — the tool ALWAYS returns, so the turn never freezes on it.
475
+ const timedOut = e?.killed === true || e?.signal === "SIGKILL" || /timed?\s*out|ETIMEDOUT/i.test(String(e?.message || ""));
476
+ if (timedOut)
477
+ return "error: checkpoint aborted — a git step exceeded its time limit and was killed (a very large tree, a stuck index lock, or a slow hook; hooks are already skipped via --no-verify). Your memory notes are unaffected — retry, or commit specific paths manually.";
392
478
  return `error: ${e.stderr || e.message}`;
393
479
  }
394
480
  }
@@ -467,6 +553,36 @@ async function webSearch(args) {
467
553
  clearTimeout(timer);
468
554
  }
469
555
  }
556
+ // Retry a bot-blocked fetch through the AXE autopilot's real-browser /markdown route — same
557
+ // KODE_AUTOPILOT_URL backend web_search's /serp uses. Returns rendered markdown, or null if no
558
+ // backend is configured, the request fails, or the response has no usable body.
559
+ async function autopilotMarkdown(url, signal) {
560
+ const ap = process.env.KODE_AUTOPILOT_URL;
561
+ if (!ap)
562
+ return null;
563
+ try {
564
+ const res = await fetch(`${ap.replace(/\/$/, "")}/markdown`, {
565
+ method: "POST", signal,
566
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi" },
567
+ body: JSON.stringify({ url }),
568
+ });
569
+ if (!res.ok)
570
+ return null;
571
+ const body = await res.text();
572
+ let md;
573
+ try {
574
+ const j = JSON.parse(body);
575
+ md = j.markdown ?? j.content ?? j.text;
576
+ }
577
+ catch {
578
+ md = body;
579
+ }
580
+ return md && md.trim() ? md.trim() : null;
581
+ }
582
+ catch {
583
+ return null;
584
+ }
585
+ }
470
586
  async function webFetch(args) {
471
587
  const url = str(args.url);
472
588
  if (!/^https?:\/\//i.test(url))
@@ -474,9 +590,23 @@ async function webFetch(args) {
474
590
  const ctrl = new AbortController();
475
591
  const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 20_000));
476
592
  try {
477
- const res = await fetch(url, { signal: ctrl.signal, redirect: "follow", headers: { "User-Agent": "operator/kode-tsi" } });
478
- if (!res.ok)
593
+ // A realistic browser UA (not "operator/kode-tsi") — many public sites (Cloudflare-fronted, e.g. x.ai)
594
+ // 403 a bot UA, which forced a curl fallback and a red error in the transcript. This fetches the page.
595
+ const res = await fetch(url, { signal: ctrl.signal, redirect: "follow", headers: { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } });
596
+ if (!res.ok) {
597
+ // A bot-blocked site (Cloudflare et al. favor 403/429 over a real error page) still needs an
598
+ // answer. Retry through a real browser if one is configured; otherwise this reads as guidance,
599
+ // not a scary raw error, since the block is expected behavior rather than a tool failure.
600
+ if (res.status === 403 || res.status === 429) {
601
+ const rendered = await autopilotMarkdown(url, ctrl.signal);
602
+ if (rendered) {
603
+ const max = Number(args.max_chars ?? 20_000);
604
+ return rendered.length > max ? `${rendered.slice(0, max)}\n…[truncated ${rendered.length - max} chars]` : rendered;
605
+ }
606
+ return `note: ${url} blocks automated fetch (HTTP ${res.status}) — it needs a real browser; try web_search or the browser tools instead.`;
607
+ }
479
608
  return `error: HTTP ${res.status} fetching ${url}`;
609
+ }
480
610
  const ct = res.headers.get("content-type") ?? "";
481
611
  let text = await res.text();
482
612
  if (/html/i.test(ct))
@@ -637,8 +767,25 @@ async function shellBackground(args) {
637
767
  bgJobs.set(id, job);
638
768
  return `started background job ${id}: ${command}\nPoll it with bash_output {"id":"${id}"}; stop it with bash_kill {"id":"${id}"}.`;
639
769
  }
770
+ // A spawn_agent sub-agent id ("agent-1", "agent-2", …) is a DIFFERENT registry than shell_background's
771
+ // own job ids ("sh1", "sh2", …) — bash_output/bash_kill only ever know the latter. A model that spawned a
772
+ // sub-agent and then reached for bash_output on its id used to get a bare "no background job", read that as
773
+ // "it's gone", and re-spawned a duplicate onto the one shared endpoint (the actual damage, seen live
774
+ // 09-26). Redirect that specific shape of id instead of erroring blind, so the model gets pointed at the
775
+ // tool that's actually right (agent_status / message_agent) rather than concluding eviction.
776
+ const SUB_AGENT_ID_RE = /^agent-\d+$/i;
777
+ function subAgentRedirect(id) {
778
+ if (!SUB_AGENT_ID_RE.test(id))
779
+ return null;
780
+ return `${id} is a sub-agent (from spawn_agent), not a shell_background job — its result posts to the ` +
781
+ `conversation automatically when it finishes; don't poll it here. Use agent_status to check its real ` +
782
+ `status, or message_agent to nudge it. bash_output/bash_kill only work on shell_background job ids.`;
783
+ }
640
784
  async function bashOutput(args) {
641
785
  const id = str(args.id);
786
+ const redirect = subAgentRedirect(id);
787
+ if (redirect)
788
+ return redirect;
642
789
  const job = bgJobs.get(id);
643
790
  if (!job)
644
791
  return `error: no background job "${id}" (list ids from shell_background's return)`;
@@ -649,6 +796,9 @@ async function bashOutput(args) {
649
796
  }
650
797
  async function bashKill(args) {
651
798
  const id = str(args.id);
799
+ const redirect = subAgentRedirect(id);
800
+ if (redirect)
801
+ return redirect;
652
802
  const job = bgJobs.get(id);
653
803
  if (!job)
654
804
  return `error: no background job "${id}"`;
@@ -679,6 +829,9 @@ async function taskAdd(args) {
679
829
  return `added ${items.length} task(s):\n${renderTasks()}`;
680
830
  }
681
831
  async function taskList() { return renderTasks(); }
832
+ /** A snapshot of the session TODO list for the UI plan/checklist pane (SPEC §6). Copy, not the live array,
833
+ * so a render can't mutate it. Empty when the model hasn't tracked any tasks this session. */
834
+ export function getAgentTasks() { return agentTasks.map((t) => ({ ...t })); }
682
835
  async function taskUpdate(args) {
683
836
  const id = Number(args.id);
684
837
  const status = str(args.status);
@@ -690,6 +843,19 @@ async function taskUpdate(args) {
690
843
  t.status = status;
691
844
  return `task #${id} → ${status}\n${renderTasks()}`;
692
845
  }
846
+ // Clear the plan. Default wipes the whole list (the model had no way to honor "clear the list / reset the
847
+ // plan / move on" — it could only mark items done). `completed_only` drops finished tasks and keeps the rest.
848
+ async function taskClear(args) {
849
+ const before = agentTasks.length;
850
+ if (Boolean(args.completed_only)) {
851
+ for (let i = agentTasks.length - 1; i >= 0; i--)
852
+ if (agentTasks[i].status === "done")
853
+ agentTasks.splice(i, 1);
854
+ return `cleared ${before - agentTasks.length} completed task(s)\n${renderTasks()}`;
855
+ }
856
+ agentTasks.length = 0;
857
+ return `cleared all ${before} task(s) — plan is empty`;
858
+ }
693
859
  const TOOLS = [
694
860
  {
695
861
  name: "bash", safe: false,
@@ -699,7 +865,9 @@ const TOOLS = [
699
865
  "re-run `source .../activate && ...` or re-`cd` on every call; activate/enter once, then just " +
700
866
  "run the command. stdout and stderr come back merged (like a terminal) with the exit code. " +
701
867
  "Optional `cwd` runs that one command in a subshell without moving the session. For a " +
702
- "long-running server/build/watcher use shell_background instead so this shell isn't blocked.",
868
+ "long-running server/build/watcher use shell_background instead so this shell isn't blocked. " +
869
+ "Prefer SINGLE quotes for patterns and paths (grep -l '^x', not grep -l \"^x\"): a raw double-quote " +
870
+ "inside the command can break tool-call serialization on the local model and make the call fail.",
703
871
  parameters: { type: "object", properties: {
704
872
  command: { type: "string", description: "the bash command to run in the persistent shell" },
705
873
  cwd: { type: "string", description: "optional: run this one command from here (scoped; does not move the session)" },
@@ -724,7 +892,7 @@ const TOOLS = [
724
892
  },
725
893
  {
726
894
  name: "bash_output", safe: true,
727
- 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.",
895
+ 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.",
728
896
  parameters: { type: "object", properties: { id: { type: "string", description: "the job id from shell_background" } }, required: ["id"] },
729
897
  run: bashOutput,
730
898
  },
@@ -748,10 +916,16 @@ const TOOLS = [
748
916
  },
749
917
  {
750
918
  name: "task_update", safe: false,
751
- description: "Set a task's status. status = pending | in_progress | done.",
919
+ description: "Set a task's status. status = pending | in_progress | done. Update IMMEDIATELY as work lands — mark a task `in_progress` when you start it and `done` the moment it's finished, one at a time, not in a batch at the end. This keeps the live plan honest so the user sees real progress.",
752
920
  parameters: { type: "object", properties: { id: { type: "number" }, status: { type: "string", enum: ["pending", "in_progress", "done"] } }, required: ["id", "status"] },
753
921
  run: taskUpdate,
754
922
  },
923
+ {
924
+ name: "task_clear", safe: false,
925
+ description: "Clear the session TODO list. Default removes ALL tasks — use this when the user says to clear the list, reset the plan, start fresh, or move on (do NOT instead mark everything done). Set completed_only:true to drop only finished tasks and keep the unfinished ones.",
926
+ parameters: { type: "object", properties: { completed_only: { type: "boolean", description: "true = remove only done tasks; default false = wipe the whole list" } } },
927
+ run: taskClear,
928
+ },
755
929
  {
756
930
  name: "file_read", safe: true,
757
931
  description: "Read a file, optionally a line range, with line numbers. Without offset/limit, only the first 2000 lines are returned — pass offset/limit to page through a larger file.",
@@ -760,6 +934,25 @@ const TOOLS = [
760
934
  }, required: ["path"] },
761
935
  run: fileRead,
762
936
  },
937
+ {
938
+ name: "read_files", safe: true,
939
+ description: "Read multiple files in ONE call (parallel I/O). Use when you need several files and one doesn't depend on another — massively faster than serial file_read calls. Each entry can optionally specify offset/limit. Returns all results separated by clear headers.",
940
+ parameters: { type: "object", properties: {
941
+ paths: {
942
+ type: "array",
943
+ items: {
944
+ oneOf: [
945
+ { type: "string" },
946
+ { type: "object", properties: {
947
+ path: { type: "string" }, offset: { type: "number" }, limit: { type: "number" },
948
+ }, required: ["path"] },
949
+ ],
950
+ },
951
+ description: "file paths to read (strings, or objects with path/offset/limit)",
952
+ },
953
+ }, required: ["paths"] },
954
+ run: readFiles,
955
+ },
763
956
  {
764
957
  name: "file_write", safe: false,
765
958
  description: "Write (overwrite) a file, creating parent directories as needed.",
@@ -818,6 +1011,12 @@ const TOOLS = [
818
1011
  parameters: { type: "object", properties: { path: { type: "string" } } },
819
1012
  run: listDirectory,
820
1013
  },
1014
+ {
1015
+ name: "git_status", safe: true,
1016
+ description: "Structured git state in one read: branch, ahead/behind vs upstream, and staged/unstaged/untracked file lists — a clean tree is reported as 'nothing to commit'. Use this instead of parsing raw `git status`; don't loop re-running git to figure out state.",
1017
+ parameters: { type: "object", properties: { cwd: { type: "string" } } },
1018
+ run: gitStatus,
1019
+ },
821
1020
  {
822
1021
  name: "git_command", safe: false,
823
1022
  description: "Run an arbitrary git subcommand (args as an argv array, no shell).",
@@ -968,6 +1167,10 @@ async function skillList(query) {
968
1167
  // Prefer the ranked /search when a query is given; fall back to the full list.
969
1168
  const local = await localSkills();
970
1169
  const localBlock = local.length ? `your profile skills:\n${local.map((l) => `• ${l.name} (profile)`).join("\n")}\n\n` : "";
1170
+ // The AXE skills catalogue (operator.axe.onl / skills.axe.onl → the axe-skills-catalogue, hub.serve)
1171
+ // serves the VERSIONED contract: `/v1/skills`, `/v1/skills/search?q=`, `/v1/skills/<slug>` (verified
1172
+ // live, 200 with real data). When the tool reports "unreachable" the origin/tunnel is DOWN, not a
1173
+ // path bug — do NOT "reconcile" to an unversioned path (a different, incidental local service).
971
1174
  const path = query ? `/v1/skills/search?q=${encodeURIComponent(query)}` : "/v1/skills";
972
1175
  const r = (await operatorGet(path)) ?? (query ? await operatorGet("/v1/skills") : null);
973
1176
  if (r === null) {
@@ -0,0 +1,23 @@
1
+ // Central tool-result cap (defense-in-depth, generalized fix for the grep-self-poisoning bug): EVERY
2
+ // tool result flows straight into the model's context, so any tool — local or MCP, including ones we
3
+ // have not individually audited — that can return unbounded output is a context-bloat vector. Cap it
4
+ // here, once, for all of them: keep the head (where the useful part usually is) plus a small tail
5
+ // (trailing summary/error lines), so a truncation still shows both ends of the output.
6
+ //
7
+ // Lives in its own file (not tools/executor.ts) because it's a pure string helper with zero node
8
+ // dependencies, but executor.ts pulls in node:path + the whole node tool registry — importing
9
+ // capToolResult from there drags that entire node-only graph along. mcp/index.ts is part of the
10
+ // browser-safe barrel (index.browser.ts re-exports McpHub/withMcp for kode-web), so that import used
11
+ // to break the web bundle at build time (node:path externalized) and crash it at runtime (a
12
+ // transitively-pulled-in module referencing bare `process`).
13
+ export const TOOL_RESULT_MAX_CHARS = 40_000; // ~40KB
14
+ const TOOL_RESULT_TAIL_CHARS = 2_000;
15
+ const TOOL_RESULT_HEAD_CHARS = TOOL_RESULT_MAX_CHARS - TOOL_RESULT_TAIL_CHARS;
16
+ export function capToolResult(result) {
17
+ if (result.length <= TOOL_RESULT_MAX_CHARS)
18
+ return result;
19
+ const head = result.slice(0, TOOL_RESULT_HEAD_CHARS);
20
+ const tail = result.slice(-TOOL_RESULT_TAIL_CHARS);
21
+ const marker = `\n…[result truncated: ${TOOL_RESULT_MAX_CHARS} of ${result.length} chars — narrow your query]\n`;
22
+ return head + marker + tail;
23
+ }
@@ -155,7 +155,19 @@ async function bringUp() {
155
155
  * Return a reachable SearXNG base URL, standing up a managed container if needed. null means no backend
156
156
  * (mobile, Docker absent, auto-manage off, or startup failed) — the caller then reports the usual error.
157
157
  */
158
- export async function ensureSearxng() {
158
+ // Parallel web_search calls (executeParallel runs read-only tools concurrently) each call ensureSearxng().
159
+ // Without a guard they ALL race to `docker run` the same `operator-searxng` container: the first wins, the
160
+ // rest fail ("name already in use") → return null → those searches fall through to "no backend" and report
161
+ // no results (the parallel-web_search failure seen live 2026-09-27). Dedup concurrent callers onto ONE
162
+ // in-flight startup so they share its result; the slot clears when it settles so a later cold start can run.
163
+ let inFlight = null;
164
+ export function ensureSearxng() {
165
+ if (inFlight)
166
+ return inFlight;
167
+ inFlight = ensureSearxngOnce().finally(() => { inFlight = null; });
168
+ return inFlight;
169
+ }
170
+ async function ensureSearxngOnce() {
159
171
  const explicit = process.env.KODE_SEARXNG_URL;
160
172
  // A reachable explicit/managed URL wins with no Docker work.
161
173
  if (explicit && (await reachable(explicit))) {
@@ -183,16 +195,44 @@ export async function ensureSearxng() {
183
195
  }
184
196
  return null;
185
197
  }
186
- /** Reset the idle countdown after a successful search. */
198
+ // Session activation flag: true once web_search has actually been SERVED by SearXNG (registry.ts calls
199
+ // noteSearxngUsed on a non-empty result). Independent of `managed` — an explicit KODE_SEARXNG_URL backend
200
+ // counts as active even though Operator didn't start it. Drives the ✓ in the masthead + /services.
201
+ let used = false;
202
+ /** Reset the idle countdown after a successful search, and mark SearXNG active for the session. */
187
203
  export function noteSearxngUsed() {
204
+ used = true;
188
205
  if (managed)
189
206
  resetIdle();
190
207
  }
208
+ /** Session status snapshot for the service UIs, no side effects and never starts a container:
209
+ * "active" once a web_search has been served by SearXNG this session, "up" if a container Operator
210
+ * manages is running but unused, else "off". */
211
+ export function searxngStatus() {
212
+ if (used)
213
+ return "active";
214
+ if (managed)
215
+ return "up";
216
+ return "off";
217
+ }
218
+ /** Boot-time reachability probe: is a SearXNG backend ALREADY up (an explicit KODE_SEARXNG_URL, or a
219
+ * container already running on the managed port from a prior session's `--restart unless-stopped`)?
220
+ * Read-only — it NEVER starts a container, so SearXNG stays lazy until the first real web_search. Lets the
221
+ * boot service line show ✓ when a backend is genuinely reachable instead of always "lazy". */
222
+ export async function probeSearxng() {
223
+ const explicit = process.env.KODE_SEARXNG_URL;
224
+ if (explicit)
225
+ return reachable(explicit);
226
+ if (!autoManage())
227
+ return false;
228
+ return reachable(`http://localhost:${port()}`);
229
+ }
191
230
  /** Stop the container if we started it. Best-effort; safe to call repeatedly. */
192
231
  export async function stopManagedSearxng() {
193
232
  if (!managed)
194
233
  return;
195
234
  managed = false;
235
+ used = false; // no longer serving — next search will cold-start + re-activate
196
236
  if (idleTimer) {
197
237
  clearTimeout(idleTimer);
198
238
  idleTimer = null;
@@ -7,6 +7,7 @@ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
7
7
  // • OrbitSpinner — a background sub-agent is working (rotating arc, violet)
8
8
  import { useEffect, useState } from "react";
9
9
  import { Text } from "ink";
10
+ import { theme } from "./theme.js";
10
11
  function useFrame(frames, active, tickMs) {
11
12
  const [i, setI] = useState(0);
12
13
  useEffect(() => {
@@ -21,22 +22,22 @@ const BRAILLE = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇",
21
22
  const ORBIT = ["◜", "◠", "◝", "◞", "◡", "◟"]; // a dot orbiting a ring — "something running elsewhere"
22
23
  const SETTLE = ["◐", "◓", "◑", "◒"]; // a filling/turning disc — "adjusting, working it out" (NOT an error)
23
24
  /** Tools are executing this turn. Distinct from the star: a cyan braille run-spinner + the tool name(s). */
24
- export function StepSpinner({ active, label, tickMs = 80 }) {
25
+ export function StepSpinner({ active, label, tickMs = 125 }) {
25
26
  const glyph = useFrame(BRAILLE, active, tickMs);
26
27
  if (!active)
27
28
  return null;
28
- return (_jsxs(Text, { color: "#5ec8e8", children: [glyph, " ", label ? `${label}…` : "running…"] }));
29
+ return (_jsxs(Text, { color: theme.info, children: [glyph, " ", label ? `${label}…` : "running…"] }));
29
30
  }
30
31
  /** A background sub-agent is working. Distinct again: a violet rotating arc + the agent label. */
31
32
  export function OrbitSpinner({ active, label, tickMs = 120 }) {
32
33
  const glyph = useFrame(ORBIT, active, tickMs);
33
34
  if (!active)
34
35
  return null;
35
- return (_jsxs(Text, { color: "#b98cff", children: [glyph, " ", label ?? "sub-agent working", "\u2026"] }));
36
+ return (_jsxs(Text, { color: theme.accent, children: [glyph, " ", label ?? "sub-agent working", "\u2026"] }));
36
37
  }
37
38
  /** Just the animated orbit glyph (violet), for embedding in the bg-agents list beside a working agent. */
38
39
  export function OrbitGlyph({ tickMs = 120 }) {
39
- return _jsx(Text, { color: "#b98cff", children: useFrame(ORBIT, true, tickMs) });
40
+ return _jsx(Text, { color: theme.accent, children: useFrame(ORBIT, true, tickMs) });
40
41
  }
41
42
  /** Self-heal in progress (context compaction / reconnect). Shown INSTEAD of a raw "http 400" so a
42
43
  * recovery reads as the agent working it out, not an error — amber turning disc + a calm label. */
@@ -44,5 +45,5 @@ export function RecoverSpinner({ active, label, tickMs = 130 }) {
44
45
  const glyph = useFrame(SETTLE, active, tickMs);
45
46
  if (!active)
46
47
  return null;
47
- return (_jsxs(Text, { color: "#e8a33d", children: [glyph, " ", label ?? "adjusting", "\u2026"] }));
48
+ return (_jsxs(Text, { color: theme.running, children: [glyph, " ", label ?? "adjusting", "\u2026"] }));
48
49
  }
package/dist/ui/App.js CHANGED
@@ -1,5 +1,6 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { Box, Text } from "ink";
3
+ import { termRows } from "./term.js";
3
4
  import { StatusRule } from "./StatusRule.js";
4
5
  import { InputRule } from "./InputRule.js";
5
6
  import { Transcript } from "./Transcript.js";
@@ -7,6 +8,7 @@ import { Composer } from "./Composer.js";
7
8
  import { ThinkingSpinner } from "./ThinkingSpinner.js";
8
9
  import { StepSpinner, RecoverSpinner } from "./ActivitySpinner.js";
9
10
  import { BgPanel } from "./BgPanel.js";
11
+ import { PlanPane } from "./PlanPane.js";
10
12
  import { ToolStep } from "./ToolStep.js";
11
13
  import { ApprovalPrompt } from "./ApprovalPrompt.js";
12
14
  import { QuestionPrompt } from "./QuestionPrompt.js";
@@ -16,13 +18,29 @@ import { QuestionPrompt } from "./QuestionPrompt.js";
16
18
  // calls at once; anything past the cap is summarized as a count instead of another row.
17
19
  const MAX_LIVE_TOOL_ROWS = 6;
18
20
  export function App(props) {
19
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, onSubmit, onQueue, onInterrupt, onCycleMode, opMode, approval = null, onApprovalDecide, question = null, modelPicker = null } = props;
21
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, tasks = [], onSubmit, onQueue, onInterrupt, onCycleMode, opMode, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null } = props;
20
22
  const thinking = status === "thinking" || status === "streaming";
21
23
  // A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
22
24
  // a lone call isn't worth a bordered block, the braille spinner + name already says enough.
23
25
  const showParallelRows = status === "executing" && liveTools.length > 1;
24
- const showSpinner = status === "recovering" || (status === "executing" && !showParallelRows) || thinking;
25
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), showSpinner && (_jsx(Box, { marginTop: 1, marginBottom: 1, children: status === "recovering" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
26
+ const showSpinner = status === "recovering" || status === "compacting" || (status === "executing" && !showParallelRows) || thinking;
27
+ // The live activity band (spinner / parallel-tool view) and the bg-agents panel — shared by both layouts.
28
+ const activity = (_jsxs(_Fragment, { children: [showSpinner && (_jsx(Box, { marginTop: 1, marginBottom: 1, children: status === "recovering" || status === "compacting" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
26
29
  : status === "executing" ? _jsx(StepSpinner, { active: true, label: stepLabel })
27
- : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), showParallelRows && (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "gray", paddingX: 1, children: [_jsxs(Text, { dimColor: true, children: ["running ", liveTools.length, " tools in parallel"] }), liveTools.slice(0, MAX_LIVE_TOOL_ROWS).map((step) => _jsx(ToolStep, { step: step }, step.id)), liveTools.length > MAX_LIVE_TOOL_ROWS ? _jsxs(Text, { dimColor: true, children: [" +", liveTools.length - MAX_LIVE_TOOL_ROWS, " more\u2026"] }) : null] })), _jsx(BgPanel, { agents: bgAgents }), _jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker }), _jsx(InputRule, {})] }));
30
+ : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), showParallelRows && (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, paddingLeft: 1, children: [_jsxs(Text, { dimColor: true, children: ["running ", liveTools.length, " tools in parallel"] }), liveTools.slice(0, MAX_LIVE_TOOL_ROWS).map((step) => _jsx(ToolStep, { step: step }, step.id)), liveTools.length > MAX_LIVE_TOOL_ROWS ? _jsxs(Text, { dimColor: true, children: [" +", liveTools.length - MAX_LIVE_TOOL_ROWS, " more\u2026"] }) : null] })), _jsx(PlanPane, { tasks: tasks }), _jsx(BgPanel, { agents: bgAgents }), (thinking || status === "executing" || status === "recovering") && (_jsx(Text, { dimColor: true, children: ` ${status === "executing" ? "running tools" : status === "recovering" ? "recovering" : status === "streaming" ? "writing" : "reasoning"} · esc to interrupt` }))] }));
31
+ // Interactive prompts own the keyboard while up; kept out of the fullscreen clip region so they can't
32
+ // be scrolled off. The Composer is `suspended` (keystrokes route to the decision, not the draft).
33
+ const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(QuestionPrompt, { pending: planExitPicker })] }));
34
+ // The pinned bottom band: status rule, composer, bottom rule, then the mode/cycle FOOTER below the rule.
35
+ const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!planExitPicker }), _jsx(InputRule, {}), opMode && (_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "◆ Autonomous" : opMode === "manual" ? "◈ Manual" : "◔ Plan"} · shift+tab to cycle` }))] }));
36
+ // Fullscreen (opt-in): a full-terminal-height column. The transcript fills a clipped, bottom-anchored
37
+ // region (non-Static tail) so the newest output sits just above a composer pinned to the very bottom —
38
+ // no dead space. Off by default: inline keeps the terminal's native scrollback (mouse-scroll + copy).
39
+ if (fullscreen) {
40
+ const rows = termRows();
41
+ return (_jsxs(Box, { flexDirection: "column", height: rows, children: [_jsxs(Box, { flexGrow: 1, flexDirection: "column", overflow: "hidden", justifyContent: "flex-end", children: [_jsx(Transcript, { entries: messages, live: live, bounded: true }), activity] }), prompts, bottom] }));
42
+ }
43
+ // Inline (default): the dynamic frame grows below the Static transcript; unused space sits below it and
44
+ // fills as the conversation grows. Native scrollback preserved.
45
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), activity, prompts, bottom] }));
28
46
  }
@@ -13,5 +13,5 @@ export function AuthScreen({ version, ctxWindow, authBase, pending, error, onCho
13
13
  else if (key.return || c === "g")
14
14
  onChoice("guest");
15
15
  });
16
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Masthead, { info: `Operator${ctxWindow && ctxWindow >= 1_000_000 ? " · 1M" : ""} · v${version}` }), _jsx(Box, { marginTop: 1, flexDirection: "column", paddingLeft: 1, children: pending ? (_jsxs(_Fragment, { children: [_jsxs(Text, { children: ["Signing in \u2014 open ", _jsx(Text, { color: "cyanBright", children: pending.url })] }), _jsxs(Text, { children: ["and enter code ", _jsx(Text, { bold: true, color: "whiteBright", children: pending.userCode })] }), _jsx(Text, { dimColor: true, children: "Waiting for approval in your browser\u2026 (Esc to cancel)" })] })) : (_jsxs(_Fragment, { children: [_jsx(Text, { color: "whiteBright", children: "Welcome to Operator." }), _jsx(Text, { dimColor: true, children: "A local terminal coding agent on your own model." }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: "magentaBright", bold: true, children: " s" }), " Sign in ", _jsx(Text, { dimColor: true, children: "\u2014 connect your account (browser approval)" })] }), _jsxs(Text, { children: [_jsx(Text, { color: "magentaBright", bold: true, children: " u" }), " Create account ", _jsxs(Text, { dimColor: true, children: ["\u2014 register at ", authBase.replace(/^https?:\/\//, "")] })] }), _jsxs(Text, { children: [_jsx(Text, { color: "magentaBright", bold: true, children: " \u21B5" }), " Continue as guest ", _jsx(Text, { dimColor: true, children: "\u2014 no account needed; sign in later with /login" })] })] }), error ? _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: "red", children: error }) }) : null] })) })] }));
16
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Masthead, { info: `Operator${ctxWindow ? ` · ${ctxWindow >= 1_000_000 ? "1M" : `${Math.round(ctxWindow / 1024)}K`}` : ""} · v${version}` }), _jsx(Box, { marginTop: 1, flexDirection: "column", paddingLeft: 1, children: pending ? (_jsxs(_Fragment, { children: [_jsxs(Text, { children: ["Signing in \u2014 open ", _jsx(Text, { color: "cyanBright", children: pending.url })] }), _jsxs(Text, { children: ["and enter code ", _jsx(Text, { bold: true, color: "whiteBright", children: pending.userCode })] }), _jsx(Text, { dimColor: true, children: "Waiting for approval in your browser\u2026 (Esc to cancel)" })] })) : (_jsxs(_Fragment, { children: [_jsx(Text, { color: "whiteBright", children: "Welcome to Operator." }), _jsx(Text, { dimColor: true, children: "A local terminal coding agent on your own model." }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: "magentaBright", bold: true, children: " s" }), " Sign in ", _jsx(Text, { dimColor: true, children: "\u2014 connect your account (browser approval)" })] }), _jsxs(Text, { children: [_jsx(Text, { color: "magentaBright", bold: true, children: " u" }), " Create account ", _jsxs(Text, { dimColor: true, children: ["\u2014 register at ", authBase.replace(/^https?:\/\//, "")] })] }), _jsxs(Text, { children: [_jsx(Text, { color: "magentaBright", bold: true, children: " \u21B5" }), " Continue as guest ", _jsx(Text, { dimColor: true, children: "\u2014 no account needed; sign in later with /login" })] })] }), error ? _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: "red", children: error }) }) : null] })) })] }));
17
17
  }