@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.
- package/README.md +5 -4
- package/dist/auth/commands.js +7 -3
- package/dist/auth/identity.js +1 -0
- package/dist/auth/staff.js +55 -0
- package/dist/autonomy/delegate-mode.js +159 -0
- package/dist/autonomy/delegate.js +42 -15
- package/dist/autonomy/headless.js +7 -4
- package/dist/autonomy/index.js +2 -4
- package/dist/autonomy/session-factory.js +13 -12
- package/dist/autonomy/subagent-model.js +17 -7
- package/dist/background/capacity.js +136 -0
- package/dist/background/evidence.js +42 -0
- package/dist/background/index.js +336 -45
- package/dist/background/lane-phase.js +60 -0
- package/dist/background/lane-summary.js +151 -0
- package/dist/background/notices.js +12 -3
- package/dist/background/resume.js +125 -0
- package/dist/background/synthesis.js +25 -0
- package/dist/browser/engine.js +163 -0
- package/dist/browser/session.js +130 -140
- package/dist/bus/inbox.js +150 -6
- package/dist/cli.js +343 -86
- package/dist/config/features.js +3 -3
- package/dist/config/persona.js +29 -3
- package/dist/config/settings.js +262 -21
- package/dist/config/staff-prompt.js +12 -0
- package/dist/engine/agent.js +52 -41
- package/dist/engine/aurora.js +40 -8
- package/dist/engine/batch-scheduler.js +4 -13
- package/dist/engine/compaction.js +2 -2
- package/dist/engine/continuation.js +30 -32
- package/dist/engine/decision-points.js +2 -3
- package/dist/engine/fanout.js +16 -0
- package/dist/engine/loop-guard.js +26 -83
- package/dist/engine/messages.js +2 -2
- package/dist/engine/moa.js +18 -2
- package/dist/engine/native-vision-node.js +72 -0
- package/dist/engine/native-vision.js +103 -0
- package/dist/engine/selfheal.js +1 -1
- package/dist/engine/toolcalls.js +6 -6
- package/dist/engine/verify-gate.js +37 -7
- package/dist/gateway-cli.js +14 -3
- package/dist/index.js +3 -0
- package/dist/mcp/phone-server.js +30 -0
- package/dist/memory/live-progress.js +4 -5
- package/dist/moa/codeact-lane.js +98 -0
- package/dist/moa/codeact-sandbox.js +409 -0
- package/dist/moa/codeact.js +140 -0
- package/dist/permissions/artifact-visibility.js +10 -0
- package/dist/permissions/index.js +33 -17
- package/dist/permissions/signature.js +5 -0
- package/dist/permissions/tier.js +4 -2
- package/dist/phone-cli.js +65 -0
- package/dist/products/craft.js +2 -2
- package/dist/remote/grants.js +119 -0
- package/dist/remote/host.js +63 -6
- package/dist/router/models.js +29 -29
- package/dist/selfimprove/index.js +9 -7
- package/dist/services/preflight.js +35 -91
- package/dist/session.js +173 -46
- package/dist/skills/install-guard.js +68 -0
- package/dist/skills/install.js +67 -0
- package/dist/toolchain/manifest.json +13 -13
- package/dist/tools/background-result.js +1 -1
- package/dist/tools/classes.js +103 -0
- package/dist/tools/contract.js +1 -1
- package/dist/tools/craft.js +13 -2
- package/dist/tools/deferred.js +1 -0
- package/dist/tools/device/android.js +227 -0
- package/dist/tools/device/classify.js +127 -0
- package/dist/tools/device/deps.js +69 -0
- package/dist/tools/device/desktop.js +82 -0
- package/dist/tools/device/harness.js +262 -0
- package/dist/tools/device/iphone.js +206 -0
- package/dist/tools/device/mirroring-jxa.js +146 -0
- package/dist/tools/device/setup.js +90 -0
- package/dist/tools/device/tools.js +70 -0
- package/dist/tools/device/types.js +19 -0
- package/dist/tools/executor.js +25 -15
- package/dist/tools/generation-gateway.js +94 -0
- package/dist/tools/registry.js +95 -155
- package/dist/ui/App.js +18 -6
- package/dist/ui/ApprovalPrompt.js +10 -4
- package/dist/ui/BgPanel.js +17 -12
- package/dist/ui/Header.js +1 -6
- package/dist/ui/StatusRule.js +18 -7
- package/dist/ui/ToolStep.js +3 -3
- package/dist/ui/Transcript.js +36 -14
- package/dist/ui/UpdatePrompt.js +40 -0
- package/dist/ui/batchLine.js +4 -4
- package/dist/ui/editdiff.js +2 -4
- package/dist/ui/format.js +4 -20
- package/dist/ui/liveTools.js +3 -3
- package/dist/ui/modelPicker.js +1 -1
- package/dist/ui/opsMode.js +20 -0
- package/dist/ui/slashCommands.js +1 -0
- package/dist/ui/types.js +0 -2
- package/dist/update-check.js +145 -0
- package/dist/update.js +59 -15
- package/dist/util/slash.js +2 -2
- package/package.json +4 -2
- package/src/tools/device/NOTICE +37 -0
- package/dist/browser/cdp.js +0 -271
- package/dist/tools/mutating.js +0 -15
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// The lane's "what is it doing" line, in plain words, from real signals only: the running tool and its key argument, the
|
|
2
|
+
// plan step it marked in progress, and the stream phase with its progress. Never the backend (that explains a wait, so it
|
|
3
|
+
// lives in the queued reason and /agents <id>), never a full command line, and redacted before it reaches the TUI. Pure.
|
|
4
|
+
import { redactSecrets } from "../engine/redact.js";
|
|
5
|
+
import { fmtElapsed, fmtTok } from "../ui/format.js";
|
|
6
|
+
import { FILE_READ, LOCAL_SEARCH, PLAN_TOOLS, SHELL_ANY, WEB_FETCH, WEB_SEARCH } from "../tools/classes.js";
|
|
7
|
+
/** Fits one lane line at 100 columns beside the name, round, elapsed and tokens. */
|
|
8
|
+
export const SUMMARY_MAX = 56;
|
|
9
|
+
const WRITES = { file_write: "writing", file_create: "writing", write_file: "writing", file_edit: "editing", edit_file: "editing", multi_edit: "editing", apply_patch: "patching", notebook_edit: "editing" };
|
|
10
|
+
const str = (v) => (typeof v === "string" && v.trim() ? v.replace(/\s+/g, " ").trim() : undefined);
|
|
11
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : undefined);
|
|
12
|
+
const base = (p) => p.replace(/[/\\]+$/, "").split(/[/\\]/).pop() || p;
|
|
13
|
+
const quoted = (s, n = 28) => `"${s.length > n ? `${s.slice(0, n - 1)}…` : s}"`;
|
|
14
|
+
/** Trim to `max` cells with a clean "…" (never mid-surrogate). */
|
|
15
|
+
export function clip(s, max = SUMMARY_MAX) {
|
|
16
|
+
const chars = [...s];
|
|
17
|
+
return chars.length <= max ? s : `${chars.slice(0, max - 1).join("").trimEnd()}…`;
|
|
18
|
+
}
|
|
19
|
+
function lineWindow(args) {
|
|
20
|
+
const start = num(args.start_line) ?? num(args.offset) ?? num(args.line);
|
|
21
|
+
const end = num(args.end_line) ?? (start !== undefined && num(args.limit) !== undefined ? start + num(args.limit) - 1 : undefined);
|
|
22
|
+
if (start === undefined)
|
|
23
|
+
return num(args.limit) !== undefined ? `lines 1–${num(args.limit)}` : undefined;
|
|
24
|
+
return end !== undefined ? `lines ${start}–${end}` : `from line ${start}`;
|
|
25
|
+
}
|
|
26
|
+
const WRAPPERS = new Set(["sudo", "nice", "time", "env", "nohup", "exec"]);
|
|
27
|
+
/** The program a command runs, without its arguments: env assignments and `cd …&&` are skipped, a path is cut to its name. */
|
|
28
|
+
export function commandWord(cmd) {
|
|
29
|
+
const words = cmd.trim().split(/\s+/).filter(Boolean);
|
|
30
|
+
for (let i = 0; i < words.length; i++) {
|
|
31
|
+
const w = words[i];
|
|
32
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) || WRAPPERS.has(w) || /^-/.test(w) || /^\d+$/.test(w))
|
|
33
|
+
continue;
|
|
34
|
+
if (w === "cd") {
|
|
35
|
+
while (i < words.length && !/^(&&|;)$/.test(words[i]) && !/;$/.test(words[i]))
|
|
36
|
+
i++;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (/^(&&|;|\|\|)$/.test(w))
|
|
40
|
+
continue;
|
|
41
|
+
return base(w).replace(/[^\w.+-]/g, "") || undefined;
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
/** One tool call in plain words: "reading digest.md (lines 1–900)", "searching the repo for "relayClient"". */
|
|
46
|
+
export function toolSummary(name, args = {}) {
|
|
47
|
+
const path = str(args.path) ?? str(args.file_path) ?? str(args.file) ?? (Array.isArray(args.paths) ? str(args.paths[0]) : undefined);
|
|
48
|
+
if (FILE_READ.has(name)) {
|
|
49
|
+
const more = Array.isArray(args.paths) && args.paths.length > 1 ? ` +${args.paths.length - 1}` : "";
|
|
50
|
+
const win = lineWindow(args);
|
|
51
|
+
return path ? `reading ${base(path)}${more}${win ? ` (${win})` : ""}` : "reading files";
|
|
52
|
+
}
|
|
53
|
+
if (LOCAL_SEARCH.has(name)) {
|
|
54
|
+
const q = str(args.pattern) ?? str(args.query) ?? str(args.glob) ?? str(args.name);
|
|
55
|
+
return q ? `searching the repo for ${quoted(q)}` : "searching the repo";
|
|
56
|
+
}
|
|
57
|
+
if (WEB_SEARCH.has(name)) {
|
|
58
|
+
const q = str(args.query);
|
|
59
|
+
return q ? `searching the web for ${quoted(q)}` : "searching the web";
|
|
60
|
+
}
|
|
61
|
+
if (WEB_FETCH.has(name)) {
|
|
62
|
+
const u = str(args.url);
|
|
63
|
+
let host;
|
|
64
|
+
try {
|
|
65
|
+
host = u ? new URL(u).hostname : undefined;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
host = undefined;
|
|
69
|
+
}
|
|
70
|
+
return host ? `fetching ${host}` : "browsing";
|
|
71
|
+
}
|
|
72
|
+
if (SHELL_ANY.has(name)) {
|
|
73
|
+
const d = str(args.description);
|
|
74
|
+
if (d)
|
|
75
|
+
return d.charAt(0).toLowerCase() + d.slice(1);
|
|
76
|
+
const w = str(args.command) ? commandWord(String(args.command)) : undefined;
|
|
77
|
+
return w ? `running ${w}` : "running a command";
|
|
78
|
+
}
|
|
79
|
+
if (WRITES[name])
|
|
80
|
+
return path ? `${WRITES[name]} ${base(path)}` : `${WRITES[name]} a file`;
|
|
81
|
+
if (PLAN_TOOLS.has(name))
|
|
82
|
+
return "updating its plan";
|
|
83
|
+
if (name === "message_agent")
|
|
84
|
+
return "messaging another agent";
|
|
85
|
+
if (name === "codeact_run")
|
|
86
|
+
return `running one ${str(args.language) ? `${str(args.language)} ` : ""}program over its targets`;
|
|
87
|
+
return name.replace(/_/g, " ");
|
|
88
|
+
}
|
|
89
|
+
/** The step a task_update put in progress, read from the tool's own result ("[>] #3 Check relay callers"). */
|
|
90
|
+
export function planStepFrom(args, result) {
|
|
91
|
+
if (args.status !== "in_progress")
|
|
92
|
+
return undefined;
|
|
93
|
+
const id = num(args.id);
|
|
94
|
+
const line = result.split("\n").find((l) => l.startsWith("[>]") && (id === undefined || l.startsWith(`[>] #${id} `)));
|
|
95
|
+
return line ? str(line.replace(/^\[>\]\s*#\d+\s*/, "")) : undefined;
|
|
96
|
+
}
|
|
97
|
+
/** The first clause of the agent's own progress line ("Checking the relay callers, then…" → "checking the relay callers"). */
|
|
98
|
+
function firstClause(s) {
|
|
99
|
+
const c = s?.split(/[.;:!?](?=\s|$)|,\s|\s—\s|\s-\s/)[0]?.trim();
|
|
100
|
+
return c ? c.charAt(0).toLowerCase() + c.slice(1) : undefined;
|
|
101
|
+
}
|
|
102
|
+
function poolBusy(reason) {
|
|
103
|
+
const m = reason ? /(\d+)\/(\d+) busy/.exec(reason) : null;
|
|
104
|
+
return m ? `pool ${m[1]}/${m[2]} busy` : undefined;
|
|
105
|
+
}
|
|
106
|
+
/** What the lane is doing now, short and redacted. Falls back to the agent's progress line, then "starting". */
|
|
107
|
+
export function laneSummary(a, now) {
|
|
108
|
+
const p = a.phase;
|
|
109
|
+
const step = a.planStep ? clip(a.planStep, 30) : undefined;
|
|
110
|
+
const t = p ? fmtElapsed(now - p.since) : "";
|
|
111
|
+
let s;
|
|
112
|
+
switch (p?.kind) {
|
|
113
|
+
case "queued":
|
|
114
|
+
case "slot": {
|
|
115
|
+
const busy = p.kind === "queued" ? poolBusy(a.queueReason) : p.holder ? `held by ${p.holder}` : undefined;
|
|
116
|
+
s = `waiting for a free model slot${busy ? ` (${busy})` : ""}`;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
case "sent":
|
|
120
|
+
s = `${step ?? "waiting for the model"} (sent ${t} ago)`;
|
|
121
|
+
break;
|
|
122
|
+
case "reading": {
|
|
123
|
+
const fresh = Math.max(1, p.total - p.cached);
|
|
124
|
+
const pct = Math.min(100, Math.round((Math.max(0, p.processed - p.cached) / fresh) * 100));
|
|
125
|
+
s = `${step ? `${step}: ` : ""}reading its context (${fmtTok(fresh)} tok, ${pct}%)`;
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
case "thinking":
|
|
129
|
+
case "writing": {
|
|
130
|
+
const n = p.tokens - p.startTokens;
|
|
131
|
+
const what = step ?? firstClause(a.progress) ?? p.kind;
|
|
132
|
+
s = `${what}${n > 0 ? ` (${fmtTok(n)} tok)` : ""}`;
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
case "tool": {
|
|
136
|
+
const d = `${a.doing ?? p.name.replace(/_/g, " ")}${p.count > 1 ? ` +${p.count - 1}` : ""}`;
|
|
137
|
+
s = d.endsWith(")") ? `${d.slice(0, -1)}, ${t})` : `${d} (${t})`;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
case "between":
|
|
141
|
+
s = step ?? "between rounds";
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
s ??= firstClause(a.progress) ?? (a.steps?.length ? a.steps[a.steps.length - 1].name.replace(/_/g, " ") : undefined) ?? "starting";
|
|
145
|
+
// The trailing "(…)" carries the live numbers: keep it whole and cut the words before it.
|
|
146
|
+
const red = redactSecrets(s);
|
|
147
|
+
const tail = /\s(\([^()]*\))$/.exec(red);
|
|
148
|
+
if (!tail || [...red].length <= SUMMARY_MAX)
|
|
149
|
+
return clip(red);
|
|
150
|
+
return `${clip(red.slice(0, tail.index), SUMMARY_MAX - [...tail[1]].length - 1)} ${tail[1]}`;
|
|
151
|
+
}
|
|
@@ -10,6 +10,10 @@ const REPORT_CHARS = 8000; // the spawn brief asks for a ~1-2k token report; a r
|
|
|
10
10
|
// report on blank lines and print each paragraph — the model's instructions included — as its own "⤷" line.
|
|
11
11
|
const reports = [];
|
|
12
12
|
const listeners = new Set();
|
|
13
|
+
let gate = () => ({ ready: true, missing: "" });
|
|
14
|
+
export function setReportGate(fn) {
|
|
15
|
+
gate = fn ?? (() => ({ ready: true, missing: "" }));
|
|
16
|
+
}
|
|
13
17
|
const clip = (s, n) => s.length <= n ? s : s.slice(0, n) + `\n… [report clipped at ${n} chars — re-run the sub-agent with a tighter deliverable if the rest matters]`;
|
|
14
18
|
const who = (a) => `${a.name ? `${a.name} (${a.title ?? "sub-agent"}, ${a.id})` : `sub-agent ${a.id}`} — ${a.label}`;
|
|
15
19
|
/** The notice the model reads when a sub-agent finishes: who, what it changed, its report — and what to do with it.
|
|
@@ -38,7 +42,7 @@ export function ownerLine(agent, result) {
|
|
|
38
42
|
}
|
|
39
43
|
/** Queue a stuck notice for the next turn and wake the shell (same channel as a finished report). */
|
|
40
44
|
export function queueAgentNotice(text, owner = "a sub-agent notice") {
|
|
41
|
-
reports.push({ text, owner });
|
|
45
|
+
reports.push({ text, owner, kind: "notice" });
|
|
42
46
|
for (const fn of listeners) {
|
|
43
47
|
try {
|
|
44
48
|
fn();
|
|
@@ -48,7 +52,7 @@ export function queueAgentNotice(text, owner = "a sub-agent notice") {
|
|
|
48
52
|
}
|
|
49
53
|
/** Queue a finished agent's report for the next turn and tell the shell (which wakes an idle session). */
|
|
50
54
|
export function queueAgentReport(agent, result) {
|
|
51
|
-
reports.push({ text: formatAgentReport(agent, result), owner: ownerLine(agent, result) });
|
|
55
|
+
reports.push({ text: formatAgentReport(agent, result), owner: ownerLine(agent, result), kind: "report" });
|
|
52
56
|
for (const fn of listeners) {
|
|
53
57
|
try {
|
|
54
58
|
fn();
|
|
@@ -59,10 +63,15 @@ export function queueAgentReport(agent, result) {
|
|
|
59
63
|
export function pendingAgentReports() {
|
|
60
64
|
return reports.length;
|
|
61
65
|
}
|
|
66
|
+
/** Whether queued reports should wake the session now: any notice, or reports once the synthesis gate is ready. */
|
|
67
|
+
export function agentReportsDue() {
|
|
68
|
+
return reports.some((r) => r.kind === "notice") || (reports.length > 0 && gate().ready);
|
|
69
|
+
}
|
|
62
70
|
/** Take every queued report: the model's text (joined, byte-identical to what it always was) and the owner lines. */
|
|
63
71
|
export function drainAgentNotices() {
|
|
64
72
|
const taken = reports.splice(0);
|
|
65
|
-
|
|
73
|
+
const missing = taken.some((r) => r.kind === "report") ? gate().missing : "";
|
|
74
|
+
return { text: [...taken.map((r) => r.text), ...(missing ? [missing] : [])].join("\n\n"), owners: taken.map((r) => r.owner) };
|
|
66
75
|
}
|
|
67
76
|
/** Take every queued report (joined), or "" when none. Called at the start of a turn. */
|
|
68
77
|
export function drainAgentReports() {
|
|
@@ -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,25 @@
|
|
|
1
|
+
import { fmtElapsed } from "../ui/format.js";
|
|
2
|
+
const live = (a) => a.status === "working" || a.status === "queued";
|
|
3
|
+
export function synthesisState(agents, now) {
|
|
4
|
+
const running = agents.filter(live);
|
|
5
|
+
const waitingOn = running.filter((a) => a.optional !== true).map((a) => a.name ?? a.id);
|
|
6
|
+
const missing = running.filter((a) => a.optional === true).map((a) => ({
|
|
7
|
+
name: a.name ?? a.id,
|
|
8
|
+
reason: a.deadlineAt !== undefined && now > a.deadlineAt ? `optional, ${fmtElapsed(now - a.deadlineAt)} past its deadline` : "optional, still running",
|
|
9
|
+
}));
|
|
10
|
+
return { ready: waitingOn.length === 0, waitingOn, missing };
|
|
11
|
+
}
|
|
12
|
+
/** The line the parent reads with the reports it synthesizes from. "" when nothing is missing. */
|
|
13
|
+
export function missingLine(missing) {
|
|
14
|
+
if (!missing.length)
|
|
15
|
+
return "";
|
|
16
|
+
return `[system notice] missing: ${missing.map((m) => `${m.name} (${m.reason})`).join(", ")}. Synthesize from the reports you have ` +
|
|
17
|
+
`and say what is missing; a late report arrives on its own if it finishes — do not wait or poll for it.`;
|
|
18
|
+
}
|
|
19
|
+
/** The lane's deadline words: "4m 10s left", "overdue 1m 2s". Undefined without a deadline. */
|
|
20
|
+
export function deadlineText(a, now) {
|
|
21
|
+
if (a.deadlineAt === undefined)
|
|
22
|
+
return undefined;
|
|
23
|
+
const left = a.deadlineAt - now;
|
|
24
|
+
return left >= 0 ? `⏱ ${fmtElapsed(left)} left` : `⏱ overdue ${fmtElapsed(-left)}${a.optional ? " (not waited on)" : ""}`;
|
|
25
|
+
}
|
|
@@ -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 };
|