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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +1 -1
  2. package/dist/autonomy/delegate-mode.js +159 -0
  3. package/dist/autonomy/delegate.js +1 -1
  4. package/dist/autonomy/session-factory.js +2 -0
  5. package/dist/background/index.js +26 -2
  6. package/dist/background/resume.js +125 -0
  7. package/dist/browser/engine.js +163 -0
  8. package/dist/browser/session.js +130 -140
  9. package/dist/cli.js +174 -12
  10. package/dist/config/settings.js +1 -1
  11. package/dist/engine/agent.js +1 -1
  12. package/dist/engine/aurora.js +4 -4
  13. package/dist/engine/compaction.js +1 -1
  14. package/dist/engine/moa.js +2 -1
  15. package/dist/engine/selfheal.js +1 -1
  16. package/dist/engine/toolcalls.js +6 -6
  17. package/dist/index.js +3 -0
  18. package/dist/mcp/phone-server.js +30 -0
  19. package/dist/permissions/index.js +33 -17
  20. package/dist/permissions/signature.js +5 -0
  21. package/dist/phone-cli.js +65 -0
  22. package/dist/remote/host.js +31 -2
  23. package/dist/router/models.js +5 -15
  24. package/dist/selfimprove/index.js +1 -1
  25. package/dist/session.js +48 -7
  26. package/dist/tools/deferred.js +1 -0
  27. package/dist/tools/device/android.js +227 -0
  28. package/dist/tools/device/classify.js +127 -0
  29. package/dist/tools/device/deps.js +69 -0
  30. package/dist/tools/device/desktop.js +82 -0
  31. package/dist/tools/device/harness.js +262 -0
  32. package/dist/tools/device/iphone.js +206 -0
  33. package/dist/tools/device/mirroring-jxa.js +146 -0
  34. package/dist/tools/device/setup.js +90 -0
  35. package/dist/tools/device/tools.js +70 -0
  36. package/dist/tools/device/types.js +19 -0
  37. package/dist/tools/registry.js +12 -3
  38. package/dist/ui/App.js +4 -3
  39. package/dist/ui/ApprovalPrompt.js +10 -4
  40. package/dist/ui/BgPanel.js +2 -2
  41. package/dist/ui/UpdatePrompt.js +40 -0
  42. package/dist/ui/modelPicker.js +1 -1
  43. package/dist/ui/slashCommands.js +1 -0
  44. package/dist/update-check.js +134 -0
  45. package/dist/update.js +59 -15
  46. package/dist/util/slash.js +2 -2
  47. package/package.json +4 -2
  48. package/src/tools/device/NOTICE +37 -0
  49. package/dist/browser/cdp.js +0 -271
package/README.md CHANGED
@@ -22,7 +22,7 @@ src/
22
22
  │ │ # exponential backoff w/ jitter (honors Retry-After)
23
23
  │ ├── compaction.ts # endpoint-aware auto-compaction + fact-preserving summaryPrompt
24
24
  │ ├── messages.ts # Msg/Conversation, buildMessages, tool-pair repair, shape validation
25
- │ └── toolcalls.ts # recover text-emitted (Qwen XML / JSON) tool calls
25
+ │ └── toolcalls.ts # recover text-emitted (XML function-call / JSON) tool calls
26
26
  ├── router/router.ts # AuroraRouter — size-based routing, failover, Saddle fallback, pin/resetTurn
27
27
  ├── tools/ # the tool set (63): shell/file/grep/git/memory/checkpoint/web_fetch/knowledge
28
28
  │ │ # + wave 1-2 (missions, kanban boards, routines, validation, pkg, code search,
@@ -0,0 +1,159 @@
1
+ const env = () => globalThis.process?.env ?? {};
2
+ let live = {};
3
+ /** The guard settings every session in this process reads per call: set at startup from settings.delegate and again
4
+ * by `/delegate`, so a toggle applies to the main loop and every running sub-agent at their next tool call. */
5
+ export function setDelegateSettings(s) {
6
+ live = { ...(s ?? {}) };
7
+ }
8
+ /** KODE_DELEGATE_GUARD=1/0 wins over the setting (a headless run can fence itself without touching settings.json). */
9
+ export function delegateGuardOn(e = env(), s = live) {
10
+ const v = e.KODE_DELEGATE_GUARD;
11
+ if (v === "1" || v === "true")
12
+ return true;
13
+ if (v === "0" || v === "false")
14
+ return false;
15
+ return !!s.guard;
16
+ }
17
+ const PUSH = /\bgit\s+(?:-C\s+\S+\s+)?push\b/i;
18
+ const DEPLOY = new RegExp("\\b(systemctl\\s+(restart|start|stop)|launchctl\\s+(kickstart|bootout|bootstrap|load|unload)" +
19
+ "|docker\\s+compose\\s+up|docker-compose\\s+up|docker\\s+stack\\s+deploy" +
20
+ "|wrangler\\s+(deploy|publish)|fly(ctl)?\\s+deploy|kamal\\s+deploy|cap\\s+\\w+\\s+deploy|vercel\\s+(--prod|deploy\\s+--prod)" +
21
+ "|npm\\s+publish|cargo\\s+publish|twine\\s+upload)\\b", "i");
22
+ const SHELL_TOOLS = new Set(["bash", "shell_exec", "shell_background", "shell_task_start"]);
23
+ const WRITE_TOOLS = { file_write: "path", file_edit: "path", file_create: "path", file_delete: "path", download_file: "dest" };
24
+ function expand(p, e) {
25
+ return p === "~" || p.startsWith("~/") ? `${e.HOME ?? ""}${p.slice(1)}` : p;
26
+ }
27
+ function absolute(p, cwd, e) {
28
+ const x = expand(p, e);
29
+ const joined = x.startsWith("/") ? x : `${cwd.replace(/\/+$/, "")}/${x}`;
30
+ const out = [];
31
+ for (const part of joined.split("/")) {
32
+ if (!part || part === ".")
33
+ continue;
34
+ if (part === "..")
35
+ out.pop();
36
+ else
37
+ out.push(part);
38
+ }
39
+ return `/${out.join("/")}`;
40
+ }
41
+ /** The nearest directory at or above `dir` holding a `.git` entry, else `dir` itself. */
42
+ export function repoRoot(dir, exists) {
43
+ for (let d = dir; d && d !== "/"; d = d.slice(0, d.lastIndexOf("/")) || "/") {
44
+ if (exists(`${d}/.git`))
45
+ return d;
46
+ }
47
+ return dir;
48
+ }
49
+ /** Where a fenced write may land. */
50
+ export function taskRoots(ctx) {
51
+ const e = ctx.env ?? env();
52
+ const s = ctx.settings ?? live;
53
+ const cwd = absolute(ctx.cwd, "/", e);
54
+ const roots = [repoRoot(cwd, ctx.exists), ...(s.repos ?? []).map((r) => absolute(r, cwd, e))];
55
+ for (const v of [e.OPERATOR_SCRATCH, e.TMPDIR, "/tmp", "/private/tmp"])
56
+ if (v)
57
+ roots.push(absolute(v, cwd, e));
58
+ return [...new Set(roots.flatMap((r) => [r, ctx.realpath(r)]))];
59
+ }
60
+ function under(path, roots) {
61
+ return roots.some((r) => path === r || path.startsWith(r.endsWith("/") ? r : `${r}/`));
62
+ }
63
+ /** Why the guard refuses this call, or null to let it run. */
64
+ export function delegateGuardReason(name, args, ctx) {
65
+ const e = ctx.env ?? env();
66
+ const s = ctx.settings ?? live;
67
+ if (!delegateGuardOn(e, s))
68
+ return null;
69
+ const pushOk = !!s.allowPush;
70
+ if (SHELL_TOOLS.has(name)) {
71
+ const cmd = String(args.command ?? "");
72
+ if (PUSH.test(cmd) && !pushOk)
73
+ return "git push is blocked — set delegate.allowPush (or `/delegate push on`) to let this task push";
74
+ if (DEPLOY.test(cmd))
75
+ return "production deploys and publishes are blocked (restart / deploy / publish) — queue it for the owner";
76
+ return null;
77
+ }
78
+ if (name === "git_command") {
79
+ const argv = Array.isArray(args.args) ? args.args.map(String) : String(args.args ?? "").split(/\s+/);
80
+ if (argv.find((a) => !a.startsWith("-")) === "push" && !pushOk)
81
+ return "git push is blocked — set delegate.allowPush (or `/delegate push on`) to let this task push";
82
+ return null;
83
+ }
84
+ if (name === "git_pr" && args.action === "open" && !pushOk)
85
+ return "opening a PR pushes the branch, and pushing is blocked — set delegate.allowPush (or `/delegate push on`)";
86
+ if (name === "checkpoint" && args.push && !pushOk)
87
+ return "checkpoint with push is blocked — commit without push, or set delegate.allowPush (or `/delegate push on`)";
88
+ if (name === "deploy_config" && (args.build_command || args.run_command || args.target))
89
+ return "deploy configuration is blocked — queue it for the owner";
90
+ const key = WRITE_TOOLS[name];
91
+ if (key && typeof args[key] === "string" && args[key]) {
92
+ const cwd = typeof args.cwd === "string" && args.cwd ? args.cwd : ctx.cwd;
93
+ const target = absolute(String(args[key]), absolute(cwd, "/", e), e);
94
+ const roots = taskRoots(ctx);
95
+ const real = (() => { const dir = target.slice(0, target.lastIndexOf("/")) || "/"; return `${ctx.realpath(dir)}/${target.slice(target.lastIndexOf("/") + 1)}`; })();
96
+ if (!under(target, roots) || !under(real, roots)) {
97
+ return `writes are limited to the task repos; ${target} is outside them (${roots.filter((r, i, a) => a.indexOf(r) === i).slice(0, 3).join(", ")}) — add the folder to delegate.repos to allow it`;
98
+ }
99
+ }
100
+ return null;
101
+ }
102
+ const BLOCKED = (name, reason) => `Blocked by delegate mode: "${name}" was not run. ${reason}. Do not retry it or an equivalent; continue with what is allowed, or report this step for the owner.`;
103
+ /** Fence a session's executor. A call the guard refuses is answered here (reported blocked) and never reaches the
104
+ * permission layer; everything else, and every call while the guard is off, passes through unchanged. */
105
+ export function withDelegateGuard(inner, ctx) {
106
+ const check = (name, args) => delegateGuardReason(name, args, ctx);
107
+ return {
108
+ sched: inner.sched,
109
+ execute: async (name, args, report) => {
110
+ const why = check(name, args);
111
+ if (why) {
112
+ report?.refused("blocked");
113
+ return BLOCKED(name, why);
114
+ }
115
+ return inner.execute(name, args, report);
116
+ },
117
+ executeParallel: async (calls, onSettle, signal, onStart) => {
118
+ const refused = calls.map((c) => check(c.name, c.args));
119
+ if (refused.every((r) => r === null))
120
+ return inner.executeParallel(calls, onSettle, signal, onStart);
121
+ const allowed = calls.map((c, i) => ({ c, i })).filter(({ i }) => refused[i] === null);
122
+ const results = calls.map((c, i) => (refused[i] ? BLOCKED(c.name, refused[i]) : ""));
123
+ refused.forEach((r, i) => { if (r)
124
+ onSettle?.(i, results[i], "blocked"); });
125
+ if (allowed.length) {
126
+ const out = await inner.executeParallel(allowed.map(({ c }) => c), onSettle && ((j, r, why) => onSettle(allowed[j].i, r, why)), signal, onStart && ((j) => onStart(allowed[j].i)));
127
+ out.forEach((r, j) => { results[allowed[j].i] = r; });
128
+ }
129
+ return results;
130
+ },
131
+ };
132
+ }
133
+ export const DELEGATE_USAGE = "/delegate · /delegate planner <model> [executor] · /delegate subagents <model> · /delegate guard on|off · /delegate push on|off · /delegate off";
134
+ export function parseDelegate(argText) {
135
+ const [verb, a, b, ...rest] = argText.trim().split(/\s+/).filter(Boolean);
136
+ const onOff = (x) => (x === "on" ? true : x === "off" ? false : undefined);
137
+ if (!verb || verb === "status")
138
+ return { kind: "status" };
139
+ if (verb === "off" && !a)
140
+ return { kind: "off" };
141
+ if (verb === "planner" && a && !rest.length)
142
+ return { kind: "planner", model: a, executor: b };
143
+ if ((verb === "subagents" || verb === "subagent" || verb === "agents") && a && !b)
144
+ return { kind: "subagents", model: a };
145
+ if ((verb === "guard" || verb === "push") && onOff(a) !== undefined && !b)
146
+ return { kind: verb, on: onOff(a) };
147
+ return { kind: "error", message: `usage: ${DELEGATE_USAGE}` };
148
+ }
149
+ export function delegateStatusLines(v) {
150
+ const team = v.activeModel === "moa" && v.plannerModel
151
+ ? `planner ${v.plannerModel} → executor ${v.specialist ?? "?"} (/model moa)`
152
+ : `main loop ${v.activeModel}; no delegate planner`;
153
+ return [
154
+ `delegate · ${team}`,
155
+ `sub-agents (spawn_agent, delegate_task default): ${v.subagentModel}`,
156
+ `guard ${v.guard ? "ON" : "off"}${v.guard ? ` · push ${v.allowPush ? "allowed" : "blocked"} · deploys blocked · writes: this repo${v.repos.length ? `, ${v.repos.join(", ")}` : ""}, scratch, temp` : ""}`,
157
+ DELEGATE_USAGE,
158
+ ];
159
+ }
@@ -199,7 +199,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
199
199
  // dropped in by changing one value — the planner still overrides per call via `args.model`.
200
200
  const defaultModel = (await defaultModelStore()).getStore() || subagentModelFor(settings);
201
201
  const modelId = String(args.model ?? "").trim() || defaultModel;
202
- // Gate BYO providers (Claude/OpenAI/Gemini/Qwen/…) on the user actually having stored that provider's key,
202
+ // Gate BYO providers (Claude/OpenAI/Gemini/…) on the user actually having stored that provider's key,
203
203
  // the same check /model applies — so an unconnected provider fails fast with the actionable "store the key"
204
204
  // error BEFORE a sub-agent session is spun up (and before setModel would refuse it anyway, more expensively).
205
205
  // A key the owner stored explicitly, never an ambient vendor variable: the model picks this target, not the owner.
@@ -15,6 +15,7 @@ import { resolveMode } from "../classifier/modes.js";
15
15
  import { classifierConfig } from "../classifier/config.js";
16
16
  import { auroraOnDemand } from "../services/preflight.js";
17
17
  import { setSpeculation, speculationEnabled } from "../engine/aurora.js";
18
+ import { setDelegateSettings } from "./delegate-mode.js";
18
19
  /** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
19
20
  * multi-tier chain builder (primary → other fleet nodes → back-compat single failover → cloud), so a
20
21
  * wedged/degraded endpoint fails over through the whole fleet before the turn can error. */
@@ -41,6 +42,7 @@ export function envSubagentRole(env = process.env) {
41
42
  export function createAutonomySession(settings, opts = {}) {
42
43
  const role = opts.role ?? envSubagentRole();
43
44
  setSpeculation(speculationEnabled(settings)); // GW-26: the owner's opt-out reaches headless, ACP and delegated runs
45
+ setDelegateSettings(settings.delegate); // delegate mode's guard fences headless, ACP and delegated runs too
44
46
  const session = new Session({
45
47
  systemPrompt: role
46
48
  ? subagentSystemPrompt({ cwd: opts.cwd ?? process.cwd(), ctxTokens: modelCtxFor(settings.activeModel, settings.models), type: role })
@@ -1,6 +1,7 @@
1
1
  import { buildBrief, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, partialCounts, SUBAGENT_ROLES, roleForBrief, roleCanWrite, } from "../engine/grandmaster.js";
2
2
  import { isEngineFinal } from "../engine/continuation.js";
3
3
  import { createWorktree, finalizeWorktree } from "./worktree.js";
4
+ import { resumeBrief } from "./resume.js";
4
5
  const RECENT_STEPS = 5; // tool steps kept per agent for the live view (older ones scroll off)
5
6
  const THOUGHT_MAX = 160; // chars of the latest reasoning snippet retained (tail)
6
7
  // The work ledger + stuck checks (10/31: a sub-agent ran 54 rounds / 33 min, wrote nothing, and nobody could tell).
@@ -183,12 +184,14 @@ export class BackgroundAgents {
183
184
  * "no background job bg1", concluded the sub-agent had been "evicted", and re-spawned a duplicate onto
184
185
  * the one shared endpoint. Same-looking ids in two different registries was the whole bug; disjoint
185
186
  * namespaces make that specific confusion structurally impossible, not just better-worded. */
186
- spawn(task, role, name) {
187
+ spawn(task, role, name, resumed) {
187
188
  if (this.inFlight() >= this.maxConcurrent + this.maxQueued)
188
189
  return "";
189
190
  const id = `agent-${++this.seq}`;
190
191
  const type = role ?? roleForBrief(task);
191
- const brief = buildBrief({ objective: task, type }, process.cwd());
192
+ // A resumed agent runs on its original brief plus the engine's progress note; info.task stays the original, so a
193
+ // second quit saves the brief again rather than a note inside a note.
194
+ const brief = buildBrief({ objective: resumed ? resumeBrief(resumed) : task, type }, process.cwd());
192
195
  const lane = routeLane(brief, { type });
193
196
  const label = summarizeTask(task);
194
197
  // Starts QUEUED; pump() promotes it to working when a concurrency slot is free (startedAt is stamped
@@ -199,6 +202,7 @@ export class BackgroundAgents {
199
202
  id, label, status: "queued", task, round: 0, tokens: 0, model, lane,
200
203
  name: this.uniqueName(name?.trim().replace(/\s+/g, " ").slice(0, 24) || AGENT_NAMES[(this.seq - 1) % AGENT_NAMES.length]),
201
204
  title: SUBAGENT_ROLES[type]?.title ?? "assistant", role: type,
205
+ ...(resumed ? { resumed: true } : {}),
202
206
  };
203
207
  this.agents.set(id, { info, brief, type });
204
208
  this.queue.push(id);
@@ -667,6 +671,26 @@ export class BackgroundAgents {
667
671
  .map((a) => a.info.id);
668
672
  return ids.filter((id) => this.requestStop(id, by, byLabel));
669
673
  }
674
+ /** Every agent still working or queued, as a record the next session in `cwd` can resume (background/resume.ts).
675
+ * Finished, stopped and failed agents are left out: they are never resumed. `tasks` is the session's open task list. */
676
+ resumable(cwd, tasks = []) {
677
+ return [...this.agents.values()]
678
+ .filter((a) => a.info.status === "working" || a.info.status === "queued")
679
+ .map(({ info, session }) => {
680
+ const snap = typeof session?.snapshot === "function" ? session.snapshot() : [];
681
+ const progress = [
682
+ snap.length ? partialReport(snap, `${info.name ?? info.id} was cut off when Operator closed after ${info.round ?? 0} rounds`) : "",
683
+ info.progress ? `Last step in progress: ${info.progress}` : "",
684
+ ].filter(Boolean).join("\n\n");
685
+ return {
686
+ id: info.id, name: info.name ?? info.id, label: info.label, role: info.role ?? "generic", model: info.model,
687
+ task: info.task ?? info.label, cwd,
688
+ tasks: tasks.filter((t) => t.status === "pending" || t.status === "in_progress").map((t) => ({ ...t })),
689
+ progress, written: [...(info.written ?? [])], rounds: info.round ?? 0, startedAt: info.startedAt,
690
+ status: info.status,
691
+ };
692
+ });
693
+ }
670
694
  /** The concurrency caps (TUI plan #11): how many agents run at once, and how many may wait for a slot. */
671
695
  limits() {
672
696
  return { running: this.maxConcurrent, queued: this.maxQueued };
@@ -0,0 +1,125 @@
1
+ // Agents still working when Operator closes are picked back up when it reopens (decision:
2
+ // _ai-docs/decisions/2026-11-25-resume-agents-on-reopen.md). On quit, every live background agent (working or queued) is
3
+ // written as one record per workspace in the Operator home: its brief, role, model, task list and the progress it had made.
4
+ // The next session in the same folder re-spawns each one with that progress as an engine note (settings.agents.
5
+ // resumeOnReopen, default on) or offers them in /agents as paused. A finished, stopped or failed agent is never written, so
6
+ // it is never resumed. The file is rewritten atomically (tmp + rename, 0600) and a record that does not parse is ignored
7
+ // with a warning and removed, never half-trusted.
8
+ import { createHash } from "node:crypto";
9
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
+ import { dirname } from "node:path";
11
+ import { operatorPath } from "../config/home.js";
12
+ import { engineNote } from "../engine/continuation.js";
13
+ export const RESUME_VERSION = 1;
14
+ const MAX_AGENTS = 16;
15
+ const MAX_TEXT = 8000;
16
+ const MAX_PROGRESS = 4000;
17
+ const ROLES = new Set(["code-edit", "search", "research", "review", "plan", "generic"]);
18
+ /** One file per workspace, named by the folder's hash (the same scheme as the scratch fallback). */
19
+ export function resumeFile(cwd) {
20
+ return operatorPath("agents", "resume", `${createHash("sha1").update(cwd).digest("hex").slice(0, 16)}.json`);
21
+ }
22
+ /** The setting, read once per use: on unless the owner turned it off. */
23
+ export const resumeOnReopen = (s) => s?.agents?.resumeOnReopen !== false;
24
+ const clip = (s, n) => (s.length <= n ? s : `${s.slice(0, n - 1)}…`);
25
+ /** Write the workspace's live agents; an empty list removes the file. Atomic and owner-only. */
26
+ export function saveResumable(cwd, agents) {
27
+ const file = resumeFile(cwd);
28
+ if (!agents.length) {
29
+ clearResumable(cwd);
30
+ return undefined;
31
+ }
32
+ const doc = {
33
+ v: RESUME_VERSION, cwd, savedAt: new Date().toISOString(),
34
+ agents: agents.slice(0, MAX_AGENTS).map((a) => ({ ...a, task: clip(a.task, MAX_TEXT), progress: clip(a.progress, MAX_PROGRESS) })),
35
+ };
36
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
37
+ const tmp = `${file}.${process.pid}.tmp`;
38
+ writeFileSync(tmp, JSON.stringify(doc), { mode: 0o600 });
39
+ renameSync(tmp, file);
40
+ return file;
41
+ }
42
+ function valid(a, cwd) {
43
+ const r = a;
44
+ return !!r && typeof r.id === "string" && typeof r.task === "string" && r.task.trim() !== "" && typeof r.name === "string"
45
+ && typeof r.role === "string" && ROLES.has(r.role) && r.cwd === cwd && (r.status === "working" || r.status === "queued")
46
+ && Array.isArray(r.tasks) && typeof r.progress === "string";
47
+ }
48
+ /** The workspace's saved agents. A file that does not parse, is another version or names another folder is ignored with
49
+ * one warning and removed, so it never warns twice or resumes the wrong thing. */
50
+ export function loadResumable(cwd, warn = () => { }) {
51
+ const file = resumeFile(cwd);
52
+ if (!existsSync(file))
53
+ return [];
54
+ let doc = null;
55
+ try {
56
+ doc = JSON.parse(readFileSync(file, "utf8"));
57
+ }
58
+ catch { /* reported below */ }
59
+ if (!doc || doc.v !== RESUME_VERSION || doc.cwd !== cwd || !Array.isArray(doc.agents)) {
60
+ warn(`ignored the saved agents for this folder: ${file} is not a valid record (removed)`);
61
+ clearResumable(cwd);
62
+ return [];
63
+ }
64
+ const ok = doc.agents.filter((a) => valid(a, cwd));
65
+ if (ok.length < doc.agents.length)
66
+ warn(`ignored ${doc.agents.length - ok.length} saved agent record(s) that did not parse`);
67
+ return ok;
68
+ }
69
+ /** What a surface shows as waiting to resume in `cwd` (the desktop and remote surfaces read this; the TUI resumes them). */
70
+ export const listResumable = (cwd) => loadResumable(cwd);
71
+ export function clearResumable(cwd) {
72
+ try {
73
+ rmSync(resumeFile(cwd), { force: true });
74
+ }
75
+ catch { /* already gone */ }
76
+ }
77
+ /** The brief a resumed agent runs on: its original brief, then one engine note with what it had already done. */
78
+ export function resumeBrief(a) {
79
+ const tasks = a.tasks.length ? a.tasks.map((t) => `- [${t.status}] #${t.id} ${t.text}`).join("\n") : "(none)";
80
+ const files = a.written.length ? a.written.join(", ") : "(none)";
81
+ const note = engineNote(`resumed after the app closed; continue from this progress (${a.rounds} round(s) done before it closed). ` +
82
+ `Do NOT redo a step this progress reports as finished, and do not rewrite these files unless the step needs a change: ${files}.\n` +
83
+ `Task list when it closed:\n${tasks}\n` +
84
+ `Progress:\n${a.progress.trim() || "(it had not written notes yet)"}`);
85
+ return `${a.task}\n\n${note}`;
86
+ }
87
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
88
+ /** Re-spawn saved agents through `start` (false = no free slot); those that did not start stay paused. */
89
+ export function startSaved(saved, start) {
90
+ const started = [];
91
+ const left = [];
92
+ for (const a of saved)
93
+ (start(a) ? started : left).push(a);
94
+ const lines = [
95
+ started.length ? `↻ resumed ${plural(started.length, "agent", "agents")} from when Operator closed: ${started.map((a) => `${a.name} (round ${a.rounds})`).join(", ")}` : "",
96
+ left.length ? `${left.length} still paused (no free agent slot) — /agents resume when one frees` : "",
97
+ ];
98
+ return { started, left, line: lines.filter(Boolean).join("\n") };
99
+ }
100
+ /** Session start: the folder's saved agents are re-spawned (the record is cleared first, so a crash mid-resume cannot run
101
+ * them twice) or, with resumeOnReopen off, kept on disk and returned as paused for /agents. */
102
+ export function pickUpSaved(cwd, settings, start, warn = () => { }) {
103
+ const saved = loadResumable(cwd, warn);
104
+ if (!saved.length)
105
+ return { started: [], paused: [] };
106
+ if (!resumeOnReopen(settings)) {
107
+ return {
108
+ started: [], paused: saved,
109
+ line: `${plural(saved.length, "agent was", "agents were")} still working when Operator closed — paused: ${saved.map((a) => a.name).join(", ")}\n` +
110
+ " /agents resume to pick them up · /agents discard to drop them (settings.agents.resumeOnReopen is off)",
111
+ };
112
+ }
113
+ clearResumable(cwd);
114
+ const r = startSaved(saved, start);
115
+ return { started: r.started, paused: r.left, line: r.line };
116
+ }
117
+ /** What the quit surfaces show: the TUI's one line, and the desktop dialog's title and list. */
118
+ export function quitSummary(agents, resume) {
119
+ const n = agents.length;
120
+ const what = `${n} agent${n === 1 ? "" : "s"} still working`;
121
+ const line = resume
122
+ ? `${what} — they will resume next time (settings.agents.resumeOnReopen)`
123
+ : `${what} — saved as paused; /agents resume picks them up next time (settings.agents.resumeOnReopen is off)`;
124
+ return { count: n, line, agents: agents.map(({ id, name, label, status }) => ({ id, name, label, status })) };
125
+ }
@@ -0,0 +1,163 @@
1
+ // Browser engine — Playwright (playwright-core) under the `browser` / `browser_read` / `browser_vault` tools and
2
+ // image_analyze's page capture. WHY: one browser story. Playwright gives real input (trusted mouse and keyboard events,
3
+ // auto-wait for an element to be visible and enabled), its selector engine (CSS plus text=, role=) and a throwaway
4
+ // profile per launch; the hand-rolled CDP client it replaces dispatched synthetic el.click() and needed a system Chrome.
5
+ // Why and what was rejected: _ai-docs/decisions/2026-11-25-playwright-browser-engine.md (repo root).
6
+ // Purity: playwright-core and every node builtin are reached lazily (registry.ts imports session.ts, which imports this),
7
+ // so the neutral bundle never loads them; run() bodies only execute on the node CLI.
8
+ const IDLE_TTL_MS = 9 * 60_000; // an idle browser decommissions after 9 min (mirrors the persistent shell)
9
+ const ACTION_TIMEOUT_MS = 20_000; // per click / fill / eval
10
+ const NAV_TIMEOUT_MS = 30_000; // page-load budget
11
+ async function nodeImport(id) {
12
+ const g = globalThis;
13
+ try {
14
+ const m = g.process?.getBuiltinModule?.(id);
15
+ if (m)
16
+ return m;
17
+ }
18
+ catch { /* fall through to dynamic import */ }
19
+ return import(id);
20
+ }
21
+ // ── URL policy — the browser can read anything the network can; no file:// (secret paths adjacent), no chrome://.
22
+ export function checkNavigationUrl(raw) {
23
+ let u;
24
+ try {
25
+ u = new URL(raw);
26
+ }
27
+ catch {
28
+ return `browser: not a valid URL: ${raw.slice(0, 120)}`;
29
+ }
30
+ const scheme = u.protocol;
31
+ if (scheme === "http:" || scheme === "https:" || scheme === "about:" || scheme === "data:")
32
+ return null;
33
+ return `browser: scheme '${scheme}' blocked (allow: http, https, about, data — file:// and chrome:// are off the policy)`;
34
+ }
35
+ /** Installed Chrome / Chromium apps, used when Playwright has no browser of its own. Playwright always passes its
36
+ * own temporary --user-data-dir, so launching one of these never opens the owner's real profile. */
37
+ export function systemChromes() {
38
+ return [
39
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
40
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
41
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
42
+ "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser",
43
+ ];
44
+ }
45
+ /** Playwright's browser cache: PLAYWRIGHT_BROWSERS_PATH, else the per-OS default. */
46
+ export function playwrightCacheDir(env, platform) {
47
+ if (env.PLAYWRIGHT_BROWSERS_PATH && env.PLAYWRIGHT_BROWSERS_PATH !== "0")
48
+ return env.PLAYWRIGHT_BROWSERS_PATH;
49
+ const home = env.HOME ?? "";
50
+ if (platform === "darwin")
51
+ return `${home}/Library/Caches/ms-playwright`;
52
+ if (platform === "win32")
53
+ return `${env.LOCALAPPDATA ?? home}\\ms-playwright`;
54
+ return `${env.XDG_CACHE_HOME || `${home}/.cache`}/ms-playwright`;
55
+ }
56
+ const CACHED_EXES = [
57
+ ["chromium_headless_shell-", ["chrome-mac-arm64/headless_shell", "chrome-mac/headless_shell", "chrome-linux64/headless_shell", "chrome-linux/headless_shell"]],
58
+ ["chromium-", [
59
+ "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
60
+ "chrome-mac/Chromium.app/Contents/MacOS/Chromium", "chrome-linux64/chrome", "chrome-linux/chrome",
61
+ ]],
62
+ ];
63
+ /** The binaries to try, in order, after Playwright's own pinned build (`undefined` = let Playwright pick):
64
+ * KODE_CHROME alone when set; else any headless shell Playwright cached for another version (newest first), any
65
+ * cached Chromium, then an installed Chrome. A version mismatch between playwright-core and a cached build works for
66
+ * the actions the tool uses (measured: 1.65 drives headless shell 139 and Chrome 158). */
67
+ export function browserCandidates(env, platform, fs) {
68
+ if (env.KODE_CHROME)
69
+ return [env.KODE_CHROME];
70
+ const out = [undefined];
71
+ const cache = playwrightCacheDir(env, platform);
72
+ const revision = (d) => Number(d.slice(d.lastIndexOf("-") + 1)) || 0;
73
+ for (const [prefix, rels] of CACHED_EXES) {
74
+ const dirs = fs.list(cache).filter((d) => d.startsWith(prefix) && /-\d+$/.test(d)).sort((a, b) => revision(b) - revision(a));
75
+ for (const d of dirs)
76
+ for (const rel of rels)
77
+ if (fs.exists(`${cache}/${d}/${rel}`))
78
+ out.push(`${cache}/${d}/${rel}`);
79
+ }
80
+ for (const c of systemChromes())
81
+ if (fs.exists(c))
82
+ out.push(c);
83
+ return out;
84
+ }
85
+ const MISSING = /Executable doesn't exist|ENOENT|no such file/i;
86
+ /** Headless, and a throwaway profile unless KODE_BROWSER_PROFILE=persistent (then `<operator home>/browser`, never the
87
+ * owner's Chrome profile). Tries each candidate binary until one starts; the error names every one tried and the fix. */
88
+ export async function launchBrowser() {
89
+ let pw;
90
+ try {
91
+ pw = await nodeImport("playwright-core");
92
+ }
93
+ catch (e) {
94
+ throw new Error(`browser: playwright-core is not installed (${e.message.split("\n")[0]}) — reinstall Operator`);
95
+ }
96
+ const fs = await nodeImport("node:fs");
97
+ const proc = globalThis.process;
98
+ const candidates = browserCandidates(proc.env, proc.platform, {
99
+ exists: (p) => { try {
100
+ return fs.existsSync(p);
101
+ }
102
+ catch {
103
+ return false;
104
+ } },
105
+ list: (d) => { try {
106
+ return fs.readdirSync(d);
107
+ }
108
+ catch {
109
+ return [];
110
+ } },
111
+ });
112
+ const persistent = proc.env.KODE_BROWSER_PROFILE === "persistent";
113
+ const tried = [];
114
+ for (const executablePath of candidates) {
115
+ const name = executablePath ?? "playwright's chromium";
116
+ try {
117
+ const opts = { headless: true, executablePath, timeout: NAV_TIMEOUT_MS };
118
+ if (persistent) {
119
+ const dir = await persistentProfileDir(fs);
120
+ const context = await pw.chromium.launchPersistentContext(dir, opts);
121
+ return { context, executable: name, persistent, close: () => context.close() };
122
+ }
123
+ const browser = await pw.chromium.launch(opts);
124
+ const context = await browser.newContext();
125
+ return { context, executable: name, persistent, close: () => browser.close() };
126
+ }
127
+ catch (e) {
128
+ const msg = e.message ?? String(e);
129
+ tried.push(`${name}: ${MISSING.test(msg) ? "not installed" : msg.split("\n")[0].slice(0, 160)}`);
130
+ }
131
+ }
132
+ throw new Error(`browser: no browser could start (${tried.join("; ")}). Install one: npx playwright-core install chromium-headless-shell — or set OPERATOR_CHROME to a Chrome binary`);
133
+ }
134
+ /** `<operator home>/browser`, with prefs that keep Chrome from saving submitted credentials (the vault owns secrets). */
135
+ async function persistentProfileDir(fs) {
136
+ const { operatorPath } = await nodeImport("../config/home.js");
137
+ const dir = operatorPath("browser");
138
+ fs.mkdirSync(`${dir}/Default`, { recursive: true });
139
+ const prefFile = `${dir}/Default/Preferences`;
140
+ if (!fs.existsSync(prefFile)) {
141
+ fs.writeFileSync(prefFile, JSON.stringify({ credentials_enable_service: false, profile: { password_manager_enabled: false } }));
142
+ }
143
+ return dir;
144
+ }
145
+ /** Shape an evaluate() value into plain text. Exported for tests. */
146
+ export function valueToText(v) {
147
+ if (typeof v === "string")
148
+ return v;
149
+ if (v === undefined || v === null)
150
+ return String(v);
151
+ try {
152
+ return JSON.stringify(v);
153
+ }
154
+ catch {
155
+ return String(v);
156
+ }
157
+ }
158
+ /** Playwright's error text without its multi-line call log. */
159
+ export function shortError(e) {
160
+ const msg = e?.message ?? String(e);
161
+ return msg.split("\n").filter((l) => l.trim() && !/^\s*(Call log:|- |=+ logs)/.test(l))[0]?.trim() ?? msg;
162
+ }
163
+ export const BROWSER_CONSTANTS = { IDLE_TTL_MS, ACTION_TIMEOUT_MS, NAV_TIMEOUT_MS };