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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +159 -0
  6. package/dist/autonomy/delegate.js +42 -15
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +13 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +336 -45
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/resume.js +125 -0
  18. package/dist/background/synthesis.js +25 -0
  19. package/dist/browser/engine.js +163 -0
  20. package/dist/browser/session.js +130 -140
  21. package/dist/bus/inbox.js +150 -6
  22. package/dist/cli.js +343 -86
  23. package/dist/config/features.js +3 -3
  24. package/dist/config/persona.js +29 -3
  25. package/dist/config/settings.js +262 -21
  26. package/dist/config/staff-prompt.js +12 -0
  27. package/dist/engine/agent.js +52 -41
  28. package/dist/engine/aurora.js +40 -8
  29. package/dist/engine/batch-scheduler.js +4 -13
  30. package/dist/engine/compaction.js +2 -2
  31. package/dist/engine/continuation.js +30 -32
  32. package/dist/engine/decision-points.js +2 -3
  33. package/dist/engine/fanout.js +16 -0
  34. package/dist/engine/loop-guard.js +26 -83
  35. package/dist/engine/messages.js +2 -2
  36. package/dist/engine/moa.js +18 -2
  37. package/dist/engine/native-vision-node.js +72 -0
  38. package/dist/engine/native-vision.js +103 -0
  39. package/dist/engine/selfheal.js +1 -1
  40. package/dist/engine/toolcalls.js +6 -6
  41. package/dist/engine/verify-gate.js +37 -7
  42. package/dist/gateway-cli.js +14 -3
  43. package/dist/index.js +3 -0
  44. package/dist/mcp/phone-server.js +30 -0
  45. package/dist/memory/live-progress.js +4 -5
  46. package/dist/moa/codeact-lane.js +98 -0
  47. package/dist/moa/codeact-sandbox.js +409 -0
  48. package/dist/moa/codeact.js +140 -0
  49. package/dist/permissions/artifact-visibility.js +10 -0
  50. package/dist/permissions/index.js +33 -17
  51. package/dist/permissions/signature.js +5 -0
  52. package/dist/permissions/tier.js +4 -2
  53. package/dist/phone-cli.js +65 -0
  54. package/dist/products/craft.js +2 -2
  55. package/dist/remote/grants.js +119 -0
  56. package/dist/remote/host.js +63 -6
  57. package/dist/router/models.js +29 -29
  58. package/dist/selfimprove/index.js +9 -7
  59. package/dist/services/preflight.js +35 -91
  60. package/dist/session.js +173 -46
  61. package/dist/skills/install-guard.js +68 -0
  62. package/dist/skills/install.js +67 -0
  63. package/dist/toolchain/manifest.json +13 -13
  64. package/dist/tools/background-result.js +1 -1
  65. package/dist/tools/classes.js +103 -0
  66. package/dist/tools/contract.js +1 -1
  67. package/dist/tools/craft.js +13 -2
  68. package/dist/tools/deferred.js +1 -0
  69. package/dist/tools/device/android.js +227 -0
  70. package/dist/tools/device/classify.js +127 -0
  71. package/dist/tools/device/deps.js +69 -0
  72. package/dist/tools/device/desktop.js +82 -0
  73. package/dist/tools/device/harness.js +262 -0
  74. package/dist/tools/device/iphone.js +206 -0
  75. package/dist/tools/device/mirroring-jxa.js +146 -0
  76. package/dist/tools/device/setup.js +90 -0
  77. package/dist/tools/device/tools.js +70 -0
  78. package/dist/tools/device/types.js +19 -0
  79. package/dist/tools/executor.js +25 -15
  80. package/dist/tools/generation-gateway.js +94 -0
  81. package/dist/tools/registry.js +95 -155
  82. package/dist/ui/App.js +18 -6
  83. package/dist/ui/ApprovalPrompt.js +10 -4
  84. package/dist/ui/BgPanel.js +17 -12
  85. package/dist/ui/Header.js +1 -6
  86. package/dist/ui/StatusRule.js +18 -7
  87. package/dist/ui/ToolStep.js +3 -3
  88. package/dist/ui/Transcript.js +36 -14
  89. package/dist/ui/UpdatePrompt.js +40 -0
  90. package/dist/ui/batchLine.js +4 -4
  91. package/dist/ui/editdiff.js +2 -4
  92. package/dist/ui/format.js +4 -20
  93. package/dist/ui/liveTools.js +3 -3
  94. package/dist/ui/modelPicker.js +1 -1
  95. package/dist/ui/opsMode.js +20 -0
  96. package/dist/ui/slashCommands.js +1 -0
  97. package/dist/ui/types.js +0 -2
  98. package/dist/update-check.js +145 -0
  99. package/dist/update.js +59 -15
  100. package/dist/util/slash.js +2 -2
  101. package/package.json +4 -2
  102. package/src/tools/device/NOTICE +37 -0
  103. package/dist/browser/cdp.js +0 -271
  104. package/dist/tools/mutating.js +0 -15
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "schema": "operator.toolchain/1",
3
- "serial": 1,
3
+ "serial": 2,
4
4
  "expires": "2026-12-18",
5
5
  "targets": ["darwin-arm64"],
6
6
  "hosts": ["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com", "nodejs.org", "registry.npmjs.org",
7
7
  "ffmpeg.martin-riedl.de", "cdn.playwright.dev", "storage.googleapis.com", "huggingface.co", "*.hf.co"],
8
- "rollout": {"llamacpp-metal": {"target": "11669", "until": "2026-11-06"}},
8
+ "rollout": {"llamacpp-metal": {"target": "12242", "until": "2026-12-08"}},
9
9
  "exceptions": [
10
10
  {"box": "jl1", "match": "--port 8668", "owner": "Ghost", "until": "2026-11-10",
11
11
  "reason": "ghost1-v2-final: unmanaged Homebrew b11429 on 0.0.0.0, not in the portal registry"}
@@ -16,27 +16,27 @@
16
16
  },
17
17
  "packages": {
18
18
  "llamacpp-metal": {
19
- "version": "11669",
20
- "artifacts": {"darwin-arm64": [{"url": "https://github.com/ggml-org/llama.cpp/releases/download/b11669/llama-b11669-bin-macos-arm64.tar.gz",
21
- "sha256": "dbed55493d72bc1ba2babc8770d669c2289b5bc4ee9fb2a4dfc158d45b7d13fd", "size": 12191582, "role": "payload"}]},
22
- "entry": "llamacpp-metal-11669-darwin-arm64",
23
- "layout": {"format": "tar.gz", "strip": 1, "root": "llama-b11669"},
24
- "tree": "sha256:688c0dedae94cc60e64867d7ec1624c0099c88a1067e34cf3a1a98d22f729b76",
19
+ "version": "12242",
20
+ "artifacts": {"darwin-arm64": [{"url": "https://github.com/ggml-org/llama.cpp/releases/download/b12242/llama-b12242-bin-macos-arm64.tar.gz",
21
+ "sha256": "d58f23da84befb84b7d07590e7fd18ea68a3f1df59f9808b52370255aa60f20b", "size": 16743054, "role": "payload"}]},
22
+ "entry": "llamacpp-metal-12242-darwin-arm64",
23
+ "layout": {"format": "tar.gz", "strip": 1, "root": "llama-b12242"},
24
+ "tree": "sha256:afd1c636d915b79410306ce45936f26b6dd5167ac1ccd55a8c6794498859a79f",
25
25
  "provides": {"llama-server": "llama-server", "llama-cli": "llama-cli", "llama-bench": "llama-bench"},
26
26
  "env": {},
27
- "probe": {"bin": "llama-server", "args": ["--version"], "expect": "(build 11669, commit 620d2225c)"},
27
+ "probe": {"bin": "llama-server", "args": ["--version"], "expect": "(build 12242, commit 3b4d6ab3f)"},
28
28
  "codesign": {"expect": "adhoc"},
29
29
  "relocatable": true,
30
- "provenance": {"hash_source": "github-asset-digest", "verified": "2026-11-03", "published_at": "2026-10-15T16:10:46Z",
31
- "commit": "620d2225cc436ab0b001e3200e590e3b286ef9ab",
30
+ "provenance": {"hash_source": "github-asset-digest", "verified": "2026-11-24", "published_at": "2026-11-10T02:01:21Z",
31
+ "commit": "3b4d6ab3f79651935fba1dd93732f29022a7f5f5",
32
32
  "attest": {"repo": "ggml-org/llama.cpp", "signer_workflow": "ggml-org/llama.cpp/.github/workflows/release-publish.yml",
33
- "source_digest": "620d2225cc436ab0b001e3200e590e3b286ef9ab"}},
33
+ "source_digest": "3b4d6ab3f79651935fba1dd93732f29022a7f5f5"}},
34
34
  "license": {"spdx": "MIT", "evidence": "LICENSE in archive", "redistribute": "yes"},
35
35
  "install": "default",
36
36
  "consumers": ["aurora", "portal", "arena"],
37
37
  "previous": {
38
38
  "version": "10964",
39
- "until": "2026-11-17",
39
+ "until": "2026-12-08",
40
40
  "artifacts": {"darwin-arm64": [{"url": "https://github.com/ggml-org/llama.cpp/releases/download/b10964/llama-b10964-bin-macos-arm64.tar.gz",
41
41
  "sha256": "033c845c1df9bf945ff37bb193238b40910b2244be3e1e637b2ceb5878f1a6f5", "size": 11149739,
42
42
  "role": "payload"}]},
@@ -1,6 +1,6 @@
1
1
  // How a shell result says its command went to a background job, and how bash_output says that job ended. One definition
2
2
  // for the tool layer that writes the text (registry.ts) and the engine that reads it (verify-gate.ts): on 11/24 the gate
3
- // knew only the first prefix, so an auto-backgrounded `npm test` counted as a passed check. Dependency-free leaf, like mutating.ts.
3
+ // knew only the first prefix, so an auto-backgrounded `npm test` counted as a passed check. Dependency-free leaf, like classes.ts.
4
4
  export const MOVED_TO_BACKGROUND = "moved to background as ";
5
5
  export const AUTO_BACKGROUNDED = "[auto-backgrounded: ";
6
6
  export const STARTED_BACKGROUND_JOB = "started background job ";
@@ -0,0 +1,103 @@
1
+ const set = (...groups) => new Set(groups.flatMap((g) => (typeof g === "string" ? [g] : [...g])));
2
+ // ── Shell ─────────────────────────────────────────────────────────────────────────────────────────────────
3
+ /** Foreground shells: the turn waits on the command. They may overlap in one round (batch-scheduler), switch to
4
+ * one-shot shells when two share a round (executor), count as a verification run (verify-gate), offer ctrl+b to
5
+ * background a slow one (liveTools), and poll-style commands in them are legitimate repeats (loop-guard). */
6
+ export const SHELL_FOREGROUND = set("bash", "shell_exec");
7
+ /** Every tool that runs a shell command the call supplies in `command`, foreground or not: shown as `$ command`,
8
+ * counted as a command, and read for mutating commands by the decision-point and delegate guards. */
9
+ export const SHELL_ANY = set(SHELL_FOREGROUND, "shell_background", "shell_task_start");
10
+ /** Command tools whose optional `cwd` defaults to a rooted executor's root. */
11
+ export const CWD_DEFAULTED = set("bash", "shell_exec", "shell_background", "git_command", "git_status");
12
+ /** Tools that take an optional `workspace` and otherwise fall back to process.cwd(): a rooted session defaults it to its root. */
13
+ export const WORKSPACE_DEFAULTED = set("checkpoint");
14
+ /** Search tools whose omitted `path` means "the current dir": a rooted call searches its root. find_files is left out on
15
+ * purpose: its default is the whole home index. */
16
+ export const DIR_DEFAULTED = set("search", "grep_search", "glob", "list_directory", "code_search", "codebase_search");
17
+ // ── Files ─────────────────────────────────────────────────────────────────────────────────────────────────
18
+ /** Tools that create, change or delete files in the workspace. A landed one resets the loop-guard counts, arms
19
+ * verify-before-done, zeroes the no-edit streak and is the first change the decision point holds back. */
20
+ export const FILE_WRITE = set("file_write", "file_edit", "file_create", "file_delete");
21
+ /** Reads of named files (`path`, or `paths` for read_files). */
22
+ export const FILE_READ = set("file_read", "read_files");
23
+ /** Single-file reads whose `path` arg is the file read (the stale-reread tracker). */
24
+ export const PATH_READ = set("file_read", "image_inspect");
25
+ // ── Lookups ───────────────────────────────────────────────────────────────────────────────────────────────
26
+ /** Searches over local code, files, memory and sessions. */
27
+ export const LOCAL_SEARCH = set("grep_search", "search", "code_search", "codebase_search", "find_files", "glob", "knowledge_search", "memory_search", "session_search");
28
+ export const WEB_SEARCH = set("web_search", "deep_research");
29
+ export const WEB_FETCH = set("web_fetch", "browser", "browser_read", "http_request");
30
+ /** Everything that only looks something up: the "reads" a sub-agent's activity counters add up. */
31
+ export const LOOKUP = set(FILE_READ, "list_directory", LOCAL_SEARCH, WEB_SEARCH, WEB_FETCH);
32
+ /** Read-only tools: the same call returning the same result again is no new information. */
33
+ export const IDEMPOTENT = set("file_read", "read_files", "search", "grep_search", "list_directory", "find_files", "locate", "web_search", "web_fetch", "git_status", "memory_search", "session_search", "session_read", "skill_catalog", "skill_fetch", "skill_list");
34
+ // ── Plan, agents, polling ─────────────────────────────────────────────────────────────────────────────────
35
+ export const PLAN_TOOLS = set("task_add", "task_update", "task_list", "task_clear");
36
+ /** The plan calls that change the plan. */
37
+ export const PLAN_WRITE = set("task_add", "task_update", "task_clear");
38
+ /** Every hand-off of work to another agent. */
39
+ export const DELEGATION = set("spawn_agent", "delegate_task", "delegate_to_agent");
40
+ /** Operator sub-agents, counted against the per-turn sub-agent cap. */
41
+ export const SUBAGENT_SPAWN = set("delegate_task", "spawn_agent");
42
+ /** A dispatch that leaves sub-agents running after it returns (delegate_* block until the child is done). */
43
+ export const DISPATCH = set("spawn_agent");
44
+ /** Calls that only book-keep around a dispatch (the plan pane, the agent panel). */
45
+ export const DISPATCH_BOOKKEEPING = set(PLAN_TOOLS, "agent_status", "message_agent");
46
+ /** Supervising is progress: stopping a sub-agent or asking the owner never counts as idling. */
47
+ export const SUPERVISION = set("stop_agent", "ask_user");
48
+ /** Pollers: re-invoked with identical args while waiting on async work. Never loop-guarded. */
49
+ export const POLLERS = set("agent_status", "bash_output");
50
+ /** Pollers whose answers the engine also posts on its own, so polling them is spin. */
51
+ export const AUTOPOST_POLLERS = set("agent_status");
52
+ /** Status tools: the same facts all turn, so a repeat is refused early. */
53
+ export const STATUS_TOOLS = set("self_status");
54
+ // ── Loop guard ────────────────────────────────────────────────────────────────────────────────────────────
55
+ /** A successful call to one of these is progress: failing calls still counted are retried as new experiments. */
56
+ export const PROGRESS = set(FILE_WRITE, "bash", "shell_exec", "shell_background", "git_command", "delegate_task", "spawn_agent", "email_send", "cronjob", PLAN_WRITE, "memory_store", "checkpoint", "http_request", "browser", "chauffeur");
57
+ /** Tools whose "failure" is normal work output (a red test run, an empty page): a run of different failing calls
58
+ * is diagnosis, so the same-tool failure run only warns for them. */
59
+ export const FAILURE_TOLERANT = set("bash", "shell_exec", "shell_background", "bash_output", "browser", "web_fetch", "http_request", "chauffeur");
60
+ /** Write-progress for the investigate-loop detector. Narrower than PROGRESS: a grep inside bash is the pattern that
61
+ * detector exists for, so shells and git_command are out. */
62
+ export const WRITE_PROGRESS = set(FILE_WRITE, "checkpoint", PLAN_WRITE, "memory_store", DELEGATION, "cronjob");
63
+ // ── Scheduling ────────────────────────────────────────────────────────────────────────────────────────────
64
+ /** Calls that run alone in a batch: each can touch anything. delegate_task is a whole sub-agent session with the full
65
+ * tool set, delegate_to_agent an external CLI agent with write and shell access, spawn_cloud_agent a whole agent in a
66
+ * remote container; the app_/computer_ calls drive the desktop. Prefix matches (computer_, browser, shell, mcp__) live
67
+ * in batch-scheduler. */
68
+ export const SCHED_BARRIER = set("shell_background", "bash_kill", "git_command", "checkpoint", "tool_call", "delegate_task", "delegate_to_agent", "spawn_cloud_agent", "app_open", "app_activate", "computer_applescript", "computer_type", "computer_key", "computer_click", "computer_screenshot");
69
+ const FAILED_HEAD = /^(?:error|loop guard|\[interrupted|\[timed out)/i;
70
+ export function toolOutcome(result, refused) {
71
+ if (refused)
72
+ return refused;
73
+ const s = result.trim();
74
+ if (FAILED_HEAD.test(s))
75
+ return "fail";
76
+ const exit = exitCode(s);
77
+ if ((exit !== undefined && exit !== 0) || /^\(no output; exit \?\)/.test(s))
78
+ return "fail";
79
+ if (/\n\[timed out after [^\n]*\]$/.test(s))
80
+ return "fail";
81
+ return "ok";
82
+ }
83
+ /** A shell call's exit code from its result (registry.ts shellExec), or undefined: output then an `[exit N]` line —
84
+ * which shellResultNotes' `[note: …]`/`[hint: …]` lines and the result guard's notes may follow — or, for a command
85
+ * that printed nothing, `(no output; exit N)`. */
86
+ export function exitCode(result) {
87
+ const m = /(?:^|\n)\[exit (\d+)\](?:\n+\[[^\n]*\])*\s*$/.exec(result) ?? /^\s*\(no output; exit (\d+)\)/.exec(result);
88
+ return m ? Number(m[1]) : undefined;
89
+ }
90
+ /** The engine's own words for a call it answered instead of running (a guard, the permission gate, the interrupt).
91
+ * Only for engine code that has the result and no report: the TUI reads refusals from the report, because a command
92
+ * that ran can print the same first words. */
93
+ export const refusedResult = (result) => /^(?:loop guard|repeated action|blocked |permission denied|cancelled|\[interrupted)/i.test(result.trimStart());
94
+ /** The call ran and failed: the loop guard's test. A call the engine answered for never ran, so it is no failure of
95
+ * the tool's; the TUI, which has the report, shows those as blocked or cancelled instead. */
96
+ export const resultFailed = (result) => !refusedResult(result) && toolOutcome(result) === "fail";
97
+ /** The call ran and did not fail. */
98
+ export const ranOk = (result, refused) => !refusedResult(result) && toolOutcome(result, refused) === "ok";
99
+ export const isMutatingTool = (name) => FILE_WRITE.has(name ?? "");
100
+ /** True when a file write actually LANDED. The file tools report failure as a returned `error: …` string, and a
101
+ * gated, guarded or cancelled call never ran, so the name alone proves nothing: a failing edit must not grant a
102
+ * spinning model a fresh loop-guard runway. */
103
+ export const mutationLanded = (name, result, refused) => isMutatingTool(name) && ranOk(result, refused);
@@ -3,7 +3,7 @@
3
3
  // (the tools array is the cached prompt prefix), and `safe` stays authoritative. scripts/tool-catalog.mts
4
4
  // publishes every contract to toolchain/tools/catalog.json; test/tool-contract.test.mts and
5
5
  // test/tool-bins.test.mts hold the gaps to toolchain/tools/baseline.json, whose lists may only shrink.
6
- // A DEPENDENCY-FREE leaf like mutating.ts: registry.ts reaches it from the neutral bundle.
6
+ // A DEPENDENCY-FREE leaf like classes.ts: registry.ts reaches it from the neutral bundle.
7
7
  export const EFFECTS = ["read", "fetch", "state", "write", "egress", "exec", "destructive", "device"];
8
8
  /** What `safe` should mean once contracts drive it: every declared effect is a read. */
9
9
  export const isReadOnly = (c) => c.effects.every((e) => e === "read" || e === "fetch");
@@ -18,18 +18,27 @@ export const CRAFT_TOOLS = [
18
18
  },
19
19
  {
20
20
  name: "craft_update",
21
+ contract: { v: 1, effects: ["egress"], audit: ["id", "visibility"] },
21
22
  description: "Update a craft you own by id — new content, title, or visibility (private | link | public). Optimistic concurrency: pass expected_version (from craft_get) to avoid clobbering a change made since you read it.",
22
23
  parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
23
- id: { type: "string", description: "the craft id (from craft_create / craft_list)" },
24
+ id: { type: "string", description: "the artifact id (from artifact_create / craft_list)" },
24
25
  content: { type: "string", description: "replacement body" },
25
26
  title: { type: "string", description: "new title" },
26
27
  visibility: { type: "string", description: "private | link | public" },
27
28
  expected_version: { type: "string", description: "the version you last read (optimistic concurrency)" },
28
29
  } },
29
- async run(args) { return (await craft()).craftUpdate(args); },
30
+ async run(args) {
31
+ const { artifactVisibility } = await nodeImport("../permissions/artifact-visibility.js");
32
+ const { loadSettings } = await nodeImport("../config/settings.js");
33
+ const vis = artifactVisibility(loadSettings().permissions?.tier, args.visibility, false);
34
+ if ("error" in vis)
35
+ return `error: ${vis.error}`;
36
+ return (await craft()).craftUpdate(args);
37
+ },
30
38
  },
31
39
  {
32
40
  name: "craft_list", safe: true,
41
+ contract: { v: 1, effects: ["fetch"] },
33
42
  description: "List the crafts your account owns (id · type · title · visibility · URL). Read-only.",
34
43
  parameters: { type: "object", additionalProperties: false, properties: {
35
44
  limit: { type: "number", description: "max rows (default 20, max 100)" },
@@ -38,6 +47,7 @@ export const CRAFT_TOOLS = [
38
47
  },
39
48
  {
40
49
  name: "craft_get", safe: true,
50
+ contract: { v: 1, effects: ["fetch"], audit: ["id"] },
41
51
  description: "Fetch one craft by id — its metadata (owner, version, visibility), URL, and current content. Read-only.",
42
52
  parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
43
53
  id: { type: "string", description: "the craft id" },
@@ -46,6 +56,7 @@ export const CRAFT_TOOLS = [
46
56
  },
47
57
  {
48
58
  name: "craft_delete",
59
+ contract: { v: 1, effects: ["destructive", "fetch"], audit: ["id"] },
49
60
  description: "Delete a craft you own by id. Its share link stops working.",
50
61
  parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
51
62
  id: { type: "string", description: "the craft 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
+ }
@@ -0,0 +1,127 @@
1
+ // The phone's human-signature lines: phone.spend (money), phone.send (messages, posts, calls), phone.account (sign-in,
2
+ // password, deleting or changing an account). A call in one of these classes ALWAYS asks the owner — in every mode,
3
+ // Autonomous included (an approved plan does not cover it), and "allow always" never covers it — with a screenshot of
4
+ // the screen it will act on. Pure and node-free: permissions/signature.ts imports it from every bundle.
5
+ //
6
+ // A class is read from what the call says (the element text it taps, the text it types, the key it presses, a declared
7
+ // `intent`) and from what Operator last saw on that device (the app in front, the text under a coordinate tap). Like the
8
+ // other signature lines it is conservative: a false positive costs one approval, a miss costs the owner's money.
9
+ //
10
+ // Belt and braces: the gate grants an approved call once (grantPhone); the tool itself refuses a classed call that holds
11
+ // no grant (takeGrant). A policy that skips the gate (a bypass seat, the MCP server, a headless run) therefore still
12
+ // cannot spend, send or change an account on the owner's phone.
13
+ export const PHONE_LINES = ["phone.spend", "phone.send", "phone.account"];
14
+ export const PHONE_LINE_WHAT = {
15
+ "phone.spend": "money: pay, buy, order, book, subscribe, transfer",
16
+ "phone.send": "messages and calls: send, post, reply, call, share",
17
+ "phone.account": "account changes: sign in or out, passwords, delete or change an account",
18
+ };
19
+ export const PHONE_ACTION_TOOLS = ["phone_tap", "phone_type", "phone_swipe", "phone_key", "phone_open_app"];
20
+ const SPEND = /\b(pay|payment|buy|purchase|order|checkout|check out|place order|book( now| ride)?|subscribe|subscription|upgrade|donate|tip|transfer|send money|request money|top ?up|add to cart|confirm (purchase|payment|order)|apple pay|google pay|wallet|bid)\b|[$€£¥₹]\s?\d/i;
21
+ const SEND = /\b(send|post|publish|reply|reply all|tweet|share|call|dial|facetime|video call|forward|invite|comment|submit|message)\b/i;
22
+ const ACCOUNT = /\b(sign (in|out)|log ?(in|out)|password|passcode|delete (my )?account|close account|deactivate|remove account|reset|erase|factory|two[- ]factor|2fa|verification code|recovery|change (email|phone|number)|authorize|allow access|trust this)\b/i;
23
+ // Apps where a bare coordinate tap is presumed to cross a line (nothing better is known about what is under it).
24
+ const SEND_APPS = /\b(messages|whatsapp|signal|telegram|messenger|mail|gmail|outlook|slack|discord|phone|dialer|facetime|instagram|x|twitter|threads|facebook|linkedin|tiktok|snapchat)\b|com\.(whatsapp|google\.android\.apps\.messaging|google\.android\.gm|google\.android\.dialer|android\.dialer|facebook\.orca|twitter\.android|instagram\.android|slack|discord|snapchat\.android)|org\.thoughtcrime\.securesms|org\.telegram/i;
25
+ const SPEND_APPS = /\b(wallet|app ?store|play ?store|amazon|uber|lyft|doordash|ubereats|venmo|paypal|cash ?app|zelle|revolut|wise|bank|banking|robinhood|coinbase|stripe|shop)\b|com\.(android\.vending|amazon|ubercab|squareup\.cash|venmo|paypal|coinbase|robinhood)/i;
26
+ const ACCOUNT_APPS = /\b(settings|passwords|keychain|authenticator|apple ?id|google account)\b|com\.android\.settings|com\.google\.android\.apps\.authenticator/i;
27
+ const observed = new Map();
28
+ /** The harness records what it last saw on a device: the app in front and the text with its boxes. */
29
+ export function observe(device, o) {
30
+ const prev = observed.get(device) ?? { items: [] };
31
+ observed.set(device, { app: o.app ?? prev.app, items: o.items ?? prev.items });
32
+ }
33
+ export function resetObserved() { observed.clear(); grants.clear(); }
34
+ export const deviceOf = (args) => (typeof args.device === "string" && args.device ? args.device : "default");
35
+ function textUnder(device, x, y) {
36
+ const o = observed.get(device) ?? observed.get("default");
37
+ const hits = (o?.items ?? []).filter((t) => Math.abs(x - t.x) <= Math.max(t.w / 2, 12) && Math.abs(y - t.y) <= Math.max(t.h / 2, 12));
38
+ return hits.sort((a, b) => a.w * a.h - b.w * b.h)[0]?.text;
39
+ }
40
+ function byWords(s) {
41
+ if (SPEND.test(s))
42
+ return "phone.spend";
43
+ if (ACCOUNT.test(s))
44
+ return "phone.account";
45
+ if (SEND.test(s))
46
+ return "phone.send";
47
+ return null;
48
+ }
49
+ function byApp(app) {
50
+ if (!app)
51
+ return null;
52
+ if (SPEND_APPS.test(app))
53
+ return "phone.spend";
54
+ if (ACCOUNT_APPS.test(app))
55
+ return "phone.account";
56
+ if (SEND_APPS.test(app))
57
+ return "phone.send";
58
+ return null;
59
+ }
60
+ /** Which phone line a call crosses, or null. Reads only the call and what was last observed. */
61
+ export function phoneLine(name, args) {
62
+ if (!PHONE_ACTION_TOOLS.includes(name))
63
+ return null;
64
+ const intent = typeof args.intent === "string" ? args.intent.toLowerCase() : "";
65
+ const declared = PHONE_LINES.find((l) => intent === l || intent === l.slice(6));
66
+ if (declared)
67
+ return declared;
68
+ const device = deviceOf(args);
69
+ const app = observed.get(device)?.app ?? observed.get("default")?.app;
70
+ switch (name) {
71
+ case "phone_tap": {
72
+ if (typeof args.text === "string" && args.text.trim())
73
+ return byWords(args.text) ?? null;
74
+ const x = Number(args.x), y = Number(args.y);
75
+ const under = Number.isFinite(x) && Number.isFinite(y) ? textUnder(device, x, y) : undefined;
76
+ if (under)
77
+ return byWords(under);
78
+ return byApp(app); // a blind tap: what it hits is unknown, so the app decides
79
+ }
80
+ case "phone_type": {
81
+ const text = typeof args.text === "string" ? args.text : "";
82
+ if (/\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{1,4}\b/.test(text))
83
+ return "phone.spend"; // a card number
84
+ if (args.submit === true)
85
+ return byWords(text) ?? byApp(app);
86
+ return byApp(app) === "phone.account" ? "phone.account" : null; // typing into Settings / a password field
87
+ }
88
+ case "phone_key":
89
+ return args.key === "enter" ? byApp(app) : null; // Return sends in a messaging app and confirms elsewhere
90
+ case "phone_swipe":
91
+ return typeof args.text === "string" ? byWords(args.text) : null; // slide-to-pay / slide-to-confirm, when named
92
+ case "phone_open_app":
93
+ return null; // opening an app changes nothing; what is done inside it is classed call by call
94
+ }
95
+ return null;
96
+ }
97
+ // ── One-shot grants: the gate approves, the tool consumes ────────────────────────────────────────────────────────
98
+ const grants = new Map();
99
+ const keyOf = (name, args) => {
100
+ const { intent: _i, ...rest } = args;
101
+ return `${name}\0${JSON.stringify(Object.keys(rest).sort().map((k) => [k, rest[k]]))}`;
102
+ };
103
+ const GRANT_TTL_MS = 120_000;
104
+ /** The owner approved exactly this call (name + args) for one run. */
105
+ export function grantPhone(name, args, now = Date.now()) {
106
+ grants.set(keyOf(name, args), now + GRANT_TTL_MS);
107
+ }
108
+ /** Consume the grant for this call; false when there is none (or it expired). */
109
+ export function takeGrant(name, args, now = Date.now()) {
110
+ const k = keyOf(name, args);
111
+ const until = grants.get(k);
112
+ grants.delete(k);
113
+ return until !== undefined && until >= now;
114
+ }
115
+ let previewFn = null;
116
+ export function setPhonePreview(fn) { previewFn = fn; }
117
+ /** A fresh screenshot of the screen the call will act on, and what it will touch. Never throws. */
118
+ export async function phonePreview(name, args) {
119
+ if (!previewFn)
120
+ return {};
121
+ try {
122
+ return await previewFn(name, args);
123
+ }
124
+ catch (e) {
125
+ return { error: e instanceof Error ? e.message : String(e) };
126
+ }
127
+ }