trusted-user-agent 0.0.0-stage → 0.3.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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/dist/acp/agent.js +601 -0
  3. package/dist/acp/backend.js +2 -0
  4. package/dist/acp/config-options.js +26 -0
  5. package/dist/acp/mock-backend.js +277 -0
  6. package/dist/acp/sdk-backend.js +495 -0
  7. package/dist/browser/mcp-acp-client.js +81 -0
  8. package/dist/browser/provider.js +1045 -0
  9. package/dist/browser/schemas.js +221 -0
  10. package/dist/capability-registry.js +92 -0
  11. package/dist/client-heartbeat.js +118 -0
  12. package/dist/compose/schemas.js +90 -0
  13. package/dist/contacts/schemas.js +26 -0
  14. package/dist/installer/cli.js +70 -0
  15. package/dist/installer/common.js +93 -0
  16. package/dist/installer/index.js +341 -0
  17. package/dist/installer/mcp-clients.js +555 -0
  18. package/dist/installer/mcp.js +166 -0
  19. package/dist/installer/platforms.js +277 -0
  20. package/dist/logger.js +54 -0
  21. package/dist/mail/schemas.js +98 -0
  22. package/dist/mutation/schemas.js +31 -0
  23. package/dist/native-host/broker-ipc.js +344 -0
  24. package/dist/native-host/framing.js +76 -0
  25. package/dist/native-host/main.js +520 -0
  26. package/dist/native-host/mcp-server.js +322 -0
  27. package/dist/native-host/mcp-stdio-bridge.js +179 -0
  28. package/dist/native-host/mcp-stdio-main.js +13 -0
  29. package/dist/native-host/relay.js +84 -0
  30. package/dist/native-host/skills-startup.js +167 -0
  31. package/dist/native-host/transport.js +248 -0
  32. package/dist/permission-store.js +207 -0
  33. package/dist/repl/fs-sandbox.js +187 -0
  34. package/dist/repl/provider.js +252 -0
  35. package/dist/repl/runtime.js +436 -0
  36. package/dist/repl/types.js +10 -0
  37. package/dist/repl/worker.js +731 -0
  38. package/dist/skills/extension.js +99 -0
  39. package/dist/skills/grants-file.js +145 -0
  40. package/dist/skills/isolated-runner.js +259 -0
  41. package/dist/skills/mock-session-factory.js +49 -0
  42. package/dist/skills/package-roots.js +25 -0
  43. package/dist/skills/pi-bridge.js +8 -0
  44. package/dist/skills/pi-integration.js +110 -0
  45. package/dist/skills/planner.js +128 -0
  46. package/dist/skills/registry.js +104 -0
  47. package/dist/skills/skills-protocol.js +253 -0
  48. package/dist/skills/skills-service.js +195 -0
  49. package/dist/tool-bridge.js +8 -0
  50. package/dist/workspace.js +70 -0
  51. package/extensions/pi-browser-tools.ts +65 -0
  52. package/extensions/pi-browser.ts +60 -0
  53. package/extensions/pi-skills.ts +14 -0
  54. package/native/pi-agent-host +2 -0
  55. package/native/pi-browser-host +5 -0
  56. package/native/pi-browser-host.cmd +3 -0
  57. package/node_modules/@pi-browser/protocol/.bundled-by-trusted-user-agent +0 -0
  58. package/node_modules/@pi-browser/protocol/dist/acp.d.ts +10 -0
  59. package/node_modules/@pi-browser/protocol/dist/acp.js +9 -0
  60. package/node_modules/@pi-browser/protocol/dist/browser-tools.d.ts +33 -0
  61. package/node_modules/@pi-browser/protocol/dist/browser-tools.js +478 -0
  62. package/node_modules/@pi-browser/protocol/dist/callers.d.ts +108 -0
  63. package/node_modules/@pi-browser/protocol/dist/callers.js +56 -0
  64. package/node_modules/@pi-browser/protocol/dist/compose-tools.d.ts +30 -0
  65. package/node_modules/@pi-browser/protocol/dist/compose-tools.js +175 -0
  66. package/node_modules/@pi-browser/protocol/dist/contacts-tools.d.ts +23 -0
  67. package/node_modules/@pi-browser/protocol/dist/contacts-tools.js +63 -0
  68. package/node_modules/@pi-browser/protocol/dist/control-tools.d.ts +32 -0
  69. package/node_modules/@pi-browser/protocol/dist/control-tools.js +201 -0
  70. package/node_modules/@pi-browser/protocol/dist/errors.d.ts +63 -0
  71. package/node_modules/@pi-browser/protocol/dist/errors.js +109 -0
  72. package/node_modules/@pi-browser/protocol/dist/index.d.ts +16 -0
  73. package/node_modules/@pi-browser/protocol/dist/index.js +16 -0
  74. package/node_modules/@pi-browser/protocol/dist/integration.d.ts +409 -0
  75. package/node_modules/@pi-browser/protocol/dist/integration.js +260 -0
  76. package/node_modules/@pi-browser/protocol/dist/jsonrpc.d.ts +33 -0
  77. package/node_modules/@pi-browser/protocol/dist/jsonrpc.js +31 -0
  78. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.d.ts +27 -0
  79. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.js +88 -0
  80. package/node_modules/@pi-browser/protocol/dist/mail-tools.d.ts +133 -0
  81. package/node_modules/@pi-browser/protocol/dist/mail-tools.js +245 -0
  82. package/node_modules/@pi-browser/protocol/dist/permission.d.ts +113 -0
  83. package/node_modules/@pi-browser/protocol/dist/permission.js +257 -0
  84. package/node_modules/@pi-browser/protocol/dist/skills.d.ts +304 -0
  85. package/node_modules/@pi-browser/protocol/dist/skills.js +473 -0
  86. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.d.ts +18 -0
  87. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.js +52 -0
  88. package/node_modules/@pi-browser/protocol/dist/transport.d.ts +17 -0
  89. package/node_modules/@pi-browser/protocol/dist/transport.js +17 -0
  90. package/node_modules/@pi-browser/protocol/package.json +14 -0
  91. package/package.json +71 -6
  92. package/skills/browser-walk/SKILL.md +98 -0
  93. package/README.md +0 -3
@@ -0,0 +1,731 @@
1
+ /**
2
+ * ReplWorker — the persistent V8 REPL child behind the `javascript` tool.
3
+ *
4
+ * Ported and adapted from browser-use-pi
5
+ * (https://github.com/browser-use/browser-use-pi, package `@browser_use/pi`
6
+ * v0.1.0, MIT license): realm creation via node:inspector, cell evaluation
7
+ * semantics (replMode, object groups, last-expression capture), bounded
8
+ * output capture with secret redaction, and the artifact/checkpoint helpers.
9
+ *
10
+ * Differences from the SDK worker:
11
+ * - the CDP layer is replaced by a tool channel: `page`/`tabs` are IPC
12
+ * proxies whose methods execute browser tools on the session's current
13
+ * tab (the host routes them through the add-on; the DOM is in Firefox);
14
+ * - `require` is NOT exposed (v1) — the realm gets curated globals only;
15
+ * - no domain policy / highlight / recording / sensitiveData.
16
+ *
17
+ * Why node:inspector: it is a V8 handle to THIS process's own engine, used
18
+ * to run each cell in one persistent named context with REPL semantics
19
+ * (top-level await, last-expression capture, per-cell object-group cleanup).
20
+ * It does not connect to the browser.
21
+ */
22
+ import { Writable } from "node:stream";
23
+ import { Session } from "node:inspector";
24
+ import { createContext } from "node:vm";
25
+ import { inspect } from "node:util";
26
+ import { appendFileSync } from "node:fs";
27
+ import { writeFile, rename } from "node:fs/promises";
28
+ import { isAbsolute, join, resolve, sep } from "node:path";
29
+ import { randomUUID } from "node:crypto";
30
+ import { createReplFs } from "./fs-sandbox.js";
31
+ // IPC initialization keeps configuration out of argv and environment.
32
+ process.on("disconnect", () => process.exit(0));
33
+ const config = (await new Promise((resolve, reject) => {
34
+ const timer = setTimeout(() => reject(new Error("worker config timeout")), 10_000);
35
+ process.once("message", (message) => {
36
+ clearTimeout(timer);
37
+ resolve(message);
38
+ });
39
+ }));
40
+ process.chdir(config.workspace);
41
+ // The workspace-scoped fs is created once and shared between the realm's
42
+ // `fs` global and the page.* primitives that write into it (page.download).
43
+ const replFs = createReplFs(config.workspace);
44
+ const clean = (value) => {
45
+ // Redaction is applied to text in the sink; this guards tool-originated
46
+ // values that are serialized into output.
47
+ const json = JSON.stringify(value);
48
+ if (json === undefined)
49
+ return value;
50
+ let out = json;
51
+ for (const secret of config.redact)
52
+ if (secret)
53
+ out = out.split(secret).join("[REDACTED]");
54
+ return JSON.parse(out);
55
+ };
56
+ const send = (message) => {
57
+ try {
58
+ process.send(message);
59
+ }
60
+ catch {
61
+ /* channel gone; the runtime treats exit as state loss */
62
+ }
63
+ };
64
+ // ---------------------------------------------------------------------------
65
+ // Output capture: bounded, redacted across chunk boundaries, spilled to file
66
+ // ---------------------------------------------------------------------------
67
+ let outputFile;
68
+ let output = "";
69
+ let images = [];
70
+ let overflow = false;
71
+ /** Bound memory even when generated code writes an unbounded amount of output. */
72
+ const hardLimit = 1_000_000;
73
+ let pendingText = "";
74
+ const tailLength = Math.max(0, ...config.redact.map((value) => value.length));
75
+ function captureText(text) {
76
+ if (output.length + text.length > hardLimit)
77
+ overflow = true;
78
+ const captured = text.slice(0, Math.max(0, hardLimit - output.length));
79
+ output += captured;
80
+ if (outputFile && captured)
81
+ appendFileSync(outputFile, captured);
82
+ }
83
+ const sink = new Writable({
84
+ write(chunk, _encoding, callback) {
85
+ pendingText += chunk.toString();
86
+ // Redact before splitting, and retain the raw suffix across chunk boundaries.
87
+ const cut = Math.max(0, pendingText.length - tailLength);
88
+ let safeCut = cut;
89
+ for (const secret of config.redact) {
90
+ if (!secret)
91
+ continue;
92
+ let at = pendingText.indexOf(secret);
93
+ while (at >= 0 && at < cut) {
94
+ if (at + secret.length > cut)
95
+ safeCut = Math.min(safeCut, at);
96
+ at = pendingText.indexOf(secret, at + 1);
97
+ }
98
+ }
99
+ captureText(cleanText(pendingText.slice(0, safeCut)));
100
+ pendingText = pendingText.slice(safeCut);
101
+ callback();
102
+ },
103
+ });
104
+ function cleanText(text) {
105
+ let out = text;
106
+ for (const secret of config.redact)
107
+ if (secret)
108
+ out = out.split(secret).join("[REDACTED]");
109
+ return out;
110
+ }
111
+ // ---------------------------------------------------------------------------
112
+ // Tool channel: page/tabs primitives execute browser tools on the session's
113
+ // current tab. The host owns routing, permissions and the add-on.
114
+ // ---------------------------------------------------------------------------
115
+ /**
116
+ * Lexical pre-check for page.download destinations: reject escapes BEFORE
117
+ * issuing the download (never fetch 50 MB of video only to fail at write
118
+ * time). The sandbox's fs.write applies the full check (incl. symlinks)
119
+ * again at write time; this only saves the round-trip.
120
+ */
121
+ function assertDownloadPathInsideWorkspace(p) {
122
+ if (p.includes("\0"))
123
+ throw new Error("page.download: `path` contains a NUL byte.");
124
+ if (p.split(/[\\/]+/).includes(".."))
125
+ throw new Error(`page.download: path escapes the workspace: ${p}`);
126
+ if (isAbsolute(p)) {
127
+ const root = resolve(config.workspace);
128
+ const resolved = resolve(p);
129
+ if (resolved !== root && !resolved.startsWith(root + sep))
130
+ throw new Error(`page.download: path escapes the workspace: ${p}`);
131
+ }
132
+ }
133
+ let nextToolId = 0;
134
+ const toolPending = new Map();
135
+ function callTool(tool, args) {
136
+ const id = ++nextToolId;
137
+ return new Promise((resolve, reject) => {
138
+ toolPending.set(id, { resolve, reject });
139
+ let sent = false;
140
+ try {
141
+ sent = process.send({ type: "tool", id, tool, args });
142
+ }
143
+ catch {
144
+ sent = false;
145
+ }
146
+ if (!sent) {
147
+ toolPending.delete(id);
148
+ reject(new Error("Repl channel closed; the cell was interrupted."));
149
+ }
150
+ });
151
+ }
152
+ process.on("message", (message) => {
153
+ if (message.type === "tool-result") {
154
+ const pending = toolPending.get(message.id);
155
+ if (!pending)
156
+ return;
157
+ toolPending.delete(message.id);
158
+ if (message.error !== undefined)
159
+ pending.reject(new Error(message.error));
160
+ else
161
+ pending.resolve(clean(message.result));
162
+ }
163
+ });
164
+ /** The REPL's active tab. Undefined = the session's bound tab (the default). */
165
+ let activeTabId;
166
+ /** Targets the REPL opened itself (closed by the add-on at session end). */
167
+ const ownedTabIds = new Set();
168
+ function requireFiniteCoordinates(x, y) {
169
+ if (![x, y].every((v) => typeof v === "number" && Number.isFinite(v)))
170
+ throw new Error("Coordinates must be finite numbers.");
171
+ }
172
+ const page = {
173
+ /** Navigate the current tab. Resolves after the document stops loading. */
174
+ async goto(url) {
175
+ const result = (await callTool("browser_navigate", { url }));
176
+ if (result?.errorText)
177
+ throw new Error(`Navigation failed: ${result.errorText}`);
178
+ // Runs IN THE PAGE (serialized as source, never executed here).
179
+ await this.waitFor("() => document.readyState !== 'loading'");
180
+ return this.info();
181
+ },
182
+ /** { url, title } of the current tab. */
183
+ async info() {
184
+ const result = (await callTool("browser_get_page", {}));
185
+ return { url: result?.url ?? "", title: result?.title ?? "" };
186
+ },
187
+ /**
188
+ * Run a function or expression in the page and return its JSON result.
189
+ * `fn` may be a function (arg is passed as its single argument) or an
190
+ * expression string. Cannot capture Node variables; pass data via `arg`.
191
+ */
192
+ async evaluate(fn, arg, options = {}) {
193
+ if (typeof fn !== "string" && typeof fn !== "function")
194
+ throw new Error("page.evaluate requires a function or an expression string.");
195
+ const expression = typeof fn === "string" ? fn : fn.toString();
196
+ const result = (await callTool("browser_evaluate", {
197
+ expression,
198
+ ...(arg !== undefined ? { arg } : {}),
199
+ ...(options.frame !== undefined ? { frame: options.frame } : {}),
200
+ }));
201
+ if (result?.error)
202
+ throw new Error(result.error);
203
+ return result?.value;
204
+ },
205
+ /**
206
+ * Poll `fn` (in the page) until truthy. Survives navigations (a destroyed
207
+ * execution context is retried, like the SDK's page.waitFor).
208
+ */
209
+ async waitFor(fn, arg, options = {}) {
210
+ const timeoutMs = options.timeoutMs ?? 30_000;
211
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0)
212
+ throw new Error("waitFor timeoutMs must be a positive integer.");
213
+ const expression = typeof fn === "string" ? fn : fn.toString();
214
+ const deadline = Date.now() + timeoutMs;
215
+ for (;;) {
216
+ try {
217
+ const value = await this.evaluate(expression, arg, options);
218
+ if (value)
219
+ return;
220
+ }
221
+ catch (error) {
222
+ const message = error instanceof Error ? error.message : String(error);
223
+ // Tolerate only navigation-flavored errors (the document is being
224
+ // replaced; the next poll may already see the new one). Permanent
225
+ // failures (permissions, bad args) throw immediately.
226
+ if (!/Execution context was destroyed|context (was )?(destroyed|invalid)|BROWSER_TOOL_TIMEOUT|BROWSER_TAB_CLOSED|BROWSER_NOT_BOUND|BROWSER_FRAME_NOT_FOUND|navigated away|receiving end does not exist/i.test(message))
227
+ throw error;
228
+ }
229
+ if (Date.now() >= deadline)
230
+ throw new Error(`Page condition exceeded ${timeoutMs} ms.`);
231
+ await new Promise((resolve) => setTimeout(resolve, Math.min(100, Math.max(0, deadline - Date.now()))));
232
+ }
233
+ },
234
+ /**
235
+ * Structured accessibility snapshot of the bound tab. Defaults to a nested
236
+ * tree: { url, title, tree } where tree is the single synthetic root whose
237
+ * `children` hold the walk's nodes ({ role, name, children[] }, pre-order,
238
+ * unnamed containers promoted). Every real node carries a stable `ref` (valid
239
+ * until the page navigates) usable with page.click/page.type, plus role, name,
240
+ * and state/geometry fields. Pass format: "flat" (or "nodes") for the legacy
241
+ * flat node list { url, title, nodes[] }.
242
+ */
243
+ async snapshot(options = {}) {
244
+ if (options.format === "flat" || options.format === "nodes") {
245
+ return this.snapshotFlat(options);
246
+ }
247
+ const tree = (await callTool("browser_get_accessibility_tree", {
248
+ format: "tree",
249
+ ...(options.maxNodes !== undefined ? { maxNodes: options.maxNodes } : {}),
250
+ ...(options.maxDepth !== undefined ? { maxDepth: options.maxDepth } : {}),
251
+ ...(options.frame !== undefined ? { frame: options.frame } : {}),
252
+ }));
253
+ const info = await this.info();
254
+ return {
255
+ ...info,
256
+ tree: tree?.tree,
257
+ ...(tree?.truncated ? { truncated: true } : {}),
258
+ ...(tree?.note ? { note: tree.note } : {}),
259
+ };
260
+ },
261
+ /**
262
+ * Flat variant of page.snapshot() — the legacy node list { url, title, nodes[] }
263
+ * (pre-order, stable refs). `snapshot({ format: "flat" })` and the viewport
264
+ * filter page.snapshotVisible() route through this.
265
+ */
266
+ async snapshotFlat(options = {}) {
267
+ const tree = (await callTool("browser_get_accessibility_tree", {
268
+ format: "nodes",
269
+ ...(options.maxNodes !== undefined ? { maxNodes: options.maxNodes } : {}),
270
+ ...(options.maxDepth !== undefined ? { maxDepth: options.maxDepth } : {}),
271
+ ...(options.frame !== undefined ? { frame: options.frame } : {}),
272
+ }));
273
+ const info = await this.info();
274
+ return {
275
+ ...info,
276
+ nodes: tree?.nodes ?? [],
277
+ ...(tree?.truncated ? { truncated: true } : {}),
278
+ ...(tree?.note ? { note: tree.note } : {}),
279
+ };
280
+ },
281
+ /**
282
+ * Snapshot the accessibility tree restricted to elements in the CURRENT
283
+ * viewport: nodes whose rect intersects the visible area. `rect` is
284
+ * viewport-relative, so the test is a plain intersection with no scroll
285
+ * offset. Rect-less container nodes (e.g. a bare form/banner) have no box
286
+ * of their own and are dropped. Pure post-filter over the flat snapshot.
287
+ */
288
+ async snapshotVisible(options = {}) {
289
+ const base = await this.snapshotFlat(options);
290
+ const vp = (await this.evaluate("() => ({ w: innerWidth, h: innerHeight })", undefined, options.frame !== undefined ? { frame: options.frame } : {}));
291
+ if (!vp || !Number.isFinite(vp.w) || !Number.isFinite(vp.h)) {
292
+ throw new Error("page.snapshotVisible: could not read the viewport size.");
293
+ }
294
+ const inView = (n) => {
295
+ const r = n.rect;
296
+ if (!r)
297
+ return false;
298
+ return r.x < vp.w && r.x + r.width > 0 && r.y < vp.h && r.y + r.height > 0;
299
+ };
300
+ const all = (base.nodes ?? []);
301
+ const nodes = all.filter(inView);
302
+ return {
303
+ ...base,
304
+ nodes,
305
+ visibleCount: nodes.length,
306
+ viewport: { width: vp.w, height: vp.h },
307
+ };
308
+ },
309
+ /**
310
+ * Diff two snapshots (from two snapshot()/snapshotVisible() calls) — pure
311
+ * in-worker computation, NO extra browser round-trip. `ref` changes between
312
+ * snapshots, so identity is a content signature by default (content mode:
313
+ * role+name+href+value+type, so an in-place value change shows as one removed
314
+ * + one added); structural mode keys only role+href and reports in-place
315
+ * name/value changes as `changed`.
316
+ * Pass the full snapshot objects — tree format carries `tree`, flat format
317
+ * carries `nodes` — or a bare node[]. A tree format is flattened pre-order
318
+ * (synthetic root excluded) before diffing.
319
+ */
320
+ snapshotDiff(before, after, options = {}) {
321
+ const flattenTree = (n) => {
322
+ if (typeof n !== "object" || n === null)
323
+ return [];
324
+ const children = n.children;
325
+ const subs = Array.isArray(children) ? children.flatMap(flattenTree) : [];
326
+ return [n, ...subs];
327
+ };
328
+ const nodesOf = (v) => {
329
+ if (Array.isArray(v)) {
330
+ return v;
331
+ }
332
+ const obj = v;
333
+ if (obj && Array.isArray(obj.nodes))
334
+ return obj.nodes;
335
+ if (obj && obj.tree !== undefined)
336
+ return obj.tree.children?.flatMap(flattenTree) ?? [];
337
+ return [];
338
+ };
339
+ const b = nodesOf(before);
340
+ const a = nodesOf(after);
341
+ const mode = options.key === "structural" ? "structural" : "content";
342
+ const contentOf = (n) => {
343
+ const c = {};
344
+ for (const k of ["role", "name", "href", "value", "type"]) {
345
+ const v = n[k];
346
+ if (v !== undefined)
347
+ c[k] = v;
348
+ }
349
+ return c;
350
+ };
351
+ const keyOf = (n) => mode === "structural"
352
+ ? `${String(n.role ?? "")}::${String(n.href ?? "")}`
353
+ : JSON.stringify(contentOf(n));
354
+ const multiset = (arr) => {
355
+ const m = new Map();
356
+ for (const n of arr) {
357
+ const k = keyOf(n);
358
+ let e = m.get(k);
359
+ if (!e) {
360
+ e = { count: 0, items: [] };
361
+ m.set(k, e);
362
+ }
363
+ e.count += 1;
364
+ e.items.push({ n, ...(mode === "content" ? { content: contentOf(n) } : {}) });
365
+ }
366
+ return m;
367
+ };
368
+ const mb = multiset(b);
369
+ const ma = multiset(a);
370
+ const added = [];
371
+ const removed = [];
372
+ const unchanged = [];
373
+ const changed = [];
374
+ const pushMany = (out, bucket, limit = 25) => {
375
+ if (!bucket)
376
+ return;
377
+ for (let i = 0; i < bucket.items.length && out.length < limit; i++)
378
+ out.push(bucket.items[i]);
379
+ };
380
+ for (const [k, ba] of mb) {
381
+ const aa = ma.get(k);
382
+ const min = Math.min(ba.count, aa?.count ?? 0);
383
+ if (min > 0) {
384
+ for (let i = 0; i < min; i++)
385
+ pushMany(unchanged, ba);
386
+ }
387
+ if (ba.count > (aa?.count ?? 0))
388
+ pushMany(removed, ba);
389
+ }
390
+ for (const [k, aa] of ma) {
391
+ const ba = mb.get(k);
392
+ const min = Math.min(aa.count, ba?.count ?? 0);
393
+ if (aa.count > min)
394
+ pushMany(added, aa);
395
+ }
396
+ if (mode === "structural") {
397
+ for (const [k, ba] of mb) {
398
+ const aa = ma.get(k);
399
+ if (!aa)
400
+ continue;
401
+ const min = Math.min(ba.count, aa.count);
402
+ for (let i = 0; i < min && i < 25; i++) {
403
+ const x = ba.items[i];
404
+ const y = aa.items[i];
405
+ const cb = JSON.stringify(contentOf(x.n));
406
+ const ca = JSON.stringify(contentOf(y.n));
407
+ if (cb !== ca)
408
+ changed.push({ key: k, before: JSON.parse(cb), after: JSON.parse(ca) });
409
+ }
410
+ }
411
+ }
412
+ const countByRole = (arr) => arr.reduce((acc, { n }) => {
413
+ const r = String(n.role ?? "?");
414
+ acc[r] = (acc[r] ?? 0) + 1;
415
+ return acc;
416
+ }, {});
417
+ return {
418
+ mode,
419
+ added: { count: added.length, items: added },
420
+ removed: { count: removed.length, items: removed },
421
+ changed: { count: changed.length, items: changed },
422
+ unchangedCount: unchanged.length,
423
+ unchangedRoles: countByRole(unchanged),
424
+ ...(before && !Array.isArray(before) ? { beforeUrl: before.url } : {}),
425
+ ...(after && !Array.isArray(after) ? { afterUrl: after.url } : {}),
426
+ };
427
+ },
428
+ /** Click an element by ref (from snapshot()/browser_get_dom). */
429
+ async click(ref, options = {}) {
430
+ return callTool("browser_click", { ref, ...(options.frame !== undefined ? { frame: options.frame } : {}) });
431
+ },
432
+ /** Real (content-script) click at viewport coordinates. Returns what was hit. */
433
+ async clickAt(x, y, options = {}) {
434
+ requireFiniteCoordinates(x, y);
435
+ return callTool("browser_click_at", { x, y, ...(options.frame !== undefined ? { frame: options.frame } : {}) });
436
+ },
437
+ /** Type text into an element by ref (optionally submitting its form). */
438
+ async type(ref, text, options = {}) {
439
+ return callTool("browser_type", {
440
+ ref,
441
+ text,
442
+ ...(options.submit !== undefined ? { submit: options.submit } : {}),
443
+ ...(options.frame !== undefined ? { frame: options.frame } : {}),
444
+ });
445
+ },
446
+ /** Insert text into the currently focused element (no ref needed). */
447
+ async typeFocused(text) {
448
+ return callTool("browser_type_focused", { text });
449
+ },
450
+ /** Focus an element by ref. */
451
+ async focus(ref, options = {}) {
452
+ return callTool("browser_focus", { ref, ...(options.frame !== undefined ? { frame: options.frame } : {}) });
453
+ },
454
+ /** Scroll an element by ref into view. */
455
+ async scroll(ref, options = {}) {
456
+ return callTool("browser_scroll", { ref, ...(options.frame !== undefined ? { frame: options.frame } : {}) });
457
+ },
458
+ /**
459
+ * Capture the viewport as an image. The image is attached to the cell
460
+ * result automatically (at most 4 per cell); do not print image bytes.
461
+ */
462
+ async screenshot(options = {}) {
463
+ const count = images.length;
464
+ if (count >= 4)
465
+ throw new Error("At most four screenshots per cell.");
466
+ const quality = options.quality ?? 70;
467
+ const result = (await callTool("browser_screenshot", { format: "jpeg", quality }));
468
+ const data = result?.data;
469
+ if (typeof data !== "string" || data.length === 0)
470
+ throw new Error("Screenshot returned no image data.");
471
+ if (Buffer.byteLength(data, "base64") > 8_000_000) {
472
+ sink.write("[Screenshot omitted: 8 MB limit.]\n");
473
+ return "Screenshot omitted; see note.";
474
+ }
475
+ images.push({ type: "image", data, mimeType: result?.mimeType ?? "image/jpeg" });
476
+ return images.length > count ? "Screenshot captured." : "Screenshot omitted; see warning.";
477
+ },
478
+ /**
479
+ * Download a file (image, video, or any resource) using the browser's own
480
+ * network state — the extension issues the fetch with the user's cookies
481
+ * for the target origin, so authenticated URLs that a shell curl cannot
482
+ * reach download here. Saves into the task workspace (parent directories
483
+ * are created) and returns { path, bytes, mimeType, url }.
484
+ * @param url absolute http(s) URL to download (e.g. the src of an image on the page)
485
+ * @param path relative file path inside the task workspace (default: the
486
+ * server-provided file name)
487
+ * @param options.maxBytes byte cap for oversized resources (default 10 MB,
488
+ * cap 50 MB); larger downloads are rejected, never truncated — for
489
+ * big files pass the `javascript` tool a matching timeoutMs (max 120000)
490
+ */
491
+ async download(url, path, options = {}) {
492
+ if (typeof url !== "string" || !/^https?:\/\//i.test(url))
493
+ throw new Error("page.download requires an absolute http(s) URL.");
494
+ if (typeof path === "string") {
495
+ if (path.length === 0)
496
+ throw new Error("page.download: `path` must be a non-empty string.");
497
+ assertDownloadPathInsideWorkspace(path);
498
+ }
499
+ const result = (await callTool("browser_download", {
500
+ url,
501
+ ...(options.maxBytes !== undefined ? { maxBytes: options.maxBytes } : {}),
502
+ }));
503
+ const dataBase64 = result?.dataBase64;
504
+ if (typeof dataBase64 !== "string" || dataBase64.length === 0)
505
+ throw new Error("browser_download returned no data.");
506
+ const bytes = Buffer.from(dataBase64, "base64");
507
+ if (result && typeof result.byteLength === "number" && bytes.byteLength !== result.byteLength)
508
+ throw new Error(`downloaded data is corrupt: expected ${result.byteLength} bytes, got ${bytes.byteLength}.`);
509
+ const relative = typeof path === "string" && path.length > 0 ? path : (result?.fileName ?? "download");
510
+ const written = await replFs.write(relative, bytes, "buffer");
511
+ return { path: relative, bytes: written, mimeType: result?.mimeType ?? "", url };
512
+ },
513
+ /** Close the active REPL-opened tab and return to the bound tab. */
514
+ async close() {
515
+ if (activeTabId === undefined)
516
+ throw new Error("No REPL-opened tab to close; the bound tab belongs to the session (unbind in the UI).");
517
+ const tabId = activeTabId;
518
+ ownedTabIds.delete(tabId);
519
+ await callTool("browser_close_tab", { tabId });
520
+ activeTabId = undefined;
521
+ },
522
+ };
523
+ const tabs = {
524
+ /** All open tabs of the browser: { targetId, id, url, title, bound }[]. */
525
+ async list() {
526
+ const result = (await callTool("browser_list_tabs", {}));
527
+ return (result?.tabs ?? []).map((t) => ({
528
+ targetId: `tab:${t.id}`,
529
+ id: t.id,
530
+ url: t.url ?? "",
531
+ title: t.title ?? "",
532
+ bound: t.bound === true,
533
+ }));
534
+ },
535
+ /**
536
+ * Open a new tab (owned by the REPL: closed at session end) and make it
537
+ * the current page. The session binding follows the new tab; the previous
538
+ * tab stays open and can be returned to via tabs.get().
539
+ */
540
+ async open(url = "about:blank") {
541
+ const result = (await callTool("browser_open_tab", { url }));
542
+ if (typeof result?.tabId !== "number")
543
+ throw new Error("browser_open_tab returned no tabId.");
544
+ activeTabId = result.tabId;
545
+ ownedTabIds.add(result.tabId);
546
+ const info = await page.info();
547
+ return { targetId: `tab:${result.tabId}`, ...info };
548
+ },
549
+ /** Switch the current page to an existing tab (targetId "tab:<id>" or id). */
550
+ async get(targetId) {
551
+ const id = typeof targetId === "number" ? targetId : Number(/^tab:(\d+)$/.exec(targetId)?.[1]);
552
+ if (!Number.isInteger(id) || id <= 0)
553
+ throw new Error(`Unknown target: ${String(targetId)} (use tabs.list()).`);
554
+ activeTabId = id;
555
+ const info = await page.info();
556
+ return { targetId: `tab:${id}`, ...info };
557
+ },
558
+ };
559
+ // ---------------------------------------------------------------------------
560
+ // The V8 realm: one persistent named context, cells run via the inspector
561
+ // ---------------------------------------------------------------------------
562
+ const evaluator = new Session();
563
+ evaluator.connect();
564
+ let executionContextId;
565
+ evaluator.on("Runtime.executionContextCreated", (event) => {
566
+ const params = event.params;
567
+ if (params.context.name === "pi-repl")
568
+ executionContextId = params.context.id;
569
+ });
570
+ evaluator.post("Runtime.enable");
571
+ const realm = createContext({}, {
572
+ name: "pi-repl",
573
+ importModuleDynamically: undefined,
574
+ });
575
+ // Inspector context IDs are weak handles. The live evaluator must also own
576
+ // the realm, or V8 can collect it between cells despite persistent variables.
577
+ evaluator.realm = realm;
578
+ if (executionContextId === undefined)
579
+ throw new Error("Could not initialize the JavaScript context.");
580
+ let pendingPreamble = config.preamble ? `[javascript tool]\n${config.preamble}\n` : "";
581
+ Object.assign(realm, {
582
+ global: realm, // Node's global alias refers to this REPL realm, not the worker host.
583
+ process: undefined, // deliberately NOT exposed (v1)
584
+ Buffer,
585
+ URL,
586
+ URLSearchParams,
587
+ fetch,
588
+ AbortController,
589
+ AbortSignal,
590
+ setTimeout,
591
+ clearTimeout,
592
+ setInterval,
593
+ clearInterval,
594
+ queueMicrotask,
595
+ structuredClone,
596
+ TextEncoder,
597
+ TextDecoder,
598
+ console: new (await import("node:console")).Console(sink, sink),
599
+ workspace: config.workspace,
600
+ // Workspace-scoped filesystem: every path resolves against the session's
601
+ // task workspace; escapes (.., outside absolute paths, symlinks out) are
602
+ // rejected. See fs-sandbox.ts.
603
+ fs: replFs,
604
+ page,
605
+ tabs,
606
+ async screenshot(options) {
607
+ return page.screenshot(options);
608
+ },
609
+ async snapshot(options) {
610
+ return page.snapshot(options);
611
+ },
612
+ /** Accessible tree restricted to the elements in the current viewport. */
613
+ async snapshotVisible(options) {
614
+ return page.snapshotVisible(options);
615
+ },
616
+ /** Diff two snapshot node arrays — see page.snapshotDiff. */
617
+ snapshotDiff(before, after, options) {
618
+ return page.snapshotDiff(before, after, options);
619
+ },
620
+ async artifact(name, data) {
621
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,119}$/.test(name))
622
+ throw new Error("Use a plain filename, max 120 characters.");
623
+ const path = join(config.workspace, name);
624
+ await writeFile(path, data, { flag: "wx", mode: 0o600 });
625
+ return path;
626
+ },
627
+ async checkpoint(name, value) {
628
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,119}$/.test(name))
629
+ throw new Error("Use a plain checkpoint filename.");
630
+ const valueJson = JSON.stringify(clean(value));
631
+ if (typeof valueJson !== "string")
632
+ throw new Error("Checkpoint must be JSON serializable.");
633
+ const path = join(config.workspace, name);
634
+ const temporary = `${path}.${randomUUID()}.tmp`;
635
+ await writeFile(temporary, valueJson, { flag: "wx", mode: 0o600 });
636
+ await rename(temporary, path);
637
+ return path;
638
+ },
639
+ /**
640
+ * Reset the REPL's browser view (active tab handle). Node variables and
641
+ * files are preserved. Inspect the page before acting.
642
+ */
643
+ async reconnect() {
644
+ activeTabId = undefined;
645
+ return "Page handles reset. Inspect the page before acting; no browser action was replayed.";
646
+ },
647
+ });
648
+ async function post(method, parameters) {
649
+ return new Promise((resolve, reject) => {
650
+ evaluator.post(method, parameters, (error, response) => {
651
+ if (error)
652
+ reject(error);
653
+ else
654
+ resolve(response);
655
+ });
656
+ });
657
+ }
658
+ async function evaluateCell(code) {
659
+ try {
660
+ // V8 supports replMode; Node's generated protocol types omit the field.
661
+ const { result, exceptionDetails } = await post("Runtime.evaluate", {
662
+ expression: code,
663
+ contextId: executionContextId,
664
+ awaitPromise: true,
665
+ replMode: true,
666
+ objectGroup: "cell",
667
+ });
668
+ if (exceptionDetails)
669
+ throw new Error(exceptionDetails.exception?.description ?? exceptionDetails.text);
670
+ if (result.objectId) {
671
+ // Print objects through the realm's console (inspect-style output).
672
+ await post("Runtime.callFunctionOn", {
673
+ objectId: result.objectId,
674
+ functionDeclaration: "function() { console.log(this); }",
675
+ returnByValue: true,
676
+ });
677
+ }
678
+ else if (result.type !== "undefined") {
679
+ sink.write(result.unserializableValue ?? inspect(result.value, { maxStringLength: 20_000 }));
680
+ }
681
+ }
682
+ finally {
683
+ evaluator.post("Runtime.releaseObjectGroup", { objectGroup: "cell" });
684
+ }
685
+ }
686
+ process.on("message", async (message) => {
687
+ if (message.type === "close") {
688
+ evaluator.disconnect();
689
+ send({ type: "closed" });
690
+ return;
691
+ }
692
+ if (message.type !== "execute")
693
+ return;
694
+ output = "";
695
+ pendingText = "";
696
+ images = [];
697
+ overflow = false;
698
+ outputFile = message.outputFile;
699
+ let failure;
700
+ if (pendingPreamble) {
701
+ sink.write(pendingPreamble);
702
+ pendingPreamble = "";
703
+ }
704
+ for (const note of message.notes ?? [])
705
+ sink.write(`[repl] ${note}\n`);
706
+ try {
707
+ await evaluateCell(message.code);
708
+ }
709
+ catch (error) {
710
+ failure = error instanceof Error ? error.message : String(error);
711
+ }
712
+ // Flush any redaction tail held back across chunk boundaries.
713
+ captureText(cleanText(pendingText));
714
+ pendingText = "";
715
+ if (overflow)
716
+ output += "\n[Output exceeded the 1 MB capture limit.]";
717
+ let text = output;
718
+ if (text.length > config.maxOutputChars)
719
+ text = `${text.slice(0, config.maxOutputChars)}\n[Truncated. Full captured output: ${outputFile}]`;
720
+ const cellResult = {
721
+ text: text || (failure ? "" : "(no output)"),
722
+ images,
723
+ ...(outputFile ? { outputFile } : {}),
724
+ };
725
+ if (failure)
726
+ send({ type: "result", result: cellResult, error: failure });
727
+ else
728
+ send({ type: "result", result: cellResult });
729
+ });
730
+ send({ type: "ready" });
731
+ //# sourceMappingURL=worker.js.map