@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
@@ -15,14 +15,16 @@ export const READONLY_SAFE_EXCLUDED = ["scratchpad", "session_handoff"];
15
15
  // ALLOWLIST by design — anything not safe and not named here (fleet MCP tools mcp__*, computer_* control,
16
16
  // future privileged tools) is denied, so new mutating tools are safe-by-default. Deliberately NOT granted:
17
17
  // http_request / file_upload (arbitrary outbound bodies / file egress), image_generate / video_generate /
18
- // image_recreate (GPU spend), artifact_create (publishes a public URL). task_clear is granted — it only
19
- // resets the session-local todo list, the same class as the already-granted task_add / task_update.
18
+ // image_recreate (GPU spend). artifact_create and the artifact library writes are granted (2026-11-29): an
19
+ // enterprise seat publishes private by default and never public (permissions/artifact-visibility.ts). task_clear is
20
+ // granted — it only resets the session-local todo list, the same class as the already-granted task_add / task_update.
20
21
  const ENTERPRISE_MUTATING = [
21
22
  "file_write", "file_edit",
22
23
  "bash", "shell_exec", "shell_background", "bash_kill",
23
24
  "git_command", "checkpoint",
24
25
  "task_add", "task_update", "task_clear",
25
26
  "memory_store", "skill_save",
27
+ "artifact_create", "craft_update", "craft_delete",
26
28
  ];
27
29
  const ENTERPRISE_ALLOW = new Set([...SAFE_TOOLS, ...ENTERPRISE_MUTATING]);
28
30
  // Readonly seat: inspection only = the registry-safe tools minus READONLY_SAFE_EXCLUDED. Every member is
@@ -0,0 +1,65 @@
1
+ // `operator phone …` — plain console, no TTY needed.
2
+ // setup [--json] [--yes] [--device D] scan every backend, print the checklist and the one next action; when a phone
3
+ // is ready, offer one read-only screenshot + description (asked, or --yes)
4
+ // mcp [--allow-actions] the device tools as a stdio MCP server (src/mcp/phone-server.ts)
5
+ import { createInterface } from "node:readline";
6
+ import { readOnlyCheck, renderSetup, setupReport } from "./tools/device/setup.js";
7
+ function flag(args, name) { return args.includes(name); }
8
+ function value(args, name) { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }
9
+ async function ask(question) {
10
+ if (!process.stdin.isTTY)
11
+ return false;
12
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
13
+ const answer = await new Promise((resolve) => rl.question(question, resolve));
14
+ rl.close();
15
+ return /^y(es)?$/i.test(answer.trim());
16
+ }
17
+ async function setup(args) {
18
+ const report = await setupReport();
19
+ if (flag(args, "--json")) {
20
+ process.stdout.write(JSON.stringify({ os: report.os, sections: report.sections, next: report.next, ready: report.ready, statuses: report.statuses }, null, 2) + "\n");
21
+ return report.ready.length ? 0 : 2;
22
+ }
23
+ process.stdout.write(renderSetup(report) + "\n");
24
+ if (!report.ready.length)
25
+ return 2;
26
+ const device = value(args, "--device") ?? (report.ready.length === 1 ? report.ready[0] : undefined);
27
+ const go = flag(args, "--yes") || await ask(`\nTake one screenshot of the ${device ?? "phone"} and describe it (read-only, nothing is tapped)? [y/N] `);
28
+ if (!go) {
29
+ process.stdout.write("Skipped the read-only check.\n");
30
+ return 0;
31
+ }
32
+ const r = await readOnlyCheck(device);
33
+ process.stdout.write(`\n${r}\n`);
34
+ return r.startsWith("error") ? 1 : 0;
35
+ }
36
+ async function mcp(args) {
37
+ const { handlePhoneMcp } = await import("./mcp/phone-server.js");
38
+ const allowActions = flag(args, "--allow-actions");
39
+ const rl = createInterface({ input: process.stdin });
40
+ for await (const line of rl) {
41
+ if (!line.trim())
42
+ continue;
43
+ let req;
44
+ try {
45
+ req = JSON.parse(line);
46
+ }
47
+ catch {
48
+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } }) + "\n");
49
+ continue;
50
+ }
51
+ const res = await handlePhoneMcp(req, { allowActions });
52
+ if (res)
53
+ process.stdout.write(JSON.stringify(res) + "\n");
54
+ }
55
+ return 0;
56
+ }
57
+ export async function runPhone(args) {
58
+ const [sub = "setup", ...rest] = args;
59
+ if (sub === "setup" || sub === "status" || sub === "doctor")
60
+ return setup(rest);
61
+ if (sub === "mcp")
62
+ return mcp(rest);
63
+ process.stderr.write("usage: operator phone setup [--json] [--yes] [--device iphone|android|<serial>]\n operator phone mcp [--allow-actions]\n");
64
+ return 1;
65
+ }
@@ -45,7 +45,7 @@ export async function craftCreate(args, auth) {
45
45
  export async function craftUpdate(args, auth) {
46
46
  const id = str(args.id);
47
47
  if (!id)
48
- return "error: craft_update needs `id` (from craft_create / craft_list)";
48
+ return "error: craft_update needs `id` (from artifact_create / craft_list)";
49
49
  const visibility = visibilityOf(args.visibility);
50
50
  if (!str(args.content) && !str(args.title) && !visibility)
51
51
  return "error: craft_update needs at least one of `content`, `title`, `visibility`";
@@ -71,7 +71,7 @@ export async function craftList(args, auth) {
71
71
  const r = await temple.list(Number(args.limit) || 20, auth);
72
72
  if (!r.ok)
73
73
  return `error: ${r.error}`;
74
- return r.value.length ? r.value.map(temple.format.line).join("\n") : "no craft yet — make one with craft_create";
74
+ return r.value.length ? r.value.map(temple.format.line).join("\n") : "no artifacts yet — make one with artifact_create";
75
75
  }
76
76
  export async function craftGet(args, auth) {
77
77
  const id = str(args.id);
@@ -0,0 +1,119 @@
1
+ // "Always allow" grants for gated tool calls, held by the host (the host runs the tool, so the host decides).
2
+ // Design + security rules: kode-mobile/_ai-docs/architecture/2026-11-26-scoped-approval-grants.md.
3
+ // The follower sends only a scope; the target is always derived here from the real pending call, matching is
4
+ // exact, grants expire, and every create/use/revoke is audited. Off unless KODE_GRANTS=1.
5
+ import { normalize, isAbsolute } from "node:path";
6
+ export const grantsEnabled = (env = process.env) => env.KODE_GRANTS === "1";
7
+ const DAY_MS = 86_400_000;
8
+ export function isGrantScope(v) {
9
+ return v === "session" || v === "day";
10
+ }
11
+ const str = (v) => typeof v === "string" && v.trim() !== "" ? v : undefined;
12
+ /** The exact thing a grant for this call would cover, or undefined when the tool can't be granted. */
13
+ export function deriveGrantTarget(tool, args) {
14
+ const cwd = str(args.cwd);
15
+ const inCwd = (s) => (cwd ? `${s} · in ${cwd}` : s);
16
+ switch (tool) {
17
+ case "shell_exec":
18
+ case "bash": {
19
+ const command = str(args.command);
20
+ return command && inCwd(command);
21
+ }
22
+ case "git_command": {
23
+ const a = args.args;
24
+ const parts = Array.isArray(a) && a.every((x) => typeof x === "string") ? a : typeof a === "string" ? [a] : [];
25
+ return parts.length ? inCwd(["git", ...parts].join(" ")) : undefined;
26
+ }
27
+ case "file_write":
28
+ case "file_edit": {
29
+ const raw = str(args.path) ?? str(args.file_path);
30
+ if (!raw || !isAbsolute(raw) || raw.split("/").includes(".."))
31
+ return undefined;
32
+ return normalize(raw);
33
+ }
34
+ case "web_read": {
35
+ const raw = str(args.url);
36
+ if (!raw)
37
+ return undefined;
38
+ try {
39
+ const u = new URL(raw);
40
+ return u.protocol === "https:" || u.protocol === "http:" ? u.hostname.toLowerCase() || undefined : undefined;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
46
+ default:
47
+ return undefined;
48
+ }
49
+ }
50
+ export function grantMatches(g, tool, target, sessionId, now) {
51
+ if (g.tool !== tool || g.target !== target)
52
+ return false;
53
+ if (g.expiresAt !== undefined && now >= g.expiresAt)
54
+ return false;
55
+ return g.scope === "day" || g.sessionId === sessionId;
56
+ }
57
+ export class GrantStore {
58
+ onAudit;
59
+ grants = [];
60
+ audit = [];
61
+ seq = 0;
62
+ constructor(onAudit = () => { }) {
63
+ this.onAudit = onAudit;
64
+ }
65
+ /** Record a grant for exactly this call. Undefined (nothing stored) when the call isn't grantable. */
66
+ add(tool, args, scope, sessionId, now = Date.now()) {
67
+ const target = deriveGrantTarget(tool, args);
68
+ if (!target)
69
+ return undefined;
70
+ const g = {
71
+ id: `gr_${now.toString(36)}_${(this.seq++).toString(36)}`, tool, target, scope, sessionId,
72
+ createdAt: now, ...(scope === "day" ? { expiresAt: now + DAY_MS } : {}), uses: 0,
73
+ };
74
+ this.grants.push(g);
75
+ this.log("grant", g, now);
76
+ return g;
77
+ }
78
+ /** The live grant covering this exact call, with its use recorded; undefined means ask. */
79
+ use(tool, args, sessionId, now = Date.now()) {
80
+ this.prune(now);
81
+ const target = deriveGrantTarget(tool, args);
82
+ if (!target)
83
+ return undefined;
84
+ const g = this.grants.find((x) => grantMatches(x, tool, target, sessionId, now));
85
+ if (!g)
86
+ return undefined;
87
+ g.uses += 1;
88
+ g.lastUsedAt = now;
89
+ this.log("use", g, now);
90
+ return g;
91
+ }
92
+ revoke(id, now = Date.now()) {
93
+ const i = this.grants.findIndex((g) => g.id === id);
94
+ if (i < 0)
95
+ return false;
96
+ this.log("revoke", this.grants[i], now);
97
+ this.grants.splice(i, 1);
98
+ return true;
99
+ }
100
+ revokeAll(now = Date.now()) {
101
+ for (const g of this.grants)
102
+ this.log("revoke", g, now);
103
+ this.grants = [];
104
+ }
105
+ list(now = Date.now()) {
106
+ this.prune(now);
107
+ return this.grants.map((g) => ({ ...g }));
108
+ }
109
+ prune(now) {
110
+ this.grants = this.grants.filter((g) => g.expiresAt === undefined || now < g.expiresAt);
111
+ }
112
+ log(event, g, at) {
113
+ const a = { at, event, grantId: g.id, tool: g.tool, target: g.target };
114
+ this.audit.push(a);
115
+ if (this.audit.length > 500)
116
+ this.audit.shift();
117
+ this.onAudit(a);
118
+ }
119
+ }
@@ -1,5 +1,6 @@
1
1
  import { frameKey as deriveFrameKey, pairingId as derivePairingId, encryptFrame, decryptFrame } from "./pairing.js";
2
2
  import { redactSecrets } from "../engine/redact.js";
3
+ import { grantsEnabled, isGrantScope } from "./grants.js";
3
4
  let socketCtor = globalThis.WebSocket;
4
5
  /** The WebSocket constructor for this runtime: the global one, else `ws`'s (same addEventListener / send / close shape). */
5
6
  async function loadSocketCtor() {
@@ -28,8 +29,8 @@ const RECONNECT_MAX_MS = 15_000;
28
29
  // control frames stay plaintext so the relay can route blind. These sets mirror the mobile's frozen
29
30
  // dataFrameTypes byte-for-byte (kode-mobile RemoteSession.swift). The INNER encrypted bytes are
30
31
  // JSON.stringify(payloadDict) — just the payload dict, never {type,payload}.
31
- const DATA_HOST_TYPES = new Set(["snapshot", "transcript", "tool_step", "activity", "status", "capabilities", "approval_request", "ask_user", "delta"]);
32
- const DATA_DRIVE_TYPES = new Set(["prompt", "command", "approval_response", "ask_user_response", "interrupt", "agent_stop", "agent_steer"]);
32
+ const DATA_HOST_TYPES = new Set(["snapshot", "transcript", "tool_step", "activity", "status", "capabilities", "approval_request", "ask_user", "delta", "agents", "grants"]);
33
+ const DATA_DRIVE_TYPES = new Set(["prompt", "command", "approval_response", "ask_user_response", "interrupt", "agent_stop", "agent_steer", "grant_revoke"]);
33
34
  // A paired snapshot is encrypted (base64 ≈ 1.37× plaintext), and the relay drops/truncates any frame over
34
35
  // its 256 KB cap — which would corrupt ciphertext. Cap the paired snapshot's plaintext so the encrypted
35
36
  // frame stays comfortably under 256 KB; token-mode keeps the full 512 KB budget.
@@ -42,6 +43,13 @@ const SNAPSHOT_MAX_BYTES_PAIRED = 170 * 1024;
42
43
  const SNAPSHOT_MAX_ENTRIES = 200; // SPEC §8: last 200 message-entries + their tool steps, whichever binds first
43
44
  const SNAPSHOT_MAX_BYTES = 512 * 1024; // SPEC §8 snapshot cap
44
45
  const MCP_TOOL_PREVIEW = 20; // per-server tool NAMES kept when a server's inventory is large — see capCapabilities
46
+ /** The shell's agent list as followers see it: live ones and finished ones until they decommission. */
47
+ export function toRemoteAgents(list) {
48
+ return list.map((a) => ({
49
+ id: a.id, name: a.name ?? a.id, label: a.label, status: a.status, round: a.round ?? 0,
50
+ ...(a.resumed ? { resumed: true } : {}), ...(a.endKind ? { endKind: a.endKind } : {}), ...(a.headline ? { headline: a.headline } : {}),
51
+ }));
52
+ }
45
53
  const byteLen = (v) => Buffer.byteLength(JSON.stringify(v), "utf8");
46
54
  // BLOCKER fix (REMOTE_RICH_HEAD_AUDIT.md §4, "summarize, don't enumerate"): a server's `tools[]` is
47
55
  // prefixed to MCP_TOOL_PREVIEW entries — `toolCount` still carries the real total, so a follower's UI
@@ -79,6 +87,7 @@ export class RemoteHost {
79
87
  livePending = null;
80
88
  turnN = 0;
81
89
  capabilities = null;
90
+ agentRows = [];
82
91
  // Paired (QR) mode — set from the one-time code the owner shows as a QR. When paired, the host registers
83
92
  // its pairingId with the relay and e2e-encrypts every DATA-frame payload with frameKey; the relay (and
84
93
  // anyone but the scanning phone) sees only ciphertext.
@@ -141,7 +150,7 @@ export class RemoteHost {
141
150
  ws.addEventListener("open", () => {
142
151
  // §1: advertise the engine contract + features so the relay/followers can version-gate. sessionId (when
143
152
  // set) makes this a RESUME. Additive — an old relay ignores proto/features.
144
- this.send("hello", null, { token: this.token, role: "host", sessionId: this.sessionId ?? undefined, proto: ENGINE_CONTRACT, features: HOST_FEATURES });
153
+ this.send("hello", null, { token: this.token, role: "host", sessionId: this.sessionId ?? undefined, proto: ENGINE_CONTRACT, features: grantsEnabled() ? [...HOST_FEATURES, "grants.v1"] : HOST_FEATURES });
145
154
  });
146
155
  ws.addEventListener("message", (ev) => this.onMessage(String(ev.data)));
147
156
  ws.addEventListener("close", () => {
@@ -236,7 +245,7 @@ export class RemoteHost {
236
245
  if (typeof f.payload?.epoch === "number")
237
246
  this.epoch = f.payload.epoch; // RC v2 A2
238
247
  this.reconnectAttempts = 0; // a successful welcome resets the backoff ladder
239
- this.send("register", this.sessionId, { title: this.meta.title, surface: this.meta.surface ?? "cli", cwd: this.meta.cwd, host: this.meta.host });
248
+ this.register();
240
249
  if (this.paired && this.pairingId)
241
250
  this.send("pair-register", this.sessionId, { pairingId: this.pairingId }); // control frame (plaintext) — binds pairingId -> this session at the relay
242
251
  // RC v2 A2: a welcome AFTER the first is a RESUME. While the socket was down, state frames were dropped
@@ -276,6 +285,8 @@ export class RemoteHost {
276
285
  break;
277
286
  case "attach": // a follower joined — send a full snapshot BEFORE any further delta (§8)
278
287
  this.sendSnapshot();
288
+ if (grantsEnabled())
289
+ this.state("grants", { items: this.grantItems });
279
290
  break;
280
291
  // Drive frames (follower -> host actions). Defense-in-depth: the relay is SUPPOSED to only
281
292
  // ever forward a frame that belongs to this connection's session, but a relay bug or a
@@ -287,8 +298,24 @@ export class RemoteHost {
287
298
  this.cb.onPrompt(f.payload.text);
288
299
  break;
289
300
  case "approval_response":
290
- if (this.isOwnFrame(f) && f.payload?.id)
291
- this.cb.onApprovalResponse(String(f.payload.id), !!f.payload.approve);
301
+ if (this.isOwnFrame(f) && f.payload?.id) {
302
+ const approve = !!f.payload.approve;
303
+ // Only a scope is read from the follower. The target is derived host-side from the pending call.
304
+ const scope = f.payload.grant?.scope;
305
+ const grant = approve && grantsEnabled() && isGrantScope(scope) ? { scope } : undefined;
306
+ if (grant)
307
+ this.cb.onApprovalResponse(String(f.payload.id), approve, grant);
308
+ else
309
+ this.cb.onApprovalResponse(String(f.payload.id), approve);
310
+ }
311
+ break;
312
+ case "grant_revoke":
313
+ if (this.isOwnFrame(f) && grantsEnabled()) {
314
+ if (f.payload?.all === true)
315
+ this.cb.onGrantRevoke?.({ all: true });
316
+ else if (typeof f.payload?.id === "string")
317
+ this.cb.onGrantRevoke?.({ id: f.payload.id });
318
+ }
292
319
  break;
293
320
  case "ask_user_response":
294
321
  if (this.isOwnFrame(f) && f.payload?.id)
@@ -353,8 +380,29 @@ export class RemoteHost {
353
380
  ...(this.epoch != null ? { epoch: this.epoch } : {}), // RC v2 A2: the reliable place to stamp epoch (welcome fires pre-attach)
354
381
  ...(truncated ? { truncated: true, omittedBefore } : {}),
355
382
  ...(this.capabilities ? { capabilities: this.capabilities } : {}), // absent until the shell's first setCapabilities() call; already capped by capCapabilities() in setCapabilities()
383
+ ...(this.agentRows.length ? { agents: this.agentRows } : {}),
356
384
  }, this.seq);
357
385
  }
386
+ /** The session row on the relay's list carries how many agents work here, so a phone shows "N agents working" without
387
+ * attaching. Re-sent whenever that count changes; an older relay keeps the fields it knows. */
388
+ register() {
389
+ const agentsWorking = this.agentRows.filter((a) => a.status === "working" || a.status === "queued").length;
390
+ this.send("register", this.sessionId, { title: this.meta.title, surface: this.meta.surface ?? "cli", cwd: this.meta.cwd, host: this.meta.host, agentsWorking });
391
+ }
392
+ /** The host's background agents. Sent as an `agents` state frame when they change (never on an identical list). */
393
+ setAgents(rows) {
394
+ const next = rows.map((a) => ({ ...a }));
395
+ if (JSON.stringify(next) === JSON.stringify(this.agentRows))
396
+ return;
397
+ const working = (r) => r.filter((a) => a.status === "working" || a.status === "queued").length;
398
+ const countChanged = working(next) !== working(this.agentRows);
399
+ this.agentRows = next;
400
+ if (!this.sessionId)
401
+ return;
402
+ this.state("agents", { agents: next });
403
+ if (countChanged)
404
+ this.register();
405
+ }
358
406
  /** SPEC §8 snapshot cap: last 200 message/tool entries, then shrink further (oldest-first) until the
359
407
  * serialized transcript fits 512 KB — `capabilities` gets its own budget (capCapabilities), so this
360
408
  * only accounts for the transcript half. `omittedBefore` is this host's CURRENT seq at truncation
@@ -482,4 +530,13 @@ export class RemoteHost {
482
530
  * follower's ask_user_response race first-wins in the host (settleQuestion in cli.tsx); local
483
531
  * ask_user keeps working unchanged when no remote-control session is active. */
484
532
  askUser(id, question, options) { this.state("ask_user", { id, question, options }); }
533
+ grantItems = [];
534
+ /** Mirror the live grants to followers (owner-scoped `grants` state frame) so their list is what the host holds. */
535
+ setGrants(items) {
536
+ if (!grantsEnabled())
537
+ return;
538
+ this.grantItems = items;
539
+ if (this.sessionId)
540
+ this.state("grants", { items });
541
+ }
485
542
  }
@@ -13,17 +13,22 @@
13
13
  import { LEGACY_API_HOST, PRODUCT_API_HOST } from "../config/product-hosts.js"; // no imports of its own — no cycle
14
14
  /** Fallback walk order, strongest → cheapest. */
15
15
  export const TIER_LADDER = ["power_turbo", "power", "economy", "lite", "free"];
16
- /** The Aurora row whose endpoints are the shell's own chain (endpoints.aurora + its failover legs). Since 0.1.361 it is
17
- * no longer the model a fresh install starts on — that is DEFAULT_ACTIVE_MODEL. */
18
- export const DEFAULT_MODEL_ID = "operator-1m";
16
+ export function isRetired(p) {
17
+ return p?.status === "retired";
18
+ }
19
+ /** The row that owns the shell's endpoint chain (buildEndpointChain: the router's `main`, then the fleet and cloud legs):
20
+ * a session with no /model pick runs on it, and `/model main` restores the chain. Was the Aurora row `operator-1m` until
21
+ * Aurora was retired (11/25). Not the model a fresh install starts on — that is DEFAULT_ACTIVE_MODEL. */
22
+ export const CHAIN_MODEL_ID = "main";
19
23
  /** The model a session starts on when settings.activeModel is not set (a fresh install): the router's
20
24
  * `operator-flash` route. A persisted activeModel always wins. */
21
25
  export const DEFAULT_ACTIVE_MODEL = "operator-flash";
22
26
  /** Rows retired from the picker (11/25): never in /model or the ACP dropdown, still resolvable by id so a persisted
23
27
  * activeModel, a script or a delegate target keeps working. A settings.models row with one of these ids is hidden too
24
- * unless it says `hidden: false`. */
28
+ * unless it says `hidden: false`. Hidden is not the lifecycle: a row whose `status` is "retired" (operator-1m) resolves
29
+ * to the fallback model; the others here still answer as themselves. */
25
30
  export const RETIRED_MODEL_IDS = new Set([
26
- "operator-1m", "aurora", "cortana", "thor", "scout", "casanova", "falcon-h1-34b", "qwen-coder", "belmont-30b", "venice-24b", "dolphin-7b",
31
+ "operator-1m", "aurora", "cortana", "thor", "scout", "casanova", "falcon-h1-34b", "belmont-30b", "venice-24b", "dolphin-7b",
27
32
  ]);
28
33
  // Back-compat aliases: the user-facing ids were renamed aurora-* -> operator-* (the outward name is
29
34
  // Operator; "aurora" is the internal model, never shown). The OLD ids still resolve — a persisted
@@ -49,12 +54,9 @@ export const LEGACY_GATEWAY_BASE = `https://${LEGACY_API_HOST}/v1`;
49
54
  const ANTHROPIC_BASE = "https://api.anthropic.com/v1";
50
55
  const GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai"; // Google's OpenAI-compatible surface — no native transport
51
56
  const GEMINI_CHAT_PATH = "/chat/completions"; // the base already carries its version: …/v1beta/openai/chat/completions
52
- const QWEN_BASE = "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1";
53
57
  /** Output ceilings (ModelProfile.maxOutput) — only where the vendor's limit is cited. Anthropic: the current Claude
54
- * family's max_tokens ceiling (a larger value is a 400). QwenCloud qwen3.8-flash: the vendor's own 400,
55
- * 2026-10-28 — "Range of max_tokens should be [1, 131072]". */
58
+ * family's max_tokens ceiling (a larger value is a 400). */
56
59
  export const ANTHROPIC_MAX_OUTPUT = 128_000;
57
- const QWEN_FLASH_MAX_OUTPUT = 131_072;
58
60
  const NOUS_BASE = "https://inference-api.nousresearch.com/v1";
59
61
  // Registry order IS picker order (visibleModels keeps it): the main three, the local row, then the gateway rows, then the
60
62
  // connected-provider rows (hidden until their key is connected), then the by-id-only lanes, then MOA. Free
@@ -66,13 +68,11 @@ export const BUILTIN_MODELS = [
66
68
  // Router routes of the same name, gateway-first like every gateway row. `ctx` is the window the route serves.
67
69
  { id: "operator-flash", tier: "power", label: "Operator-Flash", params: "125B-A6B", box: "gateway", kind: "single", desc: "the default model: a fast MoE with n-gram speculation", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-flash", "operator-flash"], model: "operator-flash", ctx: 131072 },
68
70
  { id: "kimi-linear-48b", tier: "power", label: "Kimi-Linear", params: "48B-A3B", box: "gateway", kind: "single", desc: "long-context MoE", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["kimi-linear-48b", "kimi-linear-48b"], model: "kimi-linear-48b", ctx: 262144 },
69
- { id: "qwen3.8-27b", tier: "power", label: "Qwen3.8", params: "27B", box: "gateway", kind: "single", desc: "dense model with n-gram and MTP speculation; loads on demand", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["qwen3.8-27b", "qwen3.8-27b"], model: "qwen3.8-27b", ctx: 131072 },
71
+ { id: "operator-dense", tier: "power", label: "Operator-Dense", params: "27B", box: "gateway", kind: "single", desc: "dense model with n-gram and MTP speculation; loads on demand", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-dense", "operator-dense"], model: "operator-dense", ctx: 131072 },
70
72
  // ── local ───────────────────────────────────────────────────────────────────────────────────────────────
71
- // THE one Aurora row (0.1.332), retired from the picker 11/25 (RETIRED_MODEL_IDS). The 300K/600K/1M choice is a
72
- // context PIN (settings.contextPin, /context, Ctrl+X) applied over the served window — not three profiles of one
73
- // model. The static :8097 is the gateway-less fallback; on a gateway box Session.setModel restores the shell's chain
74
- // for this id (the dynamic port + the fleet and cloud legs buildEndpointChain assembles).
75
- { id: "operator-1m", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "local", kind: "single", desc: "served on this machine; the gateway takes over when it is down", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1000000, hidden: true },
73
+ // THE one Aurora row (0.1.332), retired 11/25 (`status: "retired"`): kept so the id resolves, and every pick of it
74
+ // resolves to the fallback model (selectModel). Nothing in the client starts its gateway.
75
+ { id: "operator-1m", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "local", kind: "single", desc: "served on this machine; the gateway takes over when it is down", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1000000, hidden: true, status: "retired" },
76
76
  // ── gateway ─────────────────────────────────────────────────────────────────────────────────────────────
77
77
  // GATEWAY-FIRST: the local gateway when this machine runs one, then the public face. `ctx` is the window the
78
78
  // gateway serves. The 0.1.260 lesson stands: a profile that claims MORE than the server's --ctx-size makes the
@@ -84,7 +84,7 @@ export const BUILTIN_MODELS = [
84
84
  { id: "scout", tier: "lite", label: "Scout", params: "4B", box: "gateway", kind: "single", desc: "fast small model", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["scout", "scout"], model: "scout", ctx: 32000, hidden: true },
85
85
  // ── connected providers (BYO: hidden until the vendor key is connected — /model "+ Connect a provider key") ──
86
86
  // Claude — BYO Anthropic connectors, so "delegate to Claude" and `/model claude-sonnet` work. Unlike the
87
- // qwen/OpenAI connectors (OpenAI dialect), Claude speaks the NATIVE Anthropic Messages wire — transport
87
+ // OpenAI-dialect connectors, Claude speaks the NATIVE Anthropic Messages wire — transport
88
88
  // "anthropic" routes it through engine/anthropic-chat.ts (x-api-key auth from the BYO "anthropic" key; the
89
89
  // Operator token is NEVER sent here — authHeaders scoping + anthropic-chat's own key resolution). Model ids
90
90
  // are the vendor's complete 5.5-family ids (never a date suffix); ctx is the documented 1M, self-clamps to served truth.
@@ -95,12 +95,6 @@ export const BUILTIN_MODELS = [
95
95
  // strict openai dialect is what that surface accepts). Same "gemini" key account as the byo-model preset.
96
96
  { id: "gemini-pro", tier: "power_turbo", label: "Gemini 2.5 Pro", box: "Google", kind: "single", desc: "BYO Google — Gemini 2.5 Pro over the OpenAI-compatible base, your Gemini key", endpoint: GEMINI_BASE, model: "gemini-2.5-pro", ctx: 1000000, byo: "gemini", transport: "openai", chatPath: GEMINI_CHAT_PATH },
97
97
  { id: "gemini-flash", tier: "economy", label: "Gemini 2.5 Flash", box: "Google", kind: "single", desc: "BYO Google — the fast Gemini tier, your Gemini key", endpoint: GEMINI_BASE, model: "gemini-2.5-flash", ctx: 1000000, byo: "gemini", transport: "openai", chatPath: GEMINI_CHAT_PATH },
98
- // QwenCloud Token Plan BYO connectors (SPEC/providers.md §2 "API-key connectors"). Same keychain
99
- // account ("qwen") serves both; the picker hides them until connected (§1 honest availability), and
100
- // authHeaders NEVER sends the Operator token to this host. ctx starts conservative and self-clamps
101
- // to the served truth (observeContext).
102
- { id: "qwen3.8-max", tier: "power_turbo", label: "Qwen 3.8 Max", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: QWEN_BASE, model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
103
- { id: "qwen3.8-flash", tier: "economy", label: "Qwen 3.8 Flash", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: QWEN_BASE, model: "qwen3.8-flash", ctx: 262144, maxOutput: QWEN_FLASH_MAX_OUTPUT, byo: "qwen", transport: "openai" },
104
98
  // ── by-id lanes (hidden from the picker, still resolve) ────────────────────────────────────────────────
105
99
  // The cloud slot of the SAME Aurora, folded out of the picker in 0.1.332 (one Aurora row; the cloud legs ride
106
100
  // in buildEndpointChain's failover chain). Reachable by id for scripts. api.0perator.co is AXE's OWN gateway
@@ -115,6 +109,7 @@ export const BUILTIN_MODELS = [
115
109
  // chain instead of queueing. Swapping or promoting a model moves a pointer on the server and no client changes. Hidden: never
116
110
  // a picker row and never offered by tier (profilesByTier skips hidden rows), reached by id (delegate_task, spawn_agent). `ctx`
117
111
  // is the smallest window any model in the chain serves, so compaction is safe wherever the request lands.
112
+ { id: "main", tier: "power", label: "Main", box: "gateway", kind: "single", desc: "capability: the router's main route — owns the shell's endpoint chain and answers a failed turn", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["main", "main"], model: "main", ctx: 262144, hidden: true },
118
113
  { id: "subagent", tier: "power", label: "Sub-agent", box: "fleet", kind: "single", desc: "capability: the default sub-agent — the gateway picks the best healthy model", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["subagent", "subagent"], model: "subagent", ctx: 262144, hidden: true },
119
114
  // ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
120
115
  { id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — a planner hands steps to specialists, checks their work and writes the answer (settings.moa overrides)" },
@@ -130,7 +125,6 @@ export const BYO_PRESETS = {
130
125
  openrouter: { label: "OpenRouter", box: "OpenRouter", endpoint: "https://openrouter.ai/api/v1", model: "openai/gpt-5", ctx: 200000, account: "openrouter", envAlias: "OPENROUTER_API_KEY" },
131
126
  together: { label: "Together", box: "Together", endpoint: "https://api.together.xyz/v1", model: "meta-llama/Llama-3.3-70B-Instruct-Turbo", ctx: 131072, account: "together", envAlias: "TOGETHER_API_KEY" },
132
127
  xai: { label: "xAI Grok", box: "xAI", endpoint: "https://api.x.ai/v1", model: "grok-4", ctx: 256000, account: "xai", envAlias: "XAI_API_KEY" },
133
- qwen: { label: "QwenCloud", box: "QwenCloud", endpoint: QWEN_BASE, model: "qwen3.8-max", ctx: 262144, account: "qwen" },
134
128
  // Nous Portal — the free cloud tier (router/free-models.ts lists its `:free` rows once this key is connected;
135
129
  // the vendor requires an account even for free models). 50 RPM / 500k TPM; prompts may be used for training.
136
130
  // 0perator's own free catalog (portal router behind AuthGate): the free models we serve with OUR provider accounts,
@@ -163,12 +157,11 @@ export function findModel(registry, id) {
163
157
  export const DEFAULT_FALLBACK_MODEL = "main";
164
158
  /** The model that answers a turn whose own legs all failed (Session.turnModel). A registry row with that id answers as
165
159
  * itself; any other id is a router capability, reached through the gateway (loopback first, then the public face).
166
- * Never the launchd-owned default row: a fallback must not wake a model the owner parked, so that id resolves to the
167
- * default capability instead. */
160
+ * Never a retired row: that id resolves to the default capability instead. */
168
161
  export function fallbackProfile(registry, id) {
169
162
  const want = id?.trim() || DEFAULT_FALLBACK_MODEL;
170
163
  const canon = MODEL_ALIASES[want] ?? want;
171
- const name = canon === DEFAULT_MODEL_ID ? DEFAULT_FALLBACK_MODEL : canon;
164
+ const name = isRetired(findModel(registry, canon)) ? DEFAULT_FALLBACK_MODEL : canon;
172
165
  const row = findModel(registry, name);
173
166
  if (row?.kind === "single")
174
167
  return row;
@@ -223,9 +216,14 @@ export function laneTier(lane) {
223
216
  export function modelCtxFor(id, overrides) {
224
217
  if (!id)
225
218
  return Number.POSITIVE_INFINITY;
226
- return findModel(modelRegistry(overrides), id)?.ctx ?? Number.POSITIVE_INFINITY;
219
+ return resolveModel(modelRegistry(overrides), id)?.ctx ?? Number.POSITIVE_INFINITY;
220
+ }
221
+ /** The row a session on `id` actually runs: a retired row's successor, else the row itself. */
222
+ export function resolveModel(registry, id) {
223
+ const p = findModel(registry, id);
224
+ return isRetired(p) ? fallbackProfile(registry, undefined) : p;
227
225
  }
228
- /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora/Qwen (128K+) stay
226
+ /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora and the gateway models (128K+) stay
229
227
  * full; a self-hosted small model (8K, or a 16K bump) goes lean. */
230
228
  export const LEAN_HARNESS_CTX = 32768;
231
229
  /** The default served-window floor for the model a session runs its full harness on (settings.contextFloor): below it
@@ -241,7 +239,7 @@ export const MIN_CONTEXT_PIN = 32_000;
241
239
  export function leanHarnessFor(id, overrides) {
242
240
  if (modelCtxFor(id, overrides) < LEAN_HARNESS_CTX)
243
241
  return true;
244
- return !!findModel(modelRegistry(overrides), id ?? "")?.leanPersona;
242
+ return !!resolveModel(modelRegistry(overrides), id ?? "")?.leanPersona;
245
243
  }
246
244
  /** Pure selection reducer for /model — no I/O (no settings read/write, no router mutation), so it's
247
245
  * directly testable. The moa-needs-config check lives in Session.setModel (it needs settings.moa,
@@ -251,6 +249,8 @@ export function selectModel(registry, id, hasByo, isOwner = true) {
251
249
  const profile = findModel(registry, id);
252
250
  if (!profile)
253
251
  return { error: `unknown model "${id}" — choices: ${registry.map((m) => m.id).join(", ")}` };
252
+ if (isRetired(profile))
253
+ return { profile: fallbackProfile(registry, undefined), retired: profile };
254
254
  if (profile.kind === "single" && !profile.endpoint && !profile.endpoints?.length)
255
255
  return { error: `model "${id}" has no endpoint configured` };
256
256
  if (profile.ownerOnly && !isOwner)
@@ -5,14 +5,14 @@
5
5
  // (same mobile/JSCore-bundle discipline as services/preflight.ts) so the neutral bundle carries none of it.
6
6
  import { operatorPath, globalMemoriesPath } from "../config/home.js";
7
7
  import { redactSecrets } from "../engine/redact.js";
8
- import { isEngineFinal } from "../engine/continuation.js"; // a stop/pause/no-reply note is the engine's text, never a promotable answer
8
+ import { engineEnded } from "../engine/continuation.js"; // an engine stop is the engine's text, never a promotable answer
9
9
  import { isLooped } from "../engine/loop-guard.js";
10
10
  import { fixLessonLine, isSubagentBrief, loopLessonLine, ownerWords, reinforcedRules, stuckLessonLine, upsertLesson } from "./lessons.js";
11
11
  import { inferType } from "../engine/grandmaster.js";
12
12
  import { methodFromSteps, mergeSkill, skillClassSlug } from "./skills.js";
13
13
  const nodeImport = (m) => import(/* @vite-ignore */ m);
14
14
  // GW-18 (flywheel gate): markers of a STRUCTURED tool call that leaked into the assistant's plain text instead
15
- // of being parsed into tool_calls — the documented Qwen3 failure when the server runs without `--jinja` (the
15
+ // of being parsed into tool_calls — a documented failure of XML tool-call models when the server runs without `--jinja` (the
16
16
  // heuristic parser passes the XML through as content with finish_reason:"stop"). A turn like this is the worst
17
17
  // possible training row: it's recorded as a "completed" turn, but the assistant text IS raw tool markup, so
18
18
  // training on it teaches the model to EMIT the markup as prose — the agent self-poisons on its own parser bug.
@@ -33,7 +33,7 @@ export function hasLeakedToolCall(content) {
33
33
  * engine-final note, not looped, not interrupted. The one source of this predicate: flywheelRow tags rows with it and
34
34
  * the skill distiller (captureSkill) gates on it (the second save-time verify gate). */
35
35
  export function isGraded(r) {
36
- return !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !hasLeakedToolCall(r.content) && !isEngineFinal(r.content) && !isLooped(r.loop) && !r.interrupted;
36
+ return !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !hasLeakedToolCall(r.content) && !engineEnded(r) && !isLooped(r.loop) && !r.interrupted;
37
37
  }
38
38
  /** One turn's flywheel row: the day file it goes in (under the operator home's flywheel/) and the JSONL line. Pure. */
39
39
  export function flywheelRow(r, ts) {
@@ -65,11 +65,13 @@ async function captureFlywheel(r, ts) {
65
65
  }
66
66
  catch { /* best-effort — capture never blocks or fails a turn */ }
67
67
  }
68
- /** True when a turn ended STUCK — a loop/guard stop, not a normal completion. The forced-redirect and
69
- * self-loop guards both hand back a "[stopped — …]" note; a repetition stopReason is the other signal.
70
- * A normal answer, or an empty (aborted) turn, is NOT a lesson. */
68
+ /** The engine stops that mean the turn got STUCK: the loop, circling, repetition and window guards and the owner's
69
+ * ignored "answer now". A pause, the round cap, a sub-agent yield or nothing answering is not a lesson. */
70
+ const STUCK_STOPS = new Set(["stopped", "repetition", "reasoning_budget", "window", "owner"]);
71
+ /** True when a turn ended STUCK — a guard stop (its typed stopKind) or a reply cut for repetition, not a normal
72
+ * completion. A normal answer, or an empty (aborted) turn, is NOT a lesson. */
71
73
  function endedStuck(r) {
72
- return r.stopReason === "repetition" || /^\[stopped\s[—-]/.test(r.content.trim());
74
+ return r.stopReason === "repetition" || (r.stopKind !== undefined && STUCK_STOPS.has(r.stopKind));
73
75
  }
74
76
  /** MEMORY sink (the closed self-improvement loop). A LOOPED turn — it ignored its loop warnings (engine/loop-guard.ts
75
77
  * isLooped) — or one that ended STUCK on an engine stop becomes a lesson in the GLOBAL memories.md, which every session