@0perator/operator 0.1.360-next.2 → 0.2.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 (49) hide show
  1. package/README.md +1 -1
  2. package/dist/autonomy/delegate-mode.js +159 -0
  3. package/dist/autonomy/delegate.js +1 -1
  4. package/dist/autonomy/session-factory.js +2 -0
  5. package/dist/background/index.js +26 -2
  6. package/dist/background/resume.js +125 -0
  7. package/dist/browser/engine.js +163 -0
  8. package/dist/browser/session.js +130 -140
  9. package/dist/cli.js +174 -12
  10. package/dist/config/settings.js +1 -1
  11. package/dist/engine/agent.js +1 -1
  12. package/dist/engine/aurora.js +4 -4
  13. package/dist/engine/compaction.js +1 -1
  14. package/dist/engine/moa.js +2 -1
  15. package/dist/engine/selfheal.js +1 -1
  16. package/dist/engine/toolcalls.js +6 -6
  17. package/dist/index.js +3 -0
  18. package/dist/mcp/phone-server.js +30 -0
  19. package/dist/permissions/index.js +33 -17
  20. package/dist/permissions/signature.js +5 -0
  21. package/dist/phone-cli.js +65 -0
  22. package/dist/remote/host.js +31 -2
  23. package/dist/router/models.js +5 -15
  24. package/dist/selfimprove/index.js +1 -1
  25. package/dist/session.js +48 -7
  26. package/dist/tools/deferred.js +1 -0
  27. package/dist/tools/device/android.js +227 -0
  28. package/dist/tools/device/classify.js +127 -0
  29. package/dist/tools/device/deps.js +69 -0
  30. package/dist/tools/device/desktop.js +82 -0
  31. package/dist/tools/device/harness.js +262 -0
  32. package/dist/tools/device/iphone.js +206 -0
  33. package/dist/tools/device/mirroring-jxa.js +146 -0
  34. package/dist/tools/device/setup.js +90 -0
  35. package/dist/tools/device/tools.js +70 -0
  36. package/dist/tools/device/types.js +19 -0
  37. package/dist/tools/registry.js +12 -3
  38. package/dist/ui/App.js +4 -3
  39. package/dist/ui/ApprovalPrompt.js +10 -4
  40. package/dist/ui/BgPanel.js +2 -2
  41. package/dist/ui/UpdatePrompt.js +40 -0
  42. package/dist/ui/modelPicker.js +1 -1
  43. package/dist/ui/slashCommands.js +1 -0
  44. package/dist/update-check.js +134 -0
  45. package/dist/update.js +59 -15
  46. package/dist/util/slash.js +2 -2
  47. package/package.json +4 -2
  48. package/src/tools/device/NOTICE +37 -0
  49. package/dist/browser/cdp.js +0 -271
@@ -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
+ }
@@ -28,7 +28,7 @@ const RECONNECT_MAX_MS = 15_000;
28
28
  // control frames stay plaintext so the relay can route blind. These sets mirror the mobile's frozen
29
29
  // dataFrameTypes byte-for-byte (kode-mobile RemoteSession.swift). The INNER encrypted bytes are
30
30
  // 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"]);
31
+ const DATA_HOST_TYPES = new Set(["snapshot", "transcript", "tool_step", "activity", "status", "capabilities", "approval_request", "ask_user", "delta", "agents"]);
32
32
  const DATA_DRIVE_TYPES = new Set(["prompt", "command", "approval_response", "ask_user_response", "interrupt", "agent_stop", "agent_steer"]);
33
33
  // A paired snapshot is encrypted (base64 ≈ 1.37× plaintext), and the relay drops/truncates any frame over
34
34
  // its 256 KB cap — which would corrupt ciphertext. Cap the paired snapshot's plaintext so the encrypted
@@ -42,6 +42,13 @@ const SNAPSHOT_MAX_BYTES_PAIRED = 170 * 1024;
42
42
  const SNAPSHOT_MAX_ENTRIES = 200; // SPEC §8: last 200 message-entries + their tool steps, whichever binds first
43
43
  const SNAPSHOT_MAX_BYTES = 512 * 1024; // SPEC §8 snapshot cap
44
44
  const MCP_TOOL_PREVIEW = 20; // per-server tool NAMES kept when a server's inventory is large — see capCapabilities
45
+ /** The shell's agent list as followers see it: live ones and finished ones until they decommission. */
46
+ export function toRemoteAgents(list) {
47
+ return list.map((a) => ({
48
+ id: a.id, name: a.name ?? a.id, label: a.label, status: a.status, round: a.round ?? 0,
49
+ ...(a.resumed ? { resumed: true } : {}), ...(a.endKind ? { endKind: a.endKind } : {}), ...(a.headline ? { headline: a.headline } : {}),
50
+ }));
51
+ }
45
52
  const byteLen = (v) => Buffer.byteLength(JSON.stringify(v), "utf8");
46
53
  // BLOCKER fix (REMOTE_RICH_HEAD_AUDIT.md §4, "summarize, don't enumerate"): a server's `tools[]` is
47
54
  // prefixed to MCP_TOOL_PREVIEW entries — `toolCount` still carries the real total, so a follower's UI
@@ -79,6 +86,7 @@ export class RemoteHost {
79
86
  livePending = null;
80
87
  turnN = 0;
81
88
  capabilities = null;
89
+ agentRows = [];
82
90
  // Paired (QR) mode — set from the one-time code the owner shows as a QR. When paired, the host registers
83
91
  // its pairingId with the relay and e2e-encrypts every DATA-frame payload with frameKey; the relay (and
84
92
  // anyone but the scanning phone) sees only ciphertext.
@@ -236,7 +244,7 @@ export class RemoteHost {
236
244
  if (typeof f.payload?.epoch === "number")
237
245
  this.epoch = f.payload.epoch; // RC v2 A2
238
246
  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 });
247
+ this.register();
240
248
  if (this.paired && this.pairingId)
241
249
  this.send("pair-register", this.sessionId, { pairingId: this.pairingId }); // control frame (plaintext) — binds pairingId -> this session at the relay
242
250
  // RC v2 A2: a welcome AFTER the first is a RESUME. While the socket was down, state frames were dropped
@@ -353,8 +361,29 @@ export class RemoteHost {
353
361
  ...(this.epoch != null ? { epoch: this.epoch } : {}), // RC v2 A2: the reliable place to stamp epoch (welcome fires pre-attach)
354
362
  ...(truncated ? { truncated: true, omittedBefore } : {}),
355
363
  ...(this.capabilities ? { capabilities: this.capabilities } : {}), // absent until the shell's first setCapabilities() call; already capped by capCapabilities() in setCapabilities()
364
+ ...(this.agentRows.length ? { agents: this.agentRows } : {}),
356
365
  }, this.seq);
357
366
  }
367
+ /** The session row on the relay's list carries how many agents work here, so a phone shows "N agents working" without
368
+ * attaching. Re-sent whenever that count changes; an older relay keeps the fields it knows. */
369
+ register() {
370
+ const agentsWorking = this.agentRows.filter((a) => a.status === "working" || a.status === "queued").length;
371
+ this.send("register", this.sessionId, { title: this.meta.title, surface: this.meta.surface ?? "cli", cwd: this.meta.cwd, host: this.meta.host, agentsWorking });
372
+ }
373
+ /** The host's background agents. Sent as an `agents` state frame when they change (never on an identical list). */
374
+ setAgents(rows) {
375
+ const next = rows.map((a) => ({ ...a }));
376
+ if (JSON.stringify(next) === JSON.stringify(this.agentRows))
377
+ return;
378
+ const working = (r) => r.filter((a) => a.status === "working" || a.status === "queued").length;
379
+ const countChanged = working(next) !== working(this.agentRows);
380
+ this.agentRows = next;
381
+ if (!this.sessionId)
382
+ return;
383
+ this.state("agents", { agents: next });
384
+ if (countChanged)
385
+ this.register();
386
+ }
358
387
  /** SPEC §8 snapshot cap: last 200 message/tool entries, then shrink further (oldest-first) until the
359
388
  * serialized transcript fits 512 KB — `capabilities` gets its own budget (capCapabilities), so this
360
389
  * only accounts for the transcript half. `omittedBefore` is this host's CURRENT seq at truncation
@@ -23,7 +23,7 @@ export const DEFAULT_ACTIVE_MODEL = "operator-flash";
23
23
  * activeModel, a script or a delegate target keeps working. A settings.models row with one of these ids is hidden too
24
24
  * unless it says `hidden: false`. */
25
25
  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",
26
+ "operator-1m", "aurora", "cortana", "thor", "scout", "casanova", "falcon-h1-34b", "belmont-30b", "venice-24b", "dolphin-7b",
27
27
  ]);
28
28
  // Back-compat aliases: the user-facing ids were renamed aurora-* -> operator-* (the outward name is
29
29
  // Operator; "aurora" is the internal model, never shown). The OLD ids still resolve — a persisted
@@ -49,12 +49,9 @@ export const LEGACY_GATEWAY_BASE = `https://${LEGACY_API_HOST}/v1`;
49
49
  const ANTHROPIC_BASE = "https://api.anthropic.com/v1";
50
50
  const GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai"; // Google's OpenAI-compatible surface — no native transport
51
51
  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
52
  /** 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]". */
53
+ * family's max_tokens ceiling (a larger value is a 400). */
56
54
  export const ANTHROPIC_MAX_OUTPUT = 128_000;
57
- const QWEN_FLASH_MAX_OUTPUT = 131_072;
58
55
  const NOUS_BASE = "https://inference-api.nousresearch.com/v1";
59
56
  // Registry order IS picker order (visibleModels keeps it): the main three, the local row, then the gateway rows, then the
60
57
  // connected-provider rows (hidden until their key is connected), then the by-id-only lanes, then MOA. Free
@@ -66,7 +63,7 @@ export const BUILTIN_MODELS = [
66
63
  // Router routes of the same name, gateway-first like every gateway row. `ctx` is the window the route serves.
67
64
  { 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
65
  { 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 },
66
+ { 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
67
  // ── local ───────────────────────────────────────────────────────────────────────────────────────────────
71
68
  // THE one Aurora row (0.1.332), retired from the picker 11/25 (RETIRED_MODEL_IDS). The 300K/600K/1M choice is a
72
69
  // context PIN (settings.contextPin, /context, Ctrl+X) applied over the served window — not three profiles of one
@@ -84,7 +81,7 @@ export const BUILTIN_MODELS = [
84
81
  { 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
82
  // ── connected providers (BYO: hidden until the vendor key is connected — /model "+ Connect a provider key") ──
86
83
  // 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
84
+ // OpenAI-dialect connectors, Claude speaks the NATIVE Anthropic Messages wire — transport
88
85
  // "anthropic" routes it through engine/anthropic-chat.ts (x-api-key auth from the BYO "anthropic" key; the
89
86
  // Operator token is NEVER sent here — authHeaders scoping + anthropic-chat's own key resolution). Model ids
90
87
  // 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 +92,6 @@ export const BUILTIN_MODELS = [
95
92
  // strict openai dialect is what that surface accepts). Same "gemini" key account as the byo-model preset.
96
93
  { 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
94
  { 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
95
  // ── by-id lanes (hidden from the picker, still resolve) ────────────────────────────────────────────────
105
96
  // The cloud slot of the SAME Aurora, folded out of the picker in 0.1.332 (one Aurora row; the cloud legs ride
106
97
  // in buildEndpointChain's failover chain). Reachable by id for scripts. api.0perator.co is AXE's OWN gateway
@@ -130,7 +121,6 @@ export const BYO_PRESETS = {
130
121
  openrouter: { label: "OpenRouter", box: "OpenRouter", endpoint: "https://openrouter.ai/api/v1", model: "openai/gpt-5", ctx: 200000, account: "openrouter", envAlias: "OPENROUTER_API_KEY" },
131
122
  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
123
  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
124
  // Nous Portal — the free cloud tier (router/free-models.ts lists its `:free` rows once this key is connected;
135
125
  // the vendor requires an account even for free models). 50 RPM / 500k TPM; prompts may be used for training.
136
126
  // 0perator's own free catalog (portal router behind AuthGate): the free models we serve with OUR provider accounts,
@@ -225,7 +215,7 @@ export function modelCtxFor(id, overrides) {
225
215
  return Number.POSITIVE_INFINITY;
226
216
  return findModel(modelRegistry(overrides), id)?.ctx ?? Number.POSITIVE_INFINITY;
227
217
  }
228
- /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora/Qwen (128K+) stay
218
+ /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora and the gateway models (128K+) stay
229
219
  * full; a self-hosted small model (8K, or a 16K bump) goes lean. */
230
220
  export const LEAN_HARNESS_CTX = 32768;
231
221
  /** The default served-window floor for the model a session runs its full harness on (settings.contextFloor): below it
@@ -12,7 +12,7 @@ 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.
package/dist/session.js CHANGED
@@ -14,13 +14,14 @@ import { compact, compactionSplit, fitToWindow, turnStarts, SUMMARY_INSTRUCTION,
14
14
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
15
15
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
16
16
  import { engineRouter } from "./engine/router-adapter.js";
17
- import { appendFileSync, mkdirSync } from "node:fs";
17
+ import { appendFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
18
18
  import { dirname } from "node:path";
19
19
  import { operatorPath } from "./config/home.js";
20
20
  import { moaTeam, plannerBrief } from "./engine/moa.js";
21
21
  import { routeTurn } from "./classifier/route.js";
22
22
  import { engineNote, isStatusAsk, STATUS_FIRST_NOTE } from "./engine/continuation.js";
23
23
  import { withDelegateDefault } from "./autonomy/delegate.js";
24
+ import { withDelegateGuard } from "./autonomy/delegate-mode.js";
24
25
  import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0 observability (KODE_MOA_SHADOW)
25
26
  import { AuroraRouter } from "./router/router.js";
26
27
  import { operatorAgentPersona } from "./config/operator-harness.js";
@@ -686,7 +687,14 @@ export class Session {
686
687
  : this.policy;
687
688
  const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
688
689
  const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
689
- const hooked = withHooks(base, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
690
+ // Delegate mode's fence sits above the gate: a call it refuses never asks the owner to approve it. Off = pass-through.
691
+ const guarded = withDelegateGuard(base, { cwd: this.cwd ?? process.cwd(), exists: existsSync, realpath: (p) => { try {
692
+ return realpathSync(p);
693
+ }
694
+ catch {
695
+ return p;
696
+ } } });
697
+ const hooked = withHooks(guarded, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
690
698
  if (this.nativeDeferred)
691
699
  return withNativeDeferred(hooked, this.nativeDeferred);
692
700
  return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
@@ -796,7 +804,13 @@ export class Session {
796
804
  * selected endpoint's. */
797
805
  healthTarget() {
798
806
  const planner = findModel(this.liveRegistry(), this.modelId)?.kind === "orchestrated" ? moaTeam(this.moaConfig)?.planner : undefined;
799
- return planner ? endpointBase(planner.endpoint) : this.inner.base;
807
+ if (!planner)
808
+ return this.inner.base;
809
+ if (planner.endpoint)
810
+ return endpointBase(planner.endpoint);
811
+ const row = findModel(this.liveRegistry(), planner.id);
812
+ const ep = row ? profileEndpoint(row) : undefined;
813
+ return ep ? endpointBase(ep) : this.inner.base;
800
814
  }
801
815
  /** Is the endpoint the current model talks to reachable? Lets the shell fail clearly before a turn. Probes the
802
816
  * way reachable() does, because a non-default model's endpoint is often the portal router, which has /healthz
@@ -1152,13 +1166,37 @@ export class Session {
1152
1166
  * to. "moa" has no endpoint of its own; send() special-cases it (sendMoa) instead. Returns an
1153
1167
  * error instead of throwing, so the shell can show it inline: an unknown id, or "moa" selected
1154
1168
  * with no settings.moa configured. */
1169
+ /** `/delegate planner`: a /model id plans MoA turns (moa.plannerModel), with `specialist` as the executor when given.
1170
+ * "" clears it back to moa.planner. Applies from the next MoA turn (sendMoa reads the team per turn). Refused when
1171
+ * the id cannot run: unknown, no endpoint of its own, or a provider row whose key is not stored. */
1172
+ setMoaPlanner(plannerModel, specialist) {
1173
+ for (const id of [plannerModel, specialist]) {
1174
+ if (!id)
1175
+ continue;
1176
+ const p = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
1177
+ if (p.error || p.profile?.kind !== "single")
1178
+ return { ok: false, error: p.error ?? `"${id}" has no endpoint of its own` };
1179
+ }
1180
+ this.moaConfig = { ...this.moaConfig, plannerModel, ...(specialist ? { specialist: { id: specialist } } : {}) };
1181
+ return { ok: true };
1182
+ }
1183
+ moaTeam() {
1184
+ return moaTeam(this.moaConfig);
1185
+ }
1155
1186
  setModel(id) {
1156
1187
  const { profile, error } = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
1157
1188
  if (error || !profile)
1158
1189
  return { ok: false, error };
1159
1190
  this.decodeSamples = []; // another model's rate says nothing about this one
1160
- if (profile.kind === "orchestrated" && !moaTeam(this.moaConfig)) {
1161
- return { ok: false, error: `MOA needs a "moa" block (planner + specialist) in settings.json` };
1191
+ if (profile.kind === "orchestrated") {
1192
+ const team = moaTeam(this.moaConfig);
1193
+ if (!team)
1194
+ return { ok: false, error: `MOA needs a "moa" block (planner + specialist) in settings.json` };
1195
+ if (!team.planner.endpoint) { // a /model id as the planner: it must resolve, and a provider row needs its key stored
1196
+ const p = selectModel(this.liveRegistry(), team.planner.id, hasByoToken, this.isOwner);
1197
+ if (p.error || p.profile?.kind !== "single")
1198
+ return { ok: false, error: `MoA planner: ${p.error ?? `"${team.planner.id}" has no endpoint of its own`}` };
1199
+ }
1162
1200
  }
1163
1201
  if (profile.kind === "single" && profile.id === DEFAULT_MODEL_ID && this.chain) {
1164
1202
  // The default local model IS the shell's endpoint chain (the gateway's published port + its failover
@@ -1600,8 +1638,11 @@ export class Session {
1600
1638
  this.telemetry.record({ type: "moa", planner: team.planner.id, specialist: team.specialist, route: specialist ? "direct" : route || fd === "work" ? "planned" : "unrouted", pDirect: route?.pDirect });
1601
1639
  if (specialist)
1602
1640
  return this.execute(text, h, this.wrap(this.routerForProfile(specialist)), this.sysWithThink(), specialist.id);
1603
- const plannerRouter = this.wrap(new AuroraRouter([
1604
- { name: team.planner.id, base: endpointBase(team.planner.endpoint), model: team.planner.model, ctxLimit: this.inner.ctxLimit() },
1641
+ const plannerRow = team.planner.endpoint ? undefined : findModel(this.liveRegistry(), team.planner.id);
1642
+ if (!team.planner.endpoint && plannerRow?.kind !== "single")
1643
+ throw new Error(`MoA planner "${team.planner.id}" is not a /model id with an endpoint`);
1644
+ const plannerRouter = this.wrap(plannerRow?.kind === "single" ? this.routerForProfile(plannerRow) : new AuroraRouter([
1645
+ { name: team.planner.id, base: endpointBase(team.planner.endpoint), model: team.planner.model ?? team.planner.id, ctxLimit: this.inner.ctxLimit() },
1605
1646
  ]));
1606
1647
  const sys = `${this.sysWithThink() ?? ""}\n\n## MOA: planner\n${plannerBrief(team)}`;
1607
1648
  return withDelegateDefault(team.specialist, () => this.execute(text, h, plannerRouter, sys, team.planner.id));
@@ -202,6 +202,7 @@ const SYNONYMS = new Map(Object.entries({
202
202
  login: "browser", log: "log_tail", click: "desktop browser", window: "desktop", server: "background", daemon: "background",
203
203
  subagent: "agent", conversation: "session", chat: "session", movie: "video", clip: "video", healthy: "health", uptime: "health",
204
204
  kanban: "board", outage: "incident", playbook: "skill", cron: "cronjob", commit: "checkpoint", test: "validate verify",
205
+ iphone: "phone", android: "phone", mobile: "phone", tap: "phone_tap", swipe: "phone_swipe", adb: "phone",
205
206
  }).map(([k, v]) => [stem(k), v.split(" ").map((x) => (x.includes("_") ? x : stem(x)))]));
206
207
  function nativeSearch(cat, query) {
207
208
  const all = [...cat.native.values(), ...cat.mcp.values()];
@@ -0,0 +1,227 @@
1
+ // Android over adb — macOS, Linux and Windows alike. Ported from phone-harness's android.py (MIT, see ./NOTICE):
2
+ // `adb devices -l` states, screencap for pixels, `uiautomator dump` for the text tree, `input` for taps, swipes, keys
3
+ // and text, `am start` / `cmd package resolve-activity` for apps, and the lock gate (a locked phone is the owner's;
4
+ // a PIN is never typed). Tightened: every adb call is an argv array with a deadline. `adb shell` hands its words to
5
+ // the phone's own sh, so every word that reaches it is either a validated number, a key from a fixed table, a
6
+ // package id matching PACKAGE, or text single-quoted by devQuote — nothing the model sends is spliced in raw.
7
+ import { deviceDeps, pngSize } from "./deps.js";
8
+ import { NeedsOwner, Unsupported } from "./types.js";
9
+ export const ADB_INSTALL = {
10
+ darwin: "brew install android-platform-tools",
11
+ linux: "sudo apt install adb (Fedora: sudo dnf install android-tools)",
12
+ win32: "winget install Google.PlatformTools",
13
+ };
14
+ const T_QUICK = 10_000;
15
+ const T_SHOT = 20_000;
16
+ const T_TREE = 30_000;
17
+ const KEYCODES = {
18
+ home: "HOME", back: "BACK", recents: "APP_SWITCH", enter: "ENTER", delete: "DEL", tab: "TAB", space: "SPACE",
19
+ escape: "ESCAPE", up: "DPAD_UP", down: "DPAD_DOWN", left: "DPAD_LEFT", right: "DPAD_RIGHT", volume_up: "VOLUME_UP",
20
+ volume_down: "VOLUME_DOWN", power: "POWER", search: "SEARCH", menu: "MENU",
21
+ };
22
+ // Names people say → package ids that do not contain them (phone-harness _APP_IDS). First installed one wins.
23
+ const APP_IDS = {
24
+ tiktok: ["com.zhiliaoapp.musically", "com.ss.android.ugc.trill"], x: ["com.twitter.android"], twitter: ["com.twitter.android"],
25
+ threads: ["com.instagram.barcelona"], facebook: ["com.facebook.katana", "com.facebook.lite"], messenger: ["com.facebook.orca"],
26
+ signal: ["org.thoughtcrime.securesms"], gmail: ["com.google.android.gm"], playstore: ["com.android.vending"],
27
+ googleplay: ["com.android.vending"], uber: ["com.ubercab"], ubereats: ["com.ubercab.eats"], cashapp: ["com.squareup.cash"],
28
+ amazon: ["com.amazon.mShop.android.shopping"], googlemaps: ["com.google.android.apps.maps"], maps: ["com.google.android.apps.maps"],
29
+ messages: ["com.google.android.apps.messaging"], phone: ["com.google.android.dialer", "com.android.dialer"],
30
+ clock: ["com.google.android.deskclock", "com.android.deskclock"], files: ["com.google.android.documentsui", "com.android.documentsui"],
31
+ settings: ["com.android.settings"], chrome: ["com.android.chrome"], camera: ["com.google.android.GoogleCamera", "com.android.camera"],
32
+ };
33
+ export const PACKAGE = /^[A-Za-z][\w]*(\.[A-Za-z_][\w]*)+$/;
34
+ const SERIAL = /^[\w.:\-[\]%]+$/;
35
+ /** One word for the phone's sh: single-quoted, with embedded quotes closed and escaped. */
36
+ export function devQuote(s) {
37
+ return `'${s.replace(/'/g, `'\\''`)}'`;
38
+ }
39
+ /** `adb devices -l` → rows. The first line is the header; a row is `<serial> <state> [key:value …]`. */
40
+ export function parseDevices(out) {
41
+ return out.split(/\r?\n/).slice(1).map((l) => l.trim()).filter(Boolean).map((l) => {
42
+ const [serial = "", state = "", ...rest] = l.split(/\s+/);
43
+ const model = rest.find((p) => p.startsWith("model:"))?.slice(6).replace(/_/g, " ");
44
+ return { serial, state, model, transport: serial.includes(":") || serial.startsWith("adb-") ? "wifi" : "usb" };
45
+ }).filter((d) => d.serial && d.state);
46
+ }
47
+ const XML_ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
48
+ const unxml = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (_, e) => e[0] === "#" ? String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)) : XML_ENT[e.toLowerCase()] ?? _);
49
+ /** `uiautomator dump` XML → the visible text with box centres (device pixels = screenshot pixels on Android). */
50
+ export function parseTree(xml) {
51
+ const out = [];
52
+ for (const m of xml.matchAll(/<node\b([^>]*?)\/?>/g)) {
53
+ const attrs = {};
54
+ for (const a of m[1].matchAll(/([\w-]+)="([^"]*)"/g))
55
+ attrs[a[1]] = unxml(a[2]);
56
+ const text = (attrs.text || attrs["content-desc"] || "").trim();
57
+ const b = /\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(attrs.bounds ?? "");
58
+ if (!text || !b)
59
+ continue;
60
+ const [x1, y1, x2, y2] = b.slice(1).map(Number);
61
+ out.push({ text, x: Math.round((x1 + x2) / 2), y: Math.round((y1 + y2) / 2), w: x2 - x1, h: y2 - y1 });
62
+ }
63
+ return out;
64
+ }
65
+ export class AndroidBackend {
66
+ serial;
67
+ adb;
68
+ kind = "android";
69
+ gateAt = 0;
70
+ constructor(serial, adb = "adb") {
71
+ this.serial = serial;
72
+ this.adb = adb;
73
+ if (serial !== undefined && !SERIAL.test(serial))
74
+ throw new Unsupported(`"${serial}" is not an adb serial`);
75
+ }
76
+ async raw(args, timeoutMs = T_QUICK) {
77
+ return deviceDeps().run(this.adb, this.serial ? ["-s", this.serial, ...args] : args, { timeoutMs });
78
+ }
79
+ async must(args, timeoutMs = T_QUICK) {
80
+ const r = await this.raw(args, timeoutMs);
81
+ if (r.missing)
82
+ throw new NeedsOwner("adb is not installed", ADB_INSTALL[deviceDeps().platform] ?? "install Android platform-tools");
83
+ if (r.timedOut)
84
+ throw new Error(`adb ${args[0]} did not answer in ${Math.round(timeoutMs / 1000)} s`);
85
+ if (r.code !== 0)
86
+ throw new Error(`adb ${args[0]} failed: ${(r.stderr || r.stdout).trim().slice(0, 300)}`);
87
+ return r;
88
+ }
89
+ sh(...words) { return this.must(["shell", ...words]); }
90
+ async devices() {
91
+ const r = await deviceDeps().run(this.adb, ["devices", "-l"], { timeoutMs: T_QUICK });
92
+ if (r.missing)
93
+ return { devices: [], missing: true };
94
+ return { devices: r.code === 0 ? parseDevices(r.stdout) : [], missing: false };
95
+ }
96
+ async status() {
97
+ const base = { kind: "android", backend: "adb" };
98
+ const { devices, missing } = await this.devices();
99
+ if (missing)
100
+ return { ...base, state: "missing-tool", detail: "adb is not installed", fix: ADB_INSTALL[deviceDeps().platform] ?? "install Android platform-tools" };
101
+ const mine = this.serial ? devices.filter((d) => d.serial === this.serial) : devices;
102
+ const ready = mine.filter((d) => d.state === "device");
103
+ if (ready.length > 1 && !this.serial) {
104
+ return { ...base, state: "ready", detail: `${ready.length} phones attached: ${ready.map((d) => `${d.serial} (${d.model ?? "?"})`).join(", ")} — pass device: "<serial>"`, name: ready[0].model, serial: ready[0].serial };
105
+ }
106
+ if (ready.length) {
107
+ const d = ready[0];
108
+ const locked = await this.lockState(d.serial).catch(() => null);
109
+ if (locked)
110
+ return { ...base, state: "locked", detail: `${d.model ?? d.serial} is locked`, fix: "unlock the phone (Operator never types a PIN)", name: d.model, serial: d.serial };
111
+ return { ...base, state: "ready", detail: `${d.model ?? "Android phone"} over ${d.transport}`, name: d.model, serial: d.serial };
112
+ }
113
+ if (mine.some((d) => d.state === "unauthorized")) {
114
+ return { ...base, state: "unauthorized", detail: "a phone is attached but has not allowed this computer", fix: 'on the phone tap "Allow USB debugging" (tick "Always allow from this computer")' };
115
+ }
116
+ if (mine.length)
117
+ return { ...base, state: "offline", detail: `phone ${mine[0].serial} is ${mine[0].state}`, fix: "unplug and replug the cable, or run: adb kill-server" };
118
+ return { ...base, state: "no-device", detail: "no Android phone attached", fix: "Settings > About phone > tap Build number 7 times, then Developer options > USB debugging on, and plug the phone in" };
119
+ }
120
+ /** true when the keyguard is up. Two dumpsys reads, filtered here (no pipes on the phone). */
121
+ async lockState(serial) {
122
+ const r = await deviceDeps().run(this.adb, ["-s", serial, "shell", "dumpsys", "window"], { timeoutMs: T_QUICK });
123
+ return /isKeyguardShowing=true|mDreamingLockscreen=true/.test(r.stdout);
124
+ }
125
+ /** Wake the screen if it is off (harmless), refuse when it is locked. Cached 2 s so a burst of taps checks once. */
126
+ async gate() {
127
+ const d = deviceDeps();
128
+ if (d.now() - this.gateAt < 2000)
129
+ return;
130
+ const power = await this.sh("dumpsys", "power");
131
+ if (!/mWakefulness=Awake/.test(power.stdout)) {
132
+ await this.sh("input", "keyevent", "KEYCODE_WAKEUP");
133
+ await d.sleep(500);
134
+ }
135
+ const win = await this.sh("dumpsys", "window");
136
+ if (/isKeyguardShowing=true/.test(win.stdout))
137
+ throw new NeedsOwner("the Android phone is locked", "unlock it (PIN or fingerprint); Operator never types a PIN");
138
+ this.gateAt = d.now();
139
+ }
140
+ async ensure() {
141
+ const s = await this.status();
142
+ if (s.state !== "ready")
143
+ throw new NeedsOwner(s.detail, s.fix);
144
+ }
145
+ async screenshot() {
146
+ await this.ensure();
147
+ const r = await this.must(["exec-out", "screencap", "-p"], T_SHOT);
148
+ const size = pngSize(r.bytes);
149
+ if (!size)
150
+ throw new Error("screencap returned no PNG (the screen may be protected: DRM video and some banking apps capture black)");
151
+ const path = await deviceDeps().tempFile("android", "png");
152
+ await deviceDeps().writeFile(path, r.bytes);
153
+ return { path, ...size };
154
+ }
155
+ async read() {
156
+ await this.gate();
157
+ const r = await this.raw(["exec-out", "uiautomator", "dump", "/dev/tty"], T_TREE);
158
+ const xml = r.stdout.slice(Math.max(0, r.stdout.indexOf("<?xml")));
159
+ if (r.code !== 0 || !xml.startsWith("<?xml")) {
160
+ const why = (r.stdout || r.stderr).trim();
161
+ return { source: "none", items: [], note: /idle/.test(why) ? "the accessibility tree is not available on this screen (it never goes idle: video, animation)" : `uiautomator: ${why.slice(0, 200) || "no tree"}` };
162
+ }
163
+ return { source: "accessibility", items: parseTree(xml) };
164
+ }
165
+ async tap(x, y) {
166
+ await this.gate();
167
+ await this.sh("input", "tap", String(Math.round(x)), String(Math.round(y)));
168
+ }
169
+ async swipe(from, to, _shot, durationMs) {
170
+ await this.gate();
171
+ const n = (v) => String(Math.round(v));
172
+ await this.sh("input", "swipe", n(from.x), n(from.y), n(to.x), n(to.y), n(Math.min(Math.max(durationMs, 50), 5000)));
173
+ }
174
+ /** `input text` takes one token: spaces become %s, a newline is ENTER, and the rest is quoted for the phone's sh. */
175
+ async type(text) {
176
+ await this.gate();
177
+ const lines = text.split("\n");
178
+ for (let i = 0; i < lines.length; i++) {
179
+ if (i)
180
+ await this.sh("input", "keyevent", "KEYCODE_ENTER");
181
+ const line = lines[i];
182
+ if (/[^\x20-\x7e]/.test(line))
183
+ throw new Unsupported("adb `input text` types ASCII only; this text has characters it cannot send (emoji, accents)");
184
+ for (let at = 0; at < line.length; at += 200) {
185
+ const chunk = line.slice(at, at + 200).replace(/ /g, "%s"); // a literal "%s" in the text also arrives as a space (an `input text` limit)
186
+ if (chunk)
187
+ await this.sh("input", "text", devQuote(chunk));
188
+ }
189
+ }
190
+ }
191
+ async key(key) {
192
+ const code = KEYCODES[key];
193
+ if (!code)
194
+ throw new Unsupported(`Android has no key named ${key}`);
195
+ if (key !== "power")
196
+ await this.gate();
197
+ await this.sh("input", "keyevent", `KEYCODE_${code}`);
198
+ }
199
+ async packages(all = true) {
200
+ const r = await this.sh("pm", "list", "packages", ...(all ? [] : ["-3"]));
201
+ return r.stdout.split(/\r?\n/).filter((l) => l.startsWith("package:")).map((l) => l.slice(8).trim()).sort();
202
+ }
203
+ /** A package id, or the name a person would say: an installed id, a well-known app, then a fragment of an id. */
204
+ async openApp(name) {
205
+ await this.gate();
206
+ const pkgs = await this.packages();
207
+ const want = name.toLowerCase().replace(/[^a-z0-9]+/g, "");
208
+ let pkg = pkgs.includes(name) ? name : (APP_IDS[want] ?? []).find((p) => pkgs.includes(p));
209
+ if (!pkg && want)
210
+ pkg = pkgs.filter((p) => p.toLowerCase().replace(/\./g, "").includes(want)).sort((a, b) => a.length - b.length)[0];
211
+ if (!pkg || !PACKAGE.test(pkg)) {
212
+ const third = await this.packages(false).catch(() => []);
213
+ throw new Error(`no installed app matches "${name}". Installed apps: ${third.slice(0, 40).join(", ") || "none"}. Pass one of these package ids.`);
214
+ }
215
+ const res = await this.sh("cmd", "package", "resolve-activity", "--brief", "-c", "android.intent.category.LAUNCHER", pkg);
216
+ const comp = res.stdout.split(/\r?\n/).reverse().map((l) => l.trim()).find((l) => l.includes("/"));
217
+ if (!comp || !/^[\w.]+\/[\w.$]+$/.test(comp))
218
+ throw new Error(`${pkg} has no launchable activity`);
219
+ await this.sh("am", "start", "-W", "-n", comp);
220
+ return pkg;
221
+ }
222
+ async currentApp() {
223
+ const r = await this.sh("dumpsys", "activity", "activities");
224
+ const m = /topResumedActivity=ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(r.stdout) ?? /mResumedActivity: ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(r.stdout);
225
+ return m?.[1];
226
+ }
227
+ }