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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +159 -0
  6. package/dist/autonomy/delegate.js +42 -15
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +13 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +336 -45
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/resume.js +125 -0
  18. package/dist/background/synthesis.js +25 -0
  19. package/dist/browser/engine.js +163 -0
  20. package/dist/browser/session.js +130 -140
  21. package/dist/bus/inbox.js +150 -6
  22. package/dist/cli.js +343 -86
  23. package/dist/config/features.js +3 -3
  24. package/dist/config/persona.js +29 -3
  25. package/dist/config/settings.js +262 -21
  26. package/dist/config/staff-prompt.js +12 -0
  27. package/dist/engine/agent.js +52 -41
  28. package/dist/engine/aurora.js +40 -8
  29. package/dist/engine/batch-scheduler.js +4 -13
  30. package/dist/engine/compaction.js +2 -2
  31. package/dist/engine/continuation.js +30 -32
  32. package/dist/engine/decision-points.js +2 -3
  33. package/dist/engine/fanout.js +16 -0
  34. package/dist/engine/loop-guard.js +26 -83
  35. package/dist/engine/messages.js +2 -2
  36. package/dist/engine/moa.js +18 -2
  37. package/dist/engine/native-vision-node.js +72 -0
  38. package/dist/engine/native-vision.js +103 -0
  39. package/dist/engine/selfheal.js +1 -1
  40. package/dist/engine/toolcalls.js +6 -6
  41. package/dist/engine/verify-gate.js +37 -7
  42. package/dist/gateway-cli.js +14 -3
  43. package/dist/index.js +3 -0
  44. package/dist/mcp/phone-server.js +30 -0
  45. package/dist/memory/live-progress.js +4 -5
  46. package/dist/moa/codeact-lane.js +98 -0
  47. package/dist/moa/codeact-sandbox.js +409 -0
  48. package/dist/moa/codeact.js +140 -0
  49. package/dist/permissions/artifact-visibility.js +10 -0
  50. package/dist/permissions/index.js +33 -17
  51. package/dist/permissions/signature.js +5 -0
  52. package/dist/permissions/tier.js +4 -2
  53. package/dist/phone-cli.js +65 -0
  54. package/dist/products/craft.js +2 -2
  55. package/dist/remote/grants.js +119 -0
  56. package/dist/remote/host.js +63 -6
  57. package/dist/router/models.js +29 -29
  58. package/dist/selfimprove/index.js +9 -7
  59. package/dist/services/preflight.js +35 -91
  60. package/dist/session.js +173 -46
  61. package/dist/skills/install-guard.js +68 -0
  62. package/dist/skills/install.js +67 -0
  63. package/dist/toolchain/manifest.json +13 -13
  64. package/dist/tools/background-result.js +1 -1
  65. package/dist/tools/classes.js +103 -0
  66. package/dist/tools/contract.js +1 -1
  67. package/dist/tools/craft.js +13 -2
  68. package/dist/tools/deferred.js +1 -0
  69. package/dist/tools/device/android.js +227 -0
  70. package/dist/tools/device/classify.js +127 -0
  71. package/dist/tools/device/deps.js +69 -0
  72. package/dist/tools/device/desktop.js +82 -0
  73. package/dist/tools/device/harness.js +262 -0
  74. package/dist/tools/device/iphone.js +206 -0
  75. package/dist/tools/device/mirroring-jxa.js +146 -0
  76. package/dist/tools/device/setup.js +90 -0
  77. package/dist/tools/device/tools.js +70 -0
  78. package/dist/tools/device/types.js +19 -0
  79. package/dist/tools/executor.js +25 -15
  80. package/dist/tools/generation-gateway.js +94 -0
  81. package/dist/tools/registry.js +95 -155
  82. package/dist/ui/App.js +18 -6
  83. package/dist/ui/ApprovalPrompt.js +10 -4
  84. package/dist/ui/BgPanel.js +17 -12
  85. package/dist/ui/Header.js +1 -6
  86. package/dist/ui/StatusRule.js +18 -7
  87. package/dist/ui/ToolStep.js +3 -3
  88. package/dist/ui/Transcript.js +36 -14
  89. package/dist/ui/UpdatePrompt.js +40 -0
  90. package/dist/ui/batchLine.js +4 -4
  91. package/dist/ui/editdiff.js +2 -4
  92. package/dist/ui/format.js +4 -20
  93. package/dist/ui/liveTools.js +3 -3
  94. package/dist/ui/modelPicker.js +1 -1
  95. package/dist/ui/opsMode.js +20 -0
  96. package/dist/ui/slashCommands.js +1 -0
  97. package/dist/ui/types.js +0 -2
  98. package/dist/update-check.js +145 -0
  99. package/dist/update.js +59 -15
  100. package/dist/util/slash.js +2 -2
  101. package/package.json +4 -2
  102. package/src/tools/device/NOTICE +37 -0
  103. package/dist/browser/cdp.js +0 -271
  104. package/dist/tools/mutating.js +0 -15
@@ -1,11 +1,13 @@
1
1
  // Persistent browser session + the two registry surfaces for HV3-02.
2
- // ONE headless Chrome per Operator session (mirrors src/tools/shell-session.ts): pages, cookies and
3
- // scroll state persist across tool calls; an idle browser decommissions on TTL; a dead Chrome
4
- // respawns transparently. Tools are split READ vs ACT so the registry-derived permission policy
5
- // (0.1.226) can let gated/plan mode READ pages freely while every page MUTATION stays gated.
6
- import { CdpConnection, launchChrome, checkNavigationUrl, evalResultToText, fillScript, BROWSER_CONSTANTS, } from "./cdp.js";
2
+ // ONE headless browser per Operator session (mirrors src/tools/shell-session.ts): pages and cookies persist across
3
+ // tool calls; an idle browser decommissions on TTL; a dead browser relaunches transparently. The engine is Playwright
4
+ // (./engine.ts) with a throwaway profile, so nothing outlives the session unless KODE_BROWSER_PROFILE=persistent.
5
+ // Tools are split READ vs ACT so the registry-derived permission policy (0.1.226) can let gated/plan mode READ pages
6
+ // freely while every page MUTATION stays gated.
7
+ import { launchBrowser, checkNavigationUrl, valueToText, shortError, BROWSER_CONSTANTS } from "./engine.js";
7
8
  /** A full-page capture stops here (CSS px): past it Chrome's capture gets slow and the PNG heavy. */
8
9
  export const MAX_PAGE_PX = 16_384;
10
+ const { ACTION_TIMEOUT_MS, NAV_TIMEOUT_MS, IDLE_TTL_MS } = BROWSER_CONSTANTS;
9
11
  async function nodeImport(id) {
10
12
  const g = globalThis;
11
13
  try {
@@ -30,92 +32,76 @@ async function shotBase(kind) {
30
32
  return `${os.tmpdir()}/kode-${kind}-${Date.now()}`;
31
33
  }
32
34
  }
35
+ /** Chrome's network error for a failed load (net::ERR_NAME_NOT_RESOLVED, …), else Playwright's first line. */
36
+ function loadErrorOf(e) {
37
+ const msg = e?.message ?? String(e);
38
+ return /net::[A-Z_]+/.exec(msg)?.[0] ?? shortError(e);
39
+ }
33
40
  class BrowserSession {
34
- conn = null;
35
- proc = null;
41
+ launched = null;
36
42
  tabs = [];
37
43
  active = -1;
38
44
  lastUsed = 0;
39
45
  async ensure() {
40
46
  const now = Date.now();
41
- const alive = this.conn && this.proc && this.proc.exitCode == null &&
42
- now - this.lastUsed < BROWSER_CONSTANTS.IDLE_TTL_MS;
43
- if (alive) {
47
+ if (this.launched && now - this.lastUsed < IDLE_TTL_MS) {
44
48
  this.lastUsed = now;
45
- return this.conn;
49
+ return this.launched;
46
50
  }
47
- await this.dispose(); // TTL expiry or dead child: rebuild clean (cookies live in the $KODE_HOME/browser profile, so a relaunch is cheap for state)
48
- const { proc, wsUrl } = await launchChrome();
49
- const conn = new CdpConnection(wsUrl);
50
- await conn.connect();
51
- this.proc = proc;
52
- this.conn = conn;
51
+ await this.dispose(); // TTL expiry: rebuild clean
52
+ this.launched = await launchBrowser();
53
53
  this.tabs = [];
54
54
  this.active = -1;
55
55
  this.lastUsed = Date.now();
56
- return conn;
56
+ return this.launched;
57
57
  }
58
- /** Attach a fresh tab (target) and make it active. */
59
- async newTab(conn, url) {
60
- const created = await conn.send("Target.createTarget", { url: "about:blank" });
61
- const attached = await conn.send("Target.attachToTarget", { targetId: created.targetId, flatten: true });
62
- const tab = { targetId: created.targetId, sessionId: attached.sessionId, url: "about:blank" };
63
- this.tabs.push(tab);
58
+ /** Open a fresh tab and make it active. */
59
+ async newTab(url) {
60
+ const b = await this.ensure();
61
+ const page = await b.context.newPage();
62
+ this.tabs.push(page);
64
63
  this.active = this.tabs.length - 1;
65
- await conn.send("Page.enable", {}, tab.sessionId);
66
- await conn.send("Runtime.enable", {}, tab.sessionId);
67
64
  if (url !== "about:blank")
68
- await this.navigate(conn, tab, url);
69
- return tab;
65
+ await this.navigate(page, url);
66
+ return page;
70
67
  }
71
68
  tab() {
69
+ this.tabs = this.tabs.filter((t) => !t.isClosed());
70
+ if (this.active >= this.tabs.length)
71
+ this.active = this.tabs.length - 1;
72
72
  if (this.active < 0 || !this.tabs[this.active])
73
73
  throw new Error("browser: no active tab — call open first");
74
74
  return this.tabs[this.active];
75
75
  }
76
- /** Resolves to Chrome's network error for the load (net::ERR_NAME_NOT_RESOLVED, …), or undefined. */
77
- async navigate(conn, tab, url) {
76
+ async navigate(page, url) {
78
77
  const blocked = checkNavigationUrl(url);
79
78
  if (blocked)
80
79
  throw new Error(blocked);
81
- const loadFired = conn.once("Page.loadEventFired"); // subscribe BEFORE navigate so we never miss it
82
- const nav = await conn.send("Page.navigate", { url }, tab.sessionId);
83
- const settled = await Promise.race([
84
- loadFired.then(() => "load"),
85
- new Promise((res) => setTimeout(() => res("timeout"), BROWSER_CONSTANTS.NAV_TIMEOUT_MS)),
86
- ]);
87
- // load fired (or timed out) — give SPAs a beat to paint, then confirm readyState
88
- await new Promise((r) => setTimeout(r, 300));
89
80
  try {
90
- const rs = await conn.send("Runtime.evaluate", { expression: "document.readyState", returnByValue: true }, tab.sessionId);
91
- tab.url = (await conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, tab.sessionId))?.result?.value ?? url;
92
- void settled;
93
- void rs;
81
+ const res = await page.goto(url, { waitUntil: "load", timeout: NAV_TIMEOUT_MS });
82
+ return { status: res?.status() || undefined };
94
83
  }
95
- catch {
96
- tab.url = url;
84
+ catch (e) {
85
+ if (/Timeout/i.test(e.message ?? ""))
86
+ return {}; // a page that never fires load is still readable
87
+ return { loadError: loadErrorOf(e) };
97
88
  }
98
- return nav?.errorText || undefined;
99
89
  }
100
90
  /** Render `url` in a tab of its own, sized `width`×`height`, and save a PNG (the viewport, or the whole page up to
101
91
  * MAX_PAGE_PX tall). A long page also yields up to `tiles` viewport-sized slices spread top to bottom, so vision
102
92
  * sees readable pieces instead of one strip downscaled to nothing. The `browser` tool's tabs are left as they were. */
103
93
  async capture(url, o) {
104
- const conn = await this.ensure();
105
- const before = this.active;
106
- const tab = await this.newTab(conn, "about:blank");
94
+ const b = await this.ensure();
95
+ const page = await b.context.newPage();
107
96
  try {
108
- await conn.send("Emulation.setDeviceMetricsOverride", { width: o.width, height: o.height, deviceScaleFactor: 1, mobile: false }, tab.sessionId);
109
- const loadError = await this.navigate(conn, tab, url);
110
- const value = async (expression) => (await conn.send("Runtime.evaluate", { expression, returnByValue: true }, tab.sessionId).catch(() => undefined))?.result?.value;
97
+ await page.setViewportSize({ width: o.width, height: o.height });
98
+ const { status, loadError } = await this.navigate(page, url);
99
+ const value = async (expression) => (await page.evaluate(expression).catch(() => undefined));
111
100
  const title = (await value("document.title")) ?? "";
112
- const status = (await value("performance.getEntriesByType('navigation')[0]?.responseStatus || 0")) || undefined;
113
101
  const fullHeight = Math.max(o.height, Math.ceil((await value("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)")) ?? o.height));
114
102
  const height = o.fullPage ? Math.min(fullHeight, MAX_PAGE_PX) : o.height;
115
103
  const shoot = async (y, h, path) => {
116
- const shot = await conn.send("Page.captureScreenshot", { format: "png", captureBeyondViewport: o.fullPage, clip: { x: 0, y, width: o.width, height: h, scale: 1 } }, tab.sessionId);
117
- const { writeFileSync } = await nodeImport("node:fs");
118
- writeFileSync(path, shot.data, "base64");
104
+ await page.screenshot({ path, fullPage: o.fullPage, clip: { x: 0, y, width: o.width, height: h } });
119
105
  return path;
120
106
  };
121
107
  const base = await shotBase("page");
@@ -125,110 +111,118 @@ class BrowserSession {
125
111
  for (let i = 0; i < n; i++)
126
112
  tiles.push(await shoot(n === 1 ? 0 : Math.round((i * (height - o.height)) / (n - 1)), o.height, `${base}-${i + 1}.png`));
127
113
  const probe = o.probe ? await value(o.probe) : undefined;
128
- return { path, tiles, title, finalUrl: tab.url, status, loadError, width: o.width, height, fullHeight, probe };
114
+ return { path, tiles, title, finalUrl: page.url(), status, loadError, width: o.width, height, fullHeight, probe };
129
115
  }
130
116
  finally {
131
- await conn.send("Target.closeTarget", { targetId: tab.targetId }).catch(() => undefined);
132
- this.tabs = this.tabs.filter((t) => t !== tab);
133
- this.active = Math.min(before, this.tabs.length - 1);
117
+ await page.close().catch(() => undefined);
134
118
  }
135
119
  }
136
- async evaluate(expr, awaitPromise = false) {
137
- const conn = await this.ensure();
138
- const t = this.tab();
139
- const raw = await conn.send("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise }, t.sessionId);
140
- return evalResultToText(raw);
120
+ async evaluate(expr) {
121
+ await this.ensure();
122
+ try {
123
+ return valueToText(await this.tab().evaluate(expr));
124
+ }
125
+ catch (e) {
126
+ throw new Error(`browser js error: ${shortError(e)}`);
127
+ }
141
128
  }
142
129
  async run(action, a) {
143
- const conn = await this.ensure();
130
+ await this.ensure();
131
+ const opts = { timeout: ACTION_TIMEOUT_MS };
144
132
  switch (action) {
145
133
  case "open": {
146
- const url = String(a.url ?? "about:blank");
147
- await this.newTab(conn, url);
148
- return this.infoInner(conn);
134
+ await this.newTab(String(a.url ?? "about:blank"));
135
+ return this.info();
149
136
  }
150
137
  case "navigate": {
151
- await this.navigate(conn, this.tab(), String(a.url));
152
- return this.infoInner(conn);
138
+ const { loadError } = await this.navigate(this.tab(), String(a.url));
139
+ return loadError ? `load failed: ${loadError}` : this.info();
153
140
  }
154
141
  case "reload": {
155
- await conn.send("Page.reload", { ignoreCache: !!a.cache_bust }, this.tab().sessionId);
156
- await new Promise((r) => setTimeout(r, 500));
157
- return this.infoInner(conn);
142
+ const t = this.tab();
143
+ if (a.cache_bust) { // Playwright's reload has no ignoreCache; Chromium's own Page.reload does
144
+ const cdp = await this.launched.context.newCDPSession(t);
145
+ try {
146
+ await cdp.send("Page.reload", { ignoreCache: true });
147
+ }
148
+ finally {
149
+ await cdp.detach().catch(() => undefined);
150
+ }
151
+ await t.waitForLoadState("load", { timeout: NAV_TIMEOUT_MS }).catch(() => undefined);
152
+ }
153
+ else
154
+ await t.reload({ waitUntil: "load", timeout: NAV_TIMEOUT_MS });
155
+ return this.info();
158
156
  }
159
157
  case "back":
160
158
  case "forward": {
161
- // history via JS (no CDP history domain): simplest reliable path
162
- await this.evaluate(action === "back" ? "history.back(); 'back'" : "history.forward(); 'forward'");
163
- await new Promise((r) => setTimeout(r, 400));
164
- return this.infoInner(conn);
159
+ const t = this.tab();
160
+ await (action === "back" ? t.goBack({ timeout: NAV_TIMEOUT_MS }) : t.goForward({ timeout: NAV_TIMEOUT_MS }));
161
+ return this.info();
165
162
  }
166
- case "info": return this.infoInner(conn);
163
+ case "info": return this.info();
167
164
  case "text": {
168
165
  const max = Math.max(500, Math.min(Number(a.max_chars ?? 20000), 100_000));
169
166
  const title = await this.evaluate("document.title");
170
- const url = await this.evaluate("location.href");
167
+ const url = this.tab().url();
171
168
  const body = await this.evaluate("(() => { const b = document.body; const t = b ? b.innerText : ''; return t.replace(/\\n{3,}/g, '\\n\\n').slice(0, " + max + "); })()");
172
169
  return `# ${title}\n${url}\n\n${body}`;
173
170
  }
174
- case "eval": {
175
- const out = await this.evaluate(String(a.js ?? "1"), true);
176
- return String(out);
177
- }
171
+ case "eval": return this.evaluate(String(a.js ?? "1"));
178
172
  case "click": {
179
173
  const sel = String(a.selector);
180
- const out = await this.evaluate(`(() => {
181
- const el = document.querySelector(${JSON.stringify(sel)});
182
- if (!el) throw new Error("element not found: " + ${JSON.stringify(sel)});
183
- el.scrollIntoView({ block: "center" });
184
- if (typeof el.click === "function") el.click(); else el.dispatchEvent(new MouseEvent("click", { bubbles: true }));
185
- return "clicked " + (el.tagName + (el.id ? "#" + el.id : "")).toLowerCase();
186
- })()`);
174
+ const t = this.tab();
175
+ const what = await t.$eval(sel, (el) => (el.tagName + (el.id ? "#" + el.id : "")).toLowerCase()).catch(() => sel);
176
+ await t.click(sel, opts);
187
177
  await new Promise((r) => setTimeout(r, Number(a.settle_ms ?? 250)));
188
- return String(out);
178
+ return `clicked ${what}`;
189
179
  }
190
180
  case "fill": {
191
- const out = await this.evaluate(fillScript(String(a.selector), String(a.text ?? "")));
192
- return `filled ${a.selector}: ${out}`;
181
+ const sel = String(a.selector);
182
+ const text = String(a.text ?? "");
183
+ const t = this.tab();
184
+ await t.fill(sel, text, opts);
185
+ return `filled ${sel}: ${await t.inputValue(sel, opts).catch(() => text)}`;
193
186
  }
194
187
  case "submit": {
195
- return String(await this.evaluate(`(() => {
196
- const el = document.querySelector(${JSON.stringify(String(a.selector))});
197
- const f = el && (el.form || (el.tagName === "FORM" ? el : null));
198
- if (!f) throw new Error("no form for selector: " + ${JSON.stringify(String(a.selector))});
199
- if (typeof f.requestSubmit === "function") f.requestSubmit(); else f.submit();
200
- return "submitted " + (f.action || "(inline)");
201
- })()`));
188
+ return valueToText(await this.tab().$eval(String(a.selector), (el) => {
189
+ const f = el.form || (el.tagName === "FORM" ? el : null);
190
+ if (!f)
191
+ throw new Error("no form for selector");
192
+ if (typeof f.requestSubmit === "function")
193
+ f.requestSubmit();
194
+ else
195
+ f.submit();
196
+ return "submitted " + (f.action || "(inline)");
197
+ }));
202
198
  }
203
199
  case "tab_list": {
204
- const list = await conn.send("Target.getTargets", {});
205
- const pages = list.targetInfos.filter((x) => x.type === "page");
206
- return pages.map((p, i) => `${i === this.active ? "*" : " "} ${i} ${p.title || "(untitled)"} — ${p.url.slice(0, 120)}`).join("\n") || "(no pages)";
200
+ this.tabs = this.tabs.filter((t) => !t.isClosed());
201
+ const rows = await Promise.all(this.tabs.map(async (p, i) => `${i === this.active ? "*" : " "} ${i} ${(await p.title().catch(() => "")) || "(untitled)"} — ${p.url().slice(0, 120)}`));
202
+ return rows.join("\n") || "(no pages)";
207
203
  }
208
204
  case "tab_select": {
209
205
  const i = Number(a.index);
210
206
  if (!this.tabs[i])
211
207
  throw new Error(`browser: no tab ${i} (have ${this.tabs.length})`);
212
208
  this.active = i;
213
- return this.infoInner(conn);
209
+ return this.info();
214
210
  }
215
211
  case "tab_close": {
216
212
  const i = Number.isFinite(Number(a.index)) ? Number(a.index) : this.active;
217
213
  const t = this.tabs[i];
218
214
  if (!t)
219
215
  throw new Error(`browser: no tab ${i}`);
220
- await conn.send("Target.closeTarget", { targetId: t.targetId }).catch(() => undefined);
216
+ await t.close().catch(() => undefined);
221
217
  this.tabs.splice(i, 1);
222
218
  this.active = Math.min(this.active, this.tabs.length - 1);
223
219
  return `closed tab ${i}; ${this.tabs.length} left`;
224
220
  }
225
221
  case "screenshot": {
226
- const shot = await conn.send("Page.captureScreenshot", { format: "png" }, this.tab().sessionId);
227
- const bytes = Math.round(shot.data.length * 3 / 4); // base64 → raw size
228
- const { writeFileSync } = await nodeImport("node:fs");
229
222
  const path = `${await shotBase("shot")}.png`;
230
- writeFileSync(path, shot.data, "base64");
231
- return `screenshot ${path} (${Math.round(bytes / 1024)} KB) — pass to image_analyze if you must see pixels; prefer text/eval`;
223
+ await this.tab().screenshot({ path });
224
+ const { statSync } = await nodeImport("node:fs");
225
+ return `screenshot ${path} (${Math.round(statSync(path).size / 1024)} KB) — pass to image_analyze if you must see pixels; prefer text/eval`;
232
226
  }
233
227
  case "close": {
234
228
  await this.dispose();
@@ -237,45 +231,40 @@ class BrowserSession {
237
231
  default: throw new Error(`browser: unknown action '${action}'`);
238
232
  }
239
233
  }
240
- async infoInner(conn) {
234
+ async info() {
241
235
  try {
242
- const title = await conn.send("Runtime.evaluate", { expression: "document.title", returnByValue: true }, this.tab().sessionId);
243
- const url = await conn.send("Runtime.evaluate", { expression: "location.href + ' | ' + document.readyState", returnByValue: true }, this.tab().sessionId);
244
- return `${title?.result?.value || "(untitled)"} — ${url?.result?.value ?? "?"}`;
236
+ const t = this.tab();
237
+ const title = await t.title();
238
+ const state = await t.evaluate("document.readyState").catch(() => "?");
239
+ return `${title || "(untitled)"} — ${t.url()} | ${state}`;
245
240
  }
246
241
  catch (e) {
247
- return `info failed: ${e.message}`;
242
+ return `info failed: ${shortError(e)}`;
248
243
  }
249
244
  }
250
245
  async dispose() {
251
- try {
252
- this.conn?.close();
253
- }
254
- catch { /* gone */ }
255
- this.conn = null;
256
- try {
257
- this.proc?.kill?.("SIGTERM");
258
- }
259
- catch { /* gone */ }
260
- this.proc = null;
246
+ const b = this.launched;
247
+ this.launched = null;
261
248
  this.tabs = [];
262
249
  this.active = -1;
250
+ if (b)
251
+ await b.close().catch(() => undefined);
263
252
  }
264
253
  /** href of the active tab (origin-bound vault checks). Throws cleanly when no page. */
265
254
  async href() {
266
- const conn = await this.ensure();
267
- const t = this.tab();
268
- const r = await conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, t.sessionId);
269
- const v = r?.result?.value;
255
+ await this.ensure();
256
+ const v = this.tab().url();
270
257
  if (!v)
271
258
  throw new Error("no active page href");
272
259
  return v;
273
260
  }
274
- /** Fill user+password fields atomically from the VAULT PATH — the secret value is a parameter to
275
- * this function only; callers above (tool glue) must never echo it back. */
261
+ /** Fill user+password fields from the VAULT PATH — the secret value is a parameter to this function only; callers
262
+ * above (tool glue) must never echo it back. */
276
263
  async fillPair(userSel, userVal, passSel, passVal) {
277
- await this.evaluate(fillScript(userSel, userVal));
278
- await this.evaluate(fillScript(passSel, passVal));
264
+ await this.ensure();
265
+ const t = this.tab();
266
+ await t.fill(userSel, userVal, { timeout: ACTION_TIMEOUT_MS });
267
+ await t.fill(passSel, passVal, { timeout: ACTION_TIMEOUT_MS });
279
268
  }
280
269
  }
281
270
  let singleton = null;
@@ -291,9 +280,8 @@ export async function disposeBrowser() {
291
280
  singleton = null;
292
281
  }
293
282
  }
294
- /** SYNC teardown for process-exit hooks — the same contract as disposeShellSession(): the SIGTERM
295
- * is delivered synchronously inside dispose(), so the Chrome child is signaled before
296
- * process.exit() can leave it orphaned. */
283
+ /** Teardown for process-exit hooks. Closing is async; Playwright's own exit handler kills any browser it launched
284
+ * that is still up when the process ends, so nothing is left behind either way. */
297
285
  export function disposeBrowserNow() {
298
286
  if (!singleton)
299
287
  return;
@@ -311,7 +299,7 @@ export const browserSessionHooks = {
311
299
  activeHref: () => session().href(),
312
300
  fillPair: (u, uv, p, pv) => session().fillPair(u, uv, p, pv),
313
301
  };
314
- /** image_analyze `page` renders through the same Chrome as the `browser` tool; tests replace `capture`. */
302
+ /** image_analyze `page` renders through the same browser as the `browser` tool; tests replace `capture`. */
315
303
  export const pageCaptureHooks = {
316
304
  capture: (url, o) => session().capture(url, o),
317
305
  };
@@ -324,9 +312,11 @@ export async function runBrowser(args) {
324
312
  return await session().run(String(args.action ?? "info"), args);
325
313
  }
326
314
  catch (e) {
327
- const msg = e?.message ?? String(e);
328
- if (/devtools|spawn|ws |Chrome|chrome/.test(msg))
329
- return `browser: ${msg}`;
315
+ const msg = shortError(e);
316
+ if (/has been closed|Browser closed|crashed/i.test(msg))
317
+ await disposeBrowser(); // the next call relaunches
318
+ if (/^browser/.test(msg))
319
+ return msg;
330
320
  return `browser error: ${msg}`;
331
321
  }
332
322
  }
package/dist/bus/inbox.js CHANGED
@@ -6,9 +6,11 @@
6
6
  //
7
7
  // SECURITY: a bus message is DATA written by another agent — untrusted input. The UI surfaces it to the
8
8
  // operator; nothing here executes message contents.
9
- import { readdirSync, readFileSync, renameSync, mkdirSync, existsSync } from "node:fs";
10
- import { join } from "node:path";
9
+ import { readdirSync, readFileSync, renameSync, mkdirSync, existsSync, writeFileSync, realpathSync } from "node:fs";
10
+ import { randomUUID } from "node:crypto";
11
+ import { isAbsolute, join, sep } from "node:path";
11
12
  import { homedir, hostname } from "node:os";
13
+ import { redactSecrets } from "../engine/redact.js";
12
14
  /** The bus state root — mirrors the switchboard CLI's SWITCHBOARD_DIR. Neutral default (~/.switchboard) so
13
15
  * this works on any box/surface, not just the AXE fleet; the env var repoints it wherever the bus lives. */
14
16
  export function busDir() {
@@ -63,13 +65,19 @@ export function pollBus(agent = selfAgent(), opts = {}) {
63
65
  * allowlist). PURE + tested — the cli.tsx poller calls this, then routes the text to the submit/queue path.
64
66
  * Contract: a rendered bus message is only displayed; THIS is what puts a peer message into the model's context
65
67
  * as an actionable turn. `allow` unset/empty = any sender wakes; otherwise only senders in the list. */
66
- export function buildMentorWake(incoming, allow) {
67
- const toWake = allow && allow.length ? incoming.filter((m) => allow.includes(m.from)) : incoming;
68
+ export function buildMentorWake(incoming, allow, rootPolicy) {
69
+ const toWake = (allow && allow.length ? incoming.filter((m) => allow.includes(m.from)) : incoming).filter((m) => !isAutoReport(m));
68
70
  if (!toWake.length)
69
71
  return null;
70
- return (`[mentor-wake] ${toWake.length} new bus message(s) arrived — review and act on them now:\n\n` +
72
+ const dir = rootPolicy ? wakeWorkdir(toWake, rootPolicy) : null;
73
+ const frame = `[mentor-wake] ${toWake.length} new bus message(s) arrived — review and act on them now:\n\n` +
71
74
  toWake.map((m) => `--- from ${m.from}${m.subject ? ` · ${m.subject}` : ""} (${m.ts}) ---\n${m.body}`).join("\n\n") +
72
- `\n\n${replyProtocol([...new Set(toWake.map((m) => m.from))])}`);
75
+ (dir ? `\n\nThe harness set this turn's working directory to ${dir} (the brief's worktree): relative paths and shell commands resolve there for this turn only, then the session returns to its own folder.` : "") +
76
+ `\n\n${replyProtocol([...new Set(toWake.map((m) => m.from))])}`;
77
+ wakeRegistry.set(frame, { msgs: toWake, dir });
78
+ while (wakeRegistry.size > WAKE_REGISTRY_MAX)
79
+ wakeRegistry.delete(wakeRegistry.keys().next().value);
80
+ return frame;
73
81
  }
74
82
  /** The reply contract a woken turn owes its sender, spelled out in the frame itself. The sender is another agent
75
83
  * on the bus and cannot see this screen: a turn that works in silence is invisible to the teacher, and the plan
@@ -127,3 +135,139 @@ export function pollSent(agent = selfAgent(), opts = {}) {
127
135
  }
128
136
  return out;
129
137
  }
138
+ // ── Report delivery: a woken turn's answer reaches its sender ────────────────────────────────────────────────────
139
+ // replyProtocol asks the turn to send a report; nothing checked it, so a turn that ended without one left the sender
140
+ // with nothing (11/24: four D6 turns, zero replies). Claude Code returns a sub-agent's final message to its parent and
141
+ // `codex exec -o` writes the last message for its caller; the bus counterpart is below: at the end of a mentor-wake
142
+ // turn, each sender that got nothing from this agent during the turn receives the turn's final answer, marked
143
+ // auto-delivered. A turn that did reply is left alone.
144
+ /** The senders a `[mentor-wake]` frame came from (its `--- from <name>[ · subject] (<ts>) ---` headers), in order. */
145
+ /** The bus messages a wake frame was built from, recorded when the harness built it. The senders a woken turn
146
+ * owes a report come from here, never from the frame's text: a message body can contain a line that looks like a
147
+ * "--- from X ---" header. */
148
+ const wakeRegistry = new Map();
149
+ const WAKE_REGISTRY_MAX = 64;
150
+ function wakeEntry(turnText) {
151
+ for (const [frame, e] of wakeRegistry)
152
+ if (turnText === frame || turnText.endsWith(frame))
153
+ return e;
154
+ return undefined;
155
+ }
156
+ /** The messages behind the wake frame in this turn's text (a job notice may be prepended), or [] for any other turn. */
157
+ export function wakeMessages(turnText) {
158
+ return wakeEntry(turnText)?.msgs ?? [];
159
+ }
160
+ /** The working directory the harness chose for this wake turn (wakeWorkdir), or null. Read from the registry, never
161
+ * from the frame's text: a message body cannot set it. */
162
+ export function wakeRoot(turnText) {
163
+ return wakeEntry(turnText)?.dir ?? null;
164
+ }
165
+ const realDir = (p) => { try {
166
+ return realpathSync(p);
167
+ }
168
+ catch {
169
+ return null;
170
+ } };
171
+ const isCheckoutTop = (dir) => existsSync(join(dir, ".git"));
172
+ /** The one working directory a batch of wake messages names in its refs (`worktree`, else `cwd`), or null. It must be
173
+ * the same across the batch, absolute, and after realpath a git checkout's top folder inside one of the policy's
174
+ * roots — never `/`, $HOME, ~/.ssh or a root itself. The bus counterpart of Codex `--cd` and Claude Code's worktree
175
+ * isolation for a delegated agent. */
176
+ export function wakeWorkdir(msgs, policy, isTop = isCheckoutTop) {
177
+ const dirs = new Set();
178
+ for (const m of msgs) {
179
+ const v = m.refs?.worktree ?? m.refs?.cwd;
180
+ if (typeof v === "string" && v.trim())
181
+ dirs.add(v.trim().replace(/\/+$/, ""));
182
+ }
183
+ if (dirs.size !== 1)
184
+ return null;
185
+ const [named] = [...dirs];
186
+ if (!named || !isAbsolute(named))
187
+ return null;
188
+ const dir = realDir(named);
189
+ if (!dir || !isTop(dir))
190
+ return null;
191
+ const inside = policy.roots.map(realDir).some((r) => r && dir !== r && dir.startsWith(r.endsWith(sep) ? r : r + sep));
192
+ return inside ? dir : null;
193
+ }
194
+ /** An auto-delivered report: delivered to the inbox like any message but never wakes a turn, so two Operators
195
+ * can't answer each other's auto-reports forever. */
196
+ export function isAutoReport(m) {
197
+ return m.meta?.auto === true;
198
+ }
199
+ /** Whether `agent` already sent `to` this answer since `sinceMs` (the model replied itself, or quoted its final
200
+ * answer). A plan or progress message to the sender does not count: only the final answer closes the loop. */
201
+ export function reportedTo(agent, to, sinceMs, answer) {
202
+ const probe = answer.replace(/\s+/g, " ").trim().slice(0, 200);
203
+ for (const dir of [sentOf(agent), sentReadOf(agent)]) {
204
+ if (!existsSync(dir))
205
+ continue;
206
+ let files;
207
+ try {
208
+ files = readdirSync(dir).filter((f) => f.endsWith(".json") && !f.startsWith(".tmp-"));
209
+ }
210
+ catch {
211
+ continue;
212
+ }
213
+ for (const f of files) {
214
+ const stamp = Number(f.split("-")[0]);
215
+ if (Number.isFinite(stamp) && stamp && stamp < sinceMs)
216
+ continue; // the file name leads with its send time (ms)
217
+ try {
218
+ const m = JSON.parse(readFileSync(join(dir, f), "utf8"));
219
+ if (m.to === to && Date.parse(m.ts) >= sinceMs && m.body.replace(/\s+/g, " ").includes(probe))
220
+ return true;
221
+ }
222
+ catch { /* skip corrupt */ }
223
+ }
224
+ }
225
+ return false;
226
+ }
227
+ export function busSend(from, to, body, opts = {}) {
228
+ const id = randomUUID();
229
+ const msg = { id, from, to, ts: new Date().toISOString(), subject: opts.subject ?? null, thread: opts.thread ?? null, body, ...(opts.auto ? { meta: { auto: true } } : {}) };
230
+ const name = `${String(Date.now()).padStart(15, "0")}-${id.slice(0, 8)}.json`;
231
+ for (const dir of [inboxOf(to), sentOf(from)]) {
232
+ mkdirSync(dir, { recursive: true });
233
+ const tmp = join(dir, `.tmp-${name}`);
234
+ writeFileSync(tmp, JSON.stringify(msg), { mode: 0o600 });
235
+ renameSync(tmp, join(dir, name));
236
+ }
237
+ return id;
238
+ }
239
+ export const AUTO_REPORT_MAX = 8_000;
240
+ /** Who a woken turn owes a report, with the thread to answer in (the sender's last message's). */
241
+ function owed(turnText, agent) {
242
+ const last = new Map();
243
+ for (const m of wakeMessages(turnText))
244
+ if (m.from !== agent)
245
+ last.set(m.from, m);
246
+ return [...last.values()].map((m) => ({ to: m.from, thread: m.thread ?? m.id }));
247
+ }
248
+ /** A woken turn ended without sending its final answer to a sender: the harness delivers it (Claude Code returns a
249
+ * sub-agent's final message to its parent; `codex exec -o` writes it for the caller). One sender gets the answer;
250
+ * when one turn answered several senders, each gets a short note instead, so one agent's report never goes to
251
+ * another. Secrets are redacted and the message is tagged auto, so it never wakes the receiver. */
252
+ export function autoDeliverReport(turnText, finalAnswer, sinceMs, agent = selfAgent()) {
253
+ const answer = redactSecrets(finalAnswer.trim());
254
+ if (!answer)
255
+ return [];
256
+ const due = owed(turnText, agent).filter((o) => !reportedTo(agent, o.to, sinceMs, answer));
257
+ const shared = owed(turnText, agent).length > 1;
258
+ for (const o of due) {
259
+ const body = shared
260
+ ? `Auto-delivered by Operator's harness: one turn handled messages from several agents and ended without a report to you. Its answer is not forwarded to keep reports separate; ask ${agent} or its owner for your part.`
261
+ : `Auto-delivered by Operator's harness: this turn ended without a report to you, so its final answer follows.\n\n${answer.length > AUTO_REPORT_MAX ? `${answer.slice(0, AUTO_REPORT_MAX)}\n… (cut at ${AUTO_REPORT_MAX} characters)` : answer}`;
262
+ busSend(agent, o.to, body, { subject: "Report (auto-delivered)", thread: o.thread, auto: true });
263
+ }
264
+ return due.map((o) => o.to);
265
+ }
266
+ /** A woken turn was interrupted or failed: its senders get a short note instead of silence. */
267
+ export function autoDeliverFailure(turnText, reason, agent = selfAgent()) {
268
+ const due = owed(turnText, agent);
269
+ for (const o of due) {
270
+ busSend(agent, o.to, `Auto-delivered by Operator's harness: the turn that took your message was ${reason} before it finished. No report was produced; resend the task if it is still needed.`, { subject: `Report (${reason})`, thread: o.thread, auto: true });
271
+ }
272
+ return due.map((o) => o.to);
273
+ }