@howaboua/pi-browser 0.0.4 → 0.0.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @howaboua/pi-browser
2
2
 
3
+ ## 0.0.6
4
+
5
+ - Requires Pi 1.0.0 or later.
6
+
7
+ Browser now uses help-first discovery in ordinary Pi and Structured mode. Native calls accept help and single or batched JSON requests through `command`, matching Code and Notebook. Existing object calls remain supported.
8
+
9
+ ## 0.0.5
10
+
11
+ - Browser snapshots now include link destinations.
12
+
13
+ - Browser help and schemas now describe single-action requests, shared batch fields and JSON results with less repetition.
14
+ - Click errors now identify zero-sized browser viewports.
15
+
3
16
  ## 0.0.4
4
17
 
5
18
  - Added session-owned background browser work and direct form controls.
package/README.md CHANGED
@@ -10,19 +10,19 @@ The extension is the TypeScript counterpart of Pi Codex's browser custom tool. I
10
10
  pi install npm:@howaboua/pi-browser
11
11
  ```
12
12
 
13
- Requires Pi 0.84.3 or newer, Node.js 22.19 or newer, and a Chrome-family browser with remote debugging enabled at `chrome://inspect/#remote-debugging`.
13
+ Requires Pi 1.0.0 or newer, Node.js 22.19 or newer, and a Chrome-family browser with remote debugging enabled at `chrome://inspect/#remote-debugging`.
14
14
 
15
15
  Pi Codex 3.0.25 or newer is optional. Without it, Browser remains a normal top-level Pi tool. Do not load Pi Codex's example `browser.toml` custom tool alongside this extension.
16
16
 
17
17
  ## Use
18
18
 
19
- In normal Pi, call `browser` with `action: "help"` before first use. In Code or Notebook Mode, start with:
19
+ In normal Pi, call `browser` with `command: "help"` before first use, then send JSON request strings in `command`. Existing object requests remain accepted. In Code or Notebook Mode, start with:
20
20
 
21
21
  ```js
22
22
  await tools.browser("help")
23
23
  ```
24
24
 
25
- Normal Pi exposes the single-action contract. Code and Notebook Mode also accept batched freeform requests. A common route is `tabs`, then `open`, then `click` or `type` with the returned `ref_id` and element ID.
25
+ All modes accept single-action and batched requests described by help. A common route is `tabs`, then `open`, then `click` or `type` with the returned `ref_id` and element ID.
26
26
 
27
27
  Long Code and Notebook calls use the normal `exec` and `wait` lifecycle. Cancellation stops pending CDP work, though an already dispatched browser mutation may still take effect.
28
28
 
@@ -32,7 +32,7 @@ Ownership survives extension reloads and managed-worker restarts while the brows
32
32
 
33
33
  ## Host routing
34
34
 
35
- In Pi's interactive TUI, run `/browser`, add the SSH host names, identify the current machine, then save. Pi reloads the extension with the corresponding `host` choices. Advanced settings expose the remote Node command, which defaults to `node`.
35
+ In Pi's interactive TUI, run `/browser`, add the SSH host names, identify the current machine, then save. Browser help lists the configured `host` choices. Advanced settings expose the remote Node command, which defaults to `node`.
36
36
 
37
37
  Each name must be an existing SSH alias. On first use, the extension atomically installs or updates its managed worker at `~/.pi/agent/pi-browser-worker.mjs` on that host, then invokes it against the host's local CDP browser. No package installation is required on routed machines. Screenshots return through SCP and the remote artifact is removed. Keep `host` on follow-up calls that use a returned ref, screenshot, or continuation handle. Settings are stored in `pi-browser.json` under Pi's agent directory; `PI_BROWSER_CONFIG` overrides that storage path.
38
38
 
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { BrowserRoutes, loadBrowserRoutes } from "./src/browser/routes.js";
2
2
  import { BrowserRuntime } from "./src/browser/runtime.js";
3
3
  import { registerBrowserCommand } from "./src/browser/settings.js";
4
- import { createBrowserTool, prepareBrowserCodeModeInput, } from "./src/browser-tool.js";
4
+ import { createBrowserTool, prepareBrowserInput } from "./src/browser-tool.js";
5
5
  export { createBrowserTool } from "./src/browser-tool.js";
6
6
  const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
7
7
  const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
@@ -36,7 +36,7 @@ async function registerBrowserInCodeMode(pi, tool) {
36
36
  return registerCodeModeExtensionTools(pi, () => [
37
37
  adaptToolForCodeMode(tool, {
38
38
  kind: "freeform",
39
- prepareInput: prepareBrowserCodeModeInput,
39
+ prepareInput: prepareBrowserInput,
40
40
  usage: 'await tools.browser("help") // Logged-in browser; help before other actions',
41
41
  }),
42
42
  ]);
@@ -311,18 +311,18 @@ function parseActionRequest(value) {
311
311
  };
312
312
  }
313
313
  if (action === "open") {
314
- const refId2 = optionalString(value["ref_id"], "ref_id");
314
+ const refId = optionalString(value["ref_id"], "ref_id");
315
315
  const url = optionalString(value["url"], "url");
316
- if (Boolean(refId2) === Boolean(url)) {
316
+ if (Boolean(refId) === Boolean(url)) {
317
317
  throw new Error("open requires exactly one of ref_id or url");
318
318
  }
319
319
  if (url)
320
320
  return { action, url };
321
- if (!refId2)
321
+ if (!refId)
322
322
  throw new Error("open requires ref_id or url");
323
323
  return {
324
324
  action,
325
- ref_id: refId2,
325
+ ref_id: refId,
326
326
  lineno: line(value["lineno"]),
327
327
  response_length: responseLength(value["response_length"])
328
328
  };
@@ -347,8 +347,8 @@ function parseActionRequest(value) {
347
347
  return { action, handle: resultHandle(value["handle"]) };
348
348
  }
349
349
  if (action === "stop") {
350
- const refId2 = optionalString(value["ref_id"], "ref_id");
351
- return { action, ...refId2 ? { ref_id: refId2 } : {} };
350
+ const refId = optionalString(value["ref_id"], "ref_id");
351
+ return { action, ...refId ? { ref_id: refId } : {} };
352
352
  }
353
353
  const refId = requiredRef(value["ref_id"], action);
354
354
  if (action === "network" || action === "show" || action === "close")
@@ -442,7 +442,7 @@ function parseActionRequest(value) {
442
442
  }
443
443
  if (action === "wait") {
444
444
  const conditions = ["selector", "text", "url_includes"];
445
- const provided = conditions.filter((field2) => value[field2] !== undefined);
445
+ const provided = conditions.filter((field) => value[field] !== undefined);
446
446
  const field = provided[0];
447
447
  if (provided.length !== 1 || !field) {
448
448
  throw new Error("wait requires exactly one of selector, text, or url_includes");
@@ -1214,7 +1214,7 @@ class BrowserTabs {
1214
1214
  }
1215
1215
  async resolve(refId, signal) {
1216
1216
  const pages = await this.list(signal);
1217
- const ids = pages.map((page2) => page2.targetId);
1217
+ const ids = pages.map((page) => page.targetId);
1218
1218
  const targetId = resolvePrefix(refId, ids, "target", "Run tabs.");
1219
1219
  const page = pages.find((candidate) => candidate.targetId === targetId);
1220
1220
  if (!page)
@@ -1488,8 +1488,8 @@ class BrowserCdpSession {
1488
1488
  }
1489
1489
  async stop(refId) {
1490
1490
  if (!refId) {
1491
- for (const targetId2 of this.tabPromises.keys()) {
1492
- this.stopPendingTab(targetId2, "All tab bridges were stopped");
1491
+ for (const targetId of this.tabPromises.keys()) {
1492
+ this.stopPendingTab(targetId, "All tab bridges were stopped");
1493
1493
  }
1494
1494
  for (const bridge of this.tabs.values())
1495
1495
  bridge.close();
@@ -1659,17 +1659,17 @@ async function pruneArtifacts(now = Date.now()) {
1659
1659
  }
1660
1660
  return removed;
1661
1661
  }
1662
- function chunkForJson(value, offset2 = 0, budget = TEXT_BUDGET_BYTES) {
1662
+ function chunkForJson(value, offset = 0, budget = TEXT_BUDGET_BYTES) {
1663
1663
  let bytes = 2;
1664
- let end = offset2;
1665
- for (const character of value.slice(offset2)) {
1664
+ let end = offset;
1665
+ for (const character of value.slice(offset)) {
1666
1666
  const next = Buffer.byteLength(JSON.stringify(character)) - 2;
1667
1667
  if (bytes + next > budget)
1668
1668
  break;
1669
1669
  bytes += next;
1670
1670
  end += character.length;
1671
1671
  }
1672
- return { text: value.slice(offset2, end), end };
1672
+ return { text: value.slice(offset, end), end };
1673
1673
  }
1674
1674
  async function cacheResult(value) {
1675
1675
  const handle = crypto.randomUUID();
@@ -1729,19 +1729,19 @@ async function discardCachedResult(handle) {
1729
1729
  function browserHelp(hosts = []) {
1730
1730
  const routed = hosts.length > 0;
1731
1731
  return {
1732
- input: "Code=JSON.stringify(request); normal=request",
1732
+ input: "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
1733
1733
  ...routed ? {
1734
1734
  host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`
1735
1735
  } : {},
1736
1736
  refs: "tabs -> open; keep ref_id/id/cursors with their result",
1737
1737
  safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
1738
- batch: "top-level nonempty action arrays; items omit action/host/response_length; independent only",
1738
+ batch: "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
1739
1739
  actions: {
1740
1740
  tabs: "query? offset? owned_only? -> ref_id title url owned",
1741
- open: "ref_id lineno? response_length? | url; new tabs open in background",
1741
+ open: "ref_id lineno? | url; new tabs open in background",
1742
1742
  show: "ref_id; bring tab to foreground",
1743
1743
  close: "ref_id",
1744
- find: "ref_id pattern lineno? response_length?",
1744
+ find: "ref_id pattern lineno?",
1745
1745
  click: "ref_id id|selector|x+y",
1746
1746
  type: "ref_id text id?; id focuses",
1747
1747
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
@@ -1829,6 +1829,10 @@ async function backendCenter(cdp, sessionId, backendNodeId, scroll = true, signa
1829
1829
  const response = await withBackendObject(cdp, sessionId, backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
1830
1830
  objectId,
1831
1831
  functionDeclaration: `function() {
1832
+ const view = this.ownerDocument.defaultView;
1833
+ if (view && (view.innerWidth <= 0 || view.innerHeight <= 0)) {
1834
+ return { ok: false, error: 'Browser viewport is ' + view.innerWidth + 'x' + view.innerHeight + '; restore or resize its window, then retry' };
1835
+ }
1832
1836
  const rect = this.getBoundingClientRect();
1833
1837
  const style = getComputedStyle(this);
1834
1838
  const disabled = this.matches(':disabled') ||
@@ -2020,10 +2024,10 @@ function prepareFill(value) {
2020
2024
  }
2021
2025
  const indeterminate = this.type === "checkbox" && this.indeterminate;
2022
2026
  if (indeterminate && this.checked === value) {
2023
- const setter2 = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "checked")?.set;
2024
- if (!setter2)
2027
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "checked")?.set;
2028
+ if (!setter)
2025
2029
  throw new Error("Checkbox has no native checked setter");
2026
- setter2.call(this, !value);
2030
+ setter.call(this, !value);
2027
2031
  }
2028
2032
  return {
2029
2033
  kind: "checked",
@@ -2057,8 +2061,8 @@ function prepareFill(value) {
2057
2061
  if (this.multiple)
2058
2062
  throw new Error("fill requires a single-select control");
2059
2063
  const options = Array.from(this.options);
2060
- const byValue = options.filter((option2) => option2.value === value);
2061
- const matches = byValue.length ? byValue : options.filter((option2) => option2.label.trim() === value);
2064
+ const byValue = options.filter((option) => option.value === value);
2065
+ const matches = byValue.length ? byValue : options.filter((option) => option.label.trim() === value);
2062
2066
  const option = matches[0];
2063
2067
  if (matches.length !== 1 || !option)
2064
2068
  throw new Error("Option value/label must match exactly one option");
@@ -2550,7 +2554,7 @@ function isNavigationContextError(error) {
2550
2554
  }
2551
2555
  async function waitForCondition(cdp, sessionId, condition, timeoutMs, signal) {
2552
2556
  const details = conditionDetails(condition);
2553
- const timeoutError2 = new Error(`Timed out after ${timeoutMs}ms waiting for ${details.label}`);
2557
+ const timeoutError = new Error(`Timed out after ${timeoutMs}ms waiting for ${details.label}`);
2554
2558
  const deadline = Date.now() + timeoutMs;
2555
2559
  const controller = new AbortController;
2556
2560
  let timedOut = false;
@@ -2564,7 +2568,7 @@ async function waitForCondition(cdp, sessionId, condition, timeoutMs, signal) {
2564
2568
  }
2565
2569
  const timer = setTimeout(() => {
2566
2570
  timedOut = true;
2567
- controller.abort(timeoutError2);
2571
+ controller.abort(timeoutError);
2568
2572
  }, timeoutMs);
2569
2573
  try {
2570
2574
  while (Date.now() < deadline) {
@@ -2586,10 +2590,10 @@ async function waitForCondition(cdp, sessionId, condition, timeoutMs, signal) {
2586
2590
  break;
2587
2591
  await sleep(Math.min(POLL_INTERVAL_MS, remaining), controller.signal);
2588
2592
  }
2589
- throw timeoutError2;
2593
+ throw timeoutError;
2590
2594
  } catch (error) {
2591
2595
  if (timedOut)
2592
- throw timeoutError2;
2596
+ throw timeoutError;
2593
2597
  throw error;
2594
2598
  } finally {
2595
2599
  clearTimeout(timer);
@@ -2716,7 +2720,7 @@ function interactiveText(role, name, value, state) {
2716
2720
  }
2717
2721
  async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
2718
2722
  const lineno = positiveInteger(options.lineno ?? 1, "line cursor");
2719
- const responseLength2 = snapshotResponseLength(options.responseLength);
2723
+ const responseLength = snapshotResponseLength(options.responseLength);
2720
2724
  const response = asRecord(await cdp.send("Accessibility.getFullAXTree", {}, sessionId, options.signal), "Accessibility response");
2721
2725
  if (!Array.isArray(response["nodes"])) {
2722
2726
  throw new Error("Accessibility response has no nodes");
@@ -2780,10 +2784,12 @@ async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
2780
2784
  addLine(text, undefined, "interactive");
2781
2785
  renderedName = name;
2782
2786
  } else {
2787
+ const href = role === "link" ? node.properties?.find((property) => property.name === "url")?.value?.value : undefined;
2783
2788
  const element = {
2784
2789
  id: nextElementId(),
2785
2790
  role,
2786
2791
  ...name ? { name } : {},
2792
+ ...typeof href === "string" && href ? { href } : {},
2787
2793
  ...value === "" || value == null ? {} : { value },
2788
2794
  ...state
2789
2795
  };
@@ -2812,10 +2818,10 @@ async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
2812
2818
  visit(node);
2813
2819
  const metadata = asRecord(await evaluate(cdp, sessionId, "({title: document.title, url: location.href})", options.signal), "page metadata");
2814
2820
  const pattern = options.pattern?.toLowerCase();
2815
- const matching = pattern ? lines.filter((line2) => line2.text.toLowerCase().includes(pattern)) : lines;
2821
+ const matching = pattern ? lines.filter((line) => line.text.toLowerCase().includes(pattern)) : lines;
2816
2822
  const start = lineno - 1;
2817
- const content = matching.slice(start, start + SNAPSHOT_LIMITS[responseLength2]).map(({ kind: _kind, ...line2 }) => line2);
2818
- const visibleIds = new Set(content.flatMap((line2) => line2.element_id === undefined ? [] : [line2.element_id]));
2823
+ const content = matching.slice(start, start + SNAPSHOT_LIMITS[responseLength]).map(({ kind: _kind, ...line }) => line);
2824
+ const visibleIds = new Set(content.flatMap((line) => line.element_id === undefined ? [] : [line.element_id]));
2819
2825
  const hasMore = start + content.length < matching.length;
2820
2826
  return {
2821
2827
  ...options.refId ? { ref_id: options.refId } : {},
@@ -2847,6 +2853,7 @@ function truncateUtf8(value, maxBytes) {
2847
2853
  return new StringDecoder("utf8").write(bytes.subarray(0, maxBytes));
2848
2854
  }
2849
2855
  function boundedElement(element) {
2856
+ const { href, ...rest } = element;
2850
2857
  let value = element.value;
2851
2858
  if (typeof value === "string") {
2852
2859
  value = truncateUtf8(value, SNAPSHOT_ELEMENT_VALUE_BYTES);
@@ -2857,13 +2864,14 @@ function boundedElement(element) {
2857
2864
  }
2858
2865
  }
2859
2866
  return {
2860
- ...element,
2867
+ ...rest,
2868
+ ...href === undefined ? {} : Buffer.byteLength(href) > SNAPSHOT_URL_BYTES ? { href_omitted: true } : { href },
2861
2869
  role: truncateUtf8(element.role, 128),
2862
2870
  ...element.name === undefined ? {} : { name: truncateUtf8(element.name, SNAPSHOT_ELEMENT_NAME_BYTES) },
2863
2871
  ...value === undefined ? {} : { value }
2864
2872
  };
2865
2873
  }
2866
- function boundTabs(pages, query, offset2, ownedOnly = false) {
2874
+ function boundTabs(pages, query, offset, ownedOnly = false) {
2867
2875
  const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
2868
2876
  let filtered = ownedOnly ? pages.filter((page) => page.owned === true) : pages;
2869
2877
  if (query) {
@@ -2871,11 +2879,11 @@ function boundTabs(pages, query, offset2, ownedOnly = false) {
2871
2879
  filtered = filtered.filter((page) => `${page.title}
2872
2880
  ${page.url}`.toLowerCase().includes(normalized));
2873
2881
  }
2874
- if (offset2 > filtered.length) {
2875
- throw new Error(`offset ${offset2} exceeds tab count ${filtered.length}`);
2882
+ if (offset > filtered.length) {
2883
+ throw new Error(`offset ${offset} exceeds tab count ${filtered.length}`);
2876
2884
  }
2877
2885
  const tabs = [];
2878
- for (const page of filtered.slice(offset2)) {
2886
+ for (const page of filtered.slice(offset)) {
2879
2887
  const compact = {
2880
2888
  ref_id: page.targetId.slice(0, prefixLength),
2881
2889
  title: page.title.slice(0, 500),
@@ -2887,14 +2895,14 @@ ${page.url}`.toLowerCase().includes(normalized));
2887
2895
  }
2888
2896
  tabs.push(compact);
2889
2897
  }
2890
- const remaining = filtered.length - offset2 - tabs.length;
2898
+ const remaining = filtered.length - offset - tabs.length;
2891
2899
  return {
2892
- offset: offset2,
2900
+ offset,
2893
2901
  tabs,
2894
2902
  ...remaining > 0 ? {
2895
2903
  truncated: true,
2896
2904
  omitted_tabs: remaining,
2897
- next_offset: offset2 + tabs.length
2905
+ next_offset: offset + tabs.length
2898
2906
  } : {}
2899
2907
  };
2900
2908
  }
@@ -2910,11 +2918,11 @@ function boundSnapshot(page) {
2910
2918
  const content = [];
2911
2919
  const includedElements = [];
2912
2920
  const includedIds = new Set;
2913
- for (const line2 of page.content) {
2914
- const nextContent = [...content, line2];
2921
+ for (const line of page.content) {
2922
+ const nextContent = [...content, line];
2915
2923
  const nextElements = [...includedElements];
2916
- if (line2.element_id !== undefined && !includedIds.has(line2.element_id) && elements.has(line2.element_id)) {
2917
- const element = elements.get(line2.element_id);
2924
+ if (line.element_id !== undefined && !includedIds.has(line.element_id) && elements.has(line.element_id)) {
2925
+ const element = elements.get(line.element_id);
2918
2926
  if (element)
2919
2927
  nextElements.push(element);
2920
2928
  }
@@ -2925,10 +2933,10 @@ function boundSnapshot(page) {
2925
2933
  }) > OUTPUT_BUDGET_BYTES) {
2926
2934
  break;
2927
2935
  }
2928
- content.push(line2);
2929
- if (line2.element_id !== undefined && !includedIds.has(line2.element_id) && elements.has(line2.element_id)) {
2930
- includedIds.add(line2.element_id);
2931
- const element = elements.get(line2.element_id);
2936
+ content.push(line);
2937
+ if (line.element_id !== undefined && !includedIds.has(line.element_id) && elements.has(line.element_id)) {
2938
+ includedIds.add(line.element_id);
2939
+ const element = elements.get(line.element_id);
2932
2940
  if (element)
2933
2941
  includedElements.push(element);
2934
2942
  }
@@ -3193,13 +3201,13 @@ class BrowserOperationExecutor {
3193
3201
  async screenshot(operation, signal) {
3194
3202
  const file = await screenshotPath(operation);
3195
3203
  return this.cdp.withTab(operation.ref_id, signal, async (tab) => {
3196
- const capture2 = operation.id !== undefined ? await captureRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, file, signal) : operation.selector ? await captureSelector(tab.cdp, tab.sessionId, operation.selector, file, signal) : await captureViewport(tab.cdp, tab.sessionId, file, signal);
3204
+ const capture = operation.id !== undefined ? await captureRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, file, signal) : operation.selector ? await captureSelector(tab.cdp, tab.sessionId, operation.selector, file, signal) : await captureViewport(tab.cdp, tab.sessionId, file, signal);
3197
3205
  return {
3198
3206
  ref_id: tab.refId,
3199
3207
  ...operation.id === undefined ? {} : { id: operation.id },
3200
3208
  ...operation.selector ? { selector: operation.selector } : {},
3201
- file: capture2.file,
3202
- dpr: capture2.dpr,
3209
+ file: capture.file,
3210
+ dpr: capture.dpr,
3203
3211
  coordinates: "CSS pixels; screenshot pixels / DPR"
3204
3212
  };
3205
3213
  });
@@ -3499,8 +3507,8 @@ class BrowserRuntime {
3499
3507
  if (first) {
3500
3508
  options.onOperation?.(first, 0, request.operations.length);
3501
3509
  }
3502
- const result2 = await executeRemoteBrowser(route, request.operations, ownerId, options.signal);
3503
- return { host: request.host, ...result2 };
3510
+ const result = await executeRemoteBrowser(route, request.operations, ownerId, options.signal);
3511
+ return { host: request.host, ...result };
3504
3512
  }
3505
3513
  }
3506
3514
  const result = await this.executeLocal(request.operations, ownerId, options);
@@ -3756,11 +3764,11 @@ async function requestOnce(input, workerId, signal) {
3756
3764
  signal?.addEventListener("abort", abort, { once: true });
3757
3765
  socket.once("connect", () => socket.write(`${input}
3758
3766
  `));
3759
- readLine(socket).then((line2) => {
3767
+ readLine(socket).then((line) => {
3760
3768
  signal?.removeEventListener("abort", abort);
3761
3769
  socket.destroy();
3762
3770
  try {
3763
- const response = JSON.parse(line2);
3771
+ const response = JSON.parse(line);
3764
3772
  if (!isRecordValue(response) || typeof response["ok"] !== "boolean") {
3765
3773
  throw new Error("Browser worker returned an invalid response");
3766
3774
  }
@@ -16,6 +16,7 @@ function truncateUtf8(value, maxBytes) {
16
16
  return new StringDecoder("utf8").write(bytes.subarray(0, maxBytes));
17
17
  }
18
18
  function boundedElement(element) {
19
+ const { href, ...rest } = element;
19
20
  let value = element.value;
20
21
  if (typeof value === "string") {
21
22
  value = truncateUtf8(value, SNAPSHOT_ELEMENT_VALUE_BYTES);
@@ -28,7 +29,12 @@ function boundedElement(element) {
28
29
  }
29
30
  }
30
31
  return {
31
- ...element,
32
+ ...rest,
33
+ ...(href === undefined
34
+ ? {}
35
+ : Buffer.byteLength(href) > SNAPSHOT_URL_BYTES
36
+ ? { href_omitted: true }
37
+ : { href }),
32
38
  role: truncateUtf8(element.role, 128),
33
39
  ...(element.name === undefined
34
40
  ? {}
@@ -1,7 +1,7 @@
1
1
  export function browserHelp(hosts = []) {
2
2
  const routed = hosts.length > 0;
3
3
  return {
4
- input: "Code=JSON.stringify(request); normal=request",
4
+ input: "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
5
5
  ...(routed
6
6
  ? {
7
7
  host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`,
@@ -9,13 +9,13 @@ export function browserHelp(hosts = []) {
9
9
  : {}),
10
10
  refs: "tabs -> open; keep ref_id/id/cursors with their result",
11
11
  safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
12
- batch: "top-level nonempty action arrays; items omit action/host/response_length; independent only",
12
+ batch: "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
13
13
  actions: {
14
14
  tabs: "query? offset? owned_only? -> ref_id title url owned",
15
- open: "ref_id lineno? response_length? | url; new tabs open in background",
15
+ open: "ref_id lineno? | url; new tabs open in background",
16
16
  show: "ref_id; bring tab to foreground",
17
17
  close: "ref_id",
18
- find: "ref_id pattern lineno? response_length?",
18
+ find: "ref_id pattern lineno?",
19
19
  click: "ref_id id|selector|x+y",
20
20
  type: "ref_id text id?; id focuses",
21
21
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
@@ -1,58 +1,8 @@
1
- import { BROWSER_ACTIONS } from "./browser/operation.js";
1
+ import { Type } from "typebox";
2
2
  import { BrowserRuntime } from "./browser/runtime.js";
3
- interface BrowserToolParams {
4
- action: (typeof BROWSER_ACTIONS)[number];
5
- }
6
- export declare function prepareBrowserCodeModeInput(input: unknown): BrowserToolParams;
7
- export declare function createBrowserTool(runtime: BrowserRuntime): import("@earendil-works/pi-coding-agent").ToolDefinition<import("typebox").TUnion<[import("typebox").TObject<{
8
- [x: string]: import("typebox").TSchema;
9
- }>, import("typebox").TObject<{
10
- [x: string]: import("typebox").TSchema;
11
- }>, import("typebox").TObject<{
12
- [x: string]: import("typebox").TSchema;
13
- }>, import("typebox").TObject<{
14
- [x: string]: import("typebox").TSchema;
15
- }>, import("typebox").TObject<{
16
- [x: string]: import("typebox").TSchema;
17
- }>, import("typebox").TObject<{
18
- [x: string]: import("typebox").TSchema;
19
- }>, import("typebox").TObject<{
20
- [x: string]: import("typebox").TSchema;
21
- }>, import("typebox").TObject<{
22
- [x: string]: import("typebox").TSchema;
23
- }>, import("typebox").TObject<{
24
- [x: string]: import("typebox").TSchema;
25
- }>, import("typebox").TObject<{
26
- [x: string]: import("typebox").TSchema;
27
- }>, import("typebox").TObject<{
28
- [x: string]: import("typebox").TSchema;
29
- }>, import("typebox").TObject<{
30
- [x: string]: import("typebox").TSchema;
31
- }>, import("typebox").TObject<{
32
- [x: string]: import("typebox").TSchema;
33
- }>, ...import("typebox").TObject<{
34
- [x: string]: import("typebox").TSchema;
35
- }>[], import("typebox").TObject<{
36
- [x: string]: import("typebox").TSchema;
37
- }>, import("typebox").TObject<{
38
- [x: string]: import("typebox").TSchema;
39
- }>, import("typebox").TObject<{
40
- [x: string]: import("typebox").TSchema;
41
- }>, import("typebox").TObject<{
42
- [x: string]: import("typebox").TSchema;
43
- }>, import("typebox").TObject<{
44
- [x: string]: import("typebox").TSchema;
45
- }>, import("typebox").TObject<{
46
- [x: string]: import("typebox").TSchema;
47
- }>, import("typebox").TObject<{
48
- [x: string]: import("typebox").TSchema;
49
- }>, import("typebox").TObject<{
50
- [x: string]: import("typebox").TSchema;
51
- }>, import("typebox").TObject<{
52
- [x: string]: import("typebox").TSchema;
53
- }>, import("typebox").TObject<{
54
- [x: string]: import("typebox").TSchema;
55
- }>, import("typebox").TObject<{
56
- [x: string]: import("typebox").TSchema;
57
- }>]>, unknown, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
58
- export {};
3
+ export declare function prepareBrowserInput(input: unknown): {
4
+ command: string;
5
+ };
6
+ export declare function createBrowserTool(runtime: BrowserRuntime): import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
7
+ command: Type.TString;
8
+ }>, unknown, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
@@ -1,37 +1,32 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
- import { BROWSER_ACTIONS } from "./browser/operation.js";
2
+ import { Type } from "typebox";
3
+ import { isRecordValue } from "./browser/parse-operation.js";
3
4
  import { parseBrowserRequest } from "./browser/request.js";
4
5
  import { BrowserRuntime } from "./browser/runtime.js";
5
- import { browserParameters } from "./browser-parameters.js";
6
- const preparedBrowserRequest = Symbol("preparedBrowserRequest");
7
- export function prepareBrowserCodeModeInput(input) {
8
- // Freeform requests can batch operations that the normal Pi schema does not
9
- // expose. Carry the parsed request beside a schema-valid adapter input.
10
- const prepared = { action: "help" };
11
- Object.defineProperty(prepared, preparedBrowserRequest, {
12
- value: parseBrowserRequest(input),
13
- });
14
- return prepared;
15
- }
16
- function isPreparedBrowserInput(input) {
17
- return (typeof input === "object" &&
18
- input !== null &&
19
- preparedBrowserRequest in input);
20
- }
21
- function browserRequest(input) {
22
- return isPreparedBrowserInput(input)
23
- ? input[preparedBrowserRequest]
24
- : parseBrowserRequest(input);
6
+ export function prepareBrowserInput(input) {
7
+ if (typeof input === "string")
8
+ return { command: input };
9
+ if (!isRecordValue(input)) {
10
+ throw new Error("browser input must be a command envelope or JSON request");
11
+ }
12
+ if (Object.hasOwn(input, "command")) {
13
+ if (typeof input["command"] !== "string") {
14
+ throw new Error('browser command must be "help" or a JSON request string');
15
+ }
16
+ return { ...input, command: input["command"] };
17
+ }
18
+ // Resume old object calls without changing their stored history representation.
19
+ return { command: JSON.stringify(input) };
25
20
  }
26
21
  export function createBrowserTool(runtime) {
27
- const parameters = browserParameters(runtime.hosts);
28
22
  return defineTool({
29
23
  name: "browser",
30
24
  label: "Browser",
31
25
  description: "Control logged-in browser; call help before other actions",
32
- parameters,
26
+ parameters: Type.Object({ command: Type.String({ description: "help or JSON request" }) }, { additionalProperties: false }),
27
+ prepareArguments: prepareBrowserInput,
33
28
  async execute(_toolCallId, input, signal, onUpdate, ctx) {
34
- const result = await runtime.execute(browserRequest(input), {
29
+ const result = await runtime.execute(parseBrowserRequest(input.command), {
35
30
  ownerId: ctx.sessionManager.getSessionId(),
36
31
  signal: signal ?? new AbortController().signal,
37
32
  onOperation(operation, index, total) {
@@ -42,6 +42,10 @@ export async function backendCenter(cdp, sessionId, backendNodeId, scroll = true
42
42
  const response = await withBackendObject(cdp, sessionId, backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
43
43
  objectId,
44
44
  functionDeclaration: `function() {
45
+ const view = this.ownerDocument.defaultView;
46
+ if (view && (view.innerWidth <= 0 || view.innerHeight <= 0)) {
47
+ return { ok: false, error: 'Browser viewport is ' + view.innerWidth + 'x' + view.innerHeight + '; restore or resize its window, then retry' };
48
+ }
45
49
  const rect = this.getBoundingClientRect();
46
50
  const style = getComputedStyle(this);
47
51
  const disabled = this.matches(':disabled') ||
@@ -9,6 +9,8 @@ export interface SnapshotElement {
9
9
  id: number;
10
10
  role: string;
11
11
  name?: string | undefined;
12
+ href?: string | undefined;
13
+ href_omitted?: true | undefined;
12
14
  value?: unknown;
13
15
  checked?: boolean | "mixed" | undefined;
14
16
  selected?: boolean | undefined;
@@ -205,10 +205,15 @@ export async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
205
205
  renderedName = name;
206
206
  }
207
207
  else {
208
+ const href = role === "link"
209
+ ? node.properties?.find((property) => property.name === "url")
210
+ ?.value?.value
211
+ : undefined;
208
212
  const element = {
209
213
  id: nextElementId(),
210
214
  role,
211
215
  ...(name ? { name } : {}),
216
+ ...(typeof href === "string" && href ? { href } : {}),
212
217
  ...(value === "" || value == null ? {} : { value }),
213
218
  ...state,
214
219
  };
package/index.ts CHANGED
@@ -2,10 +2,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { BrowserRoutes, loadBrowserRoutes } from "./src/browser/routes.js";
3
3
  import { BrowserRuntime } from "./src/browser/runtime.js";
4
4
  import { registerBrowserCommand } from "./src/browser/settings.js";
5
- import {
6
- createBrowserTool,
7
- prepareBrowserCodeModeInput,
8
- } from "./src/browser-tool.js";
5
+ import { createBrowserTool, prepareBrowserInput } from "./src/browser-tool.js";
9
6
 
10
7
  export { createBrowserTool } from "./src/browser-tool.js";
11
8
 
@@ -49,7 +46,7 @@ async function registerBrowserInCodeMode(
49
46
  return registerCodeModeExtensionTools(pi, () => [
50
47
  adaptToolForCodeMode(tool, {
51
48
  kind: "freeform",
52
- prepareInput: prepareBrowserCodeModeInput,
49
+ prepareInput: prepareBrowserInput,
53
50
  usage:
54
51
  'await tools.browser("help") // Logged-in browser; help before other actions',
55
52
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-browser",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "description": "Logged-in browser inspection and control for Pi, Code Mode and Notebook Mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -46,11 +46,11 @@
46
46
  "pack:dry": "npm pack --dry-run"
47
47
  },
48
48
  "peerDependencies": {
49
- "@howaboua/pi-codex-conversion": ">=3.0.35",
50
- "@earendil-works/pi-ai": ">=0.84.3",
51
- "@earendil-works/pi-coding-agent": ">=0.84.3",
49
+ "@howaboua/pi-codex-conversion": ">=3.0.43",
50
+ "@earendil-works/pi-ai": ">=1.0.0",
51
+ "@earendil-works/pi-coding-agent": ">=1.0.0",
52
52
  "typebox": "*",
53
- "@earendil-works/pi-tui": "*"
53
+ "@earendil-works/pi-tui": ">=1.0.0"
54
54
  },
55
55
  "peerDependenciesMeta": {
56
56
  "@howaboua/pi-codex-conversion": {
@@ -58,10 +58,10 @@
58
58
  }
59
59
  },
60
60
  "devDependencies": {
61
- "@howaboua/pi-codex-conversion": "3.0.35",
61
+ "@howaboua/pi-codex-conversion": "3.0.43",
62
62
  "@biomejs/biome": "^2.5.10",
63
- "@earendil-works/pi-ai": "0.86.1",
64
- "@earendil-works/pi-coding-agent": "0.86.1",
63
+ "@earendil-works/pi-ai": "1.0.0",
64
+ "@earendil-works/pi-coding-agent": "1.0.0",
65
65
  "@types/node": "^26.2.0",
66
66
  "tsx": "^4.23.12",
67
67
  "typebox": "1.3.18",
@@ -24,6 +24,7 @@ function truncateUtf8(value: string, maxBytes: number): string {
24
24
  }
25
25
 
26
26
  function boundedElement(element: SnapshotElement): SnapshotElement {
27
+ const { href, ...rest } = element;
27
28
  let value = element.value;
28
29
  if (typeof value === "string") {
29
30
  value = truncateUtf8(value, SNAPSHOT_ELEMENT_VALUE_BYTES);
@@ -37,7 +38,12 @@ function boundedElement(element: SnapshotElement): SnapshotElement {
37
38
  }
38
39
  }
39
40
  return {
40
- ...element,
41
+ ...rest,
42
+ ...(href === undefined
43
+ ? {}
44
+ : Buffer.byteLength(href) > SNAPSHOT_URL_BYTES
45
+ ? { href_omitted: true as const }
46
+ : { href }),
41
47
  role: truncateUtf8(element.role, 128),
42
48
  ...(element.name === undefined
43
49
  ? {}
@@ -3,7 +3,8 @@ export function browserHelp(
3
3
  ): Record<string, unknown> {
4
4
  const routed = hosts.length > 0;
5
5
  return {
6
- input: "Code=JSON.stringify(request); normal=request",
6
+ input:
7
+ "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
7
8
  ...(routed
8
9
  ? {
9
10
  host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`,
@@ -13,13 +14,13 @@ export function browserHelp(
13
14
  safety:
14
15
  "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
15
16
  batch:
16
- "top-level nonempty action arrays; items omit action/host/response_length; independent only",
17
+ "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
17
18
  actions: {
18
19
  tabs: "query? offset? owned_only? -> ref_id title url owned",
19
- open: "ref_id lineno? response_length? | url; new tabs open in background",
20
+ open: "ref_id lineno? | url; new tabs open in background",
20
21
  show: "ref_id; bring tab to foreground",
21
22
  close: "ref_id",
22
- find: "ref_id pattern lineno? response_length?",
23
+ find: "ref_id pattern lineno?",
23
24
  click: "ref_id id|selector|x+y",
24
25
  type: "ref_id text id?; id focuses",
25
26
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
@@ -1,52 +1,38 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
- import { BROWSER_ACTIONS } from "./browser/operation.js";
3
- import { type BrowserRequest, parseBrowserRequest } from "./browser/request.js";
2
+ import { Type } from "typebox";
3
+ import { isRecordValue } from "./browser/parse-operation.js";
4
+ import { parseBrowserRequest } from "./browser/request.js";
4
5
  import { BrowserRuntime } from "./browser/runtime.js";
5
- import { browserParameters } from "./browser-parameters.js";
6
6
 
7
- interface BrowserToolParams {
8
- action: (typeof BROWSER_ACTIONS)[number];
9
- }
10
-
11
- const preparedBrowserRequest = Symbol("preparedBrowserRequest");
12
-
13
- interface PreparedBrowserInput {
14
- [preparedBrowserRequest]: BrowserRequest;
15
- }
16
-
17
- export function prepareBrowserCodeModeInput(input: unknown): BrowserToolParams {
18
- // Freeform requests can batch operations that the normal Pi schema does not
19
- // expose. Carry the parsed request beside a schema-valid adapter input.
20
- const prepared: BrowserToolParams = { action: "help" };
21
- Object.defineProperty(prepared, preparedBrowserRequest, {
22
- value: parseBrowserRequest(input),
23
- });
24
- return prepared;
25
- }
26
-
27
- function isPreparedBrowserInput(input: unknown): input is PreparedBrowserInput {
28
- return (
29
- typeof input === "object" &&
30
- input !== null &&
31
- preparedBrowserRequest in input
32
- );
33
- }
34
-
35
- function browserRequest(input: unknown): BrowserRequest {
36
- return isPreparedBrowserInput(input)
37
- ? input[preparedBrowserRequest]
38
- : parseBrowserRequest(input);
7
+ export function prepareBrowserInput(input: unknown): { command: string } {
8
+ if (typeof input === "string") return { command: input };
9
+ if (!isRecordValue(input)) {
10
+ throw new Error("browser input must be a command envelope or JSON request");
11
+ }
12
+ if (Object.hasOwn(input, "command")) {
13
+ if (typeof input["command"] !== "string") {
14
+ throw new Error(
15
+ 'browser command must be "help" or a JSON request string',
16
+ );
17
+ }
18
+ return { ...input, command: input["command"] };
19
+ }
20
+ // Resume old object calls without changing their stored history representation.
21
+ return { command: JSON.stringify(input) };
39
22
  }
40
23
 
41
24
  export function createBrowserTool(runtime: BrowserRuntime) {
42
- const parameters = browserParameters(runtime.hosts);
43
25
  return defineTool({
44
26
  name: "browser",
45
27
  label: "Browser",
46
28
  description: "Control logged-in browser; call help before other actions",
47
- parameters,
29
+ parameters: Type.Object(
30
+ { command: Type.String({ description: "help or JSON request" }) },
31
+ { additionalProperties: false },
32
+ ),
33
+ prepareArguments: prepareBrowserInput,
48
34
  async execute(_toolCallId, input, signal, onUpdate, ctx) {
49
- const result = await runtime.execute(browserRequest(input), {
35
+ const result = await runtime.execute(parseBrowserRequest(input.command), {
50
36
  ownerId: ctx.sessionManager.getSessionId(),
51
37
  signal: signal ?? new AbortController().signal,
52
38
  onOperation(operation, index, total) {
@@ -117,6 +117,10 @@ export async function backendCenter(
117
117
  {
118
118
  objectId,
119
119
  functionDeclaration: `function() {
120
+ const view = this.ownerDocument.defaultView;
121
+ if (view && (view.innerWidth <= 0 || view.innerHeight <= 0)) {
122
+ return { ok: false, error: 'Browser viewport is ' + view.innerWidth + 'x' + view.innerHeight + '; restore or resize its window, then retry' };
123
+ }
120
124
  const rect = this.getBoundingClientRect();
121
125
  const style = getComputedStyle(this);
122
126
  const disabled = this.matches(':disabled') ||
@@ -16,6 +16,8 @@ export interface SnapshotElement {
16
16
  id: number;
17
17
  role: string;
18
18
  name?: string | undefined;
19
+ href?: string | undefined;
20
+ href_omitted?: true | undefined;
19
21
  value?: unknown;
20
22
  checked?: boolean | "mixed" | undefined;
21
23
  selected?: boolean | undefined;
@@ -275,10 +275,16 @@ export async function snapshotData(
275
275
  addLine(text, undefined, "interactive");
276
276
  renderedName = name;
277
277
  } else {
278
+ const href =
279
+ role === "link"
280
+ ? node.properties?.find((property) => property.name === "url")
281
+ ?.value?.value
282
+ : undefined;
278
283
  const element: SnapshotElement = {
279
284
  id: nextElementId(),
280
285
  role,
281
286
  ...(name ? { name } : {}),
287
+ ...(typeof href === "string" && href ? { href } : {}),
282
288
  ...(value === "" || value == null ? {} : { value }),
283
289
  ...state,
284
290
  };
@@ -1,52 +0,0 @@
1
- import { type TSchema, Type } from "typebox";
2
- export declare function browserParameters(hosts: readonly string[]): Type.TUnion<[Type.TObject<{
3
- [x: string]: TSchema;
4
- }>, Type.TObject<{
5
- [x: string]: TSchema;
6
- }>, Type.TObject<{
7
- [x: string]: TSchema;
8
- }>, Type.TObject<{
9
- [x: string]: TSchema;
10
- }>, Type.TObject<{
11
- [x: string]: TSchema;
12
- }>, Type.TObject<{
13
- [x: string]: TSchema;
14
- }>, Type.TObject<{
15
- [x: string]: TSchema;
16
- }>, Type.TObject<{
17
- [x: string]: TSchema;
18
- }>, Type.TObject<{
19
- [x: string]: TSchema;
20
- }>, Type.TObject<{
21
- [x: string]: TSchema;
22
- }>, Type.TObject<{
23
- [x: string]: TSchema;
24
- }>, Type.TObject<{
25
- [x: string]: TSchema;
26
- }>, Type.TObject<{
27
- [x: string]: TSchema;
28
- }>, ...Type.TObject<{
29
- [x: string]: TSchema;
30
- }>[], Type.TObject<{
31
- [x: string]: TSchema;
32
- }>, Type.TObject<{
33
- [x: string]: TSchema;
34
- }>, Type.TObject<{
35
- [x: string]: TSchema;
36
- }>, Type.TObject<{
37
- [x: string]: TSchema;
38
- }>, Type.TObject<{
39
- [x: string]: TSchema;
40
- }>, Type.TObject<{
41
- [x: string]: TSchema;
42
- }>, Type.TObject<{
43
- [x: string]: TSchema;
44
- }>, Type.TObject<{
45
- [x: string]: TSchema;
46
- }>, Type.TObject<{
47
- [x: string]: TSchema;
48
- }>, Type.TObject<{
49
- [x: string]: TSchema;
50
- }>, Type.TObject<{
51
- [x: string]: TSchema;
52
- }>]>;
@@ -1,145 +0,0 @@
1
- import { StringEnum } from "@earendil-works/pi-ai";
2
- import { Type } from "typebox";
3
- export function browserParameters(hosts) {
4
- const route = hosts.length > 0
5
- ? {
6
- host: Type.Optional(StringEnum(hosts, { description: "Configured browser host" })),
7
- }
8
- : {};
9
- const request = (properties) => Type.Object({ ...route, ...properties }, { additionalProperties: false });
10
- const refId = Type.String({
11
- minLength: 1,
12
- description: "Tab ref_id returned by tabs",
13
- });
14
- const elementId = Type.Integer({
15
- minimum: 1,
16
- description: "Element id returned by open or find",
17
- });
18
- const responseLength = StringEnum(["short", "medium", "long"]);
19
- const handle = Type.String({
20
- minLength: 1,
21
- description: "Continuation handle returned by browser",
22
- });
23
- const fillValue = Type.Union([Type.String(), Type.Boolean()], {
24
- description: "Replacement text/option; boolean for checkbox/radio",
25
- });
26
- const timeout = Type.Optional(Type.Integer({ minimum: 1, maximum: 60_000 }));
27
- return Type.Union([
28
- request({ action: StringEnum(["help", "start"]) }),
29
- request({
30
- action: Type.Literal("tabs"),
31
- query: Type.Optional(Type.String({ minLength: 1 })),
32
- offset: Type.Optional(Type.Integer({ minimum: 0 })),
33
- owned_only: Type.Optional(Type.Boolean()),
34
- }),
35
- request({
36
- action: Type.Literal("open"),
37
- ref_id: refId,
38
- lineno: Type.Optional(Type.Integer({ minimum: 1 })),
39
- response_length: Type.Optional(responseLength),
40
- }),
41
- request({
42
- action: Type.Literal("open"),
43
- url: Type.String({ minLength: 1 }),
44
- }),
45
- request({
46
- action: Type.Literal("find"),
47
- ref_id: refId,
48
- pattern: Type.String({ minLength: 1 }),
49
- lineno: Type.Optional(Type.Integer({ minimum: 1 })),
50
- response_length: Type.Optional(responseLength),
51
- }),
52
- request({
53
- action: StringEnum(["show", "close"]),
54
- ref_id: refId,
55
- }),
56
- request({ action: Type.Literal("click"), ref_id: refId, id: elementId }),
57
- request({
58
- action: Type.Literal("click"),
59
- ref_id: refId,
60
- selector: Type.String({ minLength: 1 }),
61
- }),
62
- request({
63
- action: Type.Literal("click"),
64
- ref_id: refId,
65
- x: Type.Number(),
66
- y: Type.Number(),
67
- }),
68
- request({
69
- action: Type.Literal("type"),
70
- ref_id: refId,
71
- id: Type.Optional(elementId),
72
- text: Type.String({ minLength: 1 }),
73
- }),
74
- request({
75
- action: Type.Literal("fill"),
76
- ref_id: refId,
77
- id: elementId,
78
- value: fillValue,
79
- }),
80
- request({
81
- action: Type.Literal("fill"),
82
- ref_id: refId,
83
- selector: Type.String({ minLength: 1 }),
84
- value: fillValue,
85
- }),
86
- request({
87
- action: Type.Literal("press"),
88
- ref_id: refId,
89
- key: Type.String({ minLength: 1 }),
90
- }),
91
- ...["selector", "text", "url_includes"].map((condition) => request({
92
- action: Type.Literal("wait"),
93
- ref_id: refId,
94
- [condition]: Type.String({ minLength: 1 }),
95
- timeout_ms: timeout,
96
- })),
97
- request({
98
- action: StringEnum(["screenshot", "html"]),
99
- ref_id: refId,
100
- }),
101
- request({
102
- action: StringEnum(["screenshot", "html"]),
103
- ref_id: refId,
104
- id: elementId,
105
- }),
106
- request({
107
- action: StringEnum(["screenshot", "html"]),
108
- ref_id: refId,
109
- selector: Type.String({ minLength: 1 }),
110
- }),
111
- request({
112
- action: Type.Literal("navigate"),
113
- ref_id: refId,
114
- url: Type.String({ minLength: 1 }),
115
- }),
116
- request({
117
- action: Type.Literal("evaluate"),
118
- ref_id: refId,
119
- expression: Type.String({ minLength: 1 }),
120
- }),
121
- request({ action: Type.Literal("network"), ref_id: refId }),
122
- request({
123
- action: Type.Literal("load_all"),
124
- ref_id: refId,
125
- selector: Type.String({ minLength: 1 }),
126
- interval_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 60_000 })),
127
- }),
128
- request({
129
- action: Type.Literal("raw"),
130
- ref_id: refId,
131
- method: Type.String({ minLength: 1 }),
132
- params: Type.Optional(Type.Object({}, { additionalProperties: true })),
133
- }),
134
- request({
135
- action: Type.Literal("read_result"),
136
- handle,
137
- offset: Type.Optional(Type.Integer({ minimum: 0 })),
138
- }),
139
- request({ action: Type.Literal("discard_result"), handle }),
140
- request({
141
- action: Type.Literal("stop"),
142
- ref_id: Type.Optional(refId),
143
- }),
144
- ]);
145
- }
@@ -1,152 +0,0 @@
1
- import { StringEnum } from "@earendil-works/pi-ai";
2
- import { type TSchema, Type } from "typebox";
3
-
4
- export function browserParameters(hosts: readonly string[]) {
5
- const route: Record<string, TSchema> =
6
- hosts.length > 0
7
- ? {
8
- host: Type.Optional(
9
- StringEnum(hosts, { description: "Configured browser host" }),
10
- ),
11
- }
12
- : {};
13
- const request = (properties: Record<string, TSchema>) =>
14
- Type.Object({ ...route, ...properties }, { additionalProperties: false });
15
- const refId = Type.String({
16
- minLength: 1,
17
- description: "Tab ref_id returned by tabs",
18
- });
19
- const elementId = Type.Integer({
20
- minimum: 1,
21
- description: "Element id returned by open or find",
22
- });
23
- const responseLength = StringEnum(["short", "medium", "long"] as const);
24
- const handle = Type.String({
25
- minLength: 1,
26
- description: "Continuation handle returned by browser",
27
- });
28
- const fillValue = Type.Union([Type.String(), Type.Boolean()], {
29
- description: "Replacement text/option; boolean for checkbox/radio",
30
- });
31
- const timeout = Type.Optional(Type.Integer({ minimum: 1, maximum: 60_000 }));
32
- return Type.Union([
33
- request({ action: StringEnum(["help", "start"] as const) }),
34
- request({
35
- action: Type.Literal("tabs"),
36
- query: Type.Optional(Type.String({ minLength: 1 })),
37
- offset: Type.Optional(Type.Integer({ minimum: 0 })),
38
- owned_only: Type.Optional(Type.Boolean()),
39
- }),
40
- request({
41
- action: Type.Literal("open"),
42
- ref_id: refId,
43
- lineno: Type.Optional(Type.Integer({ minimum: 1 })),
44
- response_length: Type.Optional(responseLength),
45
- }),
46
- request({
47
- action: Type.Literal("open"),
48
- url: Type.String({ minLength: 1 }),
49
- }),
50
- request({
51
- action: Type.Literal("find"),
52
- ref_id: refId,
53
- pattern: Type.String({ minLength: 1 }),
54
- lineno: Type.Optional(Type.Integer({ minimum: 1 })),
55
- response_length: Type.Optional(responseLength),
56
- }),
57
- request({
58
- action: StringEnum(["show", "close"] as const),
59
- ref_id: refId,
60
- }),
61
- request({ action: Type.Literal("click"), ref_id: refId, id: elementId }),
62
- request({
63
- action: Type.Literal("click"),
64
- ref_id: refId,
65
- selector: Type.String({ minLength: 1 }),
66
- }),
67
- request({
68
- action: Type.Literal("click"),
69
- ref_id: refId,
70
- x: Type.Number(),
71
- y: Type.Number(),
72
- }),
73
- request({
74
- action: Type.Literal("type"),
75
- ref_id: refId,
76
- id: Type.Optional(elementId),
77
- text: Type.String({ minLength: 1 }),
78
- }),
79
- request({
80
- action: Type.Literal("fill"),
81
- ref_id: refId,
82
- id: elementId,
83
- value: fillValue,
84
- }),
85
- request({
86
- action: Type.Literal("fill"),
87
- ref_id: refId,
88
- selector: Type.String({ minLength: 1 }),
89
- value: fillValue,
90
- }),
91
- request({
92
- action: Type.Literal("press"),
93
- ref_id: refId,
94
- key: Type.String({ minLength: 1 }),
95
- }),
96
- ...(["selector", "text", "url_includes"] as const).map((condition) =>
97
- request({
98
- action: Type.Literal("wait"),
99
- ref_id: refId,
100
- [condition]: Type.String({ minLength: 1 }),
101
- timeout_ms: timeout,
102
- }),
103
- ),
104
- request({
105
- action: StringEnum(["screenshot", "html"] as const),
106
- ref_id: refId,
107
- }),
108
- request({
109
- action: StringEnum(["screenshot", "html"] as const),
110
- ref_id: refId,
111
- id: elementId,
112
- }),
113
- request({
114
- action: StringEnum(["screenshot", "html"] as const),
115
- ref_id: refId,
116
- selector: Type.String({ minLength: 1 }),
117
- }),
118
- request({
119
- action: Type.Literal("navigate"),
120
- ref_id: refId,
121
- url: Type.String({ minLength: 1 }),
122
- }),
123
- request({
124
- action: Type.Literal("evaluate"),
125
- ref_id: refId,
126
- expression: Type.String({ minLength: 1 }),
127
- }),
128
- request({ action: Type.Literal("network"), ref_id: refId }),
129
- request({
130
- action: Type.Literal("load_all"),
131
- ref_id: refId,
132
- selector: Type.String({ minLength: 1 }),
133
- interval_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 60_000 })),
134
- }),
135
- request({
136
- action: Type.Literal("raw"),
137
- ref_id: refId,
138
- method: Type.String({ minLength: 1 }),
139
- params: Type.Optional(Type.Object({}, { additionalProperties: true })),
140
- }),
141
- request({
142
- action: Type.Literal("read_result"),
143
- handle,
144
- offset: Type.Optional(Type.Integer({ minimum: 0 })),
145
- }),
146
- request({ action: Type.Literal("discard_result"), handle }),
147
- request({
148
- action: Type.Literal("stop"),
149
- ref_id: Type.Optional(refId),
150
- }),
151
- ]);
152
- }