@capybara-hq/plugin-browser 0.0.0-stage → 0.1.0-rc.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 (63) hide show
  1. package/.capybara-plugin/plugin.json +100 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +2 -0
  4. package/README.md +77 -2
  5. package/dist/index.mjs +920 -0
  6. package/icon.svg +1 -0
  7. package/package.json +19 -4
  8. package/ui/panel.js +704 -0
  9. package/ui/service/daemon.mjs +2077 -0
  10. package/ui/service/vendor/playwright-core/LICENSE +202 -0
  11. package/ui/service/vendor/playwright-core/NOTICE +5 -0
  12. package/ui/service/vendor/playwright-core/README.md +3 -0
  13. package/ui/service/vendor/playwright-core/ThirdPartyNotices.txt +13 -0
  14. package/ui/service/vendor/playwright-core/browsers.json +52 -0
  15. package/ui/service/vendor/playwright-core/cli.js +22 -0
  16. package/ui/service/vendor/playwright-core/index.js +17 -0
  17. package/ui/service/vendor/playwright-core/index.mjs +28 -0
  18. package/ui/service/vendor/playwright-core/lib/bootstrap.js +149 -0
  19. package/ui/service/vendor/playwright-core/lib/coreBundle.js +78764 -0
  20. package/ui/service/vendor/playwright-core/lib/entry/cliDaemon.js +5 -0
  21. package/ui/service/vendor/playwright-core/lib/entry/dashboardApp.js +3 -0
  22. package/ui/service/vendor/playwright-core/lib/entry/mcp.js +10 -0
  23. package/ui/service/vendor/playwright-core/lib/entry/oopBrowserDownload.js +3 -0
  24. package/ui/service/vendor/playwright-core/lib/package.js +50 -0
  25. package/ui/service/vendor/playwright-core/lib/server/chromium/appIcon.png +0 -0
  26. package/ui/service/vendor/playwright-core/lib/server/electron/loader.js +130 -0
  27. package/ui/service/vendor/playwright-core/lib/serverRegistry.js +1939 -0
  28. package/ui/service/vendor/playwright-core/lib/serverRegistry.js.LICENSE +65 -0
  29. package/ui/service/vendor/playwright-core/lib/tools/cli-client/channelSessions.js +143 -0
  30. package/ui/service/vendor/playwright-core/lib/tools/cli-client/cli.js +7 -0
  31. package/ui/service/vendor/playwright-core/lib/tools/cli-client/help.json +813 -0
  32. package/ui/service/vendor/playwright-core/lib/tools/cli-client/minimist.js +128 -0
  33. package/ui/service/vendor/playwright-core/lib/tools/cli-client/output.js +352 -0
  34. package/ui/service/vendor/playwright-core/lib/tools/cli-client/program.js +422 -0
  35. package/ui/service/vendor/playwright-core/lib/tools/cli-client/registry.js +180 -0
  36. package/ui/service/vendor/playwright-core/lib/tools/cli-client/session.js +261 -0
  37. package/ui/service/vendor/playwright-core/lib/tools/dashboard/appIcon.png +0 -0
  38. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/SKILL.md +493 -0
  39. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
  40. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
  41. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/pr-attachments.md +60 -0
  42. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
  43. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/running-code.md +247 -0
  44. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/session-management.md +227 -0
  45. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/storage-state.md +278 -0
  46. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
  47. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/tracing.md +146 -0
  48. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/video-recording.md +216 -0
  49. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/SKILL.md +136 -0
  50. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
  51. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/migration.md +89 -0
  52. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/react.md +69 -0
  53. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/typing.md +173 -0
  54. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/vue.md +77 -0
  55. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-trace/SKILL.md +174 -0
  56. package/ui/service/vendor/playwright-core/lib/tools/utils/extension.js +112 -0
  57. package/ui/service/vendor/playwright-core/lib/tools/utils/socketConnection.js +108 -0
  58. package/ui/service/vendor/playwright-core/lib/utilsBundle.js +92408 -0
  59. package/ui/service/vendor/playwright-core/lib/utilsBundle.js.LICENSE +1917 -0
  60. package/ui/service/vendor/playwright-core/lib/webp_codec.LICENSE +173 -0
  61. package/ui/service/vendor/playwright-core/lib/webp_codec.wasm +0 -0
  62. package/ui/service/vendor/playwright-core/lib/xdg-open +1267 -0
  63. package/ui/service/vendor/playwright-core/package.json +34 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,920 @@
1
+ import { createRequire as __capybaraCreateRequire } from "node:module";
2
+ import { fileURLToPath as __capybaraFileURLToPath } from "node:url";
3
+ import { dirname as __capybaraPathDirname } from "node:path";
4
+ const require = __capybaraCreateRequire(import.meta.url);
5
+ const __capybara_filename = __capybaraFileURLToPath(import.meta.url);
6
+ const __capybara_dirname = __capybaraPathDirname(__capybara_filename);
7
+
8
+ // src/index.ts
9
+ import { defineExtension } from "@capybara-hq/plugin-sdk";
10
+
11
+ // src/handoff.ts
12
+ import {
13
+ ToolError as ToolError2
14
+ } from "@capybara-hq/plugin-sdk";
15
+
16
+ // daemon/protocol.ts
17
+ var VIEWPORT = { width: 1280, height: 800 };
18
+ var IDLE_STOP_MS = 15 * 6e4;
19
+ var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
20
+ var HANDOFF_MAX_CHARS = 4096;
21
+ var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
22
+ var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
23
+ var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
24
+
25
+ // src/browser.ts
26
+ import {
27
+ ToolError
28
+ } from "@capybara-hq/plugin-sdk";
29
+
30
+ // src/messages.ts
31
+ var NOT_OWNER_MESSAGE = "Browser tools only run for the conversation's owner on their own device.";
32
+ var TAKEN_OVER_MESSAGE = "The user is controlling the browser; call browser_wait or browser_handoff.";
33
+
34
+ // src/browser.ts
35
+ var START_FAILED_MESSAGE = "The browser could not start in the device; retry, and ask the user to check the device if it keeps failing.";
36
+ var SERVICE = "browser";
37
+ var REQUEST_TIMEOUT_MS = 9e4;
38
+ function assertOwner(call) {
39
+ if (call.ownerAccountId === void 0 || call.accountId !== call.ownerAccountId)
40
+ throw new ToolError(NOT_OWNER_MESSAGE);
41
+ }
42
+ function deviceAccessCode(e) {
43
+ if (!(e instanceof Error) || e.name !== "DeviceAccessError") return void 0;
44
+ const code = e.code;
45
+ return typeof code === "string" ? code : void 0;
46
+ }
47
+ function deviceAccessToolError(e) {
48
+ switch (deviceAccessCode(e)) {
49
+ case "no_device":
50
+ return new ToolError(
51
+ "This conversation has no device; ask the user to pick a device for the conversation first."
52
+ );
53
+ case "provider_unavailable":
54
+ return new ToolError(
55
+ "The conversation's device is unavailable (its provider is not loaded or not on in this org); ask the user to check the device."
56
+ );
57
+ case "capability_missing":
58
+ return new ToolError(
59
+ "The conversation's device cannot run the browser (its provider has no device services); ask the user to pick a device on a provider that supports them."
60
+ );
61
+ case "not_owner":
62
+ return new ToolError(NOT_OWNER_MESSAGE);
63
+ case "service_not_declared":
64
+ return new ToolError(
65
+ "The browser plugin's manifest does not declare its device service; ask an admin to check the installed browser plugin version."
66
+ );
67
+ default:
68
+ return e;
69
+ }
70
+ }
71
+ function daemonToolError(code, message) {
72
+ switch (code) {
73
+ case "taken_over":
74
+ return new ToolError(TAKEN_OVER_MESSAGE);
75
+ case "no_such_ref":
76
+ return new ToolError(`${message} Call browser_snapshot for the current element refs.`);
77
+ case "timeout":
78
+ return new ToolError(
79
+ `${message} Check the page with browser_snapshot, then retry or call browser_wait.`
80
+ );
81
+ case "blocked":
82
+ if (message.startsWith(DOWNLOAD_BLOCKED_PREFIX))
83
+ return new ToolError(
84
+ `${message} Ask the user to allow these hosts so the browser can be installed, then retry.`
85
+ );
86
+ return new ToolError(
87
+ `${message} The user is asked to allow the host; if they decline, use another site.`
88
+ );
89
+ default:
90
+ return new ToolError(`${message} Check the page with browser_snapshot before retrying.`);
91
+ }
92
+ }
93
+ function parseReply(bytes) {
94
+ let reply;
95
+ try {
96
+ reply = JSON.parse(new TextDecoder().decode(bytes));
97
+ } catch {
98
+ reply = void 0;
99
+ }
100
+ const r = reply;
101
+ if (typeof r !== "object" || r === null || typeof r.ok !== "boolean")
102
+ throw new ToolError(
103
+ "The browser service answered something unreadable; retry, and ask the user to check the device if it keeps failing."
104
+ );
105
+ return r;
106
+ }
107
+ function failure(deps, call, e, starting) {
108
+ const mapped = deviceAccessToolError(e);
109
+ if (mapped !== e) return mapped;
110
+ if (e instanceof ToolError || e instanceof Error && e.name === "ToolError") return e;
111
+ if (call.signal.aborted) return e;
112
+ deps.log?.warn(starting ? "browser service start failed" : "browser service call failed", {
113
+ err: e
114
+ });
115
+ if (starting) return new ToolError(START_FAILED_MESSAGE);
116
+ return new ToolError(
117
+ "The browser service in the device failed; retry, and ask the user to check the device if it keeps failing."
118
+ );
119
+ }
120
+ async function runRequest(deps, call, req, timeoutMs = REQUEST_TIMEOUT_MS) {
121
+ assertOwner(call);
122
+ let reply;
123
+ try {
124
+ await deps.deviceAccess.ensureService(call, await deps.serviceSpec());
125
+ } catch (e) {
126
+ throw failure(deps, call, e, true);
127
+ }
128
+ try {
129
+ const body = new TextEncoder().encode(JSON.stringify(req));
130
+ reply = parseReply(
131
+ await deps.deviceAccess.request(call, { service: SERVICE, body, timeoutMs })
132
+ );
133
+ } catch (e) {
134
+ throw failure(deps, call, e, false);
135
+ }
136
+ const hosts = Array.isArray(reply.blockedHosts) ? reply.blockedHosts.filter((h) => typeof h === "string" && h !== "") : [];
137
+ if (hosts.length > 0)
138
+ deps.deviceAccess.reportBlockedHosts(call, hosts, reply.ok ? { url: reply.page.url } : {});
139
+ if (!reply.ok) throw daemonToolError(reply.error, reply.message);
140
+ return reply;
141
+ }
142
+ function pageLine(page) {
143
+ return `Page: ${page.title === "" ? "(no title)" : page.title} - ${page.url} (tab ${page.tabId})`;
144
+ }
145
+ function toResult(reply) {
146
+ const lines = [];
147
+ if (reply.userControlledSince !== void 0)
148
+ lines.push(
149
+ `The user controlled the browser from ${reply.userControlledSince}; now at ${reply.page.url} (${reply.page.title}).`
150
+ );
151
+ lines.push(pageLine(reply.page));
152
+ if (reply.text !== void 0 && reply.text !== "") lines.push(reply.text);
153
+ return {
154
+ content: [
155
+ { type: "text", text: lines.join("\n") },
156
+ ...reply.image === void 0 ? [] : [{ type: "image", mimeType: "image/jpeg", data: reply.image }]
157
+ ]
158
+ };
159
+ }
160
+
161
+ // src/i18n.ts
162
+ var HANDOFF_FORM = {
163
+ label: { zh: "完成", en: "Done" },
164
+ description: {
165
+ zh: "完成后打开开关并提交,浏览器交还智能体;关闭开关提交或关闭此问题即为取消。",
166
+ en: "Turn on and submit when you are done to hand the browser back; submit with it off, or dismiss the question, to cancel."
167
+ }
168
+ };
169
+
170
+ // src/handoff.ts
171
+ var MESSAGE_MAX = Math.min(2e3, HANDOFF_MAX_CHARS);
172
+ var HANDOFF = {
173
+ name: "browser_handoff",
174
+ title: "Hand the browser to the user",
175
+ description: "Ask the user to do something in the browser themselves, such as signing in, entering a one-time code or solving a CAPTCHA, and wait until they hand it back. The message tells them what to do; they answer Done or Cancel. Returns the page state afterwards. Use it when a step needs the user's credentials or judgment; never ask for passwords in the chat.",
176
+ inputSchema: {
177
+ type: "object",
178
+ properties: {
179
+ message: {
180
+ type: "string",
181
+ maxLength: MESSAGE_MAX,
182
+ description: 'What the user should do, e.g. "Please sign in to your GitHub account."'
183
+ }
184
+ },
185
+ required: ["message"],
186
+ additionalProperties: false
187
+ },
188
+ keyArgs: ["message"],
189
+ defaultPolicy: "allow"
190
+ };
191
+ function handoffHandler(deps) {
192
+ return async (input, call) => {
193
+ const raw = input?.message;
194
+ if (typeof raw !== "string" || raw.trim() === "")
195
+ throw new ToolError2("browser_handoff needs a message for the user; pass one and retry.");
196
+ const message = raw.slice(0, MESSAGE_MAX);
197
+ if (call.resume === void 0) {
198
+ await runRequest(deps, call, { op: "handoff_notice", callId: call.callId, message });
199
+ const asked = {
200
+ kind: "input_required",
201
+ form: {
202
+ title: message,
203
+ fields: [
204
+ {
205
+ key: "done",
206
+ label: HANDOFF_FORM.label,
207
+ description: HANDOFF_FORM.description,
208
+ schema: { type: "boolean" },
209
+ required: true
210
+ }
211
+ ]
212
+ },
213
+ state: { handoff: 1 }
214
+ };
215
+ return asked;
216
+ }
217
+ assertOwner(call);
218
+ const answer = call.resume.answer;
219
+ const done = answer !== null && answer.done === true;
220
+ await runRequest(deps, call, {
221
+ op: "handoff_clear",
222
+ callId: call.callId,
223
+ ...done ? { handback: true } : {}
224
+ }).catch((e) => {
225
+ if (!(e instanceof ToolError2)) throw e;
226
+ });
227
+ if (!done)
228
+ throw new ToolError2(
229
+ "The user cancelled the handoff; ask the user how to continue, or try another approach."
230
+ );
231
+ return toResult(await runRequest(deps, call, { op: "snapshot" }));
232
+ };
233
+ }
234
+ function registerHandoffTool(ctx, deps) {
235
+ ctx.tools.register(HANDOFF, handoffHandler(deps));
236
+ }
237
+
238
+ // ui-src/panel/page.ts
239
+ var PANEL_HTML = `<!doctype html>
240
+ <html lang="en">
241
+ <head>
242
+ <meta charset="utf-8">
243
+ <meta name="viewport" content="width=device-width, initial-scale=1">
244
+ <title>Browser</title>
245
+ <style>
246
+ :root { color-scheme: dark light; }
247
+ * { box-sizing: border-box; }
248
+ html, body { height: 100%; }
249
+ body {
250
+ margin: 0; display: flex; flex-direction: column; overflow: hidden;
251
+ background: var(--cb-bg, Canvas); color: var(--cb-ink, CanvasText);
252
+ font: 12px/1.4 var(--cb-font, ui-monospace, monospace);
253
+ }
254
+ [hidden] { display: none !important; }
255
+ button, input {
256
+ font: inherit; color: inherit; background: transparent;
257
+ border: 1px solid var(--cb-line-strong, GrayText); padding: 2px 8px; min-height: 26px;
258
+ }
259
+ button:hover:not(:disabled) { background: var(--cb-hover, transparent); }
260
+ button:disabled { opacity: .5; }
261
+ button.primary { background: var(--cb-accent, Highlight); color: var(--cb-on-accent, HighlightText); border-color: transparent; }
262
+ #tabs { display: flex; gap: 2px; overflow-x: auto; padding: 4px 4px 0; border-bottom: 1px solid var(--cb-line, GrayText); }
263
+ .tab { display: flex; align-items: center; max-width: 160px; border: 1px solid var(--cb-line, GrayText); border-bottom: 0; padding: 0 4px 0 8px; gap: 4px; min-height: 26px; }
264
+ .tab[data-active="true"] { background: var(--cb-panel, Canvas); font-weight: 600; }
265
+ .tab button { border: 0; padding: 0 4px; min-height: 22px; }
266
+ .tab .label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; text-align: left; padding: 0; }
267
+ #bar { display: flex; gap: 4px; padding: 4px; align-items: center; }
268
+ #url { flex: 1; min-width: 0; }
269
+ #lock { display: inline-flex; color: var(--cb-muted, GrayText); }
270
+ #status { color: var(--cb-muted, GrayText); padding: 0 8px 4px; min-height: 18px; }
271
+ #status[data-control="user"] { color: var(--cb-accent, Highlight); }
272
+ #stage { flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; background: var(--cb-panel, Canvas); position: relative; overflow: hidden; }
273
+ #view { background: #fff; outline: none; display: block; }
274
+ #view:focus-visible { outline: 2px solid var(--cb-accent, Highlight); }
275
+ #flash { position: absolute; width: 24px; height: 24px; margin: -12px 0 0 -12px; border: 2px solid var(--cb-accent, Highlight); border-radius: 50%; pointer-events: none; }
276
+ .strip { display: flex; gap: 8px; align-items: center; padding: 4px 8px; border-top: 1px solid var(--cb-line, GrayText); background: var(--cb-panel, Canvas); }
277
+ .strip span { flex: 1; min-width: 0; overflow-wrap: anywhere; }
278
+ .center { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 6px; align-items: center; justify-content: center; text-align: center; padding: 16px; background: var(--cb-bg, Canvas); }
279
+ .center h2 { margin: 0; font-size: 13px; }
280
+ .center p { margin: 0; color: var(--cb-muted, GrayText); }
281
+ </style>
282
+ </head>
283
+ <body>
284
+ <div id="tabs" role="tablist"></div>
285
+ <div id="bar">
286
+ <button type="button" id="back"></button>
287
+ <button type="button" id="forward"></button>
288
+ <button type="button" id="reload"></button>
289
+ <span id="lock" role="img" hidden><svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true"><rect x="2" y="5" width="8" height="6" fill="currentColor"/><path d="M4 5V3.5a2 2 0 0 1 4 0V5" fill="none" stroke="currentColor" stroke-width="1.2"/></svg></span>
290
+ <input id="url" type="text" spellcheck="false" autocomplete="off">
291
+ <button type="button" id="takeover" class="primary"></button>
292
+ <button type="button" id="handback" class="primary" hidden></button>
293
+ </div>
294
+ <div id="handoff" class="strip" hidden><p><span id="handoff-label"></span> <span id="handoff-message"></span></p><button type="button" id="handoff-done" class="primary"></button><button type="button" id="handoff-cancel"></button></div>
295
+ <p id="status" role="status"></p>
296
+ <div id="stage">
297
+ <canvas id="view" tabindex="0"></canvas>
298
+ <div id="flash" hidden></div>
299
+ <div id="empty" class="center" hidden>
300
+ <h2 id="empty-title"></h2>
301
+ <p id="empty-body"></p>
302
+ <button type="button" id="reconnect"></button>
303
+ </div>
304
+ </div>
305
+ <div id="blocked" class="strip" hidden><p><span id="blocked-label"></span> <span id="blocked-host"></span></p><button type="button" id="allow" class="primary"></button></div>
306
+ <div id="dialog" class="strip" hidden><p><span id="dialog-label"></span> <span id="dialog-text"></span></p></div>
307
+ <div id="notice" class="strip" role="alert" hidden><p><span id="notice-text"></span></p></div>
308
+ <script src="panel.js"></script>
309
+ </body>
310
+ </html>
311
+ `;
312
+
313
+ // src/routes.ts
314
+ var MAX_HOSTS = 20;
315
+ var HOST_RE = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
316
+ var CALL_ID_MAX = 200;
317
+ var STATIC_HEADERS = {
318
+ "x-content-type-options": "nosniff",
319
+ "content-security-policy": "sandbox allow-scripts allow-forms; frame-ancestors 'self'",
320
+ "cache-control": "no-cache"
321
+ };
322
+ var json = (status, body) => Response.json(body, { status });
323
+ var error = (status, code, message) => json(status, { error: { code, message } });
324
+ function scopeOf(caller) {
325
+ if (caller.access !== "embed" || caller.scope !== "org") return null;
326
+ if (caller.conversationId === void 0 || caller.conversationId === "") return null;
327
+ return {
328
+ orgId: caller.orgId,
329
+ accountId: caller.accountId,
330
+ conversationId: caller.conversationId
331
+ };
332
+ }
333
+ function statusOf(code) {
334
+ if (code === "not_owner") return 403;
335
+ if (code === "question.not_found") return 404;
336
+ if (code === "service_not_declared") return 500;
337
+ return 409;
338
+ }
339
+ var isRefusalName = (name) => name === "DeviceAccessError" || name === "ApiError";
340
+ function refusal(e) {
341
+ const code = e?.code;
342
+ if (!(e instanceof Error) || !isRefusalName(e.name) || typeof code !== "string") throw e;
343
+ return error(statusOf(code), code, e.message);
344
+ }
345
+ async function readJson(req) {
346
+ try {
347
+ const v = await req.json();
348
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? v : void 0;
349
+ } catch {
350
+ return void 0;
351
+ }
352
+ }
353
+ function data(run) {
354
+ return async (req, caller) => {
355
+ const scope = scopeOf(caller);
356
+ if (scope === null)
357
+ return error(403, "forbidden", "The browser panel needs a conversation embed token");
358
+ try {
359
+ return await run(scope, req);
360
+ } catch (e) {
361
+ return refusal(e);
362
+ }
363
+ };
364
+ }
365
+ function registerRoutes(ctx, deps) {
366
+ ctx.http.route("GET", "/ui/browser", async () => {
367
+ return new Response(PANEL_HTML, {
368
+ headers: { "content-type": "text/html; charset=utf-8", ...STATIC_HEADERS }
369
+ });
370
+ });
371
+ ctx.http.route("GET", "/ui/panel.js", async () => {
372
+ const js = await deps.panelScript();
373
+ if (js === void 0) return error(404, "not_found", "The panel script is not built");
374
+ return new Response(js, {
375
+ headers: { "content-type": "text/javascript; charset=utf-8", ...STATIC_HEADERS }
376
+ });
377
+ });
378
+ ctx.http.route(
379
+ "POST",
380
+ "/ui/stream-ticket",
381
+ data(async (scope) => {
382
+ const { url } = await deps.deviceAccess.streamTicket({ ...scope, service: SERVICE });
383
+ return json(200, { url });
384
+ })
385
+ );
386
+ ctx.http.route(
387
+ "POST",
388
+ "/ui/network-hosts",
389
+ data(async (scope, req) => {
390
+ const body = await readJson(req);
391
+ const hosts = body?.hosts;
392
+ if (!Array.isArray(hosts) || hosts.length === 0 || hosts.length > MAX_HOSTS || !hosts.every((h) => typeof h === "string" && HOST_RE.test(h)))
393
+ return error(400, "invalid_body", `hosts must list 1 to ${MAX_HOSTS} host names`);
394
+ await deps.deviceAccess.addNetworkHosts({ ...scope, hosts });
395
+ return json(200, { ok: true });
396
+ })
397
+ );
398
+ ctx.http.route(
399
+ "POST",
400
+ "/ui/handoff-answer",
401
+ data(async (scope, req) => {
402
+ const body = await readJson(req);
403
+ const callId = body?.callId;
404
+ const done = body?.done;
405
+ if (typeof callId !== "string" || callId === "" || callId.length > CALL_ID_MAX || typeof done !== "boolean")
406
+ return error(400, "invalid_body", "the body must be { callId: string, done: boolean }");
407
+ await deps.deviceAccess.answerHandoff({ ...scope, callId, done });
408
+ return json(200, { ok: true });
409
+ })
410
+ );
411
+ }
412
+
413
+ // src/service.ts
414
+ import { readdir, readFile } from "node:fs/promises";
415
+ import { relative, sep } from "node:path";
416
+ import { fileURLToPath } from "node:url";
417
+ var SERVICE_ENTRY = "daemon.mjs";
418
+ async function readServiceFiles(dir) {
419
+ const root = fileURLToPath(dir);
420
+ const files = {};
421
+ const entries = await readdir(root, { recursive: true, withFileTypes: true });
422
+ for (const e of entries) {
423
+ if (!e.isFile()) continue;
424
+ const abs = `${e.parentPath}${sep}${e.name}`;
425
+ files[relative(root, abs).split(sep).join("/")] = new Uint8Array(await readFile(abs));
426
+ }
427
+ return files;
428
+ }
429
+ function serviceSpecLoader(dir = new URL("../ui/service/", import.meta.url)) {
430
+ let loading;
431
+ return () => {
432
+ loading ??= (async () => {
433
+ const files = await readServiceFiles(dir);
434
+ if (!Object.hasOwn(files, SERVICE_ENTRY))
435
+ throw new Error(
436
+ `browser: ${SERVICE_ENTRY} is missing under ${fileURLToPath(dir)} (run build:ui)`
437
+ );
438
+ return { name: SERVICE, runtime: "node", entry: SERVICE_ENTRY, args: [], files };
439
+ })();
440
+ loading.catch(() => {
441
+ loading = void 0;
442
+ });
443
+ return loading;
444
+ };
445
+ }
446
+ function panelScriptLoader(file = new URL("../ui/panel.js", import.meta.url)) {
447
+ let cached;
448
+ return () => {
449
+ cached ??= readFile(file, "utf8").catch(() => {
450
+ cached = void 0;
451
+ return void 0;
452
+ });
453
+ return cached;
454
+ };
455
+ }
456
+
457
+ // src/tools.ts
458
+ import { ToolError as ToolError3 } from "@capybara-hq/plugin-sdk";
459
+ var SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
460
+ var WAIT_MAX_MS = 6e4;
461
+ var WAIT_DEFAULT_MS = 1e4;
462
+ var REF = {
463
+ type: "string",
464
+ description: 'An element ref from the latest browser_snapshot, e.g. "e12".'
465
+ };
466
+ var NAVIGATE = {
467
+ name: "browser_navigate",
468
+ title: "Open a page",
469
+ description: "Open a URL in the active tab of the browser running in the user's device, or go back, forward or reload. Use it to start browsing or to go to a known address; then call browser_snapshot to read the page. Do not use it to follow a link on the page (use browser_click on the link's ref). Only http and https URLs open.",
470
+ inputSchema: {
471
+ type: "object",
472
+ properties: {
473
+ url: { type: "string", description: 'The address to open, e.g. "https://example.com".' },
474
+ action: {
475
+ type: "string",
476
+ enum: ["back", "forward", "reload"],
477
+ description: "Instead of a url: go back, forward or reload the page."
478
+ }
479
+ },
480
+ additionalProperties: false
481
+ },
482
+ keyArgs: ["url", "action"],
483
+ defaultPolicy: "allow"
484
+ };
485
+ var TABS = {
486
+ name: "browser_tabs",
487
+ title: "Browser tabs",
488
+ description: "List, open, switch or close tabs of the browser in the user's device (at most 10 tabs). Use list to see the tab ids, open to load a url in a new tab, switch to make a tab active (the other tools act on the active tab) and close to close one.",
489
+ inputSchema: {
490
+ type: "object",
491
+ properties: {
492
+ action: {
493
+ type: "string",
494
+ enum: ["list", "open", "switch", "close"],
495
+ description: "What to do."
496
+ },
497
+ tabId: { type: "string", description: "The tab for switch and close, from list." },
498
+ url: { type: "string", description: "The address for open (optional: a blank tab)." }
499
+ },
500
+ required: ["action"],
501
+ additionalProperties: false
502
+ },
503
+ keyArgs: ["action", "url"],
504
+ defaultPolicy: "allow"
505
+ };
506
+ var SNAPSHOT = {
507
+ name: "browser_snapshot",
508
+ title: "Read the page",
509
+ description: "Read the active page as an accessibility tree in text, with a ref (e.g. e12) on every element you can act on. Call it after opening a page and after any action that changes the page: refs from older snapshots may no longer exist. Prefer it to browser_screenshot unless the layout or an image matters.",
510
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
511
+ defaultPolicy: "allow"
512
+ };
513
+ var SCREENSHOT = {
514
+ name: "browser_screenshot",
515
+ title: "Screenshot",
516
+ description: "Take a JPEG screenshot of the active page (viewport 1280x800 CSS pixels, or the full page). Use it when the visual layout, an image or a canvas matters, or to find coordinates for browser_click_at and browser_type_at. To read text and find elements, use browser_snapshot instead.",
517
+ inputSchema: {
518
+ type: "object",
519
+ properties: {
520
+ fullPage: { type: "boolean", description: "Capture the whole page instead of the viewport." }
521
+ },
522
+ additionalProperties: false
523
+ },
524
+ defaultPolicy: "allow"
525
+ };
526
+ var CLICK = {
527
+ name: "browser_click",
528
+ title: "Click",
529
+ description: "Click the element with the given ref from the latest browser_snapshot (links, buttons, checkboxes). Waits for a navigation it starts. Use browser_click_at only for things the snapshot does not list.",
530
+ inputSchema: {
531
+ type: "object",
532
+ properties: { ref: REF },
533
+ required: ["ref"],
534
+ additionalProperties: false
535
+ },
536
+ keyArgs: ["ref"],
537
+ defaultPolicy: "ask"
538
+ };
539
+ var TYPE = {
540
+ name: "browser_type",
541
+ title: "Type",
542
+ description: "Replace the text of the input or text area with the given ref, optionally pressing Enter afterwards (submit). Use browser_select for drop-downs and browser_press for single keys.",
543
+ inputSchema: {
544
+ type: "object",
545
+ properties: {
546
+ ref: REF,
547
+ text: { type: "string", description: "The text to fill in." },
548
+ submit: { type: "boolean", description: "Press Enter after typing (e.g. to search)." }
549
+ },
550
+ required: ["ref", "text"],
551
+ additionalProperties: false
552
+ },
553
+ keyArgs: ["ref", "text"],
554
+ defaultPolicy: "ask"
555
+ };
556
+ var SELECT = {
557
+ name: "browser_select",
558
+ title: "Select",
559
+ description: "Choose options of the select element with the given ref, by value or label. Several values only for a multiple select.",
560
+ inputSchema: {
561
+ type: "object",
562
+ properties: {
563
+ ref: REF,
564
+ values: {
565
+ type: "array",
566
+ items: { type: "string" },
567
+ minItems: 1,
568
+ description: 'The option values or labels, e.g. ["Germany"].'
569
+ }
570
+ },
571
+ required: ["ref", "values"],
572
+ additionalProperties: false
573
+ },
574
+ keyArgs: ["ref", "values"],
575
+ defaultPolicy: "ask"
576
+ };
577
+ var PRESS = {
578
+ name: "browser_press",
579
+ title: "Press a key",
580
+ description: "Press a key or a key combination on the active page, e.g. Enter, Escape, ArrowDown, Tab or Control+A. Use browser_type to enter text.",
581
+ inputSchema: {
582
+ type: "object",
583
+ properties: {
584
+ key: {
585
+ type: "string",
586
+ description: 'A key name (KeyboardEvent.key), e.g. "Enter" or "Control+A".'
587
+ }
588
+ },
589
+ required: ["key"],
590
+ additionalProperties: false
591
+ },
592
+ keyArgs: ["key"],
593
+ defaultPolicy: "ask"
594
+ };
595
+ var SCROLL = {
596
+ name: "browser_scroll",
597
+ title: "Scroll",
598
+ description: "Scroll the page, or scroll the element with the given ref into view and then by dy. Use it to load more content of a long page; browser_snapshot already lists elements outside the viewport, so scrolling is not needed to read them.",
599
+ inputSchema: {
600
+ type: "object",
601
+ properties: {
602
+ ref: REF,
603
+ dy: { type: "number", description: "Pixels to scroll down (negative scrolls up), e.g. 600." }
604
+ },
605
+ required: ["dy"],
606
+ additionalProperties: false
607
+ },
608
+ keyArgs: ["ref", "dy"],
609
+ defaultPolicy: "ask"
610
+ };
611
+ var HOVER = {
612
+ name: "browser_hover",
613
+ title: "Hover",
614
+ description: "Move the mouse over the element with the given ref, e.g. to open a menu that appears on hover. Call browser_snapshot afterwards to see what appeared.",
615
+ inputSchema: {
616
+ type: "object",
617
+ properties: { ref: REF },
618
+ required: ["ref"],
619
+ additionalProperties: false
620
+ },
621
+ keyArgs: ["ref"],
622
+ defaultPolicy: "ask"
623
+ };
624
+ var UPLOAD = {
625
+ name: "browser_upload",
626
+ title: "Upload a file",
627
+ description: "Set a file on the file input with the given ref. The path must be an absolute path of a file inside the device's workspace; copy a file there first if it is elsewhere. Use it when the page asks for a file (a file chooser opened, or an upload field).",
628
+ inputSchema: {
629
+ type: "object",
630
+ properties: {
631
+ ref: REF,
632
+ path: { type: "string", description: "Absolute path of a file in the workspace." }
633
+ },
634
+ required: ["ref", "path"],
635
+ additionalProperties: false
636
+ },
637
+ keyArgs: ["ref", "path"],
638
+ defaultPolicy: "ask"
639
+ };
640
+ var POINT = {
641
+ x: {
642
+ type: "number",
643
+ minimum: 0,
644
+ maximum: VIEWPORT.width,
645
+ description: `Viewport x in CSS pixels (0-${VIEWPORT.width}), from a viewport screenshot.`
646
+ },
647
+ y: {
648
+ type: "number",
649
+ minimum: 0,
650
+ maximum: VIEWPORT.height,
651
+ description: `Viewport y in CSS pixels (0-${VIEWPORT.height}), from a viewport screenshot.`
652
+ }
653
+ };
654
+ var CLICK_AT = {
655
+ name: "browser_click_at",
656
+ title: "Click at a point",
657
+ description: "Click at viewport coordinates taken from a viewport browser_screenshot. Use it only for targets the snapshot does not list (canvas, maps, custom widgets); otherwise use browser_click with a ref.",
658
+ inputSchema: {
659
+ type: "object",
660
+ properties: POINT,
661
+ required: ["x", "y"],
662
+ additionalProperties: false
663
+ },
664
+ keyArgs: ["x", "y"],
665
+ defaultPolicy: "ask"
666
+ };
667
+ var TYPE_AT = {
668
+ name: "browser_type_at",
669
+ title: "Type at a point",
670
+ description: "Click at viewport coordinates from a viewport browser_screenshot, then type text there. Use it only for fields the snapshot does not list; otherwise use browser_type with a ref.",
671
+ inputSchema: {
672
+ type: "object",
673
+ properties: { ...POINT, text: { type: "string", description: "The text to type." } },
674
+ required: ["x", "y", "text"],
675
+ additionalProperties: false
676
+ },
677
+ keyArgs: ["x", "y", "text"],
678
+ defaultPolicy: "ask"
679
+ };
680
+ var WAIT = {
681
+ name: "browser_wait",
682
+ title: "Wait",
683
+ description: "Wait until a text appears on the page, an element ref appears, a navigation finishes, or the time cap passes (at most 60000 ms; call it again to wait longer). Use it after an action that loads content slowly, or while the user controls the browser. To have the user do something in the browser, use browser_handoff instead.",
684
+ inputSchema: {
685
+ type: "object",
686
+ properties: {
687
+ text: { type: "string", description: "Wait for this text on the page." },
688
+ ref: REF,
689
+ navigation: { type: "boolean", description: "Wait for the next navigation to finish." },
690
+ timeoutMs: {
691
+ type: "integer",
692
+ minimum: 0,
693
+ maximum: WAIT_MAX_MS,
694
+ description: `The time cap in milliseconds (default ${WAIT_DEFAULT_MS}).`
695
+ }
696
+ },
697
+ additionalProperties: false
698
+ },
699
+ keyArgs: ["text", "timeoutMs"],
700
+ defaultPolicy: "allow"
701
+ };
702
+ var obj = (input) => typeof input === "object" && input !== null ? input : {};
703
+ var str = (v) => typeof v === "string" ? v : void 0;
704
+ var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
705
+ function defined(o) {
706
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
707
+ }
708
+ function need(v, field, tool) {
709
+ if (v === void 0) throw new ToolError3(`${tool} needs ${field}; pass it and retry.`);
710
+ return v;
711
+ }
712
+ function handler(deps, toRequest, timeoutOf = () => REQUEST_TIMEOUT_MS) {
713
+ return async (input, call) => {
714
+ const req = toRequest(obj(input));
715
+ return toResult(await runRequest(deps, call, req, timeoutOf(req)));
716
+ };
717
+ }
718
+ function registerBrowserTools(ctx, deps) {
719
+ ctx.tools.register(
720
+ NAVIGATE,
721
+ handler(deps, (i) => {
722
+ const url = str(i.url);
723
+ const action = str(i.action);
724
+ if (url === void 0 === (action === void 0))
725
+ throw new ToolError3("browser_navigate needs either a url or an action; pass exactly one.");
726
+ return defined({ op: "navigate", url, action });
727
+ })
728
+ );
729
+ ctx.tools.register(
730
+ TABS,
731
+ handler(
732
+ deps,
733
+ (i) => defined({
734
+ op: "tabs",
735
+ action: need(str(i.action), "an action", "browser_tabs"),
736
+ tabId: str(i.tabId),
737
+ url: str(i.url)
738
+ })
739
+ )
740
+ );
741
+ ctx.tools.register(
742
+ SNAPSHOT,
743
+ handler(deps, () => ({ op: "snapshot" }))
744
+ );
745
+ ctx.tools.register(SCREENSHOT, async (input, call) => {
746
+ const i = obj(input);
747
+ const shot = (maxBytes) => runRequest(
748
+ deps,
749
+ call,
750
+ defined({
751
+ op: "screenshot",
752
+ fullPage: i.fullPage === true ? true : void 0,
753
+ maxBytes
754
+ })
755
+ );
756
+ try {
757
+ return toResult(await shot(SCREENSHOT_MAX_BYTES));
758
+ } catch (e) {
759
+ if (!(e instanceof ToolError3) || !e.message.startsWith(REPLY_TOO_LARGE_MESSAGE)) throw e;
760
+ return toResult(await shot(Math.floor(SCREENSHOT_MAX_BYTES / 2)));
761
+ }
762
+ });
763
+ ctx.tools.register(
764
+ CLICK,
765
+ handler(deps, (i) => ({
766
+ op: "click",
767
+ ref: need(str(i.ref), "a ref", "browser_click")
768
+ }))
769
+ );
770
+ ctx.tools.register(
771
+ TYPE,
772
+ handler(
773
+ deps,
774
+ (i) => defined({
775
+ op: "type",
776
+ ref: need(str(i.ref), "a ref", "browser_type"),
777
+ text: need(str(i.text), "text", "browser_type"),
778
+ submit: typeof i.submit === "boolean" ? i.submit : void 0
779
+ })
780
+ )
781
+ );
782
+ ctx.tools.register(
783
+ SELECT,
784
+ handler(deps, (i) => ({
785
+ op: "select",
786
+ ref: need(str(i.ref), "a ref", "browser_select"),
787
+ values: Array.isArray(i.values) ? i.values.filter((v) => typeof v === "string") : []
788
+ }))
789
+ );
790
+ ctx.tools.register(
791
+ PRESS,
792
+ handler(deps, (i) => ({
793
+ op: "press",
794
+ key: need(str(i.key), "a key", "browser_press")
795
+ }))
796
+ );
797
+ ctx.tools.register(
798
+ SCROLL,
799
+ handler(
800
+ deps,
801
+ (i) => defined({
802
+ op: "scroll",
803
+ ref: str(i.ref),
804
+ dy: need(num(i.dy), "dy", "browser_scroll")
805
+ })
806
+ )
807
+ );
808
+ ctx.tools.register(
809
+ HOVER,
810
+ handler(deps, (i) => ({
811
+ op: "hover",
812
+ ref: need(str(i.ref), "a ref", "browser_hover")
813
+ }))
814
+ );
815
+ ctx.tools.register(
816
+ UPLOAD,
817
+ handler(deps, (i) => ({
818
+ op: "upload",
819
+ ref: need(str(i.ref), "a ref", "browser_upload"),
820
+ path: need(str(i.path), "a path", "browser_upload")
821
+ }))
822
+ );
823
+ ctx.tools.register(
824
+ CLICK_AT,
825
+ handler(deps, (i) => ({
826
+ op: "click_at",
827
+ x: need(num(i.x), "x", "browser_click_at"),
828
+ y: need(num(i.y), "y", "browser_click_at")
829
+ }))
830
+ );
831
+ ctx.tools.register(
832
+ TYPE_AT,
833
+ handler(deps, (i) => ({
834
+ op: "type_at",
835
+ x: need(num(i.x), "x", "browser_type_at"),
836
+ y: need(num(i.y), "y", "browser_type_at"),
837
+ text: need(str(i.text), "text", "browser_type_at")
838
+ }))
839
+ );
840
+ ctx.tools.register(
841
+ WAIT,
842
+ handler(
843
+ deps,
844
+ (i) => defined({
845
+ op: "wait",
846
+ text: str(i.text),
847
+ ref: str(i.ref),
848
+ navigation: i.navigation === true ? true : void 0,
849
+ timeoutMs: Math.max(
850
+ 0,
851
+ Math.min(WAIT_MAX_MS, Math.floor(num(i.timeoutMs) ?? WAIT_DEFAULT_MS))
852
+ )
853
+ }),
854
+ (r) => (r.op === "wait" ? r.timeoutMs : 0) + REQUEST_TIMEOUT_MS
855
+ )
856
+ );
857
+ }
858
+
859
+ // src/index.ts
860
+ var index_default = defineExtension({
861
+ name: "browser",
862
+ version: "0.1.0-rc.1",
863
+ sdk: "^0.1.0-rc.69",
864
+ provides: [],
865
+ ui: [
866
+ {
867
+ id: "browser",
868
+ title: { zh: "浏览器", en: "Browser" },
869
+ slot: "conversation.panel",
870
+ kind: "embed",
871
+ path: "/ui/browser",
872
+ icon: "globe"
873
+ }
874
+ ],
875
+ permissions: {
876
+ tools: [
877
+ "browser_navigate",
878
+ "browser_tabs",
879
+ "browser_snapshot",
880
+ "browser_screenshot",
881
+ "browser_click",
882
+ "browser_type",
883
+ "browser_select",
884
+ "browser_press",
885
+ "browser_scroll",
886
+ "browser_hover",
887
+ "browser_upload",
888
+ "browser_click_at",
889
+ "browser_type_at",
890
+ "browser_wait",
891
+ "browser_handoff"
892
+ ],
893
+ http: [
894
+ { method: "GET", path: "/ui/browser", access: "public" },
895
+ { method: "GET", path: "/ui/panel.js", access: "public" },
896
+ { method: "POST", path: "/ui/stream-ticket", access: "embed" },
897
+ { method: "POST", path: "/ui/network-hosts", access: "embed" },
898
+ { method: "POST", path: "/ui/handoff-answer", access: "embed" }
899
+ ],
900
+ ui: { embeds: ["browser"] },
901
+ deviceAccess: { services: ["browser"] }
902
+ },
903
+ setup(ctx) {
904
+ const deviceAccess = {
905
+ ensureService: (...a) => ctx.deviceAccess.ensureService(...a),
906
+ request: (...a) => ctx.deviceAccess.request(...a),
907
+ reportBlockedHosts: (...a) => ctx.deviceAccess.reportBlockedHosts(...a),
908
+ streamTicket: (...a) => ctx.deviceAccess.streamTicket(...a),
909
+ addNetworkHosts: (...a) => ctx.deviceAccess.addNetworkHosts(...a),
910
+ answerHandoff: (...a) => ctx.deviceAccess.answerHandoff(...a)
911
+ };
912
+ const deps = { deviceAccess, serviceSpec: serviceSpecLoader(), log: ctx.log };
913
+ registerBrowserTools(ctx, deps);
914
+ registerHandoffTool(ctx, deps);
915
+ registerRoutes(ctx, { deviceAccess, panelScript: panelScriptLoader() });
916
+ }
917
+ });
918
+ export {
919
+ index_default as default
920
+ };