@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
@@ -0,0 +1,103 @@
1
+ /** What goes on the wire for an attached image. 1568 px keeps a screenshot's text legible; a file heavier than
2
+ * `maxBytes` at that size is re-encoded as JPEG. At most `maxImages` per message. `keepBlank`: a flat picture is still
3
+ * the owner's picture, so the tool's "image is blank" refusal does not apply. */
4
+ export const NATIVE_IMAGE_LIMITS = { maxEdge: 1568, maxBytes: 1_500_000, maxImages: 4, keepBlank: true };
5
+ // ── capability ────────────────────────────────────────────────────────────────────────────────────────────
6
+ /** llama.cpp `GET /props`: `modalities.vision` is true only when the server was started with a multimodal projector. */
7
+ export function visionFromProps(props) {
8
+ const v = props?.modalities?.vision;
9
+ return typeof v === "boolean" ? (v ? "yes" : "no") : "unknown";
10
+ }
11
+ /** A model row from `GET /v1/models/<id>` on a gateway or vendor. Understands the shapes in use (`modalities.vision`,
12
+ * `capabilities.vision`, `vision`, `input_modalities`/`architecture.input_modalities` listing "image"); anything
13
+ * else is unknown, never a guess. */
14
+ export function visionFromModelRow(row) {
15
+ const r = row;
16
+ if (!r || typeof r !== "object")
17
+ return "unknown";
18
+ for (const v of [r.modalities?.vision, r.capabilities?.vision, r.vision])
19
+ if (typeof v === "boolean")
20
+ return v ? "yes" : "no";
21
+ const list = r.input_modalities ?? r.architecture?.input_modalities;
22
+ if (Array.isArray(list))
23
+ return list.includes("image") ? "yes" : "no";
24
+ return "unknown";
25
+ }
26
+ const SUPPORT_TTL_MS = 10 * 60_000;
27
+ const support = new Map();
28
+ const supportKey = (base, model) => `${base.replace(/\/+$/, "").replace(/\/v1$/, "")}|${model}`;
29
+ async function getJson(url, timeoutMs, f) {
30
+ try {
31
+ const r = await f(url, { signal: AbortSignal.timeout(timeoutMs) });
32
+ return r.ok ? await r.json() : null;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ /** Whether the endpoint serves a model that takes images. llama.cpp's own `/props` first, then the model's row on a
39
+ * gateway; "unknown" when neither says. Cached per endpoint and model (10 minutes); a rejected image flips it to "no". */
40
+ export async function detectVision(base, model, opts = {}) {
41
+ const key = supportKey(base, model);
42
+ const now = opts.now ?? Date.now();
43
+ const hit = support.get(key);
44
+ if (hit && now - hit.at < SUPPORT_TTL_MS)
45
+ return hit.v;
46
+ const f = opts.fetchImpl ?? fetch;
47
+ const timeoutMs = opts.timeoutMs ?? 1500;
48
+ const bare = key.split("|")[0];
49
+ let v = visionFromProps(await getJson(`${bare}/props`, timeoutMs, f));
50
+ if (v === "unknown")
51
+ v = visionFromModelRow(await getJson(`${bare}/v1/models/${encodeURIComponent(model)}`, timeoutMs, f));
52
+ support.set(key, { v, at: now });
53
+ return v;
54
+ }
55
+ /** The server turned an image down: remember it, so the rest of the session sends no more. */
56
+ export function markVisionRejected(base, model) {
57
+ support.set(supportKey(base, model), { v: "no", at: Date.now() });
58
+ }
59
+ export function resetVisionCache() { support.clear(); }
60
+ /** The error an endpoint raises for an image it cannot take (llama.cpp without a projector: "image input is not
61
+ * supported"; vendors: "does not support image"/"multimodal"). Only a client or server error that names it. */
62
+ const IMAGE_REJECT_RE = /\bimage(?:_url|s)?\b.*\b(?:not supported|unsupported|not support|invalid|cannot|can't|does not|doesn't)\b|\b(?:not supported|unsupported|does not support|doesn't support)\b.*\b(?:image|multimodal|vision)|\bmmproj\b|\bmultimodal\b/i;
63
+ export function imageRejected(err) {
64
+ const status = err?.status;
65
+ if (typeof status !== "number" || status < 400)
66
+ return false;
67
+ return IMAGE_REJECT_RE.test(err instanceof Error ? err.message : String(err));
68
+ }
69
+ // ── message construction ──────────────────────────────────────────────────────────────────────────────────
70
+ const SEEN_NOTE = "[The image(s) above are attached to this message and you can see them directly: describe or read them from the picture, with no image_analyze call.]";
71
+ /** The request's messages with each message's `images` turned into image_url parts after its text. An image that
72
+ * cannot be encoded is left out (its path is still in the text). `images` itself never reaches the wire. */
73
+ export async function toWireMessages(messages, encode) {
74
+ const out = [];
75
+ for (const m of messages) {
76
+ const { images, ...rest } = m;
77
+ if (!images?.length) {
78
+ out.push(rest);
79
+ continue;
80
+ }
81
+ const parts = [];
82
+ for (const p of images) {
83
+ const url = await encode(p);
84
+ if (url)
85
+ parts.push({ type: "image_url", image_url: { url } });
86
+ }
87
+ out.push(parts.length ? { ...rest, content: [{ type: "text", text: `${m.content}\n\n${SEEN_NOTE}` }, ...parts] } : rest);
88
+ }
89
+ return out;
90
+ }
91
+ /** The conversation with every message's images taken back off: the owner's text gains a line pointing at each file,
92
+ * so the model can still look at it with image_analyze. Returns how many images were taken off. */
93
+ export function withoutImages(messages) {
94
+ let removed = 0;
95
+ const out = messages.map((m) => {
96
+ if (!m.images?.length)
97
+ return m;
98
+ removed += m.images.length;
99
+ const { images, ...rest } = m;
100
+ return { ...rest, content: `${m.content}\n\n[Attached image${images.length > 1 ? "s" : ""} not sent to the model directly: ${images.join(", ")}. Look at ${images.length > 1 ? "them" : "it"} with image_analyze.]` };
101
+ });
102
+ return { messages: out, removed };
103
+ }
@@ -37,7 +37,7 @@ export function servedContextLimit(err) {
37
37
  return Number.isFinite(n) && n > 0 ? n : undefined;
38
38
  }
39
39
  // A 400 whose body states the endpoint's OUTPUT ceiling: the request's max_tokens is larger than the vendor
40
- // accepts (JL2 2026-10-28, QwenCloud qwen3.8-flash: "Range of max_tokens should be [1, 131072]" while we sent
40
+ // accepts (JL2 2026-10-28, a BYO cloud provider: "Range of max_tokens should be [1, 131072]" while we sent
41
41
  // ~220K). Not a context problem — compacting or failing over can't help — so it gets its own class: retry the
42
42
  // round ONCE at the stated ceiling and remember it for the endpoint. Each pattern captures the ceiling; they
43
43
  // all name max_tokens or output/completion tokens, so a context-length 400 ("maximum context length is N
@@ -33,8 +33,8 @@ function toArgumentsString(v) {
33
33
  return "{}";
34
34
  return typeof raw === "string" ? raw : JSON.stringify(raw);
35
35
  }
36
- /** Parse Qwen XML: <function=NAME><parameter=P>V</parameter>...</function> from inside a <tool_call> body. */
37
- function parseQwenXmlFunction(body) {
36
+ /** Parse the XML function-call format: <function=NAME><parameter=P>V</parameter>...</function> from inside a <tool_call> body. */
37
+ function parseXmlFunctionCall(body) {
38
38
  const fnMatch = /<function=([^>]+)>([\s\S]*?)<\/function>/.exec(body);
39
39
  if (!fnMatch)
40
40
  return null;
@@ -128,7 +128,7 @@ export function recoverToolCalls(content) {
128
128
  const calls = [];
129
129
  let remaining = "";
130
130
  let cursor = 0;
131
- // Pass 1: <tool_call>...</tool_call> — try JSON first, then Qwen XML.
131
+ // Pass 1: <tool_call>...</tool_call> — try JSON first, then the XML function-call format.
132
132
  const tagRe = /<tool_call>([\s\S]*?)<\/tool_call>/g;
133
133
  let m;
134
134
  while ((m = tagRe.exec(content))) {
@@ -144,7 +144,7 @@ export function recoverToolCalls(content) {
144
144
  }
145
145
  }
146
146
  catch {
147
- const xml = parseQwenXmlFunction(body);
147
+ const xml = parseXmlFunctionCall(body);
148
148
  if (xml) {
149
149
  calls.push(buildToolCall(xml.name, xml.args));
150
150
  recognized = true;
@@ -154,13 +154,13 @@ export function recoverToolCalls(content) {
154
154
  remaining += m[0]; // unrecognized — leave it visible rather than silently eating it
155
155
  }
156
156
  remaining += content.slice(cursor);
157
- // Pass 1b: a Qwen XML <function=NAME>...</function> whose <tool_call> opener went missing (the opener can land in
157
+ // Pass 1b: an XML <function=NAME>...</function> whose <tool_call> opener went missing (the opener can land in
158
158
  // the reasoning channel while the rest streams as content).
159
159
  const bareFn = /<function=([^>]+)>([\s\S]*?)<\/function>/g;
160
160
  let bare = "";
161
161
  let bareCursor = 0;
162
162
  while ((m = bareFn.exec(remaining))) {
163
- const xml = parseQwenXmlFunction(m[0]);
163
+ const xml = parseXmlFunctionCall(m[0]);
164
164
  if (!xml)
165
165
  continue;
166
166
  bare += remaining.slice(bareCursor, m.index);
@@ -156,9 +156,20 @@ export function isStrongVerifyCmd(cmd) {
156
156
  export function reportedChecks(text) {
157
157
  return REPORTED.filter(([, re]) => re.test(text)).map(([k]) => k);
158
158
  }
159
- import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts)
159
+ import { FILE_WRITE, SHELL_FOREGROUND } from "../tools/classes.js";
160
160
  import { backgroundJobId, finishedJob, stillInBackground } from "../tools/background-result.js";
161
- const VERIFY_TOOLS = new Set(["bash", "shell_exec"]);
161
+ // A prose / document deliverable (markdown, a report, plain text) is verified by a CONTENT or DOC check,
162
+ // never a code test/build — so a research write-up must not read as "not verified" just because no test ran.
163
+ const PROSE_EXT_RE = /\.(?:md|markdown|mdx|mdc|txt|text|rst|adoc|asciidoc)$/i;
164
+ /** A content check of a written file — read it back (wc/cat/head/tail/sed -n/grep) or lint the prose
165
+ * (markdownlint, markdown-link-check, vale, …). This is what verifies a document deliverable. */
166
+ function isContentCheckCmd(cmd) {
167
+ if (!cmd || /\$\(|`/.test(cmd))
168
+ return false;
169
+ return /(?:^|\|\||&&|[;|]\s*)\s*(?:wc|cat|head|tail|less|more|nl|bat|fold|markdownlint|markdownlint-cli2|markdown-link-check|lychee|vale|mdl|textlint|cspell)\b/.test(cmd) ||
170
+ /(?:^|\|\||&&|[;|]\s*)\s*sed\s+-n\b/.test(cmd) ||
171
+ /(?:^|\|\||&&|[;|]\s*)\s*grep\b[^|]*\.(?:md|txt|markdown|rst)\b/i.test(cmd);
172
+ }
162
173
  /** Turn-local ledger. The loop calls observe() after each tool batch, then gate() at the done-exit.
163
174
  * Turn-scoped (one runTurn = one task): a verify from an earlier turn must not satisfy this turn's new
164
175
  * changes — the same reason grandmaster re-derives `verified` per result and never trusts prior state. */
@@ -166,6 +177,8 @@ export class TaskVerification {
166
177
  mutated = false;
167
178
  verified = false;
168
179
  verifiedStrong = false; // a STRONG verify ran+passed (test/build/typecheck/run) — the enforced-gate signal
180
+ codeMutated = false; // a NON-prose (code/config) file changed → a real test/build is the verify
181
+ contentChecked = false; // a content/doc check ran (read the file back, or a prose linter) — verifies a doc deliverable
169
182
  ran = new Set(); // run at all this turn: a piped `tsc | head` exits 0 whatever it found
170
183
  latest = new Map(); // each check's LAST result this turn: null = it passed
171
184
  background = new Map(); // job id → the check it runs, started after the last change, result unread
@@ -176,12 +189,16 @@ export class TaskVerification {
176
189
  const name = names[i];
177
190
  let res = results[i] ?? "";
178
191
  let cmd = (commands[i] ?? "").trim();
179
- let shell = VERIFY_TOOLS.has(name);
192
+ let shell = SHELL_FOREGROUND.has(name);
180
193
  // a change makes every earlier check stale, a job started before it included: only a check that runs after the last change verifies it
181
- if (MUTATING_TOOLS.has(name) && !/^error/i.test(res.trim())) {
194
+ if (FILE_WRITE.has(name) && !/^error/i.test(res.trim())) {
182
195
  this.mutated = true;
183
- this.verified = this.verifiedStrong = false;
196
+ this.verified = this.verifiedStrong = this.contentChecked = false;
184
197
  this.background.clear();
198
+ // file_edit/file_write report "edited <path>" / "wrote <path>"; a non-prose (or unknown) path needs a real test/build.
199
+ const path = /^(?:edited|wrote|created|updated)\s+(\S+)/i.exec(res.trim())?.[1] ?? "";
200
+ if (!path || !PROSE_EXT_RE.test(path))
201
+ this.codeMutated = true;
185
202
  }
186
203
  const jobId = shell || name === "shell_background" ? backgroundJobId(res) : undefined;
187
204
  if (jobId && isVerifyCmd(cmd))
@@ -200,6 +217,8 @@ export class TaskVerification {
200
217
  this.verified = true;
201
218
  if (isStrongVerifyCmd(cmd))
202
219
  this.verifiedStrong = true;
220
+ if (isContentCheckCmd(cmd))
221
+ this.contentChecked = true;
203
222
  }
204
223
  if (shell && !/^error running command:/i.test(res.trim()) && !stillInBackground(res))
205
224
  for (const k of checksRun(cmd))
@@ -232,13 +251,24 @@ export class TaskVerification {
232
251
  changedFiles() {
233
252
  return this.mutated;
234
253
  }
235
- /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate (ADVISORY path). */
254
+ /** A document/prose deliverable: files changed but NONE were code/config — it is verified by a content or
255
+ * doc check, not a code test. (Falls back to "treat as code" when a mutation's path can't be read.) */
256
+ proseOnly() {
257
+ return this.mutated && !this.codeMutated;
258
+ }
259
+ /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate (ADVISORY path).
260
+ * A prose/doc deliverable is instead cleared by a content/doc check — so a verified report never reads "not verified". */
236
261
  gate() {
262
+ if (this.proseOnly())
263
+ return !this.contentChecked;
237
264
  return this.mutated && !this.verified;
238
265
  }
239
266
  /** True ⇒ changed code but never ran a STRONG (test/build/typecheck/run) check ⇒ the ENFORCED hard
240
- * precondition for unattended turns (an allowlisted-but-empty command like `npm ls` does NOT clear it). */
267
+ * precondition for unattended turns (an allowlisted-but-empty command like `npm ls` does NOT clear it).
268
+ * A prose/doc deliverable has no code to strong-verify, so it is never held for a test/build. */
241
269
  gateStrong() {
270
+ if (this.proseOnly())
271
+ return false;
242
272
  return this.mutated && !this.verifiedStrong;
243
273
  }
244
274
  /** The checks `answer` reports as clean that never ran this turn ⇒ nudge, then annotate. */
@@ -8,7 +8,10 @@ import { join } from "node:path";
8
8
  import { ToolchainError, isManaged, resolveToolchainBin, storeEntryMeta, storeEntryOf, verifyState } from "./config/toolchain.js";
9
9
  import { formatAge } from "./memory/session-catalog.js";
10
10
  import { isLaunchdDisabled } from "./services/preflight.js";
11
+ import { BUILTIN_MODELS, findModel, isRetired } from "./router/models.js";
11
12
  const LABEL = "co.0perator.gateway";
13
+ /** The catalog row this gateway serves (Aurora). While it is retired, `start` needs --force. */
14
+ const GATEWAY_MODEL_ID = "operator-1m";
12
15
  function paths() {
13
16
  const home = process.env.OPERATOR_HOME || join(homedir(), ".operator"); // the runtime's home, not the CLI's config home
14
17
  return {
@@ -80,9 +83,10 @@ function mappedExecutable(pid) {
80
83
  const r = spawnSync("/usr/sbin/lsof", ["-nP", "-a", "-p", String(pid), "-d", "txt", "-Fn"], { encoding: "utf8", timeout: 5000 });
81
84
  return r.status === 0 ? r.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) : undefined;
82
85
  }
83
- const USAGE = `usage: operator gateway {start [-d]|stop|status|health|logs}
86
+ const USAGE = `usage: operator gateway {start [-d] [--force]|stop|status|health|logs}
84
87
  start run the gateway in the foreground
85
88
  start -d start it through launchd (${LABEL})
89
+ --force start it although its model is retired
86
90
  stop stop the gateway and its llama-server
87
91
  status gateway, llama-server, models, binary and toolchain
88
92
  health llama-server /health
@@ -92,7 +96,14 @@ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n
92
96
  const [cmd = "status", ...rest] = args;
93
97
  switch (cmd) {
94
98
  case "start": {
95
- if (rest[0] === "-d") {
99
+ const force = rest.includes("--force");
100
+ const opts = rest.filter((a) => a !== "--force");
101
+ const served = findModel(BUILTIN_MODELS, GATEWAY_MODEL_ID);
102
+ if (isRetired(served) && !force) {
103
+ out(`${served.label} (${GATEWAY_MODEL_ID}) is retired — not starting the gateway. Run with --force to start it anyway.`);
104
+ return 1;
105
+ }
106
+ if (opts[0] === "-d") {
96
107
  if (!existsSync(p.plist)) {
97
108
  out(`${p.plist} is not installed — run operator-runtime/scripts/install.sh first.`);
98
109
  return 1;
@@ -107,7 +118,7 @@ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n
107
118
  out(code === 0 ? "gateway started through launchd" : "launchctl kickstart failed");
108
119
  return code;
109
120
  }
110
- return spawnSync(process.execPath, [p.gateway, ...rest], { stdio: "inherit" }).status ?? 1;
121
+ return spawnSync(process.execPath, [p.gateway, ...opts], { stdio: "inherit" }).status ?? 1;
111
122
  }
112
123
  case "stop": {
113
124
  launchctl(["bootout", `${domain()}/${LABEL}`]);
package/dist/index.js CHANGED
@@ -26,5 +26,8 @@ export { registry, toSchemas } from "./tools/registry.js";
26
26
  export { McpHub, withMcp } from "./mcp/index.js";
27
27
  export { loadMcpConfig, upsertMcpServer, mcpWritePath } from "./mcp/config.js";
28
28
  export { McpHttpClient } from "./mcp/client.js";
29
+ // Agents still working at quit (background/resume.ts): the saved records and the quit summary every surface shows.
30
+ export { listResumable, quitSummary, resumeOnReopen, saveResumable, clearResumable } from "./background/resume.js";
31
+ export { toRemoteAgents } from "./remote/host.js";
29
32
  // UI (kode-web can reuse these Ink components' patterns; kode-web renders its own React DOM tree)
30
33
  export { App } from "./ui/index.js";
@@ -0,0 +1,30 @@
1
+ import { PHONE_ACTION_NAMES, PHONE_TOOLS } from "../tools/device/tools.js";
2
+ const PROTOCOL_VERSION = "2025-06-18";
3
+ export function phoneMcpTools(o = {}) {
4
+ return PHONE_TOOLS.filter((t) => o.allowActions || !PHONE_ACTION_NAMES.includes(t.name));
5
+ }
6
+ export async function handlePhoneMcp(req, o = {}) {
7
+ const id = req.id ?? null;
8
+ const ok = (result) => ({ jsonrpc: "2.0", id, result });
9
+ const err = (code, message) => ({ jsonrpc: "2.0", id, error: { code, message } });
10
+ if (req.id === undefined && req.method.startsWith("notifications/"))
11
+ return null;
12
+ switch (req.method) {
13
+ case "initialize":
14
+ return ok({ protocolVersion: PROTOCOL_VERSION, capabilities: { tools: {} }, serverInfo: { name: "operator-phone", version: "0.1.0" } });
15
+ case "ping":
16
+ return ok({});
17
+ case "tools/list":
18
+ return ok({ tools: phoneMcpTools(o).map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters })) });
19
+ case "tools/call": {
20
+ const name = String(req.params?.name ?? "");
21
+ const tool = phoneMcpTools(o).find((t) => t.name === name);
22
+ if (!tool)
23
+ return err(-32602, PHONE_ACTION_NAMES.includes(name) ? `${name} is an action; start the server with --allow-actions to offer it` : `unknown tool ${name}`);
24
+ const text = await tool.run((req.params?.arguments ?? {}));
25
+ return ok({ content: [{ type: "text", text }], ...(/^(error|Permission denied)/.test(text) ? { isError: true } : {}) });
26
+ }
27
+ default:
28
+ return err(-32601, `method not found: ${req.method}`);
29
+ }
30
+ }
@@ -12,21 +12,20 @@
12
12
  // its plan over what the owner typed. freshHandoff drops live blocks past LIVE_MAX_AGE_MS as a second guard.
13
13
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
14
14
  import { dirname, relative, isAbsolute } from "node:path";
15
+ import { FILE_WRITE, PLAN_WRITE, ranOk } from "../tools/classes.js";
15
16
  export const LIVE_START = "<!-- live-progress:start";
16
17
  export const LIVE_END = "<!-- live-progress:end -->";
17
- const MUTATING = new Set(["file_write", "file_edit", "task_add", "task_update", "task_clear"]);
18
18
  const MAX_FILES = 12;
19
19
  const MAX_TASK_CHARS = 80;
20
20
  const MAX_BLOCK_CHARS = 1500;
21
- const ERROR_RESULT = /^\s*(?:error\b|loop guard|permission denied)/i;
22
- const landed = (e) => !ERROR_RESULT.test(e.result ?? "");
21
+ const landed = (e) => ranOk(e.result ?? "");
23
22
  /** True when a tool round changed state worth journaling (a failed write is not progress). */
24
23
  export function roundProgressed(events) {
25
- return events.some((e) => MUTATING.has(e.name) && landed(e));
24
+ return events.some((e) => (FILE_WRITE.has(e.name) || PLAN_WRITE.has(e.name)) && landed(e));
26
25
  }
27
26
  /** The file paths a round actually touched (file_write / file_edit `path` whose result was not an error). */
28
27
  export function touchedPaths(events) {
29
- return events.filter((e) => (e.name === "file_write" || e.name === "file_edit") && landed(e)).map((e) => String(e.args?.path ?? "")).filter(Boolean);
28
+ return events.filter((e) => FILE_WRITE.has(e.name) && landed(e)).map((e) => String(e.args?.path ?? "")).filter(Boolean);
30
29
  }
31
30
  const MARK = { pending: "[ ]", in_progress: "[>]", done: "[x]", cancelled: "[~]" };
32
31
  const openTag = (session) => `${LIVE_START} ${session} -->`;
@@ -0,0 +1,98 @@
1
+ import { codeActConfig, codeActReport } from "./codeact.js";
2
+ // The sandbox imports node builtins: an opaque specifier keeps it out of the platform-neutral bundle (conventions/kode-tsi.md).
3
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
4
+ /** Runs at most this many programs per delegated step: the program, and one fix after a failure. */
5
+ export const CODEACT_MAX_RUNS = 2;
6
+ /** The only tools an executor holds on a lane step besides codeact_run: reads. The step's read-only claim is enforced by
7
+ * the tool set (no shell, no writes), not trusted. */
8
+ export const CODEACT_STEP_TOOLS = ["file_read", "read_files", "list_directory", "glob", "find_files", "search", "grep_search"];
9
+ /** delegate_task's extra properties while moa.codeact.enabled; the schema is unchanged when it is off. */
10
+ export const CODEACT_DELEGATE_PROPS = {
11
+ lane: { type: "string", enum: ["tools", "codeact"], description: "codeact: a bulk, read-only, deterministic step done by ONE sandboxed program (no network, no secrets, writes only to scratch). Checked in code; a step that fails the check runs on tools and you are told why. Default tools." },
12
+ targets: { type: "array", items: { type: "string" }, description: "codeact: the paths the program reads (the step's repo dirs, logs, files)" },
13
+ items: { type: "number", description: "codeact: how many items the step covers (files, lines, records)" },
14
+ est_round_trips: { type: "number", description: "codeact: tool calls the step would take with tools" },
15
+ read_only: { type: "boolean", description: "codeact: true only if the step changes nothing" },
16
+ deterministic: { type: "boolean", description: "codeact: true only if the same inputs always give the same answer" },
17
+ needs_network: { type: "boolean" },
18
+ needs_secrets: { type: "boolean" },
19
+ };
20
+ /** delegate_task with the lane's properties added (a copy; the registry's tool is untouched). */
21
+ export function withCodeActDelegateSchema(base) {
22
+ const params = base.parameters;
23
+ return {
24
+ ...base,
25
+ description: `${base.description} Lane: pass lane:"codeact" with targets, items or est_round_trips, read_only, deterministic for a bulk read-only step (scan, count, batch check, log analysis); the sub-agent then does it in one sandboxed program.`,
26
+ parameters: { ...base.parameters, properties: { ...params.properties, ...CODEACT_DELEGATE_PROPS } },
27
+ };
28
+ }
29
+ const bool = (v) => v === true || v === "true";
30
+ const num = (v) => (typeof v === "number" ? v : typeof v === "string" && v.trim() && Number.isFinite(Number(v)) ? Number(v) : undefined);
31
+ /** The step a delegate_task call claims, or undefined when it did not ask for the lane. Missing flags read as false. */
32
+ export function codeActStepFromArgs(args, author) {
33
+ if (String(args.lane ?? "").trim().toLowerCase() !== "codeact")
34
+ return undefined;
35
+ const t = args.targets;
36
+ const targets = Array.isArray(t) ? t.map(String) : typeof t === "string" ? t.split(/[,\n]/).map((s) => s.trim()).filter(Boolean) : [];
37
+ return {
38
+ readOnly: bool(args.read_only), deterministic: bool(args.deterministic),
39
+ needsNetwork: bool(args.needs_network), needsSecrets: bool(args.needs_secrets),
40
+ items: num(args.items), estRoundTrips: num(args.est_round_trips), targets, author,
41
+ };
42
+ }
43
+ /** What the executor is told on top of the planner's task. */
44
+ export function codeActBrief(task, targets, language) {
45
+ const lang = language === "python" ? "Python 3 (standard library only)" : "Node (ES module, node:fs / node:path only)";
46
+ return [
47
+ task,
48
+ "",
49
+ "## How to do this step: the CodeAct lane",
50
+ `Do the whole step with ONE call to codeact_run: a short ${lang} program that reads the targets and computes the answer.`,
51
+ `- Targets (read-only): ${targets.join(", ")}. The program's working directory is the first target; the paths are also in`,
52
+ " argv[1:] and the CODEACT_TARGETS environment variable (JSON).",
53
+ "- It may write only under CODEACT_SCRATCH. No network, no subprocesses or shells, no secrets: they are blocked.",
54
+ '- Its LAST stdout line must be one JSON object: {"summary": "<one plain line>", "data": <the result>}.',
55
+ "- Your other tools here only read (no shell). Look first only if you must (one quick listing); then write the program.",
56
+ " If it fails, fix it once from the error.",
57
+ "- Do not edit, commit or send anything in this step. Answer with the summary and the data as the step's report.",
58
+ ].join("\n");
59
+ }
60
+ /** The executor's `codeact_run`: runs the program in the sandbox over the step's checked targets, at most
61
+ * CODEACT_MAX_RUNS times. */
62
+ export function makeCodeActTool(ctx) {
63
+ let runs = 0;
64
+ const cfg = codeActConfig(ctx.settings);
65
+ return {
66
+ name: "codeact_run",
67
+ description: `Run ONE short program over this step's read-only targets in a sandbox (no network, no subprocesses, writes only to CODEACT_SCRATCH) and get its JSON result back. The program's last stdout line must be {"summary": "...", "data": ...}. At most ${CODEACT_MAX_RUNS} runs for this step.`,
68
+ safe: false,
69
+ contract: { v: 1, effects: ["exec", "read"], bins: ["sandbox-exec", "bwrap", "python3", "node"] },
70
+ parameters: {
71
+ type: "object",
72
+ properties: {
73
+ program: { type: "string", description: `the whole program text (at most ${cfg.maxProgramBytes} bytes)` },
74
+ language: { type: "string", enum: ["python", "node"], description: `default ${ctx.language}` },
75
+ },
76
+ required: ["program"],
77
+ },
78
+ run: async (a) => {
79
+ if (runs >= CODEACT_MAX_RUNS)
80
+ return `error: codeact_run: this step already used its ${CODEACT_MAX_RUNS} runs; finish it with your other tools or report what failed`;
81
+ runs++;
82
+ const language = a.language === "node" || a.language === "python" ? a.language : ctx.language;
83
+ const req = { language, program: String(a.program ?? ""), targets: ctx.targets, settings: ctx.settings };
84
+ const run = ctx.runner ?? (await nodeImport("./codeact-sandbox.js")).runCodeAct;
85
+ const r = await run(req);
86
+ ctx.onResult?.(r);
87
+ return codeActReport(r);
88
+ },
89
+ };
90
+ }
91
+ /** The one-line trace a delegation appends to its report: how the lane ran, where the program and result are kept. */
92
+ export function codeActTraceLine(results) {
93
+ if (!results.length)
94
+ return "[codeact trace: no program ran]";
95
+ const last = results[results.length - 1];
96
+ const ms = results.reduce((s, r) => s + r.stats.wallMs, 0);
97
+ return `[codeact trace: ${last.status} · ${results.length} program run${results.length === 1 ? "" : "s"} · ${ms} ms · ${last.sandbox.mechanism} · ${last.program.language} sha256 ${last.program.sha256.slice(0, 12)}${last.runDir ? ` · ${last.runDir}` : ""}]`;
98
+ }