@0perator/operator 0.1.360-next.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +159 -0
  6. package/dist/autonomy/delegate.js +42 -15
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +13 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +336 -45
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/resume.js +125 -0
  18. package/dist/background/synthesis.js +25 -0
  19. package/dist/browser/engine.js +163 -0
  20. package/dist/browser/session.js +130 -140
  21. package/dist/bus/inbox.js +150 -6
  22. package/dist/cli.js +343 -86
  23. package/dist/config/features.js +3 -3
  24. package/dist/config/persona.js +29 -3
  25. package/dist/config/settings.js +262 -21
  26. package/dist/config/staff-prompt.js +12 -0
  27. package/dist/engine/agent.js +52 -41
  28. package/dist/engine/aurora.js +40 -8
  29. package/dist/engine/batch-scheduler.js +4 -13
  30. package/dist/engine/compaction.js +2 -2
  31. package/dist/engine/continuation.js +30 -32
  32. package/dist/engine/decision-points.js +2 -3
  33. package/dist/engine/fanout.js +16 -0
  34. package/dist/engine/loop-guard.js +26 -83
  35. package/dist/engine/messages.js +2 -2
  36. package/dist/engine/moa.js +18 -2
  37. package/dist/engine/native-vision-node.js +72 -0
  38. package/dist/engine/native-vision.js +103 -0
  39. package/dist/engine/selfheal.js +1 -1
  40. package/dist/engine/toolcalls.js +6 -6
  41. package/dist/engine/verify-gate.js +37 -7
  42. package/dist/gateway-cli.js +14 -3
  43. package/dist/index.js +3 -0
  44. package/dist/mcp/phone-server.js +30 -0
  45. package/dist/memory/live-progress.js +4 -5
  46. package/dist/moa/codeact-lane.js +98 -0
  47. package/dist/moa/codeact-sandbox.js +409 -0
  48. package/dist/moa/codeact.js +140 -0
  49. package/dist/permissions/artifact-visibility.js +10 -0
  50. package/dist/permissions/index.js +33 -17
  51. package/dist/permissions/signature.js +5 -0
  52. package/dist/permissions/tier.js +4 -2
  53. package/dist/phone-cli.js +65 -0
  54. package/dist/products/craft.js +2 -2
  55. package/dist/remote/grants.js +119 -0
  56. package/dist/remote/host.js +63 -6
  57. package/dist/router/models.js +29 -29
  58. package/dist/selfimprove/index.js +9 -7
  59. package/dist/services/preflight.js +35 -91
  60. package/dist/session.js +173 -46
  61. package/dist/skills/install-guard.js +68 -0
  62. package/dist/skills/install.js +67 -0
  63. package/dist/toolchain/manifest.json +13 -13
  64. package/dist/tools/background-result.js +1 -1
  65. package/dist/tools/classes.js +103 -0
  66. package/dist/tools/contract.js +1 -1
  67. package/dist/tools/craft.js +13 -2
  68. package/dist/tools/deferred.js +1 -0
  69. package/dist/tools/device/android.js +227 -0
  70. package/dist/tools/device/classify.js +127 -0
  71. package/dist/tools/device/deps.js +69 -0
  72. package/dist/tools/device/desktop.js +82 -0
  73. package/dist/tools/device/harness.js +262 -0
  74. package/dist/tools/device/iphone.js +206 -0
  75. package/dist/tools/device/mirroring-jxa.js +146 -0
  76. package/dist/tools/device/setup.js +90 -0
  77. package/dist/tools/device/tools.js +70 -0
  78. package/dist/tools/device/types.js +19 -0
  79. package/dist/tools/executor.js +25 -15
  80. package/dist/tools/generation-gateway.js +94 -0
  81. package/dist/tools/registry.js +95 -155
  82. package/dist/ui/App.js +18 -6
  83. package/dist/ui/ApprovalPrompt.js +10 -4
  84. package/dist/ui/BgPanel.js +17 -12
  85. package/dist/ui/Header.js +1 -6
  86. package/dist/ui/StatusRule.js +18 -7
  87. package/dist/ui/ToolStep.js +3 -3
  88. package/dist/ui/Transcript.js +36 -14
  89. package/dist/ui/UpdatePrompt.js +40 -0
  90. package/dist/ui/batchLine.js +4 -4
  91. package/dist/ui/editdiff.js +2 -4
  92. package/dist/ui/format.js +4 -20
  93. package/dist/ui/liveTools.js +3 -3
  94. package/dist/ui/modelPicker.js +1 -1
  95. package/dist/ui/opsMode.js +20 -0
  96. package/dist/ui/slashCommands.js +1 -0
  97. package/dist/ui/types.js +0 -2
  98. package/dist/update-check.js +145 -0
  99. package/dist/update.js +59 -15
  100. package/dist/util/slash.js +2 -2
  101. package/package.json +4 -2
  102. package/src/tools/device/NOTICE +37 -0
  103. package/dist/browser/cdp.js +0 -271
  104. package/dist/tools/mutating.js +0 -15
package/dist/cli.js CHANGED
@@ -14,7 +14,8 @@ import { mastheadLines } from "./ui/Masthead.js";
14
14
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
15
15
  import { initialMode, modePolicy, nextMode, parseMode, planToggleTarget } from "./permissions/modes.js";
16
16
  import { FREE_ROW_PRESETS, connectedAccounts, isMainModel, looksLikeSecret, contextLine, contextPickerView, keyStoredLine, mainPickerView, markModelRows, modelLine, modelPickerView, onceEach, pickerAnswer, providerPickerView, rereadConfirmView, wantsContextStep, wantsRereadConfirm } from "./ui/modelPicker.js";
17
- import { RemoteHost } from "./remote/host.js";
17
+ import { RemoteHost, toRemoteAgents } from "./remote/host.js";
18
+ import { GrantStore, grantsEnabled } from "./remote/grants.js";
18
19
  import { REMOTE_SAFE_COMMANDS, REMOTE_SAFE_COMMAND_NAMES } from "./remote/safe-commands.js";
19
20
  import { newCode, pairURL } from "./remote/pairing.js";
20
21
  import { qrToTerminal } from "./ui/qr.js";
@@ -28,7 +29,7 @@ import { createDecode, decodeRate, decodeRound, deltasApprox, dueCheck, noteDeco
28
29
  import { isRunawayRepetition } from "./engine/repetition-guard.js";
29
30
  import { createLedger, interruptedLine, ledgerParts, noteCompaction, noteGenEnd, noteGenStart, noteRead, noteRound, noteTools, noteWait } from "./ui/turnLedger.js";
30
31
  import { termCols } from "./ui/term.js";
31
- import { pollBus, pollSent, selfAgent, buildMentorWake, selectReadyWakes } from "./bus/inbox.js";
32
+ import { pollBus, pollSent, selfAgent, buildMentorWake, selectReadyWakes, isAutoReport, wakeRoot } from "./bus/inbox.js";
32
33
  import { isErrorResult } from "./ui/format.js";
33
34
  import { feedFold, foldStep, settleFold, settledFields } from "./ui/fold.js";
34
35
  import { turnScoped } from "./ui/turnScope.js";
@@ -39,16 +40,17 @@ import { cacheBustNotice, anyReachable, setSpeculation, speculationEnabled } fro
39
40
  import { seedCalibration } from "./engine/calibration-seed.js";
40
41
  import { AuroraRouter } from "./router/router.js";
41
42
  import { BackgroundAgents } from "./background/index.js";
42
- import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, compactionMinDecodeTps, rcAutostart, eagerAuthAtBoot, applySeat, setActiveSeat, buildEndpointChain, parseContextArg, nextContextPin } from "./config/settings.js";
43
+ import { clearResumable, pickUpSaved, quitSummary, resumeOnReopen, saveResumable, startSaved } from "./background/resume.js";
44
+ import { loadSettings, saveSettings, settingsLoadProblems, compactionThreshold, compactionCeilingTokens, compactionMinDecodeTps, rcAutostart, eagerAuthAtBoot, applySeat, setActiveSeat, buildEndpointChain, parseContextArg, nextContextPin } from "./config/settings.js";
43
45
  import { resolveSeat } from "./auth/identity.js";
44
46
  import { PermissionPolicy } from "./permissions/index.js";
45
47
  import { caps } from "./ui/capabilities.js";
46
- import { composeSystemPrompt, appendMemory, subagentSystemPrompt } from "./config/persona.js";
48
+ import { composeSystemPrompt, appendMemory, memoryBudgetNote, subagentSystemPrompt } from "./config/persona.js";
47
49
  import { SUBAGENT_ROLES, SUBAGENT_TOOL_DENY, roleCanWrite } from "./engine/grandmaster.js";
48
50
  import { applyToolsBinPath, operatorPath } from "./config/home.js";
49
51
  import { ensureOperatorHome } from "./config/scaffold.js";
50
52
  import { listLocalSkills, skillCommand } from "./config/skills-index.js";
51
- import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, fmtCtx, shortName, BYO_PRESETS, DEFAULT_MODEL_ID } from "./router/models.js";
53
+ import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, fmtCtx, shortName, BYO_PRESETS, CHAIN_MODEL_ID } from "./router/models.js";
52
54
  import { fetchPortalModels, offlineNote, portalIdFor } from "./router/portal.js";
53
55
  import { fetchFreeModels } from "./router/free-models.js";
54
56
  import { describeTurnError } from "./engine/net-error.js";
@@ -59,7 +61,10 @@ import { getDiscoveredModels } from "./router/discovery.js";
59
61
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
60
62
  import { applySandboxMode } from "./tools/sandbox.js";
61
63
  import { drainJobNotices, getJobNoticeMode, listShellJobs, onJobEvent, parseJobsArgs, pendingJobNotices, renderJobsList, runningJobCount, setJobNoticeMode, stopShellJob } from "./tools/shell-jobs.js";
62
- import { drainAgentNotices, onAgentReport, pendingAgentReports, queueAgentReport, queueAgentNotice, formatStuckNotice } from "./background/notices.js";
64
+ import { drainAgentNotices, onAgentReport, agentReportsDue, queueAgentReport, queueAgentNotice, formatStuckNotice, setReportGate } from "./background/notices.js";
65
+ import { delegateCapacity, liveDelegateRoute } from "./background/capacity.js";
66
+ import { laneSummary } from "./background/lane-summary.js";
67
+ import { missingLine, synthesisState } from "./background/synthesis.js";
63
68
  import { reportLine, deliveredLine } from "./ui/reportLine.js";
64
69
  import { pushCollapsed, popCollapsed, dropCollapsed } from "./ui/expand.js";
65
70
  import { ensureScratchDir } from "./config/scratch.js";
@@ -80,7 +85,8 @@ import { snapshotEphemeralImages } from "./util/screenshots.js";
80
85
  import { isFeatureEnabled } from "./config/features.js";
81
86
  import { classifyActVsAsk, actAskGateDirective } from "./engine/classifier.js";
82
87
  import { resolveMode } from "./classifier/modes.js";
83
- import { subagentModelFor, servingModelFor } from "./autonomy/subagent-model.js";
88
+ import { subagentModelFor, servingModelFor, delegateRouteFor } from "./autonomy/subagent-model.js";
89
+ import { parseDelegate, delegateStatusLines, delegateGuardOn, setDelegateSettings } from "./autonomy/delegate-mode.js";
84
90
  import { classifierConfig } from "./classifier/config.js";
85
91
  import { throttle } from "./util/throttle.js";
86
92
  import { isSlashCommand } from "./util/slash.js";
@@ -123,15 +129,16 @@ function ctxBadge(n) {
123
129
  return n >= 1024 ? `${Math.round(n / 1024)}K` : String(n);
124
130
  }
125
131
  // The model the session will actually start on — NOT the raw persisted id. Mirrors Session's startup
126
- // resolution (session.ts: setModel(cfg.activeModel) else DEFAULT_MODEL_ID) so the boot masthead badges the
132
+ // resolution (session.ts: setModel(cfg.activeModel) else CHAIN_MODEL_ID) so the boot masthead badges the
127
133
  // window of the model that answers, not a persisted id that the owner-only gate / missing-endpoint check
128
- // drops back to operator-1m. Pure (selectModel is a pure reducer, no health I/O), so the fast paths stay instant.
134
+ // drops back to the chain row, or a retired id that resolves to its successor. Pure (selectModel is a pure reducer,
135
+ // no health I/O), so the fast paths stay instant.
129
136
  function startupModelId(s, actor) {
130
137
  const id = s.activeModel;
131
- if (!id || id === DEFAULT_MODEL_ID)
132
- return DEFAULT_MODEL_ID;
138
+ if (!id || id === CHAIN_MODEL_ID)
139
+ return CHAIN_MODEL_ID;
133
140
  const isOwner = (actor.tier ?? "admin") === "admin";
134
- return selectModel(modelRegistry(s.models), id, hasByoToken, isOwner).profile ? id : DEFAULT_MODEL_ID;
141
+ return selectModel(modelRegistry(s.models), id, hasByoToken, isOwner).profile?.id ?? CHAIN_MODEL_ID;
135
142
  }
136
143
  // Fast paths that must NOT mount Ink/React (so `operator --version` works with no TTY and returns instantly)
137
144
  // — and must not do ANY identity I/O either. They used to sit BELOW the boot credential load, so even
@@ -156,6 +163,9 @@ if (process.argv[2] === "selfimprove") {
156
163
  }
157
164
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
158
165
  const settings = loadSettings();
166
+ for (const p of settingsLoadProblems())
167
+ process.stderr.write(`[operator] ⚠ settings: ${p}\n`);
168
+ setDelegateSettings(settings.delegate); // delegate mode's guard, read per tool call by every session in this process
159
169
  // Enterprise first-run: make the operator home's contract explicit BEFORE any module writes into it (0700
160
170
  // root, ignore-everything .gitignore, README, settings.example.json, home.json). Idempotent, never throws.
161
171
  const HOME_SCAFFOLD = ensureOperatorHome({ version: VERSION });
@@ -262,7 +272,7 @@ if (firstRunEligible) {
262
272
  // Seat resolution (enterprise SSO/RBAC readiness): with a managed auth policy deployed, the verified identity
263
273
  // decides the widest tier this process may hold (it can only NARROW, never widen). With no managed policy this
264
274
  // is a no-op and touches no network. `operator auth …` / --version / --help skip it (they must work signed-out).
265
- const SKIP_SEAT = process.argv[2] === "auth" || process.argv[2] === "audit" || process.argv[2] === "gateway" || process.argv[2] === "toolchain" || process.argv.includes("--version") || process.argv.includes("-V") || process.argv.includes("--help");
275
+ const SKIP_SEAT = process.argv[2] === "auth" || process.argv[2] === "audit" || process.argv[2] === "gateway" || process.argv[2] === "toolchain" || process.argv[2] === "phone" || process.argv.includes("--version") || process.argv.includes("-V") || process.argv.includes("--help");
266
276
  const SEAT = SKIP_SEAT
267
277
  ? { seat: { tier: settings.permissions.tier ?? "admin", source: "local-owner", reasons: ["seat resolution skipped for this command"] }, events: [], dropToken: false }
268
278
  : await resolveSeat(settings, { creds: bootCreds });
@@ -304,10 +314,15 @@ if (settings.computer.enabled) {
304
314
  // Foreground: computer_* and chauffeur ACTIONS prompt ("ask"); chauffeur READS (list_windows,
305
315
  // get_window_state, …) are intentionally NOT gated, so the model reads the screen freely and completes
306
316
  // a task end-to-end without walking the owner through each step. Only real input/mutation asks.
307
- const askNames = [...COMPUTER_TOOL_NAMES, ...(chauffeurServer ? CHAUFFEUR_ACTION_NAMES : [])];
317
+ // The device tools (phone_*: iPhone via iPhone Mirroring, Android via adb, the desktop) are the same class: their
318
+ // actions ask like computer_*, their reads run unprompted like chauffeur's, and a background agent gets none of them.
319
+ const { PHONE_TOOLS, PHONE_TOOL_NAMES, PHONE_ACTION_NAMES } = await import("./tools/device/tools.js");
320
+ for (const t of PHONE_TOOLS)
321
+ registry.set(t.name, t);
322
+ const askNames = [...COMPUTER_TOOL_NAMES, ...PHONE_ACTION_NAMES, ...(chauffeurServer ? CHAUFFEUR_ACTION_NAMES : [])];
308
323
  computerAskRules = Object.fromEntries(askNames.map((n) => [n, "ask"]));
309
324
  // Background sub-agents have no approver, so DENY every embodiment tool, reads included.
310
- const denyNames = [...COMPUTER_TOOL_NAMES, "desktop_screenshot", "desktop_read", ...(chauffeurServer ? CHAUFFEUR_TOOL_NAMES : [])];
325
+ const denyNames = [...COMPUTER_TOOL_NAMES, ...PHONE_TOOL_NAMES, "desktop_screenshot", "desktop_read", ...(chauffeurServer ? CHAUFFEUR_TOOL_NAMES : [])];
311
326
  computerDenyRules = Object.fromEntries(denyNames.map((n) => [n, "deny"]));
312
327
  }
313
328
  // STANDARD MCP: report-mcp (PDF tools) ships with Operator — always injected, even without the full-fleet
@@ -468,6 +483,17 @@ installProcessTeardown(teardown, {
468
483
  });
469
484
  // Children a previous Operator left behind (it crashed, or was killed -9; detached shells/jobs and Chrome outlive their parent).
470
485
  let REAPED = { owners: 0, killed: [], skipped: 0 };
486
+ // The update-available check (update-check.ts): started just before the TUI mounts, never awaited by the boot. "Update now"
487
+ // parks the offer in UPDATE_NOW and closes the TUI; the update runs after the teardown, in the plain terminal.
488
+ let UPDATE_CHECK = Promise.resolve(null);
489
+ let UPDATE_ASKED_AT = 0;
490
+ let UPDATE_NOW = null;
491
+ // After a sign-in (the TUI's /login, the shell's `operator auth login`): the same check, gated the same way, past the cache.
492
+ async function checkOnSignIn() {
493
+ const { checkAfterSignIn } = await import("./update-check.js");
494
+ const { isSourceCheckout } = await import("./update.js");
495
+ return checkAfterSignIn(VERSION, { env: process.env, tty: !!process.stdin.isTTY && !!process.stdout.isTTY, settings, sourceCheckout: isSourceCheckout() });
496
+ }
471
497
  // Build the endpoint router. ONE model now: Aurora at its native 1M context on :8097 — both `operator`
472
498
  // and `operator+` serve the same single tier (the air/1m/saddle roster collapsed once Aurora ran true
473
499
  // 1,048,576-token context at full speed). No size-based routing decision remains.
@@ -517,6 +543,12 @@ function formatAgentDeepView(a) {
517
543
  lines.push(` task: ${a.task.length > 120 ? a.task.slice(0, 119) + "…" : a.task}`);
518
544
  if (a.model)
519
545
  lines.push(` model: ${a.model}${a.lane ? ` · ${a.lane}` : ""}`);
546
+ if (a.leg)
547
+ lines.push(` backend: ${a.leg}`);
548
+ if (a.status === "working" || a.status === "queued")
549
+ lines.push(` doing: ${laneSummary(a, Date.now())}`);
550
+ if (a.queueReason && a.status === "queued")
551
+ lines.push(` waiting: ${a.queueReason}`);
520
552
  lines.push(` round: ${a.round ?? 0}`);
521
553
  const tokStr = a.tokens != null && a.tokens > 0 ? (a.tokens >= 1000 ? `${(a.tokens / 1000).toFixed(1)}k` : `${a.tokens}`) : "0";
522
554
  lines.push(` tokens: ${tokStr}`);
@@ -586,6 +618,7 @@ const HELP = [
586
618
  " /remember <note> store a note to recall in future sessions",
587
619
  " /memory [query] show remembered notes (all, or matching query)",
588
620
  " /allow <tool:args> auto-allow a tool+args glob pattern in gated mode (e.g. bash:npm test*)",
621
+ " /delegate any /model id as the MoA planner or the sub-agents, plus a guard (no push, deploys or writes outside this repo)",
589
622
  " /skill <name|off> activate a skill as a system-prompt directive (/skill off to deactivate)",
590
623
  " /<skill> [message] any installed skill is its own command; the rest of the line is your first message",
591
624
  " /mcp [list|on|off] MCP servers and their tools (pick a server to browse its tools) · on/off (saved) · /mcp reload (from disk) · /mcp add powertools <root>",
@@ -661,7 +694,7 @@ function Root() {
661
694
  const [liveTools, setLiveTools] = useState([]); // one row per call in the CURRENT batch,
662
695
  // live: seeded "running" by onToolStart, each flips to done/error independently as onToolResult fires
663
696
  // for it — see ui/liveTools.ts. Cleared once the batch settles (onToolBatch).
664
- const [route, setRoute] = useState("operator-1m");
697
+ const [route, setRoute] = useState(CHAIN_MODEL_ID);
665
698
  const [ctxPct, setCtxPct] = useState(0);
666
699
  const seededRef = useRef(false); // GW-06: oracle cold-start seed fires once per process, on first route
667
700
  const cacheReqsRef = useRef(0); // GW-05: requests since process start — index 1 legitimately misses everything
@@ -739,8 +772,12 @@ function Root() {
739
772
  const [planExitPicker, setPlanExitPicker] = useState(null);
740
773
  const [artifactsPicker, setArtifactsPicker] = useState(null);
741
774
  const [sessionsPicker, setSessionsPicker] = useState(null);
775
+ const [updatePrompt, setUpdatePrompt] = useState(null);
742
776
  const [finder, setFinder] = useState(null); // ctrl+g — the skills and tools finder
743
777
  const alwaysAllowRef = useRef(new Set());
778
+ // Scoped "Always allow" grants from a remote follower (grants.v1, KODE_GRANTS=1). Exact tool + derived target,
779
+ // this process's session or 24 h, revocable; see remote/grants.ts. Separate from the keyboard's per-tool set above.
780
+ const grantsRef = useRef(new GrantStore());
744
781
  // Remembers the email a `/login <email>` sent a 6-digit code to, so the follow-up `/login <code>`
745
782
  // knows which address to verify against — the in-session twin of the shell's email-code login.
746
783
  const pendingLoginEmailRef = useRef(null);
@@ -750,25 +787,34 @@ function Root() {
750
787
  // Pending gated approvals by id. Both the local keystroke and a remote follower's approval_response
751
788
  // route through settleApproval — FIRST answer wins (§7); the map delete makes it idempotent.
752
789
  const pendingApprovals = useRef(new Map());
753
- const settleApproval = useCallback((id, allow, always = false) => {
790
+ const settleApproval = useCallback((id, allow, always = false, grant) => {
754
791
  const resolve = pendingApprovals.current.get(id);
755
792
  if (!resolve)
756
793
  return; // already settled (first-wins)
757
794
  pendingApprovals.current.delete(id);
758
795
  resolve(allow);
759
796
  setApproval((cur) => {
760
- if (cur && cur.id === id && allow && always)
797
+ if (cur && cur.id === id && allow && always && !cur.ctx?.once)
761
798
  alwaysAllowRef.current.add(cur.name);
799
+ // A grant covers exactly this call's derived target; a signature (ctx.once) prompt is never granted.
800
+ if (cur && cur.id === id && allow && grant && grantsEnabled() && !cur.ctx?.once
801
+ && grantsRef.current.add(cur.name, cur.args, grant.scope, SESSION_ID)) {
802
+ remoteRef.current?.setGrants(grantsRef.current.list());
803
+ }
762
804
  return cur && cur.id === id ? null : cur;
763
805
  });
764
806
  }, []);
765
- const approveFn = useCallback((name, args) => {
766
- if (alwaysAllowRef.current.has(name))
807
+ const approveFn = useCallback((name, args, ctx) => {
808
+ if (!ctx?.once && alwaysAllowRef.current.has(name))
809
+ return Promise.resolve(true); // a phone signature line asks every time
810
+ if (!ctx?.once && grantsEnabled() && grantsRef.current.use(name, args, SESSION_ID)) {
811
+ remoteRef.current?.setGrants(grantsRef.current.list()); // the use count moved
767
812
  return Promise.resolve(true);
813
+ }
768
814
  const id = "ap_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
769
815
  return new Promise((resolve) => {
770
816
  pendingApprovals.current.set(id, resolve);
771
- setApproval({ id, name, args, resolve: (b) => settleApproval(id, b) });
817
+ setApproval({ id, name, args, ...(ctx ? { ctx } : {}), resolve: (b) => settleApproval(id, b) });
772
818
  remoteRef.current?.approvalRequest(id, name, args); // mirror to followers (owner-scoped)
773
819
  });
774
820
  }, [settleApproval]);
@@ -777,19 +823,6 @@ function Root() {
777
823
  const freeRowsRef = useRef([]);
778
824
  const freeStaleRef = useRef(false); // served from the disk cache after a failed read → the rows say " · cached"
779
825
  const sessionRef = useRef(null); // lazy — never reconstruct on re-render
780
- // Aurora loads on demand (owner, 11/03): the first turn that needs a local Aurora starts the launchd gateway, and boot
781
- // never does. The hook is built on first use; it is inert where Aurora is not a launchd job on this box.
782
- const auroraHookRef = useRef(null);
783
- const auroraForTurn = async (signal) => {
784
- if (!auroraHookRef.current) {
785
- const { auroraOnDemand } = await import("./services/preflight.js");
786
- auroraHookRef.current = auroraOnDemand(settings.endpoints.aurora, settings.services?.aurora, buildRouter, () => {
787
- push({ kind: "message", message: { id: nextId(), role: "system", content: "aurora is not loaded — loading it for this turn…" } });
788
- setPhase("loading");
789
- }, (line) => push({ kind: "message", message: { id: nextId(), role: "system", content: line } }));
790
- }
791
- return auroraHookRef.current(signal);
792
- };
793
826
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
794
827
  // only, no network fan-out at session start). Background agents stay local-only + lean.
795
828
  if (!sessionRef.current) {
@@ -798,7 +831,6 @@ function Root() {
798
831
  thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
799
832
  router: buildRouter(),
800
833
  applyActiveModel: true, // the persisted /model choice still applies with the shell's chain injected
801
- onDemand: auroraForTurn,
802
834
  memory: buildMemory(settings.memory), // provider composite when configured; bare store (byte-identical) otherwise
803
835
  mcp: settings.mcp,
804
836
  mcpHub: embodimentHub, // scoped chauffeur hub when embodiment is on (undefined otherwise → no change)
@@ -835,11 +867,12 @@ function Root() {
835
867
  // sub-agent can't spawn more (no fork bombs). BackgroundAgents itself is the single source of truth
836
868
  // for the cap (running + queued) — it refuses ("") past it, so there's exactly one number to keep in
837
869
  // sync, not a second constant here that can drift from the manager's own.
838
- spawnAgent: (task, role, name) => {
870
+ spawnSlots: () => (sessionRef.current?.currentModel() === "moa" ? bgRef.current?.freeLanes() : undefined), // a planner fan-out is sized to the free lanes
871
+ spawnAgent: (task, role, name, opts) => {
839
872
  const mgr = bgRef.current;
840
873
  if (!mgr)
841
874
  return "background manager not ready yet — retry in a moment";
842
- const id = mgr.spawn(task, role, name);
875
+ const id = mgr.spawn(task, role, name, undefined, opts);
843
876
  if (!id)
844
877
  return mgr.capacityLine();
845
878
  const a = mgr.list().find((x) => x.id === id);
@@ -856,7 +889,8 @@ function Root() {
856
889
  ? "It runs on YOUR model's only slot: tell the owner the plan, then end the turn so it gets the slot."
857
890
  : "It runs on its own server beside you: keep working on what does not depend on it, and review its work when it reports.") +
858
891
  ` Its report — or a STUCK notice — arrives as a message at the start of a later turn, never mid-turn; do not poll for it. ` +
859
- `bash_output/bash_kill do not work on ${id}; never re-spawn its task while it runs.`;
892
+ `bash_output/bash_kill do not work on ${id}; never re-spawn its task while it runs.` +
893
+ (a?.evidence ? ` WARNING: ${a.evidence}.` : "");
860
894
  },
861
895
  // The reverse channel: message a RUNNING sub-agent mid-flight (steer it / answer its question).
862
896
  messageAgent: (id, text) => {
@@ -927,7 +961,8 @@ function Root() {
927
961
  // and-capability-catalog.md). The model is resolved PER SPAWN (autonomy/subagent-model.ts): the MoA specialist
928
962
  // under /model moa, else the owner's setting, else gpt-oss-20b — never silently another provider (10/31: a
929
963
  // background agent on aurora-code-1 looped 51 rounds while Cortana was the selected model).
930
- const subagentModel = () => subagentModelFor(settings, sessionRef.current?.currentModel());
964
+ const onDelegateRouteRef = useRef(false); // the owner's delegate route answered at the router: sub-agents run there, even under moa
965
+ const subagentModel = () => subagentModelFor(settings, sessionRef.current?.currentModel(), onDelegateRouteRef.current);
931
966
  const bgRef = useRef(null);
932
967
  // Every finished sub-agent's full report, by id (live or retired), for ctrl+o and `/agents <name> report` — the
933
968
  // transcript shows one line per agent (ui/reportLine.ts). collapsedRef is ctrl+o's newest-first stack.
@@ -988,6 +1023,20 @@ function Root() {
988
1023
  }, (agent, round, how) => {
989
1024
  setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `→ ${agent.name ?? agent.id} took it ${how === "round" ? `at round ${round}` : "as a follow-up turn"}` } }]);
990
1025
  });
1026
+ // Smart slots: the lane count follows the delegate route's live capacity at the router (static cap without one).
1027
+ const registry = modelRegistry(settings.models);
1028
+ const mainModel = () => servingModelFor(settings, sessionRef.current?.currentModel());
1029
+ bgRef.current.setCapacity(delegateCapacity(registry, subagentModel(), mainModel));
1030
+ void liveDelegateRoute(registry, delegateRouteFor(settings), mainModel).then((route) => {
1031
+ if (!route)
1032
+ return;
1033
+ onDelegateRouteRef.current = true;
1034
+ bgRef.current?.setCapacity(route);
1035
+ });
1036
+ setReportGate(() => {
1037
+ const s = synthesisState(bgRef.current?.list() ?? [], Date.now());
1038
+ return { ready: s.ready, missing: missingLine(s.missing) };
1039
+ });
991
1040
  }
992
1041
  const bg = bgRef.current;
993
1042
  // Talking to sub-agents (A3.4): "@Nova <text>" and the conversation switcher on the mode line. `openConv` is the
@@ -1122,8 +1171,8 @@ function Root() {
1122
1171
  useEffect(() => { tracker.start(session.currentModel()); }, [session]);
1123
1172
  useEffect(() => {
1124
1173
  void (async () => {
1125
- // Service lever: bring Aurora (required) and autopilot (optional) up via launchd BEFORE gating on
1126
- // health, so a cold box self-heals instead of dropping the owner at "start it yourself and relaunch".
1174
+ // Service lever: resolve the gateway's published endpoint (Aurora is retired: reported, never started) and bring
1175
+ // the optional companions up via launchd BEFORE gating on health.
1127
1176
  let reports = [];
1128
1177
  try {
1129
1178
  const preflight = await import("./services/preflight.js");
@@ -1132,7 +1181,6 @@ function Root() {
1132
1181
  const auroraCfg = { base: bootBase, ...settings.services?.aurora };
1133
1182
  reports = await preflight.ensureServices({
1134
1183
  aurora: auroraCfg,
1135
- auroraOnDemand: true, // resolve and report Aurora only: the turn that needs it loads it
1136
1184
  autopilot: settings.services?.autopilot,
1137
1185
  vision: settings.services?.vision,
1138
1186
  onProgress: setBootDetail,
@@ -1156,21 +1204,18 @@ function Root() {
1156
1204
  }
1157
1205
  }
1158
1206
  catch { /* preflight is best-effort — fall through to the authoritative health check */ }
1159
- // A local Aurora that is not loaded is not a failed boot: it loads on the first turn that needs it, and a
1160
- // session on another model (moa, cortana) never needs it.
1161
- const primaryOk = reports.find((r) => r.name === "aurora")?.state === "idle" || (await session.health().catch(() => false));
1162
- // No local model is not a failed boot either when a later leg of the same chain answers: the router falls
1163
- // through to it on the first turn (a new user's machine has only the cloud tier). The Aurora row's legs are the
1164
- // shell chain; any other gateway row (operator-flash, the fresh-install default) has its own public leg.
1165
- const laterLegs = session.currentModel() === DEFAULT_MODEL_ID ? buildEndpointChain(settings).map((e) => e.base) : session.endpoints().map((e) => e.base);
1207
+ const primaryOk = await session.health().catch(() => false);
1208
+ // No local model is not a failed boot when a later leg of the same chain answers: the router falls through to it
1209
+ // on the first turn (a new user's machine has only the cloud tier). The chain row's legs are the shell chain; any
1210
+ // other gateway row (operator-flash, the fresh-install default) has its own public leg.
1211
+ const laterLegs = session.currentModel() === CHAIN_MODEL_ID ? buildEndpointChain(settings).map((e) => e.base) : session.endpoints().map((e) => e.base);
1166
1212
  const ok = primaryOk || (await anyReachable(laterLegs.slice(1)).catch(() => false));
1167
1213
  setBoot(ok ? "ready" : "down");
1214
+ const modelNote = session.takeModelNote(); // a persisted retired activeModel runs on its successor: said once
1215
+ if (modelNote)
1216
+ push({ kind: "message", message: { id: nextId(), role: "system", content: modelNote } });
1168
1217
  if (!ok) {
1169
- const a = reports.find((r) => r.name === "aurora");
1170
- // Another model (moa, cortana) failed on its own endpoint: name that one, not Aurora's.
1171
- setBootDetail(session.currentModel() === DEFAULT_MODEL_ID
1172
- ? a?.detail ?? `no response from ${session.healthTarget()}`
1173
- : `${session.currentModel()}: no response from ${session.healthTarget()}`);
1218
+ setBootDetail(`${session.currentModel()}: no response from ${session.healthTarget()}`);
1174
1219
  return;
1175
1220
  }
1176
1221
  // The primary's served window, learned now rather than after the first overflow — AFTER the lever, so the gateway's
@@ -1219,7 +1264,7 @@ function Root() {
1219
1264
  }
1220
1265
  }
1221
1266
  // Confirm, once in scrollback, what the lever did (started = it was down and we brought it up).
1222
- const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : r.state === "idle" ? "on demand" : "✗"}`).join(" · ");
1267
+ const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : r.state === "idle" ? "retired, not started" : "✗"}`).join(" · ");
1223
1268
  if (line) {
1224
1269
  // SearXNG is lazy (starts on first web_search), but if a backend is ALREADY reachable — an explicit
1225
1270
  // KODE_SEARXNG_URL, or a container still up from a prior session — show ✓ instead of a misleading
@@ -1614,6 +1659,9 @@ function Root() {
1614
1659
  sys(`↻ loop recovery ${e.attempt}/${e.max}: ${calls} came back refused as repeats — ` +
1615
1660
  `${e.rounds === 1 ? "that round" : `those ${e.rounds} rounds`} became one note of their results; reviewing and continuing`);
1616
1661
  },
1662
+ onAutoReport: (to) => {
1663
+ sys(`↗ this wake turn ended without a report, so its final answer was delivered to ${to.join(", ")} (marked auto-delivered)`);
1664
+ },
1617
1665
  onAutoContinue: (round) => {
1618
1666
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
1619
1667
  },
@@ -1881,7 +1929,7 @@ function Root() {
1881
1929
  command: (cmd) => slashRef.current(cmd),
1882
1930
  submit: (text) => submitRef.current(text),
1883
1931
  start: (text, opts) => { void startTurn(text, opts); },
1884
- wakeDue: () => (getJobNoticeMode() === "wake" && pendingJobNotices() > 0) || pendingAgentReports() > 0,
1932
+ wakeDue: () => (getJobNoticeMode() === "wake" && pendingJobNotices() > 0) || agentReportsDue(),
1885
1933
  }), []);
1886
1934
  const sendTurn = useCallback((text, opts) => flow.send(text, opts), [flow]);
1887
1935
  const drainRef = useRef(() => { });
@@ -1908,6 +1956,17 @@ function Root() {
1908
1956
  push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
1909
1957
  remoteRef.current?.system(text);
1910
1958
  }, []);
1959
+ useEffect(() => { for (const p of settingsLoadProblems())
1960
+ sys(`⚠ settings: ${p}`); }, [sys]);
1961
+ // A settings write that fails (locked, unreadable file, disk) is named; the running session keeps the change.
1962
+ const persist = useCallback((patch) => {
1963
+ try {
1964
+ saveSettings(patch);
1965
+ }
1966
+ catch (e) {
1967
+ sys(`⚠ not saved to settings.json: ${e instanceof Error ? e.message : String(e)}`);
1968
+ }
1969
+ }, [sys]);
1911
1970
  // A model turn is running (compacting is the one non-idle state with no next round to apply a setting to).
1912
1971
  const turnRunning = () => statusRef.current !== "idle" && statusRef.current !== "compacting";
1913
1972
  // /think rides in the system prompt (session.ts sysWithThink), so the turn after a toggle re-reads everything past the
@@ -1994,12 +2053,90 @@ function Root() {
1994
2053
  teardown.add("caffeinate", () => { setCaffeine(false); }, { order: 25 });
1995
2054
  return () => { setCaffeine(false); };
1996
2055
  }, [boot, setCaffeine]);
2056
+ // Agents still working when Operator closes are saved on the way out and picked back up by the next session in this folder
2057
+ // (background/resume.ts; settings.agents.resumeOnReopen). With the setting off they wait in /agents as paused.
2058
+ const pausedRef = useRef([]);
2059
+ const spawnSaved = (a) => !!bgRef.current?.spawn(a.task, a.role, a.name, a);
2060
+ useEffect(() => {
2061
+ if (boot !== "ready")
2062
+ return;
2063
+ const cwd = process.cwd();
2064
+ teardown.add("agents-resume", () => {
2065
+ const live = bgRef.current?.resumable(cwd, getAgentTasks()) ?? [];
2066
+ if (!live.length && !pausedRef.current.length)
2067
+ return;
2068
+ saveResumable(cwd, [...pausedRef.current, ...live]);
2069
+ if (live.length)
2070
+ process.stdout.write(`${quitSummary(live, resumeOnReopen(settings)).line}\n`);
2071
+ }, { order: 25 }); // before "background-agents" (30) interrupts them
2072
+ const picked = pickUpSaved(cwd, settings, spawnSaved, (m) => sys(`⚠ ${m}`));
2073
+ pausedRef.current = picked.paused;
2074
+ if (picked.line)
2075
+ sys(picked.line);
2076
+ }, [boot]);
2077
+ useEffect(() => { remoteRef.current?.setAgents(toRemoteAgents(bgAgents)); }, [bgAgents, rcActive]);
2078
+ // Say so when a memories file is over its budget: the model is told in its prompt, the owner should be too.
2079
+ useEffect(() => {
2080
+ if (boot !== "ready")
2081
+ return;
2082
+ try {
2083
+ const note = memoryBudgetNote();
2084
+ if (note)
2085
+ sys(note);
2086
+ }
2087
+ catch { /* unreadable memory files are reported elsewhere */ }
2088
+ }, [boot]);
1997
2089
  // Say so when this launch cleaned up after a previous one — silently killing processes would be worse than the orphans.
1998
2090
  useEffect(() => {
1999
2091
  const n = REAPED.killed.length;
2000
2092
  if (n)
2001
2093
  sys(`cleaned up ${n} leftover process${n === 1 ? "" : "es"} from a previous session that did not exit cleanly (${[...new Set(REAPED.killed.map((k) => k.label))].join(", ")}).`);
2002
2094
  }, []);
2095
+ // A newer build (update-check.ts): the prompt before the first turn; once the owner has typed or a turn runs, one line.
2096
+ // After a /login the prompt comes up at once, or when the running turn ends.
2097
+ const showUpdatePrompt = (offer) => setUpdatePrompt({
2098
+ current: offer.current, version: offer.version, notes: offer.notes, command: offer.command,
2099
+ resolve: (choice) => {
2100
+ setUpdatePrompt(null);
2101
+ if (choice === "update") {
2102
+ UPDATE_NOW = offer;
2103
+ void teardown.run("quit");
2104
+ exit();
2105
+ return;
2106
+ }
2107
+ if (choice === "skip-version") {
2108
+ void import("./update-check.js").then(({ skipVersion }) => skipVersion(offer.version));
2109
+ sys(`Skipped ${offer.version} · Operator asks again when a newer version is out`);
2110
+ }
2111
+ },
2112
+ });
2113
+ const signInOfferRef = useRef(null);
2114
+ useEffect(() => {
2115
+ void UPDATE_CHECK.then((offer) => {
2116
+ if (!offer)
2117
+ return;
2118
+ if (idleLastActiveAt() > UPDATE_ASKED_AT || statusRef.current !== "idle") {
2119
+ sys(`Update available · ${offer.current} → ${offer.version} · run \`${offer.command}\` (release notes: ${offer.notes})`);
2120
+ return;
2121
+ }
2122
+ showUpdatePrompt(offer);
2123
+ });
2124
+ }, []);
2125
+ useEffect(() => {
2126
+ const offer = signInOfferRef.current;
2127
+ if (offer && status === "idle") {
2128
+ signInOfferRef.current = null;
2129
+ showUpdatePrompt(offer);
2130
+ }
2131
+ }, [status]);
2132
+ const offerUpdateAfterSignIn = () => void checkOnSignIn().then((offer) => {
2133
+ if (!offer)
2134
+ return;
2135
+ if (statusRef.current === "idle")
2136
+ showUpdatePrompt(offer);
2137
+ else
2138
+ signInOfferRef.current = offer;
2139
+ });
2003
2140
  // The actual mode switch — policy, plan flag, status badge, and follower-facing capabilities, all in
2004
2141
  // lockstep. Factored out of applyMode so the plan-exit picker below can perform it from a resolve
2005
2142
  // callback without re-entering (and re-gating) applyMode itself.
@@ -2054,11 +2191,11 @@ function Root() {
2054
2191
  // pin) from the next round), persist the choice, light the footer badge, and say what it runs on now.
2055
2192
  const applyContext = useCallback((pin) => {
2056
2193
  session.setContextPin(pin);
2057
- saveSettings({ contextPin: session.contextPin() });
2194
+ persist({ contextPin: session.contextPin() });
2058
2195
  setCtxPin(session.contextPin());
2059
2196
  setCtxPct(session.ctxPct());
2060
2197
  sys(contextLine(session.contextPin(), session.servedContext(), session.ctxPct()) + (turnRunning() ? " · from the next round" : ""));
2061
- }, [sys]);
2198
+ }, [sys, persist]);
2062
2199
  // The /model, context and provider pickers share the one local QuestionPrompt slot. A row resolves by INDEX into the
2063
2200
  // entries it was drawn from (row text can repeat); the empty reply / ctrl+c (DISCUSS) closes the picker without
2064
2201
  // applying anything. The returned redraw re-renders the SAME picker while it is still the one on screen (portal
@@ -2166,8 +2303,10 @@ function Root() {
2166
2303
  sys(`${r.error} — run /model for the list`);
2167
2304
  return undefined;
2168
2305
  }
2306
+ if (r.note)
2307
+ sys(r.note);
2169
2308
  setRoute(s.currentModel());
2170
- saveSettings({ activeModel: s.currentModel() });
2309
+ persist({ activeModel: s.currentModel() });
2171
2310
  const chosen = s.modelRegistry().find((m) => m.id === s.currentModel());
2172
2311
  sys(modelLine(s.currentModel(), chosen, s.ctxPct(), s.turnCount(), cost)); // a free row repeats its caveat here
2173
2312
  // Arm the phase line's forecast of what the next message may re-read on this model (the line above names the cost).
@@ -2249,7 +2388,7 @@ function Root() {
2249
2388
  go();
2250
2389
  return;
2251
2390
  }
2252
- const here = s.currentModel() === DEFAULT_MODEL_ID ? "aurora" : s.currentModel();
2391
+ const here = s.currentModel();
2253
2392
  const est = s.compactionEstimate();
2254
2393
  const v = rereadConfirmView({
2255
2394
  target: a.entry.profile.label, current: here, cost,
@@ -2590,12 +2729,11 @@ function Root() {
2590
2729
  // In-session IO: sys lines for output, the system opener for the browser. No poll dots in the TUI —
2591
2730
  // a single "Waiting for approval…" line is clearer than a growing dot run next to the transcript.
2592
2731
  const inkIO = { log: (m) => sys(m), error: (m) => sys(m), ask: async () => "", openBrowser };
2732
+ const signedIn = (token, who) => { setOperatorToken(token); setAuthUser(who); offerUpdateAfterSignIn(); };
2593
2733
  const runBrowserLogin = async () => {
2594
2734
  const r = await signInWithBrowser(inkIO);
2595
- if (r.ok && r.account && r.token) {
2596
- setOperatorToken(r.token);
2597
- setAuthUser(r.account.email ?? r.account.external_id);
2598
- }
2735
+ if (r.ok && r.account && r.token)
2736
+ signedIn(r.token, r.account.email ?? r.account.external_id);
2599
2737
  else if (!r.ok && r.reason !== "denied")
2600
2738
  sys("try /login <email> to sign in by code instead");
2601
2739
  };
@@ -2621,10 +2759,9 @@ function Root() {
2621
2759
  const v = await signupVerify(email, a);
2622
2760
  if (v.ok) {
2623
2761
  await saveCredentials({ token: v.token, user: v.account.external_id, host: authBase(), issuedAt: Date.now() });
2624
- setOperatorToken(v.token);
2625
- setAuthUser(v.account.email ?? v.account.external_id);
2626
2762
  pendingLoginEmailRef.current = null;
2627
2763
  sys(`✓ signed in as ${v.account.email ?? v.account.external_id}`);
2764
+ signedIn(v.token, v.account.email ?? v.account.external_id);
2628
2765
  }
2629
2766
  else if (v.error === "invalid_code")
2630
2767
  sys("wrong code — /login <code> to try again");
@@ -2662,10 +2799,8 @@ function Root() {
2662
2799
  }
2663
2800
  // Otherwise treat it as a pasted personal access token (trimmed of stray whitespace/dots in sign-in.ts).
2664
2801
  const rtok = await signInWithToken(a, inkIO);
2665
- if (rtok.ok && rtok.account && rtok.token) {
2666
- setOperatorToken(rtok.token);
2667
- setAuthUser(rtok.account.email ?? rtok.account.external_id);
2668
- }
2802
+ if (rtok.ok && rtok.account && rtok.token)
2803
+ signedIn(rtok.token, rtok.account.email ?? rtok.account.external_id);
2669
2804
  else if (!rtok.ok)
2670
2805
  sys("did you mean /login <email>?");
2671
2806
  break;
@@ -2677,17 +2812,17 @@ function Root() {
2677
2812
  if (a === "on") {
2678
2813
  sys("enabling MCP tools…");
2679
2814
  const n = await s.enableMcp();
2680
- saveSettings({ mcp: true });
2815
+ persist({ mcp: true });
2681
2816
  sys(n > 0 ? `MCP on · ${n} fleet tools available (saved — on for new sessions too)` : "MCP on (saved), but no tools were discovered — the MCP gateway may be unreachable; it retries next session");
2682
2817
  }
2683
2818
  else if (a === "off") {
2684
- saveSettings({ mcp: false });
2819
+ persist({ mcp: false });
2685
2820
  sys("MCP off for new sessions (saved) — tools already loaded stay until you restart");
2686
2821
  }
2687
2822
  else if (a === "reload") {
2688
2823
  sys("reloading MCP from disk (base + the extra MCP config)…");
2689
2824
  const n = await s.reloadMcp();
2690
- saveSettings({ mcp: true });
2825
+ persist({ mcp: true });
2691
2826
  sys(n > 0 ? `MCP reloaded · ${n} fleet tools` : "MCP reloaded, but no tools discovered — check mcp_servers.json and the extra MCP config");
2692
2827
  }
2693
2828
  else if (a === "add") {
@@ -2710,7 +2845,7 @@ function Root() {
2710
2845
  env: { POWERTOOLS_ROOT: absRoot },
2711
2846
  });
2712
2847
  const n = await s.reloadMcp();
2713
- saveSettings({ mcp: true });
2848
+ persist({ mcp: true });
2714
2849
  sys(`powertools added · root=${absRoot} · wrote ${written} · ${n} fleet tools (alias: pt)`);
2715
2850
  }
2716
2851
  catch (e) {
@@ -2783,6 +2918,64 @@ function Root() {
2783
2918
  void sendTurn(`Use the deep_research tool to research this thoroughly and give me a cited, multi-source brief: ${arg}`);
2784
2919
  break;
2785
2920
  }
2921
+ case "delegate": {
2922
+ // Writes only existing settings (moa.plannerModel + moa.specialist, autonomy.subagentModel, delegate.*), in memory
2923
+ // and on disk: sub-agents resolve their model per spawn, delegate_task re-reads settings, the guard reads per call.
2924
+ const a = parseDelegate(arg);
2925
+ const setGuard = (patch) => {
2926
+ settings.delegate = { ...settings.delegate, ...patch };
2927
+ setDelegateSettings(settings.delegate);
2928
+ persist({ delegate: patch });
2929
+ };
2930
+ const status = () => {
2931
+ const team = s.moaTeam();
2932
+ const d = settings.delegate ?? {};
2933
+ return delegateStatusLines({ activeModel: s.currentModel(), plannerModel: settings.moa?.plannerModel?.trim() ? team?.planner.id : undefined, specialist: team?.specialist, subagentModel: subagentModel(), guard: delegateGuardOn(process.env, d), allowPush: !!d.allowPush, repos: d.repos ?? [] }).join("\n");
2934
+ };
2935
+ if (a.kind === "error") {
2936
+ sys(a.message);
2937
+ break;
2938
+ }
2939
+ if (a.kind === "planner") {
2940
+ const executor = a.executor ?? (settings.moa?.specialist?.id ? undefined : subagentModelFor({ autonomy: settings.autonomy }));
2941
+ const r = s.setMoaPlanner(a.model, executor);
2942
+ if (!r.ok) {
2943
+ sys(`delegate planner: ${r.error}`);
2944
+ break;
2945
+ }
2946
+ const patch = { plannerModel: a.model, ...(executor ? { specialist: { id: executor } } : {}) };
2947
+ settings.moa = { ...settings.moa, ...patch };
2948
+ persist({ moa: patch });
2949
+ const onMoa = s.currentModel() === "moa";
2950
+ sys(`delegate · planner ${a.model} → executor ${s.moaTeam()?.specialist}${onMoa ? (turnRunning() ? " · from the next turn" : "") : " · switching to /model moa"}`);
2951
+ if (!onMoa)
2952
+ submitRef.current("/model moa");
2953
+ break;
2954
+ }
2955
+ if (a.kind === "subagents") {
2956
+ const { profile, error } = selectModel(s.modelRegistry(), a.model, hasByoToken);
2957
+ if (!profile) {
2958
+ sys(`delegate subagents: ${error}`);
2959
+ break;
2960
+ }
2961
+ settings.autonomy = { ...settings.autonomy, subagentModel: a.model };
2962
+ persist({ autonomy: { subagentModel: a.model } });
2963
+ sys(`delegate · sub-agents (spawn_agent, delegate_task default) run on ${a.model}${s.currentModel() === "moa" ? ` — under /model moa the executor ${s.moaTeam()?.specialist} takes them` : ""}`);
2964
+ break;
2965
+ }
2966
+ if (a.kind === "guard")
2967
+ setGuard({ guard: a.on });
2968
+ else if (a.kind === "push")
2969
+ setGuard({ allowPush: a.on });
2970
+ else if (a.kind === "off") {
2971
+ s.setMoaPlanner("");
2972
+ settings.moa = { ...settings.moa, plannerModel: "" };
2973
+ persist({ moa: { plannerModel: "" } });
2974
+ setGuard({ guard: false, allowPush: false });
2975
+ }
2976
+ sys(status());
2977
+ break;
2978
+ }
2786
2979
  case "allow": {
2787
2980
  if (!arg) {
2788
2981
  sys("usage: /allow <tool:args> e.g. /allow bash:npm test*");
@@ -2945,8 +3138,8 @@ function Root() {
2945
3138
  break;
2946
3139
  }
2947
3140
  case "services": {
2948
- // The lever, on demand: `/services` probes + starts any down launchd service; `/services stop`
2949
- // tears down only the session-scoped SearXNG (Aurora/autopilot are shared and stay up).
3141
+ // The lever, on demand: `/services` probes + starts any down optional launchd service (never Aurora: retired,
3142
+ // reported only); `/services stop` tears down only the session-scoped SearXNG.
2950
3143
  if (arg === "stop") {
2951
3144
  const { stopSessionServices } = await import("./services/preflight.js");
2952
3145
  await stopSessionServices({ searxng: true });
@@ -2980,9 +3173,32 @@ function Root() {
2980
3173
  }
2981
3174
  case "agents": {
2982
3175
  const l = bg.list();
3176
+ const paused = pausedRef.current;
3177
+ const pausedLines = paused.length
3178
+ ? `\npaused — resume? (still working when Operator closed; /agents resume [name] · /agents discard):\n` + paused.map((a) => ` ⏸ ${a.name} · ${a.label} · round ${a.rounds}`).join("\n")
3179
+ : "";
3180
+ if (arg === "resume" || arg.startsWith("resume ")) {
3181
+ const want = arg.slice(6).trim().toLowerCase();
3182
+ const pick = want && want !== "all" ? paused.filter((a) => a.name.toLowerCase() === want || a.id === want) : paused;
3183
+ if (!pick.length) {
3184
+ sys(paused.length ? `no paused agent named ${want} — paused: ${paused.map((a) => a.name).join(", ")}` : "no paused agents");
3185
+ break;
3186
+ }
3187
+ const r = startSaved(pick, spawnSaved);
3188
+ pausedRef.current = [...paused.filter((a) => !pick.includes(a)), ...r.left];
3189
+ clearResumable(process.cwd()); // what is still paused is saved again on quit
3190
+ sys(r.line);
3191
+ break;
3192
+ }
3193
+ if (arg === "discard") {
3194
+ sys(paused.length ? `dropped ${paused.length} paused agent${paused.length === 1 ? "" : "s"}: ${paused.map((a) => a.name).join(", ")}` : "no paused agents");
3195
+ pausedRef.current = [];
3196
+ clearResumable(process.cwd());
3197
+ break;
3198
+ }
2983
3199
  if (!arg) {
2984
3200
  if (!l.length) {
2985
- sys("no sub-agents spawned this session");
3201
+ sys(`no sub-agents spawned this session${pausedLines}`);
2986
3202
  break;
2987
3203
  }
2988
3204
  const running = l.filter((a) => a.status === "working").length;
@@ -2990,7 +3206,7 @@ function Root() {
2990
3206
  const done = l.filter((a) => a.status === "idle").length;
2991
3207
  const errored = l.filter((a) => a.status === "stopped").length;
2992
3208
  const counts = [running ? `${running} running` : "", queued ? `${queued} queued` : "", done ? `${done} done` : "", errored ? `${errored} errored` : ""].filter(Boolean).join(" · ");
2993
- sys(`sub-agents (${counts}):\n` + l.map((a) => ` ${formatAgentDetail(a)}`).join("\n"));
3209
+ sys(`sub-agents (${counts}):\n` + l.map((a) => ` ${formatAgentDetail(a)}${a.resumed ? " · resumed" : ""}`).join("\n") + pausedLines);
2994
3210
  break;
2995
3211
  }
2996
3212
  const parts = parseAgentCommand(arg, [...l, ...bg.retiredList()]);
@@ -3093,7 +3309,14 @@ function Root() {
3093
3309
  let lost = false; // an outage is said once; the re-dials behind it are silent until the relay answers
3094
3310
  const rh = new RemoteHost(urls, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
3095
3311
  onPrompt: remotePrompt, // follower drives a turn (slash-shaped → the allowlisted command path)
3096
- onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
3312
+ onApprovalResponse: (id, approve, grant) => settleApproval(id, approve, false, grant), // first-wins with local
3313
+ onGrantRevoke: (req) => {
3314
+ if ("all" in req)
3315
+ grantsRef.current.revokeAll();
3316
+ else
3317
+ grantsRef.current.revoke(req.id);
3318
+ rh.setGrants(grantsRef.current.list());
3319
+ },
3097
3320
  onAskUserResponse: (id, answer) => settleQuestion(id, answer), // first-wins with local
3098
3321
  onInterrupt: () => s.interrupt(), // follower cancels the turn
3099
3322
  // RC v2 B1: a follower tapped Stop/Steer on a sub-agent row → the SAME BackgroundAgents the local
@@ -3163,7 +3386,14 @@ function Root() {
3163
3386
  let lost = false;
3164
3387
  const rh = new RemoteHost(urls, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
3165
3388
  onPrompt: remotePrompt,
3166
- onApprovalResponse: (id, approve) => settleApproval(id, approve),
3389
+ onApprovalResponse: (id, approve, grant) => settleApproval(id, approve, false, grant),
3390
+ onGrantRevoke: (req) => {
3391
+ if ("all" in req)
3392
+ grantsRef.current.revokeAll();
3393
+ else
3394
+ grantsRef.current.revoke(req.id);
3395
+ rh.setGrants(grantsRef.current.list());
3396
+ },
3167
3397
  onAskUserResponse: (id, answer) => settleQuestion(id, answer),
3168
3398
  onInterrupt: () => s.interrupt(),
3169
3399
  onAgentStop: (id) => bgRef.current?.requestStop(id) ?? false, // RC v2 B1 (paired mode)
@@ -3622,11 +3852,15 @@ function Root() {
3622
3852
  // no message is dropped. settings.wakeOnMentor.from narrows which senders may drive a turn (unset = any).
3623
3853
  if (isFeatureEnabled("wakeOnMentor", settings)) {
3624
3854
  const allow = settings.wakeOnMentor?.from;
3625
- const eligible = allow?.length ? incoming.filter((m) => allow.includes(m.from)) : incoming;
3855
+ const eligible = (allow?.length ? incoming.filter((m) => allow.includes(m.from)) : incoming).filter((m) => !isAutoReport(m));
3626
3856
  wakeBuffer.push(...eligible);
3627
3857
  const ready = selectReadyWakes(wakeBuffer, lastWakeBySource, now, WAKE_COOLDOWN_MS);
3628
- const wakeText = ready.length ? buildMentorWake(ready) : null;
3858
+ const rootPolicy = allow?.length ? { roots: settings.wakeOnMentor?.roots ?? [join(homedir(), "work")] } : undefined;
3859
+ const wakeText = ready.length ? buildMentorWake(ready, undefined, rootPolicy) : null;
3629
3860
  if (wakeText) {
3861
+ const dir = wakeRoot(wakeText);
3862
+ if (dir)
3863
+ sys(`↳ wake from ${[...new Set(ready.map((m) => m.from))].join(", ")}: this turn runs in ${dir} (from the brief)`);
3630
3864
  if (statusRef.current === "idle")
3631
3865
  submitRef.current?.(wakeText);
3632
3866
  else
@@ -3648,8 +3882,8 @@ function Root() {
3648
3882
  if (boot === "checking")
3649
3883
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
3650
3884
  if (boot === "down") {
3651
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, session.currentModel() === DEFAULT_MODEL_ID
3652
- ? _jsxs(Text, { dimColor: true, children: ["The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/", settings.services?.aurora?.launchdLabel ?? "co.0perator.gateway"] })
3885
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, session.currentModel() === CHAIN_MODEL_ID
3886
+ ? _jsx(Text, { dimColor: true, children: "No leg of the chain answered (the local router's main route, then the cloud tier). Check the router, or sign in for the cloud tier." })
3653
3887
  : _jsxs(Text, { dimColor: true, children: ["Start on another model: set \"activeModel\" in settings.json to one /model lists, then /model ", session.currentModel(), " once it is reachable."] })] }));
3654
3888
  }
3655
3889
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
@@ -3710,7 +3944,7 @@ function Root() {
3710
3944
  decode: shownPhase === "thinking" || shownPhase === "writing" || shownPhase === "drafting" ? decodeView() : undefined,
3711
3945
  }
3712
3946
  : null;
3713
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, phase: phaseView, fold: liveFold, delegate: delegate, thinkingVerb: stepVerb ?? triage ?? phaseVerb(shownPhase ?? undefined, phaseView?.read), liveTools: liveTools, route: route, ctxPct: ctxPct, ctxWindow: session.currentModel() === "moa" ? (ctxPin ? fmtCtx(ctxPin) : undefined) : fmtCtx(ctxPin ? Math.min(ctxPin, session.servedContext()) : session.servedContext()), 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, shellJobs: shellJobs, mainLane: mainLane, mainServing: servingModelFor(settings, session.currentModel()), maxRunning: bg.limits().running, onBackground: onBackground, tasks: tasks, planNow: planLive ? Date.now() : lastTurnEndRef.current, onSubmit: onSubmit, onQueue: onQueue, onSteer: onSteer, pending: pending, nextSteps: nextSteps ?? undefined, onPickNext: onPickNext, onDismissNext: onDismissNext, agents: bgAgents, onAgentMessage: onAgentMessage, conversations: convs, switcher: { focused: switcher.focused, sel: Math.max(0, convs.findIndex((c) => c.id === switcher.sel)), open: openConv }, onSwitcher: onSwitcher, onFocusSwitcher: onFocusSwitcher, conversationPane: conversationPane, onSendTo: onSendTo, actOffer: active ? actNowOffer(actRef.current, Date.now(), { thinking: thinkMode !== "off" }) : null, onActNow: onActNow, finder: finder, onOpenFinder: onOpenFinder, onEditQueued: popQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onExpand: onExpand, onCycleMode: onCycleMode, onCycleContext: onCycleContext, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, secretPrompt: secretPrompt, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
3947
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, phase: phaseView, fold: liveFold, delegate: delegate, thinkingVerb: stepVerb ?? triage ?? phaseVerb(shownPhase ?? undefined, phaseView?.read), liveTools: liveTools, route: route, ctxPct: ctxPct, ctxWindow: session.currentModel() === "moa" ? (ctxPin ? fmtCtx(ctxPin) : undefined) : fmtCtx(ctxPin ? Math.min(ctxPin, session.servedContext()) : session.servedContext()), 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, shellJobs: shellJobs, mainLane: mainLane, mainServing: servingModelFor(settings, session.currentModel()), maxRunning: bg.limits().running, lanePool: bg.slotState().line, laneWarnings: bg.evidenceWarnings(), onBackground: onBackground, tasks: tasks, planNow: planLive ? Date.now() : lastTurnEndRef.current, onSubmit: onSubmit, onQueue: onQueue, onSteer: onSteer, pending: pending, nextSteps: nextSteps ?? undefined, onPickNext: onPickNext, onDismissNext: onDismissNext, agents: bgAgents, onAgentMessage: onAgentMessage, conversations: convs, switcher: { focused: switcher.focused, sel: Math.max(0, convs.findIndex((c) => c.id === switcher.sel)), open: openConv }, onSwitcher: onSwitcher, onFocusSwitcher: onFocusSwitcher, conversationPane: conversationPane, onSendTo: onSendTo, actOffer: active ? actNowOffer(actRef.current, Date.now(), { thinking: thinkMode !== "off" }) : null, onActNow: onActNow, finder: finder, onOpenFinder: onOpenFinder, onEditQueued: popQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onExpand: onExpand, onCycleMode: onCycleMode, onCycleContext: onCycleContext, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, secretPrompt: secretPrompt, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, update: updatePrompt, onApprovalDecide: (allow, always) => {
3714
3948
  const cur = approval;
3715
3949
  if (cur)
3716
3950
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -3721,7 +3955,13 @@ function Root() {
3721
3955
  // (--version/--help fast paths hoisted to the top of the module — they must never touch keychain/network.)
3722
3956
  if (process.argv[2] === "auth") {
3723
3957
  const { runAuth } = await import("./auth/commands.js");
3724
- process.exit(await runAuth(process.argv.slice(3), settings));
3958
+ const code = await runAuth(process.argv.slice(3), settings);
3959
+ if (code === 0 && process.argv[3] === "login") {
3960
+ const offer = await checkOnSignIn();
3961
+ if (offer)
3962
+ console.log(`\n${(await import("./update-check.js")).offerLine(offer)}`);
3963
+ }
3964
+ process.exit(code);
3725
3965
  }
3726
3966
  // `operator audit verify|tail` and `operator doctor` — the enterprise review surface: prove the audit trail is
3727
3967
  // intact, and show exactly what policy/seat/home posture is in force. Plain console, no TTY needed.
@@ -3740,6 +3980,11 @@ if (process.argv[2] === "gateway") {
3740
3980
  const { runGateway } = await import("./gateway-cli.js");
3741
3981
  process.exit(await runGateway(process.argv.slice(3)));
3742
3982
  }
3983
+ // `operator phone setup|mcp` — the device harness's setup checklist and its MCP server (tools/device/).
3984
+ if (process.argv[2] === "phone") {
3985
+ const { runPhone } = await import("./phone-cli.js");
3986
+ process.exit(await runPhone(process.argv.slice(3)));
3987
+ }
3743
3988
  // `operator toolchain …` — the toolchain CLI (toolchain/ in the repo, dist/toolchain/ in the package).
3744
3989
  if (process.argv[2] === "toolchain") {
3745
3990
  const { runToolchain } = await import("./toolchain-cli.js");
@@ -3809,6 +4054,14 @@ else {
3809
4054
  catch { /* best-effort; a write failure just re-shows next boot */ }
3810
4055
  }
3811
4056
  }
4057
+ {
4058
+ const { checkEnabled, checkForUpdate } = await import("./update-check.js");
4059
+ const { isSourceCheckout } = await import("./update.js");
4060
+ if (checkEnabled({ argv: process.argv, env: process.env, tty: !!process.stdin.isTTY && !!process.stdout.isTTY, settings, sourceCheckout: isSourceCheckout() })) {
4061
+ UPDATE_ASKED_AT = Date.now();
4062
+ UPDATE_CHECK = checkForUpdate(VERSION);
4063
+ }
4064
+ }
3812
4065
  // Ink would exit on the first ctrl+c itself; the composer owns that key (interrupt mid-turn, twice to quit at rest).
3813
4066
  const inkInstance = render(_jsx(Root, {}), { exitOnCtrlC: false });
3814
4067
  if (FULLSCREEN)
@@ -3819,6 +4072,10 @@ if (FULLSCREEN)
3819
4072
  // something still holds the event loop open.
3820
4073
  void inkInstance.waitUntilExit().then(() => "quit", () => "error").then(async (reason) => {
3821
4074
  await teardown.run(reason);
4075
+ if (UPDATE_NOW) {
4076
+ const { runOfferedUpdate } = await import("./update-check.js");
4077
+ process.exitCode = await runOfferedUpdate(UPDATE_NOW);
4078
+ }
3822
4079
  setTimeout(() => process.exit(process.exitCode ?? 0), 1500).unref();
3823
4080
  });
3824
4081
  // Ink erases the previous frame by line COUNT, computed from the terminal width at draw time. When the