@0perator/operator 0.2.0 → 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 (75) hide show
  1. package/README.md +4 -3
  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 +2 -2
  6. package/dist/autonomy/delegate.js +41 -14
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +11 -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 +311 -44
  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/synthesis.js +25 -0
  18. package/dist/bus/inbox.js +150 -6
  19. package/dist/cli.js +191 -96
  20. package/dist/config/features.js +3 -3
  21. package/dist/config/persona.js +29 -3
  22. package/dist/config/settings.js +261 -20
  23. package/dist/config/staff-prompt.js +12 -0
  24. package/dist/engine/agent.js +51 -40
  25. package/dist/engine/aurora.js +36 -4
  26. package/dist/engine/batch-scheduler.js +4 -13
  27. package/dist/engine/compaction.js +1 -1
  28. package/dist/engine/continuation.js +30 -32
  29. package/dist/engine/decision-points.js +2 -3
  30. package/dist/engine/fanout.js +16 -0
  31. package/dist/engine/loop-guard.js +26 -83
  32. package/dist/engine/messages.js +2 -2
  33. package/dist/engine/moa.js +16 -1
  34. package/dist/engine/native-vision-node.js +72 -0
  35. package/dist/engine/native-vision.js +103 -0
  36. package/dist/engine/verify-gate.js +37 -7
  37. package/dist/gateway-cli.js +14 -3
  38. package/dist/memory/live-progress.js +4 -5
  39. package/dist/moa/codeact-lane.js +98 -0
  40. package/dist/moa/codeact-sandbox.js +409 -0
  41. package/dist/moa/codeact.js +140 -0
  42. package/dist/permissions/artifact-visibility.js +10 -0
  43. package/dist/permissions/tier.js +4 -2
  44. package/dist/products/craft.js +2 -2
  45. package/dist/remote/grants.js +119 -0
  46. package/dist/remote/host.js +33 -5
  47. package/dist/router/models.js +24 -14
  48. package/dist/selfimprove/index.js +8 -6
  49. package/dist/services/preflight.js +35 -91
  50. package/dist/session.js +127 -41
  51. package/dist/skills/install-guard.js +68 -0
  52. package/dist/skills/install.js +67 -0
  53. package/dist/toolchain/manifest.json +13 -13
  54. package/dist/tools/background-result.js +1 -1
  55. package/dist/tools/classes.js +103 -0
  56. package/dist/tools/contract.js +1 -1
  57. package/dist/tools/craft.js +13 -2
  58. package/dist/tools/executor.js +25 -15
  59. package/dist/tools/generation-gateway.js +94 -0
  60. package/dist/tools/registry.js +83 -152
  61. package/dist/ui/App.js +15 -4
  62. package/dist/ui/BgPanel.js +15 -10
  63. package/dist/ui/Header.js +1 -6
  64. package/dist/ui/StatusRule.js +18 -7
  65. package/dist/ui/ToolStep.js +3 -3
  66. package/dist/ui/Transcript.js +36 -14
  67. package/dist/ui/batchLine.js +4 -4
  68. package/dist/ui/editdiff.js +2 -4
  69. package/dist/ui/format.js +4 -20
  70. package/dist/ui/liveTools.js +3 -3
  71. package/dist/ui/opsMode.js +20 -0
  72. package/dist/ui/types.js +0 -2
  73. package/dist/update-check.js +17 -6
  74. package/package.json +1 -1
  75. package/dist/tools/mutating.js +0 -15
@@ -0,0 +1,140 @@
1
+ // The MoA CodeAct lane (2026-11-27, James): for a step that is bulk, read-only and deterministic, the executor writes ONE
2
+ // short program that does the whole step inside a sandbox (moa/codeact-sandbox.ts) instead of N tool-call round trips.
3
+ // This module is the pure half: settings, the eligibility check the planner's step goes through, and the result shape
4
+ // that goes back to the planner and into the trace. Whether a step may take the lane is decided here, in code, never by
5
+ // the prompt. Anything that changes the world (an edit, a commit, a push, the network, a message) stays a normal gated
6
+ // tool call. Why: _ai-docs/decisions/2026-11-27-moa-codeact-lane.md (repo root).
7
+ export const CODEACT_DEFAULTS = {
8
+ enabled: true,
9
+ minItems: 20,
10
+ minRoundTrips: 6,
11
+ deniedAuthors: ["scout", "ghost-4b"],
12
+ language: "auto",
13
+ timeoutMs: 60_000,
14
+ cpuSeconds: 60,
15
+ memoryMb: 1024,
16
+ maxOutputBytes: 256 * 1024,
17
+ maxScratchFileMb: 64,
18
+ maxProgramBytes: 32 * 1024,
19
+ };
20
+ /** The one switch: unset means on, a boolean is taken as given, anything else is off. */
21
+ export function codeActEnabled(s) {
22
+ if (s?.enabled === undefined)
23
+ return CODEACT_DEFAULTS.enabled;
24
+ return s.enabled === true;
25
+ }
26
+ /** Settings over the defaults. Bad numbers fall back to the default instead of loosening a limit. */
27
+ export function codeActConfig(s) {
28
+ const d = CODEACT_DEFAULTS;
29
+ const pos = (v, dv) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : dv);
30
+ const lang = s?.language;
31
+ return {
32
+ enabled: codeActEnabled(s),
33
+ minItems: pos(s?.minItems, d.minItems),
34
+ minRoundTrips: pos(s?.minRoundTrips, d.minRoundTrips),
35
+ deniedAuthors: Array.isArray(s?.deniedAuthors) ? s.deniedAuthors.filter((x) => typeof x === "string") : d.deniedAuthors,
36
+ language: lang === "python" || lang === "node" || lang === "auto" ? lang : d.language,
37
+ timeoutMs: pos(s?.timeoutMs, d.timeoutMs),
38
+ cpuSeconds: pos(s?.cpuSeconds, d.cpuSeconds),
39
+ memoryMb: pos(s?.memoryMb, d.memoryMb),
40
+ maxOutputBytes: pos(s?.maxOutputBytes, d.maxOutputBytes),
41
+ maxScratchFileMb: pos(s?.maxScratchFileMb, d.maxScratchFileMb),
42
+ maxProgramBytes: pos(s?.maxProgramBytes, d.maxProgramBytes),
43
+ };
44
+ }
45
+ function resolvePath(p, cwd) {
46
+ const abs = p.startsWith("/") ? p : `${cwd.replace(/\/+$/, "")}/${p}`;
47
+ const out = [];
48
+ for (const seg of abs.split("/")) {
49
+ if (seg === "" || seg === ".")
50
+ continue;
51
+ if (seg === "..")
52
+ out.pop();
53
+ else
54
+ out.push(seg);
55
+ }
56
+ return `/${out.join("/")}`;
57
+ }
58
+ const under = (p, root) => p === root || p.startsWith(root.endsWith("/") ? root : `${root}/`);
59
+ /** Paths a program may never read, relative to the home directory. Masked by the sandbox too (codeact-sandbox.ts). */
60
+ export const SECRET_HOME_PATHS = [
61
+ ".ssh", ".aws", ".gnupg", ".config/gcloud", ".axe/secrets", ".kube", ".docker", ".config/switchboard",
62
+ "Library/Keychains", ".netrc", ".git-credentials", ".npmrc", ".pypirc", ".cloudflared",
63
+ ];
64
+ /** The secret paths for this home and Operator home, absolute. */
65
+ export function secretPaths(home, operatorHome) {
66
+ const h = home.replace(/\/+$/, "");
67
+ const op = operatorHome?.replace(/\/+$/, "");
68
+ return [
69
+ ...SECRET_HOME_PATHS.map((p) => `${h}/${p}`),
70
+ "/Library/Keychains",
71
+ ...(op ? [`${op}/credentials.json`, `${op}/byo.json`, `${op}/vault`, `${op}/identity.json`] : []),
72
+ ];
73
+ }
74
+ const REASON_TEXT = {
75
+ disabled: "the lane is off (moa.codeact.enabled)",
76
+ not_read_only: "the step changes something",
77
+ not_deterministic: "the step is not deterministic",
78
+ needs_network: "the step needs the network",
79
+ needs_secrets: "the step needs secrets",
80
+ not_bulk: "the step is small",
81
+ author_not_eligible: "the author model may not write programs",
82
+ no_targets: "the step names no paths to read",
83
+ target_secret: "a target is a secret path",
84
+ target_too_broad: "a target is the home folder, the root or above them",
85
+ };
86
+ /** The deterministic check: a step takes the lane only when the lane is on, the step is read-only, deterministic, needs
87
+ * neither network nor secrets, is bulk (≥ minItems items or ≥ minRoundTrips round trips), its author is allowed, and
88
+ * every target is a readable, bounded path. Otherwise the step runs on structured tools. */
89
+ export function codeActEligibility(step, settings, env) {
90
+ const cfg = codeActConfig(settings);
91
+ const reasons = [];
92
+ const home = resolvePath(env.home, "/");
93
+ const targets = (Array.isArray(step.targets) ? step.targets : []).filter((t) => typeof t === "string" && t.trim()).map((t) => resolvePath(t.trim().replace(/^~(?=\/|$)/, home), env.cwd));
94
+ if (!cfg.enabled)
95
+ reasons.push("disabled");
96
+ if (step.readOnly !== true)
97
+ reasons.push("not_read_only");
98
+ if (step.deterministic !== true)
99
+ reasons.push("not_deterministic");
100
+ if (step.needsNetwork === true)
101
+ reasons.push("needs_network");
102
+ if (step.needsSecrets === true)
103
+ reasons.push("needs_secrets");
104
+ const items = typeof step.items === "number" && Number.isFinite(step.items) ? step.items : 0;
105
+ const trips = typeof step.estRoundTrips === "number" && Number.isFinite(step.estRoundTrips) ? step.estRoundTrips : 0;
106
+ if (items < cfg.minItems && trips < cfg.minRoundTrips)
107
+ reasons.push("not_bulk");
108
+ const author = String(step.author ?? "").trim().toLowerCase();
109
+ if (!author || cfg.deniedAuthors.some((a) => a.trim().toLowerCase() === author))
110
+ reasons.push("author_not_eligible");
111
+ if (!targets.length)
112
+ reasons.push("no_targets");
113
+ const secrets = secretPaths(home, env.operatorHome && resolvePath(env.operatorHome, "/"));
114
+ if (targets.some((t) => secrets.some((s) => under(t, s))))
115
+ reasons.push("target_secret");
116
+ if (targets.some((t) => t === "/" || under(home, t)))
117
+ reasons.push("target_too_broad");
118
+ const eligible = reasons.length === 0;
119
+ const detail = eligible
120
+ ? `codeact lane: eligible (${items ? `${items} items` : `~${trips} round trips`}, read-only, ${targets.length} target${targets.length === 1 ? "" : "s"})`
121
+ : `structured tools: ${reasons.map((r) => REASON_TEXT[r]).join("; ")}`;
122
+ return { eligible, reasons, detail, targets };
123
+ }
124
+ /** "auto" language: node for a JS/TS project without a Python project file, else python. `exists` is injected so this
125
+ * stays free of node:fs. */
126
+ export function pickLanguage(pref, targets, exists) {
127
+ if (pref === "python" || pref === "node")
128
+ return pref;
129
+ const has = (f) => targets.some((t) => exists(`${t}/${f}`));
130
+ const py = has("pyproject.toml") || has("setup.py") || has("requirements.txt");
131
+ return has("package.json") && !py ? "node" : "python";
132
+ }
133
+ /** The planner-facing text of a result: the summary line, then the data as JSON, capped. */
134
+ export function codeActReport(r, maxChars = 12_000) {
135
+ const head = `[codeact ${r.status}] ${r.summary}`;
136
+ if (!r.ok)
137
+ return `${head}${r.reason ? `\nreason: ${r.reason}` : ""}${r.stats.stderrTail ? `\nstderr: ${r.stats.stderrTail}` : ""}\nThe step was not done; do it with structured tools.`;
138
+ const body = JSON.stringify(r.data, null, 1) ?? "null";
139
+ return `${head}\n${body.length > maxChars ? `${body.slice(0, maxChars)}\n… (${body.length - maxChars} more chars in ${r.runDir ?? "the run dir"}/result.json)` : body}`;
140
+ }
@@ -0,0 +1,10 @@
1
+ /** The visibility to send, or an error to return to the model. `onCreate` fills the seat's default; an update
2
+ * with no visibility leaves the artifact's own unchanged. */
3
+ export function artifactVisibility(tier, requested, onCreate) {
4
+ const v = typeof requested === "string" && /^(private|link|public)$/.test(requested) ? requested : undefined;
5
+ if (tier !== "enterprise")
6
+ return { visibility: v ?? (onCreate ? "link" : undefined) };
7
+ if (v === "public")
8
+ return { error: "public artifacts are off for enterprise seats: use link (anyone with the link) or private" };
9
+ return { visibility: v ?? (onCreate ? "private" : undefined) };
10
+ }
@@ -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
@@ -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", "agents"]);
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.
@@ -149,7 +150,7 @@ export class RemoteHost {
149
150
  ws.addEventListener("open", () => {
150
151
  // §1: advertise the engine contract + features so the relay/followers can version-gate. sessionId (when
151
152
  // set) makes this a RESUME. Additive — an old relay ignores proto/features.
152
- 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 });
153
154
  });
154
155
  ws.addEventListener("message", (ev) => this.onMessage(String(ev.data)));
155
156
  ws.addEventListener("close", () => {
@@ -284,6 +285,8 @@ export class RemoteHost {
284
285
  break;
285
286
  case "attach": // a follower joined — send a full snapshot BEFORE any further delta (§8)
286
287
  this.sendSnapshot();
288
+ if (grantsEnabled())
289
+ this.state("grants", { items: this.grantItems });
287
290
  break;
288
291
  // Drive frames (follower -> host actions). Defense-in-depth: the relay is SUPPOSED to only
289
292
  // ever forward a frame that belongs to this connection's session, but a relay bug or a
@@ -295,8 +298,24 @@ export class RemoteHost {
295
298
  this.cb.onPrompt(f.payload.text);
296
299
  break;
297
300
  case "approval_response":
298
- if (this.isOwnFrame(f) && f.payload?.id)
299
- 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
+ }
300
319
  break;
301
320
  case "ask_user_response":
302
321
  if (this.isOwnFrame(f) && f.payload?.id)
@@ -511,4 +530,13 @@ export class RemoteHost {
511
530
  * follower's ask_user_response race first-wins in the host (settleQuestion in cli.tsx); local
512
531
  * ask_user keeps working unchanged when no remote-control session is active. */
513
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
+ }
514
542
  }
@@ -13,15 +13,20 @@
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
31
  "operator-1m", "aurora", "cortana", "thor", "scout", "casanova", "falcon-h1-34b", "belmont-30b", "venice-24b", "dolphin-7b",
27
32
  ]);
@@ -65,11 +70,9 @@ export const BUILTIN_MODELS = [
65
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 },
66
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 },
67
72
  // ── local ───────────────────────────────────────────────────────────────────────────────────────────────
68
- // THE one Aurora row (0.1.332), retired from the picker 11/25 (RETIRED_MODEL_IDS). The 300K/600K/1M choice is a
69
- // context PIN (settings.contextPin, /context, Ctrl+X) applied over the served window — not three profiles of one
70
- // model. The static :8097 is the gateway-less fallback; on a gateway box Session.setModel restores the shell's chain
71
- // for this id (the dynamic port + the fleet and cloud legs buildEndpointChain assembles).
72
- { 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" },
73
76
  // ── gateway ─────────────────────────────────────────────────────────────────────────────────────────────
74
77
  // GATEWAY-FIRST: the local gateway when this machine runs one, then the public face. `ctx` is the window the
75
78
  // gateway serves. The 0.1.260 lesson stands: a profile that claims MORE than the server's --ctx-size makes the
@@ -106,6 +109,7 @@ export const BUILTIN_MODELS = [
106
109
  // chain instead of queueing. Swapping or promoting a model moves a pointer on the server and no client changes. Hidden: never
107
110
  // a picker row and never offered by tier (profilesByTier skips hidden rows), reached by id (delegate_task, spawn_agent). `ctx`
108
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 },
109
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 },
110
114
  // ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
111
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)" },
@@ -153,12 +157,11 @@ export function findModel(registry, id) {
153
157
  export const DEFAULT_FALLBACK_MODEL = "main";
154
158
  /** The model that answers a turn whose own legs all failed (Session.turnModel). A registry row with that id answers as
155
159
  * itself; any other id is a router capability, reached through the gateway (loopback first, then the public face).
156
- * Never the launchd-owned default row: a fallback must not wake a model the owner parked, so that id resolves to the
157
- * default capability instead. */
160
+ * Never a retired row: that id resolves to the default capability instead. */
158
161
  export function fallbackProfile(registry, id) {
159
162
  const want = id?.trim() || DEFAULT_FALLBACK_MODEL;
160
163
  const canon = MODEL_ALIASES[want] ?? want;
161
- const name = canon === DEFAULT_MODEL_ID ? DEFAULT_FALLBACK_MODEL : canon;
164
+ const name = isRetired(findModel(registry, canon)) ? DEFAULT_FALLBACK_MODEL : canon;
162
165
  const row = findModel(registry, name);
163
166
  if (row?.kind === "single")
164
167
  return row;
@@ -213,7 +216,12 @@ export function laneTier(lane) {
213
216
  export function modelCtxFor(id, overrides) {
214
217
  if (!id)
215
218
  return Number.POSITIVE_INFINITY;
216
- 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;
217
225
  }
218
226
  /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora and the gateway models (128K+) stay
219
227
  * full; a self-hosted small model (8K, or a 16K bump) goes lean. */
@@ -231,7 +239,7 @@ export const MIN_CONTEXT_PIN = 32_000;
231
239
  export function leanHarnessFor(id, overrides) {
232
240
  if (modelCtxFor(id, overrides) < LEAN_HARNESS_CTX)
233
241
  return true;
234
- return !!findModel(modelRegistry(overrides), id ?? "")?.leanPersona;
242
+ return !!resolveModel(modelRegistry(overrides), id ?? "")?.leanPersona;
235
243
  }
236
244
  /** Pure selection reducer for /model — no I/O (no settings read/write, no router mutation), so it's
237
245
  * directly testable. The moa-needs-config check lives in Session.setModel (it needs settings.moa,
@@ -241,6 +249,8 @@ export function selectModel(registry, id, hasByo, isOwner = true) {
241
249
  const profile = findModel(registry, id);
242
250
  if (!profile)
243
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 };
244
254
  if (profile.kind === "single" && !profile.endpoint && !profile.endpoints?.length)
245
255
  return { error: `model "${id}" has no endpoint configured` };
246
256
  if (profile.ownerOnly && !isOwner)
@@ -5,7 +5,7 @@
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";
@@ -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