@0perator/operator 0.1.360-next.1 → 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 (54) 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 +8 -2
  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 +172 -134
  9. package/dist/cli.js +261 -70
  10. package/dist/config/settings.js +28 -7
  11. package/dist/config/skills-index.js +4 -0
  12. package/dist/engine/agent.js +1 -1
  13. package/dist/engine/aurora.js +22 -13
  14. package/dist/engine/compaction.js +1 -1
  15. package/dist/engine/moa.js +2 -1
  16. package/dist/engine/selfheal.js +1 -1
  17. package/dist/engine/speed-compaction.js +37 -0
  18. package/dist/engine/toolcalls.js +6 -6
  19. package/dist/gateway-cli.js +14 -5
  20. package/dist/index.js +3 -0
  21. package/dist/mcp/phone-server.js +30 -0
  22. package/dist/permissions/index.js +33 -17
  23. package/dist/permissions/signature.js +5 -0
  24. package/dist/phone-cli.js +65 -0
  25. package/dist/remote/host.js +31 -2
  26. package/dist/router/models.js +49 -25
  27. package/dist/selfimprove/index.js +1 -1
  28. package/dist/services/preflight.js +31 -8
  29. package/dist/session.js +96 -14
  30. package/dist/tools/deferred.js +1 -0
  31. package/dist/tools/device/android.js +227 -0
  32. package/dist/tools/device/classify.js +127 -0
  33. package/dist/tools/device/deps.js +69 -0
  34. package/dist/tools/device/desktop.js +82 -0
  35. package/dist/tools/device/harness.js +262 -0
  36. package/dist/tools/device/iphone.js +206 -0
  37. package/dist/tools/device/mirroring-jxa.js +146 -0
  38. package/dist/tools/device/setup.js +90 -0
  39. package/dist/tools/device/tools.js +70 -0
  40. package/dist/tools/device/types.js +19 -0
  41. package/dist/tools/registry.js +242 -48
  42. package/dist/tools/vision-media.js +162 -0
  43. package/dist/ui/App.js +4 -3
  44. package/dist/ui/ApprovalPrompt.js +10 -4
  45. package/dist/ui/BgPanel.js +2 -2
  46. package/dist/ui/UpdatePrompt.js +40 -0
  47. package/dist/ui/modelPicker.js +26 -8
  48. package/dist/ui/slashCommands.js +1 -0
  49. package/dist/update-check.js +134 -0
  50. package/dist/update.js +82 -13
  51. package/dist/util/slash.js +2 -2
  52. package/package.json +4 -2
  53. package/src/tools/device/NOTICE +37 -0
  54. package/dist/browser/cdp.js +0 -271
@@ -6,7 +6,7 @@ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
6
6
  import { dirname } from "node:path";
7
7
  import { operatorPath } from "./home.js";
8
8
  import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
9
- import { MIN_CONTEXT_PIN, DEFAULT_MODEL_ID, GATEWAY_BASE } from "../router/models.js";
9
+ import { MIN_CONTEXT_PIN, DEFAULT_ACTIVE_MODEL, GATEWAY_BASE, LOCAL_GATEWAY_BASE } from "../router/models.js";
10
10
  import { LEGACY_API_HOST, PRODUCT_API_HOST } from "./product-hosts.js";
11
11
  /** Resolve an endpoint's bearer from config/env/secret-file (first hit wins); undefined when none set
12
12
  * (a local/un-gated endpoint). Keeps the raw key out of settings when `apiKeyEnv`/`apiKeyFile` are used. */
@@ -40,7 +40,7 @@ const DEFAULTS = {
40
40
  // Fallback literal for hosts without a running operator-runtime gateway (mobile, browser, dev).
41
41
  // Fleet nodes with ~/.operator/runtime/server.json dynamically override this at startup via the
42
42
  // gateway-discovery path in cli.tsx — single source of truth, enterprise-safe for both postures.
43
- aurora: { base: "http://127.0.0.1:8097", ctxWindow: 1000000, model: "aurora-code-1" },
43
+ aurora: { base: "http://127.0.0.1:8097", ctxWindow: 1000000, model: "aurora-code-1" }, // == DEFAULT_AURORA_ENDPOINT: buildEndpointChain puts the router's `main` before it
44
44
  // No built-in standby: a deployment names its own in settings.json (endpoints.failover — same model and the
45
45
  // same real window as the primary, so a failover holds a live session instead of truncating it).
46
46
  },
@@ -67,19 +67,20 @@ const DEFAULTS = {
67
67
  // harmlessly and the boot screen falls back to the manual hint (autostart is best-effort by design).
68
68
  services: {
69
69
  // co.0perator.* since 2026-10-28; legacyLabels keeps a box that still runs the old job self-healing.
70
- aurora: { autostart: true, launchdLabel: "co.0perator.gateway", plistPath: "~/Library/LaunchAgents/co.0perator.gateway.plist", legacyLabels: ["ai.operator.gateway"], waitSec: 90 },
70
+ // autostart OFF since 11/25: Aurora is retired behind the router (Kimi/Athena); a box that still serves it opts in.
71
+ aurora: { autostart: false, launchdLabel: "co.0perator.gateway", plistPath: "~/Library/LaunchAgents/co.0perator.gateway.plist", legacyLabels: ["ai.operator.gateway"], waitSec: 90 },
71
72
  autopilot: { autostart: true, launchdLabel: "com.axe.autopilot", plistPath: "~/Library/LaunchAgents/com.axe.autopilot.plist", url: "http://127.0.0.1:9333" },
72
73
  vision: { autostart: false, launchdLabel: "co.0perator.vision", plistPath: "~/Library/LaunchAgents/co.0perator.vision.plist", legacyLabels: ["axe.vision-bot"], url: "http://127.0.0.1:7788" },
73
74
  stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
74
75
  },
75
- // MOA (2026-10-31, James): a planner/specialist team, Manus-style — Cortana plans, delegates each step to a
76
+ // MOA (2026-10-31, James): a planner/specialist team — Cortana plans, delegates each step to a
76
77
  // gpt-oss-20b sub-agent, checks the result and writes the answer (and reads images). Both on JL1 through the gateway.
77
78
  // Was parallel drafts (gpt-oss-20b + Cortana) merged by Cortana (10/30). settings.moa replaces it wholesale.
78
79
  moa: {
79
80
  planner: { id: "cortana", endpoint: GATEWAY_BASE, model: "cortana" },
80
81
  specialist: { id: "gpt-oss-20b" },
81
82
  },
82
- activeModel: DEFAULT_MODEL_ID, // /model default — the 1M endpoint, unchanged from before /model existed
83
+ activeModel: DEFAULT_ACTIVE_MODEL, // /model default for a fresh install: the router's operator-flash route (0.1.361; was the Aurora row)
83
84
  // Autonomy: everything conservative. keepAwake off; dream OFF and read-mostly with a board-only
84
85
  // allowlist. An interactive owner never touches any of this until they run an autonomy subcommand.
85
86
  autonomy: {
@@ -158,6 +159,9 @@ function applyEnv(s) {
158
159
  const acct = Number(process.env.KODE_AUTONOMY_CEILING_TOKENS); // higher ceiling for unattended headless/loop runs
159
160
  if (Number.isFinite(acct))
160
161
  out.compaction = { ...out.compaction, autonomyCeilingTokens: acct };
162
+ const mtps = process.env.KODE_COMPACT_MIN_TPS; // speed trigger: compact when sustained decode falls under N tok/s
163
+ if (mtps !== undefined && mtps !== "" && Number.isFinite(Number(mtps)))
164
+ out.compaction = { ...out.compaction, minDecodeTps: Number(mtps) };
161
165
  const rcAuto = process.env.KODE_RC_AUTOSTART; // RC host auto-start on boot (opt-in)
162
166
  if (rcAuto === "1" || rcAuto === "0")
163
167
  out.remote = { ...out.remote, autostart: rcAuto === "1" };
@@ -260,6 +264,12 @@ export function compactionCeilingTokens(s, mode = "interactive") {
260
264
  const explicit = mode === "autonomy" ? s.compaction?.autonomyCeilingTokens : s.compaction?.ceilingTokens;
261
265
  return typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 8000 ? Math.floor(explicit) : undefined;
262
266
  }
267
+ /** The decode-rate floor (tok/s) for speed-aware compaction in this session mode (`compaction.minDecodeTps` /
268
+ * `compaction.autonomyMinDecodeTps`), or undefined (off). Each mode reads only its own key. */
269
+ export function compactionMinDecodeTps(s, mode = "interactive") {
270
+ const v = mode === "autonomy" ? s.compaction?.autonomyMinDecodeTps : s.compaction?.minDecodeTps;
271
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
272
+ }
263
273
  /** The per-turn WALL-CLOCK budget (ms) to hand runTurn — the only bound on TIME, the brake on hour-long turns.
264
274
  * settings.autonomy.maxTurnWallClockSec, env KODE_TURN_MAX_WALLCLOCK_SEC wins; 0/unset ⇒ undefined (no cap).
265
275
  * Resolved here so headless/autonomy (and any surface that opts in) read it identically. */
@@ -349,9 +359,16 @@ function resolveModelMode(s) {
349
359
  // for an edge/zone failure of one name (config/product-hosts.ts). Opt out with
350
360
  // `settings.endpoints.cloudFailover === false` for a sovereign deployment that must never egress.
351
361
  const CLOUD_FAILOVERS = [
352
- { name: "operator-cloud", base: `https://${PRODUCT_API_HOST}`, model: "aurora-code-1", ctxLimit: 307200, transport: "openai" },
353
- { name: "axe-cloud", base: `https://${LEGACY_API_HOST}`, model: "aurora-code-1", ctxLimit: 307200, transport: "openai" },
362
+ { name: "operator-cloud", base: `https://${PRODUCT_API_HOST}`, model: "main", ctxLimit: 307200, transport: "openai" },
363
+ { name: "axe-cloud", base: `https://${LEGACY_API_HOST}`, model: "main", ctxLimit: 307200, transport: "openai" },
354
364
  ];
365
+ /** The shipped endpoints.aurora literal (DEFAULTS) — a box that never named its own primary. */
366
+ const DEFAULT_AURORA_ENDPOINT = { base: "http://127.0.0.1:8097", ctxWindow: 1000000, model: "aurora-code-1" };
367
+ function isDefaultAuroraLiteral(e) {
368
+ return e.base.replace(/\/+$/, "") === DEFAULT_AURORA_ENDPOINT.base && e.model === DEFAULT_AURORA_ENDPOINT.model && e.ctxWindow === DEFAULT_AURORA_ENDPOINT.ctxWindow;
369
+ }
370
+ /** The local router's `main` capability (the one door, loopback): the default primary when the owner named none. */
371
+ const ROUTER_MAIN = { name: "main", base: LOCAL_GATEWAY_BASE.replace(/\/v1\/?$/, ""), model: "main", ctxLimit: 262144 };
355
372
  function hostLabel(base) {
356
373
  try {
357
374
  const u = new URL(base);
@@ -382,6 +399,10 @@ export function buildEndpointChain(s) {
382
399
  seen.add(key);
383
400
  chain.push(ep);
384
401
  };
402
+ // 11/25: the built-in primary is the local router's `main` capability, not a launchd-owned Aurora. Only the shipped
403
+ // literal is demoted: an owner's own endpoints.aurora (or the gateway's discovered port) stays first.
404
+ if (isDefaultAuroraLiteral(aurora))
405
+ add({ ...ROUTER_MAIN });
385
406
  add({ name: "operator-1m", base: aurora.base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(aurora), loopbackAuth: true });
386
407
  for (const base of (s.fleet?.auroraNodes ?? []).filter(Boolean)) {
387
408
  const cfg = { base, model: aurora.model, ctxWindow: aurora.ctxWindow };
@@ -144,6 +144,10 @@ export function listLocalSkills() {
144
144
  }
145
145
  return [...byName.values()].sort((a, c) => a.name.localeCompare(c.name));
146
146
  }
147
+ /** The installed skill a typed `/<name>` names: every local skill is also a slash command, as in Claude Code. */
148
+ export function skillCommand(name) {
149
+ return name ? listLocalSkills().find((s) => s.name === name)?.name : undefined;
150
+ }
147
151
  export function resolveSkillFile(skillRoot, filePath) {
148
152
  const b = nodeBuiltins();
149
153
  if (!b || !filePath)
@@ -1383,7 +1383,7 @@ export async function runTurn(userInput, conversation, opts) {
1383
1383
  await sleep(opts.loadingBackoffMs ?? DEFAULT_LOADING_BACKOFF_MS, opts.signal, () => new TurnAbortedError());
1384
1384
  continue;
1385
1385
  }
1386
- // The vendor's 400 stated its OUTPUT ceiling (max_tokens over what it accepts — QwenCloud's "Range of
1386
+ // The vendor's 400 stated its OUTPUT ceiling (max_tokens over what it accepts — one vendor's "Range of
1387
1387
  // max_tokens should be [1, 131072]"): learn it for this endpoint, so every later clamp honours it, and
1388
1388
  // retry this round ONCE. Not a context problem (compaction/failover can't help) and no self-heal
1389
1389
  // budget spent. A ceiling no lower than what we sent, or a second hit this round, is surfaced as-is.
@@ -79,7 +79,7 @@ export function isRemoteBase(base) {
79
79
  return !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(base);
80
80
  }
81
81
  // Owner-trusted fallback scope for the OPERATOR bearer: AXE's own hosts (api.axe.onl gateway) and
82
- // private/LAN fleet nodes. A third-party BYO host (qwencloudapi.com, …) must NEVER receive the operator
82
+ // private/LAN fleet nodes. A third-party BYO host (api.openai.com, …) must NEVER receive the operator
83
83
  // token — a BYO profile carries its own vendor key via Endpoint.token (AuroraOpts.token), and an
84
84
  // endpoint with no explicit token gets NO auth on a public third-party host. This scope rule is the
85
85
  // credential-leak guard for the BYO era.
@@ -279,11 +279,23 @@ export function shipsLlamaCacheKnobs(base, transport) {
279
279
  return requiresOperatorToken(base);
280
280
  return true;
281
281
  }
282
+ let speculationOff = false;
283
+ /** Process-wide speculation default (GW-26), set once from settings at startup: false sends the ngram disable on every
284
+ * llama.cpp request that has no explicit enableSpeculation. */
285
+ export function setSpeculation(on) { speculationOff = !on; }
286
+ /** Settings then env (env wins): `KODE_SPECULATION=0` or `settings.speculation === false` turns it off. Default ON. */
287
+ export function speculationEnabled(s, env = process.env) {
288
+ if (env.KODE_SPECULATION === "0" || env.KODE_SPECULATION === "false")
289
+ return false;
290
+ if (env.KODE_SPECULATION === "1" || env.KODE_SPECULATION === "true")
291
+ return true;
292
+ return s.speculation !== false;
293
+ }
282
294
  export function requestBody(messages, o, stream) {
283
295
  // Transport dialect: llama.cpp-only fields ship to Aurora/fleet (default "llama") AND to our OWN
284
296
  // vendor gateway (*.axe.onl — LiteLLM terminating at our llama.cpp, so the wire is OpenAI but the
285
297
  // BACKEND understands the knobs; measured live 2026-10-11: extras pass api.axe.onl with no 400 and
286
- // no fallback trip). A genuine third-party "openai" BYO (qwencloudapi.com, …) still gets standard
298
+ // no fallback trip). A genuine third-party "openai" BYO (api.openai.com, …) still gets standard
287
299
  // fields only — third-party gateways can 400 on unknown keys, and silence on extras is not a
288
300
  // contract we should bank on.
289
301
  const llama = o.transport !== "openai";
@@ -311,16 +323,13 @@ export function requestBody(messages, o, stream) {
311
323
  // fleet node that doesn't ship the full cache knobs still benefits — the progress chunks keep the idle-gap
312
324
  // fed through a long cold prefill instead of looking wedged. A server that ignores the field is harmless.
313
325
  ...(stream && llama ? { return_progress: true } : {}),
314
- // GW-26 (UPDATED 2026-10-19, selective): spec-decode is a measured 3.3x on prose/code (16.7→54.5 tok/s)
315
- // but FIGHTS the tool-call grammar (the reason aurora-op.conf sits at AURORA_SPEC_TYPE=none today). So
316
- // steer it PER REQUEST: a tool-bearing request (any agent round) sends the ngram disable; a tool-free
317
- // request (summarizer, delegate prose, MOA aggregation) leaves the server default on. With today's
318
- // spec-none serving this whole knob is a no-op either way; it's the engine half that makes a future
319
- // conf flip back to ngram-mod safe. ⚠ The fleet flip is GATED on verifying the per-request disable
320
- // actually disables on the serving build — a 2026-10-16 A/B found it a NO-OP on the ngram-mod path
321
- // (GW-26 correction #9); re-verify upstream before touching AURORA_SPEC_TYPE. Explicit
322
- // enableSpeculation true/false always wins over the tool-presence default.
323
- ...(cacheKnobs && (o.enableSpeculation === false || (o.enableSpeculation === undefined && (o.tools?.length ?? 0) > 0))
326
+ // GW-26 (2026-11-25): no per-request speculative field by default, tool rounds included — the server's
327
+ // --spec-type decides. ngram-mod drafts are verified by the target model, so the output is exact (the 27B dense model,
328
+ // 6 prompts: identical sha256 with and without it; a code edit 11.1 → 52-56 tok/s). The old tool-round
329
+ // disable (sent on the belief that drafts fight the tool-call grammar) starved every agent round of that
330
+ // speed-up. Opt out with settings.speculation:false / KODE_SPECULATION=0 (setSpeculation), or per call with
331
+ // enableSpeculation:false; an explicit enableSpeculation always wins.
332
+ ...(cacheKnobs && (o.enableSpeculation === false || (o.enableSpeculation === undefined && speculationOff))
324
333
  ? { speculative: { ngram: { enabled: false } } } : {}),
325
334
  max_tokens: o.maxTokens ?? 8192, temperature: o.temperature ?? 0.7,
326
335
  ...(o.tools?.length ? { tools: o.tools, tool_choice: "auto", parallel_tool_calls: true } : {}),
@@ -342,7 +351,7 @@ export function chatUrl(base, chatPath) {
342
351
  return `${base}${chatPath ?? "/v1/chat/completions"}`;
343
352
  }
344
353
  /** Who answered an HTTP error, for the owner: the profile id + provider box when the turn loop passed them
345
- * ("qwen3.8-flash (QwenCloud)"), else the legacy "aurora /v1" — every OpenAI-dialect call used to read as Aurora. */
354
+ * ("gemini-flash (Google)"), else the legacy "aurora /v1" — every OpenAI-dialect call used to read as Aurora. */
346
355
  export function httpErrorLabel(o) {
347
356
  if (!o.label)
348
357
  return "aurora /v1";
@@ -218,7 +218,7 @@ function shedToolOutputs(out, opts, targetTokens, protectTail) {
218
218
  return out;
219
219
  const limit = out.length - protectTail;
220
220
  // Tool messages, largest content first — shed the worst offenders until it fits. GW-10-COMPLETE:
221
- // error-ish results go LAST (Manus doctrine — a failed tool trace in context suppresses repeat
221
+ // error-ish results go LAST (context-engineering practice — a failed tool trace in context suppresses repeat
222
222
  // mistakes; a success's bytes are re-fetchable from the spill file, the failure's lesson is not).
223
223
  const byLargest = out
224
224
  .map((m, i) => ({ i, len: m.role === "tool" && i < limit && !isShedStub(m.content) ? m.content.length : 0, err: /^(error[:\s]|\(no output; exit)/i.test(m.content) }))
@@ -1,7 +1,8 @@
1
1
  /** The team from settings.moa, new shape or the pre-10/31 one (aggregator → planner, first other proposer →
2
2
  * specialist). Undefined when no planner is configured. A missing specialist falls back to the planner itself. */
3
3
  export function moaTeam(cfg) {
4
- const planner = cfg?.planner ?? cfg?.aggregator;
4
+ const byId = cfg?.plannerModel?.trim();
5
+ const planner = byId ? { id: byId } : cfg?.planner ?? cfg?.aggregator;
5
6
  if (!planner)
6
7
  return undefined;
7
8
  const specialist = cfg?.specialist?.id?.trim()
@@ -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
@@ -0,0 +1,37 @@
1
+ // Speed-aware compaction: the second interactive trigger beside window fill. Decode slows as the context grows, so
2
+ // when the server's own measured rate (timings predicted_n / predicted_ms, summed per turn by runTurn) stays under
3
+ // the owner's floor, the session compacts before the next request. Pure: Session keeps the samples and runs the
4
+ // compaction; this decides.
5
+ /** A turn under this many generated tokens says nothing reliable about the rate. */
6
+ export const SPEED_MIN_TOKENS = 64;
7
+ /** How many consecutive measured turns must each sit under the floor. */
8
+ export const SPEED_SUSTAIN_TURNS = 2;
9
+ /** Below this request size compaction cannot buy speed back. */
10
+ export const SPEED_MIN_CONTEXT = 24_000;
11
+ export function sampleTps(s) {
12
+ return s.tokens / (s.genMs / 1000);
13
+ }
14
+ /** Keep the last SPEED_SUSTAIN_TURNS measurable turns; a turn too short to measure (or with no server timings) is
15
+ * skipped, neither counting toward the trigger nor resetting it. */
16
+ export function recordDecodeSample(samples, t) {
17
+ if (!t.tokens || !t.genMs || t.tokens < SPEED_MIN_TOKENS || t.genMs <= 0)
18
+ return samples;
19
+ return [...samples, { tokens: t.tokens, genMs: t.genMs, ctxTokens: t.ctxTokens }].slice(-SPEED_SUSTAIN_TURNS);
20
+ }
21
+ /** Due when the floor is set, the request is big enough for compaction to help, and each of the last
22
+ * SPEED_SUSTAIN_TURNS measured turns decoded under the floor. One slow turn never fires it. */
23
+ export function speedCompactionDue(samples, floorTps, ctxTokens) {
24
+ if (!floorTps || !(floorTps > 0))
25
+ return undefined;
26
+ if (ctxTokens < SPEED_MIN_CONTEXT)
27
+ return undefined;
28
+ if (samples.length < SPEED_SUSTAIN_TURNS)
29
+ return undefined;
30
+ const recent = samples.slice(-SPEED_SUSTAIN_TURNS);
31
+ if (!recent.every((s) => sampleTps(s) < floorTps))
32
+ return undefined;
33
+ return { tps: sampleTps(recent[recent.length - 1]), ctxTokens, floorTps };
34
+ }
35
+ export function speedCompactionLine(e) {
36
+ return `compacting — decode fell to ${Math.round(e.tps)} tok/s at ${Math.round(e.ctxTokens / 1000)}K (floor ${e.floorTps})`;
37
+ }
@@ -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);
@@ -7,6 +7,7 @@ import { homedir, userInfo } from "node:os";
7
7
  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
+ import { isLaunchdDisabled } from "./services/preflight.js";
10
11
  const LABEL = "co.0perator.gateway";
11
12
  function paths() {
12
13
  const home = process.env.OPERATOR_HOME || join(homedir(), ".operator"); // the runtime's home, not the CLI's config home
@@ -40,7 +41,10 @@ function server(file) {
40
41
  return undefined;
41
42
  }
42
43
  }
43
- const launchctl = (...args) => spawnSync("launchctl", args, { stdio: "ignore" }).status ?? 1;
44
+ const realLaunchctl = (args) => {
45
+ const r = spawnSync("launchctl", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
46
+ return { status: r.status ?? 1, out: r.stdout ?? "" };
47
+ };
44
48
  const domain = () => `gui/${userInfo().uid}`;
45
49
  /** What the gateway will launch: on a managed box the aurora consumer's binary or nothing; otherwise the legacy chain's
46
50
  * links (the PATH lookup that ends that chain happens inside the gateway, with the gateway's own PATH). */
@@ -83,7 +87,7 @@ const USAGE = `usage: operator gateway {start [-d]|stop|status|health|logs}
83
87
  status gateway, llama-server, models, binary and toolchain
84
88
  health llama-server /health
85
89
  logs follow the gateway and llama-server logs`;
86
- export async function runGateway(args, out = (s) => process.stdout.write(s + "\n")) {
90
+ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n"), launchctl = realLaunchctl) {
87
91
  const p = paths();
88
92
  const [cmd = "status", ...rest] = args;
89
93
  switch (cmd) {
@@ -93,15 +97,20 @@ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n
93
97
  out(`${p.plist} is not installed — run operator-runtime/scripts/install.sh first.`);
94
98
  return 1;
95
99
  }
96
- launchctl("bootstrap", domain(), p.plist);
97
- const code = launchctl("kickstart", "-k", `${domain()}/${LABEL}`);
100
+ const disabled = launchctl(["print-disabled", domain()]);
101
+ if (disabled.status === 0 && isLaunchdDisabled(disabled.out, LABEL)) {
102
+ out(`${LABEL} is disabled in launchd — not starting it (launchctl enable ${domain()}/${LABEL} first if you mean to)`);
103
+ return 1;
104
+ }
105
+ launchctl(["bootstrap", domain(), p.plist]);
106
+ const code = launchctl(["kickstart", "-k", `${domain()}/${LABEL}`]).status;
98
107
  out(code === 0 ? "gateway started through launchd" : "launchctl kickstart failed");
99
108
  return code;
100
109
  }
101
110
  return spawnSync(process.execPath, [p.gateway, ...rest], { stdio: "inherit" }).status ?? 1;
102
111
  }
103
112
  case "stop": {
104
- launchctl("bootout", `${domain()}/${LABEL}`);
113
+ launchctl(["bootout", `${domain()}/${LABEL}`]);
105
114
  const gw = readPid(p.bootLock);
106
115
  const llama = server(p.serverJson)?.pid;
107
116
  for (const pid of [gw, llama])
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
+ }
@@ -4,6 +4,8 @@ import { centralRecording } from "../telemetry/ingest.js";
4
4
  import { runBatch, defaultClassify, defaultKeys, cancelledResult } from "../engine/batch-scheduler.js";
5
5
  import { registrySafeTools } from "./tier.js";
6
6
  import { heldForPlanReview } from "./plan-review.js";
7
+ import { isPhoneLine } from "./signature.js";
8
+ import { grantPhone, phonePreview } from "../tools/device/classify.js";
7
9
  export { PermissionPolicy } from "./policy.js";
8
10
  const NO_RETRY = "Do not retry this call or an equivalent; choose another approach or ask the user.";
9
11
  const DENIED = (name, why) => `Permission denied: "${name}" was denied ` +
@@ -62,27 +64,41 @@ export function withPermissions(inner, policy, opts = {}) {
62
64
  // A human-signature line (money/prod/destructive) surfaces as its own control event so a dashboard/
63
65
  // mobile flags WHY a human was pulled in — and a background sub-agent (no approver) is denied below.
64
66
  const line = policy.signatureLineFor(name, args);
65
- const plan = line ? policy.planAnswer(line) : null;
66
- if (line && plan === "hold") {
67
- // Autonomous: the plan the owner approved does not list this class. Held, never prompted, and not remembered as
68
- // a denial — the same call runs once a plan that lists it is approved.
69
- sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (held for plan review)` } });
70
- tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
71
- return heldForPlanReview(name, line, policy.approvedPlanClasses());
72
- }
73
- if (plan === "run") {
74
- approved = true; // the owner approved this class with the plan
75
- // still a signature-line call: the dashboard's critical feed shows it ran, and on whose say-so
76
- sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (run under approved plan)` } });
77
- }
78
- else {
79
- if (line)
80
- sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
81
- approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
67
+ if (isPhoneLine(line)) {
68
+ // A phone line: the owner, every time, in every mode — no plan answers it — shown the screen it will act on. The
69
+ // approval becomes a one-shot grant the tool itself checks (tools/device/classify.ts).
70
+ sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
71
+ const pv = opts.approve ? await phonePreview(name, args) : {};
72
+ approved = opts.approve ? await opts.approve(name, args, { line, once: true, ...(pv.screenshot ? { preview: pv.screenshot } : {}), ...(pv.target ? { target: pv.target } : {}) }) : false;
82
73
  if (!approved) {
83
74
  tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
84
75
  return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
85
76
  }
77
+ grantPhone(name, args);
78
+ }
79
+ else {
80
+ const plan = line ? policy.planAnswer(line) : null;
81
+ if (line && plan === "hold") {
82
+ // Autonomous: the plan the owner approved does not list this class. Held, never prompted, and not remembered as
83
+ // a denial — the same call runs once a plan that lists it is approved.
84
+ sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (held for plan review)` } });
85
+ tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
86
+ return heldForPlanReview(name, line, policy.approvedPlanClasses());
87
+ }
88
+ if (plan === "run") {
89
+ approved = true; // the owner approved this class with the plan
90
+ // still a signature-line call: the dashboard's critical feed shows it ran, and on whose say-so
91
+ sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (run under approved plan)` } });
92
+ }
93
+ else {
94
+ if (line)
95
+ sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
96
+ approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
97
+ if (!approved) {
98
+ tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
99
+ return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
100
+ }
101
+ }
86
102
  }
87
103
  }
88
104
  // An esc during the (human) approval wait: the approval may land AFTER the interrupt, and an approved edit
@@ -8,6 +8,8 @@
8
8
  // Precedence: a signature line beats a per-tool "allow" rule and the mode — it can only ever be relaxed by
9
9
  // the policy being fully inert (the local owner in bypass+admin+no-rules, where the wrapper is skipped
10
10
  // entirely). The moment any enforcement is on (a tier, audit/gated mode, or a rule), the lines are live.
11
+ import { phoneLine, PHONE_LINES } from "../tools/device/classify.js";
12
+ export const isPhoneLine = (l) => !!l && PHONE_LINES.includes(l);
11
13
  // Tool-NAME patterns: money-moving integrations (mostly MCP tools) — pay/charge/refund/payout/transfer/
12
14
  // wire/invoice/billing/subscription changes. Conservative: a false positive just adds one approval.
13
15
  const MONEY_NAME = /(pay(ment|out|ee)?|charge|refund|transfer|wire|invoice|billing|subscription|checkout|stripe|disburse)/i;
@@ -61,6 +63,9 @@ function blob(name, args) {
61
63
  /** Which signature line a call crosses, or null. Checked on every gated call: null lets the normal
62
64
  * policy decide; a non-null value forces approval (and, absent an approver, a deny). */
63
65
  export function signatureLine(name, args) {
66
+ const phone = phoneLine(name, args);
67
+ if (phone)
68
+ return phone;
64
69
  if (MONEY_NAME.test(name))
65
70
  return "money";
66
71
  const b = blob(name, args);
@@ -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
+ }