@0perator/operator 0.2.0 → 0.2.2-next.0

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 (117) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +15 -5
  4. package/dist/auth/identity.js +1 -0
  5. package/dist/auth/staff.js +55 -0
  6. package/dist/autonomy/agent-cli.js +1 -1
  7. package/dist/autonomy/delegate-mode.js +2 -2
  8. package/dist/autonomy/delegate.js +41 -14
  9. package/dist/autonomy/headless.js +37 -10
  10. package/dist/autonomy/index.js +2 -4
  11. package/dist/autonomy/pr-isolation.js +92 -0
  12. package/dist/autonomy/pr-preflight.js +474 -0
  13. package/dist/autonomy/session-factory.js +13 -12
  14. package/dist/autonomy/subagent-model.js +17 -7
  15. package/dist/background/capacity.js +136 -0
  16. package/dist/background/evidence.js +42 -0
  17. package/dist/background/index.js +311 -44
  18. package/dist/background/lane-phase.js +60 -0
  19. package/dist/background/lane-summary.js +151 -0
  20. package/dist/background/notices.js +12 -3
  21. package/dist/background/synthesis.js +25 -0
  22. package/dist/browser/capture.js +505 -0
  23. package/dist/browser/engine.js +4 -3
  24. package/dist/browser/page-capture.js +167 -0
  25. package/dist/browser/png.js +116 -0
  26. package/dist/browser/visual-compare.js +229 -0
  27. package/dist/bus/beam-drop.js +55 -0
  28. package/dist/bus/inbox.js +157 -7
  29. package/dist/cli.js +316 -120
  30. package/dist/config/features.js +3 -3
  31. package/dist/config/managed.js +40 -1
  32. package/dist/config/persona.js +80 -29
  33. package/dist/config/product-hosts.js +2 -0
  34. package/dist/config/settings.js +289 -31
  35. package/dist/config/skills-index.js +37 -14
  36. package/dist/config/staff-prompt.js +12 -0
  37. package/dist/engine/agent.js +52 -41
  38. package/dist/engine/aurora.js +54 -13
  39. package/dist/engine/batch-scheduler.js +4 -13
  40. package/dist/engine/compaction.js +1 -1
  41. package/dist/engine/continuation.js +66 -32
  42. package/dist/engine/decision-points.js +2 -3
  43. package/dist/engine/fanout.js +16 -0
  44. package/dist/engine/identity.js +42 -0
  45. package/dist/engine/loop-guard.js +26 -83
  46. package/dist/engine/messages.js +2 -2
  47. package/dist/engine/moa.js +23 -1
  48. package/dist/engine/native-vision-node.js +72 -0
  49. package/dist/engine/native-vision.js +103 -0
  50. package/dist/engine/net-error.js +15 -0
  51. package/dist/engine/rolling-summary.js +142 -93
  52. package/dist/engine/verify-gate.js +37 -7
  53. package/dist/engine/waterfall.js +33 -0
  54. package/dist/gateway-cli.js +24 -4
  55. package/dist/memory/live-progress.js +4 -5
  56. package/dist/memory/session-index.js +3 -3
  57. package/dist/moa/codeact-lane.js +98 -0
  58. package/dist/moa/codeact-sandbox.js +409 -0
  59. package/dist/moa/codeact.js +140 -0
  60. package/dist/permissions/artifact-visibility.js +10 -0
  61. package/dist/permissions/index.js +2 -1
  62. package/dist/permissions/policy.js +9 -2
  63. package/dist/permissions/tier.js +13 -3
  64. package/dist/products/craft.js +92 -3
  65. package/dist/products/temple.js +20 -1
  66. package/dist/products/voice.js +112 -0
  67. package/dist/remote/grants.js +119 -0
  68. package/dist/remote/host.js +33 -5
  69. package/dist/router/free-models.js +5 -9
  70. package/dist/router/models.js +80 -26
  71. package/dist/router/provider-models.js +78 -0
  72. package/dist/router/router.js +15 -3
  73. package/dist/selfimprove/index.js +8 -6
  74. package/dist/selfimprove/lessons.js +23 -0
  75. package/dist/services/preflight.js +35 -91
  76. package/dist/session.js +316 -125
  77. package/dist/skills/catalogue.js +5 -2
  78. package/dist/skills/finder.js +4 -4
  79. package/dist/skills/install-guard.js +68 -0
  80. package/dist/skills/install.js +67 -0
  81. package/dist/toolchain/manifest.json +13 -13
  82. package/dist/tools/background-result.js +1 -1
  83. package/dist/tools/beam.js +246 -0
  84. package/dist/tools/classes.js +103 -0
  85. package/dist/tools/contract.js +1 -1
  86. package/dist/tools/craft.js +36 -2
  87. package/dist/tools/deferred.js +7 -3
  88. package/dist/tools/doc-text.js +1 -1
  89. package/dist/tools/executor.js +25 -15
  90. package/dist/tools/generation-gateway.js +94 -0
  91. package/dist/tools/registry.js +135 -158
  92. package/dist/tools/sandbox.js +6 -6
  93. package/dist/ui/App.js +17 -6
  94. package/dist/ui/ApprovalPrompt.js +1 -1
  95. package/dist/ui/BgPanel.js +15 -10
  96. package/dist/ui/Composer.js +44 -2
  97. package/dist/ui/Header.js +1 -6
  98. package/dist/ui/StatusRule.js +20 -8
  99. package/dist/ui/ToolStep.js +3 -3
  100. package/dist/ui/Transcript.js +41 -14
  101. package/dist/ui/batchLine.js +4 -4
  102. package/dist/ui/editdiff.js +2 -4
  103. package/dist/ui/format.js +4 -20
  104. package/dist/ui/liveTools.js +3 -3
  105. package/dist/ui/modelPicker.js +10 -6
  106. package/dist/ui/opsMode.js +20 -0
  107. package/dist/ui/phase.js +4 -2
  108. package/dist/ui/slashCommands.js +1 -0
  109. package/dist/ui/types.js +0 -2
  110. package/dist/ui/voice.js +185 -0
  111. package/dist/update-check.js +17 -6
  112. package/dist/update.js +1 -2
  113. package/dist/util/audio-io.js +82 -0
  114. package/dist/util/slash.js +2 -2
  115. package/dist/vision/pairs.js +239 -0
  116. package/package.json +1 -1
  117. 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
+ }
@@ -93,7 +93,8 @@ export function withPermissions(inner, policy, opts = {}) {
93
93
  else {
94
94
  if (line)
95
95
  sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
96
- approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
96
+ const ctx = policy.asksEachCall(name) ? { line: `${policy.currentTier()} seat`, once: true } : undefined;
97
+ approved = opts.approve ? await opts.approve(name, args, ctx) : false; // no approver ⇒ fail-safe deny
97
98
  if (!approved) {
98
99
  tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
99
100
  return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
@@ -3,7 +3,7 @@
3
3
  // zero gates, zero overhead — programmatic/embedded callers opt in explicitly), but the SHIPPED
4
4
  // settings default is "gated" (2026-10-23): mutating tools ask the user to Allow/Deny on spawn,
5
5
  // Claude Code-style; shift+tab or settings leave it (permissions/modes.ts). "audit" allows-but-records.
6
- import { registrySafeTools, tierAllows } from "./tier.js";
6
+ import { registrySafeTools, tierAllows, tierAsks } from "./tier.js";
7
7
  import { signatureLine } from "./signature.js";
8
8
  // Read-only tools (registry `safe: true`) — never gated unless a rule says otherwise. DERIVED from the
9
9
  // registry, never hand-copied: the old 5-item copy drifted and gated/plan/dream/manual denied 12 safe tools.
@@ -90,6 +90,10 @@ export class PermissionPolicy {
90
90
  allowsTool(name) {
91
91
  return tierAllows(this.tier, name);
92
92
  }
93
+ /** True iff this seat may call `name` only with a fresh approval each time: the approval is never remembered. */
94
+ asksEachCall(name) {
95
+ return tierAsks(this.tier, name);
96
+ }
93
97
  /** Which human-signature line a call crosses (money/prod/destructive), or null. Live only while
94
98
  * enforcing (never for the fully-inert local owner). The wrapper reports this on an approval. */
95
99
  signatureLineFor(name, args) {
@@ -105,12 +109,15 @@ export class PermissionPolicy {
105
109
  }
106
110
  /** The decision for one tool call. Precedence: tier ceiling (a denied tool can't be granted by any
107
111
  * rule) → human-signature line (money/prod/destructive always ask, beating a rule/mode; under plan
108
- * review the approved plan answers — see planAnswer) → per-tool rule → allowlist pattern match → mode. */
112
+ * review the approved plan answers — see planAnswer) → tier ask (a seat's approval-only tools) → per-tool rule →
113
+ * allowlist pattern match → mode. */
109
114
  decide(name, args) {
110
115
  if (!this.allowsTool(name))
111
116
  return "deny"; // tier ceiling — absolute, above rules and mode
112
117
  if (this.signatureLineFor(name, args))
113
118
  return "ask"; // human-signature line — always a human, beats rules
119
+ if (tierAsks(this.tier, name))
120
+ return "ask"; // granted to this seat only with approval, each call
114
121
  const rule = this.rules[name];
115
122
  if (rule)
116
123
  return rule; // explicit override within the tier
@@ -15,16 +15,22 @@ 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
- const ENTERPRISE_ALLOW = new Set([...SAFE_TOOLS, ...ENTERPRISE_MUTATING]);
29
+ // Enterprise seat, granted only with approval: every call asks, whatever the mode, rules or allow patterns
30
+ // (policy.ts decide). The Beam drop tools fetch over the LAN and write ~/Beam/in (open, get) or send a signed receipt
31
+ // (ack); owner decision 2026-11-30. beam_send (file egress) stays outside the seat, like file_upload.
32
+ const ENTERPRISE_ASK = ["beam_open", "beam_get", "beam_ack"];
33
+ const ENTERPRISE_ALLOW = new Set([...SAFE_TOOLS, ...ENTERPRISE_MUTATING, ...ENTERPRISE_ASK]);
28
34
  // Readonly seat: inspection only = the registry-safe tools minus READONLY_SAFE_EXCLUDED. Every member is
29
35
  // registry `safe: true`, so no workspace-mutating tool can be in it — widening it means marking a tool safe
30
36
  // in the registry, which a dedicated permissions test holds to account.
@@ -43,3 +49,7 @@ export function tierAllows(tier, tool) {
43
49
  default: return false;
44
50
  }
45
51
  }
52
+ /** Whether `tier` may call `tool` only with a fresh approval each time. */
53
+ export function tierAsks(tier, tool) {
54
+ return tier === "enterprise" && ENTERPRISE_ASK.includes(tool);
55
+ }
@@ -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);
@@ -97,5 +97,94 @@ export async function craftDelete(args, auth) {
97
97
  const r = await temple.remove(id, auth);
98
98
  return r.ok ? `deleted craft ${id}` : `error: ${r.error}`;
99
99
  }
100
+ // ── rooms: working on one craft with other agents and its owner (temple.room) ──────────────────────────────────────
101
+ const ROOM_ACTIONS = ["join", "get", "post", "task_add", "claim", "release", "task_state", "edit", "wait", "link"];
102
+ function roomText(r, recent = 12) {
103
+ const tasks = r.tasks.map((t) => `- ${t.id} [${t.state}] ${t.title}${t.target ? ` · ${t.target}` : ""}${t.owner_handle ? ` · ${t.owner_handle}${t.lease_until ? ` (lease until ${t.lease_until})` : ""}` : ""} · rev ${t.rev}`);
104
+ const said = r.events.filter((e) => e.kind === "message" || e.kind === "conflict").slice(-recent)
105
+ .map((e) => ` #${e.seq} ${e.handle ?? "?"}${e.author_kind === "human" ? " (person)" : ""}: ${e.kind === "conflict" ? `conflict on ${str(e.data.path)}` : e.body}`);
106
+ return [`room of ${r.artifact.id} · "${r.artifact.title}" · v${r.artifact.version} · you can ${r.access} · cursor ${r.cursor}`,
107
+ `people: ${r.participants.map((p) => `${p.handle} (${p.kind})`).join(", ") || "none yet"}`,
108
+ `tasks:\n${tasks.join("\n") || " none"}`, said.length ? `recent:\n${said.join("\n")}` : "recent: nothing said yet",
109
+ `page for people: ${temple.room.link(r.artifact.id)}`].join("\n");
110
+ }
111
+ /** One tool for the room: join/get/post/task_add/claim/release/task_state/edit/wait/link. */
112
+ export async function craftRoom(args, auth) {
113
+ const action = str(args.action);
114
+ const id = str(args.id);
115
+ if (!ROOM_ACTIONS.includes(action))
116
+ return `error: craft_room needs \`action\`: ${ROOM_ACTIONS.join(" | ")}`;
117
+ if (!id)
118
+ return "error: craft_room needs `id` (the craft's id)";
119
+ if (action === "link")
120
+ return temple.room.link(id);
121
+ const denied = gate(auth);
122
+ if (denied)
123
+ return `error: ${denied}`;
124
+ const handle = str(args.handle) || "operator";
125
+ const taskId = str(args.task_id);
126
+ const need = (k) => `error: craft_room ${action} needs \`${k}\``;
127
+ switch (action) {
128
+ case "join":
129
+ case "get": {
130
+ const r = action === "join" ? await temple.room.join(id, handle, auth) : await temple.room.get(id, undefined, auth);
131
+ return r.ok ? roomText(r.value) : `error: ${r.error}`;
132
+ }
133
+ case "post": {
134
+ if (!str(args.body))
135
+ return need("body");
136
+ const r = await temple.room.post(id, handle, str(args.body), auth);
137
+ return r.ok ? `posted #${r.value.seq} as ${handle}` : `error: ${r.error}`;
138
+ }
139
+ case "task_add": {
140
+ if (!str(args.title))
141
+ return need("title");
142
+ const r = await temple.room.taskAdd(id, handle, { title: str(args.title), detail: str(args.detail) || undefined, target: str(args.target) || undefined }, auth);
143
+ return r.ok ? `added task ${r.value.id}${r.value.target ? ` on ${r.value.target}` : ""}` : `error: ${r.error}`;
144
+ }
145
+ case "claim":
146
+ case "release": {
147
+ if (!taskId)
148
+ return need("task_id");
149
+ const r = action === "claim" ? await temple.room.claim(id, handle, taskId, auth) : await temple.room.release(id, handle, taskId, auth);
150
+ if (!r.ok)
151
+ return r.code === "claimed" ? `error: ${r.error} — pick another task, or wait (craft_room wait) and try again` : `error: ${r.error}`;
152
+ return action === "claim" ? `you hold ${r.value.target ?? `task ${r.value.id}`} until ${r.value.lease_until ?? "you release it"} (rev ${r.value.rev}); each edit renews it` : `released task ${r.value.id}`;
153
+ }
154
+ case "task_state": {
155
+ const state = str(args.state);
156
+ if (!taskId || !/^(review|done|blocked|open)$/.test(state))
157
+ return need("task_id` and `state` (review | done | blocked | open)");
158
+ const r = await temple.room.taskState(id, handle, taskId, state, Number(args.rev), str(args.note) || undefined, auth);
159
+ if (!r.ok)
160
+ return r.code === "stale_task" ? `error: ${r.error} — craft_room get, then retry with the task's current rev` : `error: ${r.error}`;
161
+ return `task ${r.value.id} is ${r.value.state} (rev ${r.value.rev})`;
162
+ }
163
+ case "edit": {
164
+ const path = str(args.path);
165
+ const base = Number(args.base_version);
166
+ if (!path || typeof args.content !== "string" || !Number.isInteger(base))
167
+ return need("path`, `content` and `base_version");
168
+ const r = await temple.room.edit(id, handle, path, args.content, base, auth);
169
+ if (r.ok)
170
+ return `saved ${path} as v${r.value.artifact.version}${r.value.rebased_from ? ` (applied on top of others' changes since v${r.value.rebased_from})` : ""}`;
171
+ if (r.code === "version_conflict") {
172
+ const live = (r.live ?? {});
173
+ return `conflict: ${path} changed in v${live.changed_in ?? "?"}${live.by ? ` by ${live.by}` : ""} after your base v${base}. Nothing was written. ` +
174
+ `Merge your change into the live file below and edit again with base_version ${live.version}.\n--- live ${path} (v${live.version}) ---\n${live.content ?? "(not shown: binary or over 256 KB; read it from the craft)"}`;
175
+ }
176
+ return `error: ${r.error}`;
177
+ }
178
+ case "wait": {
179
+ const r = await temple.room.wait(id, Number(args.after) || 0, Math.min(Math.max(Number(args.timeout_secs) || 20, 1), 25), auth);
180
+ if (!r.ok)
181
+ return `error: ${r.error}`;
182
+ if (!r.value.events.length)
183
+ return `nothing new (cursor ${r.value.cursor})`;
184
+ return r.value.events.map((e) => `#${e.seq} ${e.kind} ${e.handle ?? ""}: ${e.body || JSON.stringify(e.data)}`).join("\n") + `\ncursor ${r.value.cursor}`;
185
+ }
186
+ }
187
+ return `error: unknown action ${action}`;
188
+ }
100
189
  // Exposed for tests (pure helpers that don't touch the network).
101
- export const _internal = { resolveScopes };
190
+ export const _internal = { resolveScopes, roomText };
@@ -56,7 +56,12 @@ export async function templeCall(tool, args, opts = {}) {
56
56
  const err = value?.error;
57
57
  if (rpc.result?.isError || err) {
58
58
  const msg = err?.message ?? (typeof value === "string" ? value : "the artifact surface refused the call");
59
- return { ok: false, error: err?.code === "unauthorized" ? `${msg} — sign in again (\`operator auth login\`)` : msg };
59
+ const out = { ok: false, error: err?.code === "unauthorized" ? `${msg} — sign in again (\`operator auth login\`)` : msg };
60
+ if (err?.code)
61
+ out.code = err.code;
62
+ if (err?.live !== undefined)
63
+ out.live = err.live;
64
+ return out;
60
65
  }
61
66
  return { ok: true, value: value };
62
67
  }
@@ -228,3 +233,17 @@ export const read = (id, auth) => templeCall("temple_read", { id }, { auth });
228
233
  export const list = (limit = 20, auth) => templeCall("temple_list", { limit: Math.min(Math.max(limit, 1), 100) }, { auth });
229
234
  export const remove = (id, auth) => templeCall("temple_delete", { id }, { auth });
230
235
  export const format = { line };
236
+ export const room = {
237
+ join: (id, handle, auth) => templeCall("temple_room_join", { id, handle, kind: "agent" }, { auth }),
238
+ get: (id, after, auth) => templeCall("temple_room_get", after === undefined ? { id } : { id, after }, { auth }),
239
+ post: (id, handle, body, auth) => templeCall("temple_room_post", { id, handle, body }, { auth }),
240
+ taskAdd: (id, handle, task, auth) => templeCall("temple_room_task_add", { id, handle, ...task }, { auth }),
241
+ claim: (id, handle, task_id, auth) => templeCall("temple_room_claim", { id, handle, task_id }, { auth }),
242
+ release: (id, handle, task_id, auth) => templeCall("temple_room_release", { id, handle, task_id }, { auth }),
243
+ taskState: (id, handle, task_id, state, rev, note, auth) => templeCall("temple_room_task_state", { id, handle, task_id, state, rev, ...(note ? { note } : {}) }, { auth }),
244
+ edit: (id, handle, path, content, base_version, auth) => templeCall("temple_room_edit", { id, handle, path, content, base_version }, { auth, timeoutMs: 120_000 }),
245
+ /** Long-poll: events after `after`, waiting up to `timeoutSecs` (Temple caps it at 25). */
246
+ wait: (id, after, timeoutSecs = 20, auth) => templeCall("temple_room_wait", { id, after, timeout_secs: timeoutSecs }, { auth, timeoutMs: (timeoutSecs + 15) * 1000 }),
247
+ /** The room page for a person, on the product's own host (`0perator.co/c/<id>/room`). */
248
+ link: (id) => `${shareUrl(id)}/room`,
249
+ };
@@ -0,0 +1,112 @@
1
+ // One door for voice: every surface's speech goes to OUR gateway's audio routes — transcription to the route behind
2
+ // `POST /audio/transcriptions`, speech to the route named in `POST /audio/speech` — and the router owns which speech
3
+ // servers back them (an on-request model, the always-on service, in that order or any other). This module holds no
4
+ // host, port, model or path: it asks the same gateways vision does (the local router on loopback, then the public
5
+ // gateway with the sign-in token; `services.voice.gateway` pins one or turns voice "off").
6
+ //
7
+ // Voice is input and output AROUND a session, never its brain: speech becomes the owner's turn as text, the session's
8
+ // own model answers with its tools, and that answer is spoken. Nothing here asks a speech model a question.
9
+ import { visionGateways } from "../tools/vision-gateway.js";
10
+ import { retry, retryAfterMs, realClock, ROUTE_RETRY } from "../util/retry.js";
11
+ /** `timeoutMs` covers one whole call, a cold model load included. `loadingAfterMs`: a call still unanswered by then
12
+ * is reported through `onWait` every `tickMs`, so a cold start shows elapsed time instead of hanging. */
13
+ export const VOICE_DEFAULTS = { sttRoute: "audio.stt", ttsRoute: "audio.tts", timeoutMs: 180_000, loadingAfterMs: 3_000, tickMs: 1_000, probeMs: 3_000 };
14
+ export function voiceConfig(v = {}) {
15
+ return {
16
+ gateways: visionGateways({ gateway: v.gateway }),
17
+ sttRoute: v.sttRoute?.trim() || VOICE_DEFAULTS.sttRoute,
18
+ ttsRoute: v.ttsRoute?.trim() || VOICE_DEFAULTS.ttsRoute,
19
+ ...(v.voice?.trim() ? { voice: v.voice.trim() } : {}),
20
+ timeoutMs: v.timeoutMs && v.timeoutMs > 0 ? v.timeoutMs : VOICE_DEFAULTS.timeoutMs,
21
+ };
22
+ }
23
+ const headers = (gw) => ({ "User-Agent": "operator/kode-tsi", ...gw.auth });
24
+ const failure = (e, timeoutMs) => {
25
+ const name = e?.name;
26
+ return name === "TimeoutError" || name === "AbortError" ? `no answer in ${Math.max(1, Math.round(timeoutMs / 1000))}s` : "unreachable";
27
+ };
28
+ /** Why a route is not there, or null when the gateway lists it. Asks the gateway's model list only: no speech server
29
+ * is touched and no model is loaded. */
30
+ async function routeMissing(gw, route) {
31
+ try {
32
+ const res = await fetch(`${gw.base}/models/${encodeURIComponent(route)}`, { headers: headers(gw), signal: AbortSignal.timeout(VOICE_DEFAULTS.probeMs) });
33
+ return res.ok ? null : res.status === 404 ? `no "${route}" route` : `returned ${res.status}`;
34
+ }
35
+ catch (e) {
36
+ return failure(e, VOICE_DEFAULTS.probeMs);
37
+ }
38
+ }
39
+ /** The first gateway that has both voice routes, or one plain line saying why none does. */
40
+ export async function findVoiceGateway(cfg) {
41
+ if (!cfg.gateways.length)
42
+ return { error: "voice is off (services.voice.gateway is \"off\")" };
43
+ const down = [];
44
+ for (const gw of cfg.gateways) {
45
+ if (gw.skip) {
46
+ down.push(`${gw.label}: ${gw.skip}`);
47
+ continue;
48
+ }
49
+ const missing = (await Promise.all([routeMissing(gw, cfg.sttRoute), routeMissing(gw, cfg.ttsRoute)])).filter(Boolean);
50
+ if (!missing.length)
51
+ return { ok: gw };
52
+ down.push(`${gw.label}: ${[...new Set(missing)].join(", ")}`);
53
+ }
54
+ return { error: `voice is unavailable: ${down.join("; ")}` };
55
+ }
56
+ /** One request with the route's retry (a busy or restarting leg answers 503 at once) inside one deadline, reporting
57
+ * the wait. Throws one plain line, never a response body. */
58
+ async function call(what, timeoutMs, o, send, read) {
59
+ const clock = o.clock ?? realClock;
60
+ const started = clock.now(), deadline = started + timeoutMs;
61
+ const tick = o.tickMs ?? VOICE_DEFAULTS.tickMs, after = o.loadingAfterMs ?? VOICE_DEFAULTS.loadingAfterMs;
62
+ const timer = o.onWait ? setInterval(() => { const ms = clock.now() - started; if (ms >= after)
63
+ o.onWait?.(Math.round(ms / 1000)); }, tick) : undefined;
64
+ try {
65
+ const { result } = await retry(async () => {
66
+ const left = Math.max(1, deadline - clock.now());
67
+ try {
68
+ const res = await send(AbortSignal.timeout(left));
69
+ if (res.status === 503 || res.status === 429)
70
+ return { error: `the gateway returned ${res.status}`, retry: true, retryAfterMs: retryAfterMs(res.headers.get("retry-after"), clock.now()) };
71
+ if (!res.ok)
72
+ return { error: res.status === 404 ? "the route is not configured" : `the gateway returned ${res.status}` };
73
+ const value = await read(res).catch(() => undefined);
74
+ return value === undefined ? { error: "the gateway returned nothing usable" } : { ok: value };
75
+ }
76
+ catch (e) {
77
+ const reason = failure(e, timeoutMs);
78
+ return reason === "unreachable" ? { error: "the gateway is unreachable", retry: true } : { error: reason };
79
+ }
80
+ }, { ...ROUTE_RETRY, deadline }, clock);
81
+ if ("ok" in result)
82
+ return result.ok;
83
+ throw new Error(`${what} failed: ${result.error}`);
84
+ }
85
+ finally {
86
+ if (timer)
87
+ clearInterval(timer);
88
+ }
89
+ }
90
+ /** Recorded audio → the words said ("" when none were heard). */
91
+ export function transcribe(gw, cfg, audio, o = {}) {
92
+ return call("transcription", cfg.timeoutMs, o, (signal) => {
93
+ const form = new FormData();
94
+ form.append("file", new Blob([audio], { type: "audio/wav" }), "speech.wav");
95
+ form.append("model", cfg.sttRoute);
96
+ form.append("response_format", "json");
97
+ return fetch(`${gw.base}/audio/transcriptions`, { method: "POST", signal, headers: headers(gw), body: form }); // no Content-Type: FormData sets the boundary
98
+ }, async (res) => {
99
+ const text = (await res.json()).text;
100
+ return typeof text === "string" ? text.trim() : undefined;
101
+ });
102
+ }
103
+ /** Text → spoken WAV bytes. */
104
+ export function speak(gw, cfg, text, o = {}) {
105
+ return call("speech", cfg.timeoutMs, o, (signal) => fetch(`${gw.base}/audio/speech`, {
106
+ method: "POST", signal, headers: { "Content-Type": "application/json", ...headers(gw) },
107
+ body: JSON.stringify({ model: cfg.ttsRoute, input: text, response_format: "wav", ...(cfg.voice ? { voice: cfg.voice } : {}) }),
108
+ }), async (res) => {
109
+ const bytes = new Uint8Array(await res.arrayBuffer());
110
+ return bytes.length ? bytes : undefined;
111
+ });
112
+ }
@@ -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
+ }