@0perator/operator 0.1.263 → 0.1.275

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 (38) hide show
  1. package/dist/auth/store.js +36 -5
  2. package/dist/cli.js +119 -26
  3. package/dist/config/persona.js +14 -1
  4. package/dist/engine/agent.js +4 -4
  5. package/dist/engine/anthropic.js +48 -0
  6. package/dist/engine/batch-scheduler.js +68 -21
  7. package/dist/engine/cli.js +1171 -0
  8. package/dist/mcp/index.js +2 -1
  9. package/dist/permissions/index.js +11 -4
  10. package/dist/remote/host.js +46 -5
  11. package/dist/remote/pairing.js +70 -0
  12. package/dist/router/models.js +8 -1
  13. package/dist/router/models.js.bak +78 -0
  14. package/dist/router/models.js.bak-1791259923 +78 -0
  15. package/dist/router/models.js.bak-pre-gateway +78 -0
  16. package/dist/router/models.js.bak-pre-patch2 +78 -0
  17. package/dist/router/models.js.bak2 +78 -0
  18. package/dist/services/model-autodetect.js +240 -0
  19. package/dist/tools/chauffeur.js +16 -3
  20. package/dist/tools/deferred.js +2 -1
  21. package/dist/tools/executor.js +15 -3
  22. package/dist/tools/native-redirect.js +140 -0
  23. package/dist/tools/power-tools.js +627 -0
  24. package/dist/tools/registry.js +252 -5
  25. package/dist/tools/registry.js.bak-1791259948 +1914 -0
  26. package/dist/tools/registry.js.bak-pre-plugins +1914 -0
  27. package/dist/ui/App.js +5 -4
  28. package/dist/ui/BusTray.js +70 -0
  29. package/dist/ui/Composer.js +28 -1
  30. package/dist/ui/ToolStep.js +1 -1
  31. package/dist/ui/format.js +18 -0
  32. package/dist/ui/liveTools.js +2 -5
  33. package/dist/ui/qr.js +10 -0
  34. package/dist/ui/resize.js +160 -0
  35. package/dist/ui/slashCommands.js +43 -0
  36. package/dist/ui/term.js +17 -0
  37. package/dist/util/slash.js +1 -1
  38. package/package.json +3 -1
@@ -11,9 +11,20 @@ import { operatorPath } from "../config/home.js";
11
11
  const SERVICE = "axe-operator"; // keychain service — shared contract with the Python client
12
12
  const ACCOUNT = "default";
13
13
  const FILE = process.env.KODE_CREDENTIALS ?? operatorPath("credentials.json");
14
+ // Every keychain call is a CHILD PROCESS, and at boot one is AWAITED before the first frame (cli.tsx
15
+ // top-level). A `security`/`secret-tool` that never returns — locked login keychain behind a GUI prompt,
16
+ // SSH/launchd context, MDM enrollment hiccup — used to hang Operator's startup indefinitely (measured:
17
+ // a keychain process that sleeps 5s turns `operator --version` from 0.46s into 5.60s; the sleep is the
18
+ // unbounded case). So the lookup gets a HARD BUDGET: on expiry the child is killed and we degrade to the
19
+ // 0600-file fallback. Override with KODE_KEYCHAIN_TIMEOUT_MS (0 disables the timeout).
20
+ const KEYCHAIN_TIMEOUT_MS = (() => {
21
+ const n = Number(process.env.KODE_KEYCHAIN_TIMEOUT_MS);
22
+ return Number.isFinite(n) && n >= 0 ? n : 1500;
23
+ })();
24
+ let timedOutOnce = false;
14
25
  function run(cmd, args, input) {
15
26
  return new Promise((resolve, reject) => {
16
- const child = execFile(cmd, args, (err, stdout) => (err ? reject(err) : resolve(stdout.toString())));
27
+ const child = execFile(cmd, args, KEYCHAIN_TIMEOUT_MS > 0 ? { timeout: KEYCHAIN_TIMEOUT_MS } : {}, (err, stdout) => (err ? reject(err) : resolve(stdout.toString())));
17
28
  if (input !== undefined) {
18
29
  child.stdin?.end(input);
19
30
  }
@@ -51,8 +62,16 @@ async function keychainGet() {
51
62
  return (await run("secret-tool", ["lookup", "service", SERVICE, "account", ACCOUNT])).trim() || null;
52
63
  }
53
64
  }
54
- catch {
55
- /* not found / no keychain */
65
+ catch (err) {
66
+ // Two different silences used to be conflated here: "no entry" (normal, signed-out box) and
67
+ // "the helper never answered" (locked keychain / hung helper). The second is an operator-visible
68
+ // fault — say it ONCE on stderr, then keep booting on the file fallback.
69
+ if (err?.killed || err?.signal === "SIGTERM") {
70
+ if (!timedOutOnce) {
71
+ timedOutOnce = true;
72
+ process.stderr.write(`operator: keychain lookup timed out after ${KEYCHAIN_TIMEOUT_MS}ms — falling back to the file store (sign-in state may read stale)\n`);
73
+ }
74
+ }
56
75
  }
57
76
  return null;
58
77
  }
@@ -79,15 +98,26 @@ async function readMeta() {
79
98
  }
80
99
  /** Persist credentials: token to the keychain (or, if unavailable, the 0600 file), metadata always to file. */
81
100
  export async function saveCredentials(creds) {
101
+ credsCache = null; // any write invalidates the memoized read (a fresh sign-in beats the cached miss)
82
102
  await mkdir(dirname(FILE), { recursive: true, mode: 0o700 });
83
103
  const inKeychain = await keychainSet(creds.token);
84
104
  // File holds metadata always; it holds the token too ONLY when the keychain couldn't (fallback).
85
105
  const onDisk = { user: creds.user, host: creds.host, issuedAt: creds.issuedAt, ...(inKeychain ? {} : { token: creds.token }) };
86
106
  await writeFile(FILE, JSON.stringify(onDisk, null, 2), { mode: 0o600 });
87
107
  await chmod(FILE, 0o600).catch(() => { });
108
+ credsCache = null;
109
+ }
110
+ /** Load credentials, or null if not signed in. Prefers the keychain token; falls back to the file's.
111
+ * Single-flighted: a session boot reaches this from FOUR sites (cli top-level bootCreds, the RC
112
+ * auto-start gate, the footer sign-in effect, and every /remotecontrol|/pair invocation). Each used to
113
+ * spawn its own keychain child process on the critical path; now the first call's (now time-bounded)
114
+ * promise is shared, so one boot costs at most ONE keychain read. save/clear drop the cache so an
115
+ * in-session sign-in is seen immediately by the next caller. */
116
+ let credsCache = null;
117
+ export function loadCredentials() {
118
+ return (credsCache ??= loadCredentialsFresh());
88
119
  }
89
- /** Load credentials, or null if not signed in. Prefers the keychain token; falls back to the file's. */
90
- export async function loadCredentials() {
120
+ async function loadCredentialsFresh() {
91
121
  const meta = await readMeta();
92
122
  const token = (await keychainGet()) ?? meta.token ?? null;
93
123
  if (!token)
@@ -96,6 +126,7 @@ export async function loadCredentials() {
96
126
  }
97
127
  /** Sign out: drop the keychain entry and the on-disk file. */
98
128
  export async function clearCredentials() {
129
+ credsCache = null;
99
130
  await keychainClear();
100
131
  await rm(FILE, { force: true });
101
132
  }
package/dist/cli.js CHANGED
@@ -10,8 +10,10 @@ import { App } from "./ui/index.js";
10
10
  import { mastheadLines } from "./ui/Masthead.js";
11
11
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
12
12
  import { RemoteHost } from "./remote/host.js";
13
+ import { newCode, pairURL } from "./remote/pairing.js";
14
+ import { qrToTerminal } from "./ui/qr.js";
13
15
  import { pollBus, pollSent, selfAgent } from "./bus/inbox.js";
14
- import { isErrorResult } from "./ui/format.js";
16
+ import { isErrorResult, resultPreview } from "./ui/format.js";
15
17
  import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
16
18
  import { Session } from "./session.js";
17
19
  import { cacheBustNotice } from "./engine/aurora.js";
@@ -25,6 +27,7 @@ import { caps } from "./ui/capabilities.js";
25
27
  import { composeSystemPrompt, appendMemory } from "./config/persona.js";
26
28
  import { applyToolsBinPath, operatorPath } from "./config/home.js";
27
29
  import { ensureOperatorHome } from "./config/scaffold.js";
30
+ import { listLocalSkills } from "./config/skills-index.js";
28
31
  import { modelCtxFor, LEAN_HARNESS_CTX } from "./router/models.js";
29
32
  import { disposeShellSession, getAgentTasks } from "./tools/registry.js";
30
33
  import { disposeBrowserNow } from "./browser/session.js";
@@ -50,6 +53,20 @@ const VERSION = (() => {
50
53
  return "0.0.0";
51
54
  }
52
55
  })();
56
+ // Fast paths that must NOT mount Ink/React (so `operator --version` works with no TTY and returns instantly)
57
+ // — and must not do ANY identity I/O either. They used to sit BELOW the boot credential load, so even
58
+ // `--version` paid a keychain child-process spawn on the critical path: with a hung `security` helper the
59
+ // "instant" command took the full 5s of a 5s sleep (∞ if the keychain never answers). Hoisted above every
60
+ // awaited boot import, they now exit before the first process spawn — version/help are pure constants.
61
+ if (process.argv.includes("--version") || process.argv.includes("-V")) {
62
+ process.stdout.write(VERSION + "\n");
63
+ process.exit(0);
64
+ }
65
+ if (process.argv.includes("--help")) {
66
+ process.stdout.write(mastheadLines(`300K · v${VERSION}`).join("\n") +
67
+ "\n\nUsage:\n operator start the interactive session\n operator --resume resume the last session in this directory\n operator --update update to the latest build (git fast-forward)\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator run <task> run one task headless\n operator --version print the version\n");
68
+ process.exit(0);
69
+ }
53
70
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
54
71
  const settings = loadSettings();
55
72
  // Enterprise first-run: make the operator home's contract explicit BEFORE any module writes into it (0700
@@ -300,7 +317,7 @@ const HELP = [
300
317
  " /remember <note> store a note to recall in future sessions",
301
318
  " /memory [query] show remembered notes (all, or matching query)",
302
319
  " /mcp [on|off] fleet MCP tools: status, or switch the layer on/off (saved)",
303
- " /login <email> · /logout · /whoami sign in by 6-digit email code (then /login <code>); /login <token> or --browser",
320
+ " /login · /logout · /whoami /login opens the browser to approve; or /login <email> for a 6-digit code (then /login <code>); /login <token>",
304
321
  " /agents detailed sub-agent status: running/queued/done/errored + metrics",
305
322
  " /bg <task|stop id> spawn a background sub-agent, list, or stop one",
306
323
  " /new start a fresh conversation",
@@ -343,7 +360,6 @@ const REMOTE_SAFE_COMMANDS = [
343
360
  const REMOTE_SAFE_COMMAND_NAMES = new Set(REMOTE_SAFE_COMMANDS.map((c) => c.name));
344
361
  let ID = 0;
345
362
  const nextId = () => `e${++ID}`;
346
- const firstLine = (s) => (s.split("\n")[0] ?? "").slice(0, 100);
347
363
  // Time+token readout in the "(7m 8s · 22.6k tokens)" shape: minutes+seconds past a minute, k-abbreviated
348
364
  // tokens past 1000. One helper so the live line and the settled metric read identically.
349
365
  const fmtDuration = (sec) => (sec < 60 ? `${sec < 10 ? sec.toFixed(1) : Math.round(sec)}s` : `${Math.floor(sec / 60)}m ${Math.round(sec % 60)}s`);
@@ -586,10 +602,12 @@ function Root() {
586
602
  setLiveTok(liveTokRef.current);
587
603
  }, 64)).current;
588
604
  const queued = useRef("");
605
+ const [queuedPreview, setQueuedPreview] = useState(""); // reactive mirror of the queue, shown above the composer so a type-while-thinking message is VISIBLE
589
606
  const statusRef = useRef("idle");
590
607
  // Remote-control host (SPEC/remote-session.md): non-null only while /remotecontrol is active. Every
591
608
  // state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
592
609
  const remoteRef = useRef(null);
610
+ const [rcConnected, setRcConnected] = useState(false); // remote-control live? drives the footer controller icon
593
611
  const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); };
594
612
  const push = (e) => setEntries((prev) => [...prev, e]);
595
613
  const submitRef = useRef(() => { });
@@ -817,7 +835,7 @@ function Root() {
817
835
  const step = {
818
836
  id: nextId(), name: ev.name, args: ev.args,
819
837
  status: isErrorResult(ev.result) ? "error" : "done",
820
- durationMs, summary: firstLine(ev.result),
838
+ durationMs, summary: resultPreview(ev.result),
821
839
  };
822
840
  steps.push(step);
823
841
  remoteRef.current?.toolStep(step);
@@ -922,6 +940,7 @@ function Root() {
922
940
  remoteRef.current?.setCapabilities(buildCapabilities());
923
941
  const q = queued.current;
924
942
  queued.current = "";
943
+ setQueuedPreview("");
925
944
  if (q)
926
945
  submitRef.current(q);
927
946
  }
@@ -1211,16 +1230,12 @@ function Root() {
1211
1230
  break;
1212
1231
  }
1213
1232
  if (intent === "empty") {
1214
- // A second consecutive bare /login escalates to the browser device-grant.
1215
- if (loginEmptyRetryRef.current) {
1216
- loginEmptyRetryRef.current = false;
1217
- await runBrowserLogin();
1218
- break;
1219
- }
1220
- loginEmptyRetryRef.current = true;
1221
- sys(pendingLoginEmailRef.current
1222
- ? `a code was sent to ${pendingLoginEmailRef.current} — enter it with /login <6-digit code> (or press /login again to open the browser)`
1223
- : "usage: /login <email> — sends a 6-digit sign-in code (then /login <code>). Press /login again to open the browser; /login <token> pastes a PAT.");
1233
+ // Bare /login is the HOT sign-in: open the browser + RFC 8628 device-grant IMMEDIATELY and poll to
1234
+ // approval, signing in IN-SESSION (the 0perator.co device page + awaitApproval close the loop now,
1235
+ // so the old "janky dead-end" note no longer applies). /login <email> still does the 6-digit-code
1236
+ // flow; /login <token> pastes a PAT; /login --browser is the same browser path, explicit.
1237
+ loginEmptyRetryRef.current = false;
1238
+ await runBrowserLogin();
1224
1239
  break;
1225
1240
  }
1226
1241
  if (intent === "code") { // a 6-digit code completes a pending email sign-in
@@ -1296,6 +1311,34 @@ function Root() {
1296
1311
  }
1297
1312
  break;
1298
1313
  }
1314
+ case "skills": {
1315
+ // List the locally-installed skills (operator-home skills index). The 60k+ fleet catalogue stays
1316
+ // searchable mid-task via the skill_list tool — this is just the at-a-glance local view, like /memory.
1317
+ const q = arg.toLowerCase();
1318
+ let skills = listLocalSkills();
1319
+ if (q)
1320
+ skills = skills.filter((sk) => sk.name.toLowerCase().includes(q) || (sk.description ?? "").toLowerCase().includes(q));
1321
+ if (!skills.length) {
1322
+ sys(q ? `no installed skills match "${arg}" — the fleet catalogue is still searchable mid-task via the skill_list tool` : "no skills installed locally — the fleet's 60k+ catalogue is searchable mid-task via the skill_list tool");
1323
+ break;
1324
+ }
1325
+ const rows = skills.slice(0, 40).map((sk) => ` ◆ ${sk.name}${sk.description ? ` — ${sk.description.length > 80 ? sk.description.slice(0, 79) + "…" : sk.description}` : ""}`);
1326
+ sys(`skills (${skills.length}${q ? ` matching "${arg}"` : ""}):\n` + rows.join("\n") + (skills.length > 40 ? `\n … +${skills.length - 40} more` : "") + "\n(the fleet's 60k+ catalogue is also searchable mid-task via the skill_list tool)");
1327
+ break;
1328
+ }
1329
+ case "deep-research":
1330
+ case "deepresearch":
1331
+ case "research": {
1332
+ // Sugar for the deep_research tool: plan angles → web_search fan-out → web_fetch → cited brief.
1333
+ // Kicks a real turn so the engine runs the tool (and the owner sees progress), never fabricates sources.
1334
+ if (!arg) {
1335
+ sys("usage: /deep-research <question> — fans out web searches, reads sources, returns a cited brief. One fact is faster with plain web_search.");
1336
+ break;
1337
+ }
1338
+ sys(`◍ deep research: "${arg}" — planning angles, searching + reading sources, then a cited brief…`);
1339
+ void sendTurn(`Use the deep_research tool to research this thoroughly and give me a cited, multi-source brief: ${arg}`);
1340
+ break;
1341
+ }
1299
1342
  case "endpoints": {
1300
1343
  const h = await s.endpointHealth();
1301
1344
  sys("endpoints:\n" + s.endpoints().map((e) => ` ${h[e.name] ? "●" : "○"} ${e.name} ${e.base} ${e.model} ctx ${e.ctxWindow.toLocaleString()}`).join("\n"));
@@ -1546,6 +1589,7 @@ function Root() {
1546
1589
  submitRef.current(`/${name}${args ? " " + args : ""}`);
1547
1590
  },
1548
1591
  onState: (st, detail) => {
1592
+ setRcConnected(st === "live"); // footer controller icon: green when live, gray otherwise
1549
1593
  if (st === "live")
1550
1594
  sys(`✷ remote control LIVE — session ${rh.id}\n Continue on your phone or at https://0perator.co/session/${rh.id}\n /remotecontrol again to stop.`);
1551
1595
  else if (st === "error")
@@ -1565,6 +1609,64 @@ function Root() {
1565
1609
  sys(`connecting remote control → ${url} …`);
1566
1610
  break;
1567
1611
  }
1612
+ case "pair": {
1613
+ // Show a QR a phone scans (Operator app → "Pair Desktop") to drive THIS session, e2e-encrypted. Same
1614
+ // token preflight as /remotecontrol — the host still authenticates to the relay under the owner's
1615
+ // token (the owner-scope gate); the scanned 128-bit code is the end-to-end key the relay never sees.
1616
+ if (remoteRef.current) {
1617
+ remoteRef.current.stop();
1618
+ remoteRef.current = null;
1619
+ setRcConnected(false);
1620
+ sys("pairing stopped — followers detached");
1621
+ break;
1622
+ }
1623
+ const { loadCredentials } = await import("./auth/store.js");
1624
+ const creds = await loadCredentials().catch(() => null);
1625
+ const token = process.env.KODE_OPERATOR_TOKEN || creds?.token || "";
1626
+ if (!token) {
1627
+ sys("pairing needs an Operator sign-in on THIS machine — none found.\n" +
1628
+ " Sign in here first, then re-run /pair:\n" +
1629
+ " • run `operator auth login` in your shell (browser sign-in), or\n" +
1630
+ " • /login <token> to paste a token");
1631
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_no_token" } });
1632
+ break;
1633
+ }
1634
+ const url = process.env.KODE_RELAY_URL || "wss://api.axe.onl/session/ws";
1635
+ const code = newCode();
1636
+ const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
1637
+ onPrompt: (text) => submitRef.current(text),
1638
+ onApprovalResponse: (id, approve) => settleApproval(id, approve),
1639
+ onAskUserResponse: (id, answer) => settleQuestion(id, answer),
1640
+ onInterrupt: () => s.interrupt(),
1641
+ onCommand: (cmdName, cmdArgs) => {
1642
+ if (!REMOTE_SAFE_COMMAND_NAMES.has(cmdName)) {
1643
+ sys(`remote control: blocked "/${cmdName}" from a follower — not exposed for remote dispatch`);
1644
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command_blocked", detail: cmdName } });
1645
+ return;
1646
+ }
1647
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command", detail: cmdArgs ? `${cmdName} ${cmdArgs}` : cmdName } });
1648
+ submitRef.current(`/${cmdName}${cmdArgs ? " " + cmdArgs : ""}`);
1649
+ },
1650
+ onState: (st, detail) => {
1651
+ setRcConnected(st === "live");
1652
+ if (st === "error")
1653
+ sys(`pairing error: ${detail ?? "connection lost"} — /pair to retry`);
1654
+ else if (st === "closed")
1655
+ sys("pairing disconnected");
1656
+ if (st === "live")
1657
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_connected", detail: rh.id ?? undefined } });
1658
+ else if (st === "closed" || st === "error")
1659
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_disconnected", detail } });
1660
+ },
1661
+ }, { sessionId: SESSION_ID, code });
1662
+ remoteRef.current = rh;
1663
+ rh.setCapabilities(buildCapabilities());
1664
+ rh.connect();
1665
+ const link = pairURL(code, SESSION_ID);
1666
+ const qr = await qrToTerminal(link);
1667
+ sys(`▮ Pair this desktop — in the Operator app tap "Pair Desktop → Scan QR" and point it here:\n\n${qr}\n\n …or choose "Paste code" and paste:\n ${link}\n\n End-to-end encrypted — the relay only ever sees a blind id, never the code. /pair again to stop.`);
1668
+ break;
1669
+ }
1568
1670
  default: sys(`unknown command /${name} — try /help`);
1569
1671
  }
1570
1672
  }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode]);
@@ -1576,7 +1678,7 @@ function Root() {
1576
1678
  void sendTurn(text);
1577
1679
  }, [sendTurn, handleSlash]);
1578
1680
  submitRef.current = onSubmit;
1579
- const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; }, []);
1681
+ const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; setQueuedPreview(queued.current); }, []);
1580
1682
  // Shift+Tab cycles the operating mode (Claude-Code parity). auto→manual→plan→auto. Auto drives with
1581
1683
  // no approval gate; Manual gates mutating tools through the approve() bridge; Plan is read-only research.
1582
1684
  const onCycleMode = useCallback(() => {
@@ -1643,7 +1745,7 @@ function Root() {
1643
1745
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
1644
1746
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
1645
1747
  : metrics;
1646
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, onApprovalDecide: (allow, always) => {
1748
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, rcConnected: rcConnected, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, onApprovalDecide: (allow, always) => {
1647
1749
  const cur = approval;
1648
1750
  if (cur)
1649
1751
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -1651,16 +1753,7 @@ function Root() {
1651
1753
  }
1652
1754
  // `operator auth …` runs as a plain CLI before the Ink shell — no TTY needed, so PAT login works
1653
1755
  // headless (CI / SSH). Anything else falls through to the interactive REPL below.
1654
- // Fast paths that must NOT mount Ink/React (so `operator --version` works with no TTY and returns instantly).
1655
- if (process.argv.includes("--version") || process.argv.includes("-V")) {
1656
- process.stdout.write(VERSION + "\n");
1657
- process.exit(0);
1658
- }
1659
- if (process.argv.includes("--help")) {
1660
- process.stdout.write(mastheadLines(`300K · v${VERSION}`).join("\n") +
1661
- "\n\nUsage:\n operator start the interactive session\n operator --resume resume the last session in this directory\n operator --update update to the latest build (git fast-forward)\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator run <task> run one task headless\n operator --version print the version\n");
1662
- process.exit(0);
1663
- }
1756
+ // (--version/--help fast paths hoisted to the top of the module — they must never touch keychain/network.)
1664
1757
  if (process.argv[2] === "auth") {
1665
1758
  const { runAuth } = await import("./auth/commands.js");
1666
1759
  process.exit(await runAuth(process.argv.slice(3), settings));
@@ -234,7 +234,11 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
234
234
  `model you don't have. It also accepts \`reference\`+\`strength\`, passed through to the broker. (b) VIDEO ` +
235
235
  `— \`video_generate\` → LTX-Video-0.9.5 on the video broker, with \`expand\` and \`reference_image\` ` +
236
236
  `(IMAGE-TO-VIDEO): pass an image and LTX conditions on it as the FIRST FRAME, so the subject in the clip ` +
237
- `IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` → Qwen2-VL-7B on the fleet.` +
237
+ `IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` → a Qwen2-VL worker on the ` +
238
+ `fleet (REAL vision, not guessing from a filename). It walks an ordered endpoint chain with per-endpoint ` +
239
+ `health-cooldown + an optional cloud fallback, so a cold/busy worker never hard-fails; large images are ` +
240
+ `auto-downscaled before the model sees them. To match a reference, \`image_analyze\` it FIRST, then write ` +
241
+ `your generate prompt from what you actually SAW.` +
238
242
  `\n**Likeness is LIVE — this is how you "generate HER".** To make a SPECIFIC person, pass their FACE photo ` +
239
243
  `as \`reference\` to \`image_generate\`: it routes to the identity broker (RealVisXL + IP-Adapter-FaceID) ` +
240
244
  `which preserves that exact face (arcface-verified) in whatever new scene/pose your prompt describes — you ` +
@@ -243,6 +247,15 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
243
247
  `off as an exact match. A VIDEO of that person from a shared image works too (its first frame IS the real ` +
244
248
  `photo) via \`reference_image\` on \`video_generate\`. Every generation is logged to a provenance flywheel, ` +
245
249
  `so the pipeline compounds with use.` +
250
+ `\n## Deep research — \`deep_research\` (cited, multi-source)\nWhen a question needs more than one search — a ` +
251
+ `comparison, a state-of-the-art survey, sourced background — reach for \`deep_research\`: it plans several ` +
252
+ `search angles, fans out \`web_search\` + \`web_fetch\` across them, and returns a brief with inline source ` +
253
+ `citations. A single lookup is faster with plain \`web_search\`; use \`deep_research\` when depth and ` +
254
+ `citations matter. It never invents sources — if the search backend is down it says so rather than guessing.` +
255
+ // 96e159b swallowed the OPENING line of the section below ("## Running scripts — …\nFor anything more
256
+ // than a ONE-LINE snippet, write "), orphaning its tail mid-sentence: the LIVE interactive persona
257
+ // shipped as "...rather than guessing.the script to a file…" — no heading, no space (the persona
258
+ // parity test's red on main was the witness). Restored as its own section; do not re-splice.
246
259
  `\n## Running scripts — never inline a multi-line script\nFor anything more than a ONE-LINE snippet, write ` +
247
260
  `the script to a file with file_write and run the file (\`python3 /tmp/probe.py\`). Do NOT embed a ` +
248
261
  `multi-line program inside \`python3 -c "…"\` or \`bash -c "…"\`: the newlines, \`#\` comments and quotes ` +
@@ -257,7 +257,7 @@ function parseArgs(raw) {
257
257
  * guard (SPEC §2: identical (name,args) ≥3× this turn is short-circuited) and reporting the
258
258
  * batch via onToolBatch with a real (unrounded) duration.
259
259
  */
260
- async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolStart, onToolResult) {
260
+ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolStart, onToolResult, signal) {
261
261
  // One id for this whole round (SPEC parallel-tool-batch) — every call made here, however it
262
262
  // resolves (executed, parse error, loop-guarded), shares it, so a host can box "N tools in
263
263
  // parallel" together even for the calls that never reached the executor. Same id-shape idiom as
@@ -310,7 +310,7 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
310
310
  onToolStart?.(pending);
311
311
  const started = performance.now();
312
312
  const executed = pending.length
313
- ? await tools.executeParallel(pending, onToolResult ? (i, r) => onToolResult(pending[i].id, r, batchId) : undefined)
313
+ ? await tools.executeParallel(pending, onToolResult ? (i, r) => onToolResult(pending[i].id, r, batchId) : undefined, signal)
314
314
  : [];
315
315
  const durationMs = performance.now() - started;
316
316
  const resultById = new Map(preResolved);
@@ -860,7 +860,7 @@ export async function runTurn(userInput, conversation, opts) {
860
860
  conversation.assistant(response.content, response.toolCalls);
861
861
  // Race the batch against the abort signal so esc breaks even a hung tool (a frozen child process) —
862
862
  // the abandoned tool runs to its own timeout, but the turn is never wedged.
863
- const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
863
+ const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal), opts.signal);
864
864
  for (const tm of capToolRound(toolMsgs))
865
865
  conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
866
866
  observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
@@ -878,7 +878,7 @@ export async function runTurn(userInput, conversation, opts) {
878
878
  if (recovered.calls.length > 0) {
879
879
  throwIfAborted(opts.signal);
880
880
  conversation.assistant(recovered.cleanedContent, recovered.calls);
881
- const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
881
+ const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal), opts.signal);
882
882
  for (const tm of capToolRound(toolMsgs))
883
883
  conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
884
884
  observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
@@ -0,0 +1,48 @@
1
+ // Anthropic Messages API client — the one cloud model Operator calls DIRECTLY (outside the OpenAI-shaped
2
+ // router), used by the deep_research tool. Anthropic's wire format differs from OpenAI: `x-api-key` auth
3
+ // (not Bearer), an `anthropic-version` header, a top-level `system`, and a `content[]` array in the reply.
4
+ // Key resolution: KODE_ANTHROPIC_KEY, then ANTHROPIC_API_KEY. Model: KODE_RESEARCH_MODEL, else Haiku 4.5.
5
+ const DEFAULT_MODEL = process.env.KODE_RESEARCH_MODEL || "claude-haiku-4-5-20251001";
6
+ export function anthropicKey() {
7
+ return process.env.KODE_ANTHROPIC_KEY || process.env.ANTHROPIC_API_KEY || undefined;
8
+ }
9
+ /** POST one Anthropic Messages turn and return the concatenated text of the reply. Throws on a missing
10
+ * key, a non-200, or a timeout — the caller surfaces that to the model as a tool error. */
11
+ export async function anthropicComplete(system, user, opts = {}) {
12
+ const key = anthropicKey();
13
+ if (!key)
14
+ throw new Error("no Anthropic API key configured"); // key env vars documented in AGENTS.md
15
+ const ctrl = new AbortController();
16
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 120_000);
17
+ try {
18
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
19
+ method: "POST",
20
+ signal: ctrl.signal,
21
+ headers: {
22
+ "Content-Type": "application/json",
23
+ "x-api-key": key,
24
+ "anthropic-version": "2023-06-01",
25
+ "User-Agent": "operator/kode-tsi",
26
+ },
27
+ body: JSON.stringify({
28
+ model: opts.model || DEFAULT_MODEL,
29
+ max_tokens: opts.maxTokens ?? 4096,
30
+ temperature: opts.temperature ?? 0.3,
31
+ system,
32
+ messages: [{ role: "user", content: user }],
33
+ }),
34
+ });
35
+ if (!res.ok) {
36
+ const body = (await res.text().catch(() => "")).slice(0, 300);
37
+ throw new Error(`Anthropic ${res.status}${body ? ` — ${body}` : ""}`);
38
+ }
39
+ const j = (await res.json());
40
+ const text = (j.content ?? []).filter((b) => b.type === "text").map((b) => b.text ?? "").join("").trim();
41
+ if (!text)
42
+ throw new Error("Anthropic returned no text");
43
+ return text;
44
+ }
45
+ finally {
46
+ clearTimeout(timer);
47
+ }
48
+ }
@@ -9,14 +9,16 @@
9
9
  // key equals or is a path prefix of the other (dir vs child), when either is a device barrier, or
10
10
  // both are unknown-name writes with no keys (conservative: no keys + mutating = device-class).
11
11
  // • READS (pure ops) run alongside anything that cannot change what they observe: they wait only for
12
- // prior WRITES on conflicting keys. WRITES wait for everything conflicting (read-after-write is a
13
- // read's concern; write-after-write and write-after-read are this write's concern) — serialized
14
- // per-resource in INPUT ORDER via the resource's tail promise.
12
+ // prior WRITES on conflicting keys. WRITES wait for everything conflicting — prior writes AND prior
13
+ // reads that named an overlapping resource (RAW, WAW and WAR) — so a batch is observably equivalent to
14
+ // running it one call at a time in input order, on every resource it shares. A read that named no
15
+ // resource (web_search, memory_search…) never holds a writer back.
15
16
  // • Barrier tools (bash/shell_exec/git_command/checkpoint/computer_*/browser*/browser_vault/…) can
16
17
  // touch ANYTHING and share one persistent shell — they run alone, in input order.
17
18
  // • A rejected/denied run resolves as a string (executor contract: resolve-not-reject); one call's
18
19
  // failure never strands its dependents — the chain advances regardless.
19
20
  // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
21
+ export const cancelledResult = (name) => `cancelled: ${name} did not start — the turn was interrupted before it ran`;
20
22
  const BARRIER_EXACT = new Set([
21
23
  "bash", "shell_exec", "shell_background", "bash_kill",
22
24
  "git_command", "checkpoint", "tool_call",
@@ -34,17 +36,35 @@ export function defaultClassify(name, isSafe) {
34
36
  return isSafe(n) ? "read" : "write";
35
37
  };
36
38
  }
37
- /** Path-ish arg keys: any string value under a path-named arg, normalized to a comparable key.
38
- * A MUTATING call with no path keys gets a per-name lock — injected by runBatch (which knows the
39
- * class), never here: reads must not acquire locks or they could never pair with their writes. */
40
- export function defaultKeys(_name, args) {
39
+ const KEY_ARG = /path|dir|file|cwd|target|token|handle|^(out|output|dest|destination)$/i; // output-path args name a file the call WRITES
40
+ const KEY_DEPTH = 4;
41
+ /** Resource keys of a call: every string under a path-named arg — directly, as an array element (read_files
42
+ * `paths`), or inside a nested object (`edits:[{path}]`; a name set at the nearest object key) — normalized to a
43
+ * comparable key. `resolve` lets the node-side executor turn a spelling into the absolute path the tool will
44
+ * touch (cwd/root/~ are not the scheduler's to know). A MUTATING call with no keys gets a per-name lock —
45
+ * injected by runBatch (which knows the class), never here: reads must not acquire locks or they could never
46
+ * pair with their writes. */
47
+ export function defaultKeys(_name, args, resolve) {
41
48
  const out = [];
42
- for (const [k, v] of Object.entries(args ?? {})) {
43
- if (typeof v === "string" && v && /path|dir|file|cwd|target|token|handle/i.test(k))
44
- out.push(normKey(v));
45
- }
49
+ collectKeys(args ?? {}, "", false, 0, out, resolve);
46
50
  return out;
47
51
  }
52
+ function collectKeys(v, argName, named, depth, out, resolve) {
53
+ if (typeof v === "string") {
54
+ if (named && v)
55
+ out.push(normKey(resolve ? resolve(v, argName) : v));
56
+ return;
57
+ }
58
+ if (depth >= KEY_DEPTH || v === null || typeof v !== "object")
59
+ return;
60
+ if (Array.isArray(v)) {
61
+ for (const e of v)
62
+ collectKeys(e, argName, named, depth + 1, out, resolve);
63
+ return;
64
+ }
65
+ for (const [k, e] of Object.entries(v))
66
+ collectKeys(e, k, KEY_ARG.test(k), depth + 1, out, resolve);
67
+ }
48
68
  function normKey(p) {
49
69
  const t = p.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
50
70
  const trimmed = t.replace(/\/+$/, "");
@@ -62,8 +82,23 @@ export function runBatch(calls, opts) {
62
82
  const results = new Array(calls.length);
63
83
  const done = [];
64
84
  const writeTails = new Map(); // resource key -> last WRITE on it
85
+ const keyedReads = []; // prior reads that named a resource (a later conflicting write waits for them)
65
86
  const inflight = new Set(); // everything not yet settled (barrier gate)
66
87
  let afterBarrier = Promise.resolve(); // every op must clear the last barrier
88
+ // Cancellation: `aborted` settles when the turn is interrupted so queued calls stop waiting on their
89
+ // predecessors and are cancelled, not run late. The listener is removed when the batch ends — a long turn
90
+ // runs hundreds of batches on ONE signal and an unremoved listener per batch trips the EventTarget leak warning.
91
+ const signal = opts.signal;
92
+ let detach = () => { };
93
+ const aborted = signal && new Promise((resolve) => {
94
+ if (signal.aborted) {
95
+ resolve();
96
+ return;
97
+ }
98
+ const onAbort = () => resolve();
99
+ signal.addEventListener("abort", onAbort, { once: true });
100
+ detach = () => signal.removeEventListener("abort", onAbort);
101
+ });
67
102
  for (let i = 0; i < calls.length; i++) {
68
103
  const c = calls[i];
69
104
  const kind = opts.classify(c.name);
@@ -85,9 +120,7 @@ export function runBatch(calls, opts) {
85
120
  gate.push(t2); // path-less read: any prior write may target it
86
121
  }
87
122
  for (const k of keys) {
88
- // A read waits only for PRIOR WRITES on overlapping resources. Prior READS never matter
89
- // (nothing to serialize), and a write after a read must NOT wait for the read: the model
90
- // consumes results next turn; any pre/post read value is a valid serialization.
123
+ // A read waits only for PRIOR WRITES on overlapping resources; prior reads never block it.
91
124
  for (const [wk, wt] of writeTails)
92
125
  if (conflicts(k, wk))
93
126
  gate.push(wt);
@@ -99,15 +132,27 @@ export function runBatch(calls, opts) {
99
132
  for (const [wk, wt] of writeTails)
100
133
  if (conflicts(k, wk))
101
134
  gate.push(wt);
135
+ // WAR: a write must not overlap an EARLIER read of the same resource. A read racing a write is not
136
+ // "either old or new": file writes truncate-then-fill, so the read can observe an empty/partial file
137
+ // (measured: 10 of 40 [file_read f, file_write f] batches returned an empty read), and a delete
138
+ // can pull the file out from under it. Sequential order would always give the old content.
139
+ for (const r of keyedReads)
140
+ if (r.keys.some((rk) => conflicts(k, rk)))
141
+ gate.push(r.run);
102
142
  }
103
143
  }
104
- const run = Promise.all(gate).then(async () => {
144
+ const ready = Promise.all(gate);
145
+ const run = (aborted ? Promise.race([ready, aborted]) : ready).then(async () => {
105
146
  let r;
106
- try {
107
- r = await opts.runOne(c);
108
- }
109
- catch (e) {
110
- r = `error running ${c.name}: ${e?.message ?? String(e)}`;
147
+ if (signal?.aborted)
148
+ r = cancelledResult(c.name);
149
+ else {
150
+ try {
151
+ r = await opts.runOne(c);
152
+ }
153
+ catch (e) {
154
+ r = `error running ${c.name}: ${e?.message ?? String(e)}`;
155
+ }
111
156
  }
112
157
  results[i] = r;
113
158
  try {
@@ -120,9 +165,11 @@ export function runBatch(calls, opts) {
120
165
  else if (kind === "write")
121
166
  for (const k of keys)
122
167
  writeTails.set(k, run);
168
+ else if (keys.length)
169
+ keyedReads.push({ keys, run });
123
170
  inflight.add(run);
124
171
  run.then(() => inflight.delete(run));
125
172
  done.push(run);
126
173
  }
127
- return Promise.all(done).then(() => results);
174
+ return Promise.all(done).then(() => { detach(); return results; });
128
175
  }