@capybara-hq/plugin-browser 0.1.0-rc.11 → 0.1.0-rc.12

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/dist/index.mjs CHANGED
@@ -8,18 +8,46 @@ const __capybara_dirname = __capybaraPathDirname(__capybara_filename);
8
8
  // src/index.ts
9
9
  import { defineExtension } from "@capybara-hq/plugin-sdk";
10
10
 
11
- // src/handoff.ts
12
- import {
13
- ToolError as ToolError2
14
- } from "@capybara-hq/plugin-sdk";
15
-
16
11
  // daemon/protocol.ts
17
12
  var VIEWPORT = { width: 1280, height: 800 };
13
+ var VIEWPORT_PROFILES = {
14
+ desktop: { width: VIEWPORT.width, height: VIEWPORT.height, mobile: false, scale: 1 },
15
+ phone: { width: 390, height: 844, mobile: true, scale: 2 }
16
+ };
17
+ var DIALOG_QUOTE_CHARS = 300;
18
+ function normalizeDialogText(text) {
19
+ return text.replace(/\r\n/g, "\n").replace(/\s+/g, " ").trim();
20
+ }
21
+ function dialogQuote(message) {
22
+ return clipCodePoints(normalizeDialogText(message), DIALOG_QUOTE_CHARS).trimEnd();
23
+ }
24
+ var AUTH_SIGN_IN_TEXT = "Signing in needs the user's credentials; call browser_handoff and ask the user to sign in.";
25
+ function dialogLine(d) {
26
+ const quote = dialogQuote(d.message);
27
+ const cut = quote.length < normalizeDialogText(d.message).length ? " (cut)" : "";
28
+ const q = `${JSON.stringify(quote)}${cut}`;
29
+ const how = `Answer it with browser_dialog (dialogId ${d.id}, the message as quoted, accept or dismiss) before acting on this tab.`;
30
+ switch (d.kind) {
31
+ case "auth":
32
+ return `The site ${JSON.stringify(d.origin ?? "")} asks for HTTP sign-in (dialog ${d.id}, realm ${JSON.stringify(d.realm ?? "")}; page-supplied). ${AUTH_SIGN_IN_TEXT} To leave it, call browser_dialog with dialogId ${d.id}, the message as quoted ${q} and action dismiss.`;
33
+ case "beforeunload":
34
+ return `The page asks whether to leave (it may have unsaved changes), dialog ${d.id}: ${q}; accept leaves, dismiss stays. ${how}`;
35
+ case "prompt":
36
+ return `The page shows a prompt dialog ${d.id}: ${q} (default value ${JSON.stringify(clipCodePoints(d.defaultValue ?? "", DIALOG_QUOTE_CHARS))}). ${how} Pass text to accept with your own value.`;
37
+ default:
38
+ return `The page shows a ${d.kind} dialog ${d.id}: ${q}. ${how}`;
39
+ }
40
+ }
18
41
  var IDLE_STOP_MS = 15 * 6e4;
42
+ function clipCodePoints(text, max) {
43
+ if (text.length <= max) return text;
44
+ return Array.from(text).slice(0, max).join("");
45
+ }
19
46
  var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
20
47
  var HANDOFF_MAX_CHARS = 4096;
21
48
  var CONVERSATION_IDLE_MS = 15 * 6e4;
22
49
  var EVICT_MIN_IDLE_MS = 5 * 6e4;
50
+ var WATCH_HEARTBEAT_MS = 10 * 6e4;
23
51
  var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
24
52
  var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
25
53
  var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
@@ -74,6 +102,9 @@ function deviceAccessCode(e) {
74
102
  const code = e.code;
75
103
  return typeof code === "string" ? code : void 0;
76
104
  }
105
+ function deviceAccessErrorCode(e) {
106
+ return deviceAccessCode(e);
107
+ }
77
108
  function deviceAccessToolError(e) {
78
109
  switch (deviceAccessCode(e)) {
79
110
  case "no_device":
@@ -102,6 +133,8 @@ function daemonToolError(code, message, tail) {
102
133
  switch (code) {
103
134
  case "taken_over":
104
135
  return new ToolError(TAKEN_OVER_MESSAGE + tail);
136
+ case "dialog_open":
137
+ return new ToolError(`${message} Then call this tool again if it is still needed.${tail}`);
105
138
  case "no_such_ref":
106
139
  return new ToolError(`${message} Call browser_snapshot for the current element refs.${tail}`);
107
140
  case "timeout":
@@ -203,6 +236,28 @@ async function runRequest(deps, call, req, timeoutMs = REQUEST_TIMEOUT_MS) {
203
236
  waitUntil = Date.now() + RESTART_WAIT_MS;
204
237
  pauseMs = RESTART_PAUSE_FIRST_MS;
205
238
  }
239
+ return finishReply(deps, call, reply);
240
+ }
241
+ async function requestIfRunning(deps, call, req, timeoutMs) {
242
+ assertOwner(call);
243
+ const sent = {
244
+ ...req,
245
+ conversationId: call.conversationId,
246
+ rootConversationId: call.rootConversationId
247
+ };
248
+ const body = new TextEncoder().encode(JSON.stringify(sent));
249
+ let reply;
250
+ try {
251
+ reply = parseReply(
252
+ await deps.deviceAccess.request(call, { service: SERVICE, body, timeoutMs, ifRunning: true })
253
+ );
254
+ } catch (e) {
255
+ if (deviceAccessCode(e) === "not_running") throw e;
256
+ throw failure(deps, call, e, false);
257
+ }
258
+ return finishReply(deps, call, reply);
259
+ }
260
+ function finishReply(deps, call, reply) {
206
261
  const hosts = Array.isArray(reply.blockedHosts) ? reply.blockedHosts.flatMap((h) => {
207
262
  const b = h;
208
263
  if (typeof b !== "object" || b === null || typeof b.host !== "string" || b.host === "")
@@ -237,6 +292,7 @@ function toResult(reply) {
237
292
  );
238
293
  lines.push(reply.page === void 0 ? NO_TAB_MESSAGE : pageLine(reply.page));
239
294
  if (reply.text !== void 0 && reply.text !== "") lines.push(reply.text);
295
+ if (reply.dialog !== void 0) lines.push(dialogLine(reply.dialog));
240
296
  const tabs = tabCountOf(reply);
241
297
  if (tabs !== void 0) lines.push(tabsLine(tabs));
242
298
  return {
@@ -247,6 +303,60 @@ function toResult(reply) {
247
303
  };
248
304
  }
249
305
 
306
+ // src/dialog.ts
307
+ var DIALOG = {
308
+ name: "browser_dialog",
309
+ title: "Answer a page dialog",
310
+ description: "Answer the dialog a page shows (a confirm, a prompt, or a leave-page question): pass the dialogId and the message exactly as a browser tool result quoted them, and accept or dismiss. Accepting can delete, pay or leave unsaved changes, so dismiss when unsure. For a prompt, text is the answer to type (accept without text takes the default value). An HTTP sign-in request can only be dismissed here: call browser_handoff so the user signs in, and never ask for passwords in the chat.",
311
+ inputSchema: {
312
+ type: "object",
313
+ properties: {
314
+ dialogId: {
315
+ type: "string",
316
+ description: 'The dialog id from the tool result, e.g. "d3".'
317
+ },
318
+ message: {
319
+ type: "string",
320
+ maxLength: DIALOG_QUOTE_CHARS + 50,
321
+ description: "The dialog's message exactly as the tool result quoted it."
322
+ },
323
+ action: {
324
+ type: "string",
325
+ enum: ["accept", "dismiss"],
326
+ description: "accept (OK, leave) or dismiss (Cancel, stay)."
327
+ },
328
+ text: { type: "string", description: "For a prompt: the text to answer with." }
329
+ },
330
+ required: ["dialogId", "message", "action"],
331
+ additionalProperties: false
332
+ },
333
+ keyArgs: ["action", "message", "text"],
334
+ defaultPolicy: "ask",
335
+ // any tool may start the device first (see TOOL_TIMEOUT_MS)
336
+ timeoutMs: TOOL_TIMEOUT_MS
337
+ };
338
+ var str = (v) => typeof v === "string" ? v : void 0;
339
+ function registerDialogTool(ctx, deps) {
340
+ ctx.tools.register(DIALOG, async (input, call) => {
341
+ const i = typeof input === "object" && input !== null ? input : {};
342
+ const text = str(i.text);
343
+ return toResult(
344
+ await runRequest(deps, call, {
345
+ op: "dialog",
346
+ dialogId: str(i.dialogId) ?? "",
347
+ message: str(i.message) ?? "",
348
+ action: i.action === "accept" ? "accept" : "dismiss",
349
+ ...text === void 0 ? {} : { text }
350
+ })
351
+ );
352
+ });
353
+ }
354
+
355
+ // src/handoff.ts
356
+ import {
357
+ ToolError as ToolError2
358
+ } from "@capybara-hq/plugin-sdk";
359
+
250
360
  // src/i18n.ts
251
361
  var HANDOFF_FORM = {
252
362
  titlePrefix: { zh: "请在浏览器中完成:", en: "Finish in the browser: " },
@@ -254,6 +364,17 @@ var HANDOFF_FORM = {
254
364
  done: { zh: "完成", en: "Done" },
255
365
  cancel: { zh: "取消", en: "Cancel" }
256
366
  };
367
+ var WAIT_FORM = {
368
+ titlePrefix: { zh: "智能体正在等待:", en: "The agent is waiting until " },
369
+ end: { zh: "结束等待", en: "End the wait" },
370
+ endButton: { zh: "结束等待", en: "End wait" },
371
+ /** What the condition is, per kind (the text, ref or URL part follows where it has one). */
372
+ text: { zh: "页面出现", en: "the page shows " },
373
+ ref: { zh: "元素出现 ", en: "element appears: " },
374
+ urlContains: { zh: "网址包含", en: "the URL contains " },
375
+ navigation: { zh: "页面完成跳转", en: "the page navigates" },
376
+ download: { zh: "下载完成", en: "a download finishes" }
377
+ };
257
378
 
258
379
  // src/handoff.ts
259
380
  var PANEL = "browser";
@@ -494,6 +615,23 @@ var PANEL_HTML = `<!doctype html>
494
615
  .strip .label { color: var(--cb-muted, #5E5E5A); }
495
616
  .strip:not(:has(button)) { padding-right: 12px; }
496
617
 
618
+ /* a held page dialog: a box over the picture until it is answered */
619
+ #pdialog { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: min(360px, calc(100% - 24px)); max-height: calc(100% - 24px); overflow: auto; display: flex; flex-direction: column; gap: 8px; padding: 14px; border-radius: var(--cb-radius-md, 8px); background: var(--cb-raised, #fff); box-shadow: var(--cb-shadow-float, 0 8px 24px rgba(26,26,24,.12)), 0 0 0 1px var(--cb-line-soft, #E8E7E2); }
620
+ #pdialog .kind { margin: 0; color: var(--cb-muted, #5E5E5A); font-size: var(--cb-type-micro-size, 11px); line-height: var(--cb-type-micro-line, 14px); }
621
+ #pdialog .msg { margin: 0; font-family: var(--cb-font-prose, system-ui, sans-serif); overflow-wrap: anywhere; white-space: pre-wrap; max-height: 9em; overflow: auto; }
622
+ #pdialog .realm { margin: 0; color: var(--cb-muted, #5E5E5A); overflow-wrap: anywhere; }
623
+ #pdialog input { height: 32px; padding: 0 10px; border: 0; border-radius: var(--radius); box-shadow: inset 0 0 0 1px var(--cb-line, #D9D8D2); background: var(--cb-panel, #fff); }
624
+ #pdialog .actions { display: flex; justify-content: flex-end; gap: 6px; }
625
+ #pdialog .hint { margin: 0; color: var(--cb-muted, #5E5E5A); }
626
+
627
+ /* the takeover bar of a compact or touch screen: viewport, keyboard, hand back */
628
+ #touchbar { flex: none; display: flex; align-items: center; gap: 6px; padding: 6px 12px; }
629
+ #touchbar .grow { flex: 1; }
630
+ @media (max-width: 599px), (pointer: coarse) {
631
+ #touchbar button, #pdialog button, #pdialog input, #permission button, #phonehint button { min-height: 44px; }
632
+ #touchbar button, #pdialog button { padding: 0 16px; }
633
+ }
634
+
497
635
  /* menus (narrow: tabs, more) */
498
636
  .menu { position: absolute; z-index: 2; min-width: 180px; max-width: calc(100% - 24px); max-height: 60%; overflow: auto; padding: 4px; border-radius: var(--cb-radius-md, 8px); background: var(--cb-raised, #fff); box-shadow: var(--cb-shadow-float, 0 8px 24px rgba(26,26,24,.08)), 0 0 0 1px var(--cb-line-soft, #E8E7E2); }
499
637
  .menu button { display: flex; width: 100%; justify-content: flex-start; gap: 8px; padding: 0 8px; text-align: left; overflow: hidden; text-overflow: ellipsis; }
@@ -540,12 +678,25 @@ var PANEL_HTML = `<!doctype html>
540
678
  <p id="status" class="row" role="status"><span class="ico" id="status-icon"></span><span class="lead" id="status-lead"></span><span class="detail" id="status-detail"></span></p>
541
679
  <div id="verify" class="warn" hidden><span class="ico">${ICONS.pause}</span><div class="text"><span class="title" id="verify-title"></span><span class="body" id="verify-body"></span></div><div class="actions"><button type="button" id="verify-go" class="primary"></button></div></div>
542
680
  <div id="handoff" class="warn" hidden><span class="ico">${ICONS.pause}</span><div class="text"><span class="title" id="handoff-label"></span><span class="body" id="handoff-message"></span></div><div class="actions"><button type="button" id="handoff-done" class="primary"></button><button type="button" id="handoff-cancel" class="secondary"></button></div></div>
681
+ <div id="touchbar" hidden><button type="button" id="viewport-toggle" class="secondary"></button><button type="button" id="keyboard" class="secondary"></button><span class="grow"></span><button type="button" id="touch-handback" class="outline"></button></div>
543
682
  <div id="stage">
544
683
  <canvas id="view" tabindex="0"></canvas>
545
684
  <div id="flash" hidden></div>
685
+ <div id="pdialog" role="dialog" aria-modal="false" hidden>
686
+ <p class="kind" id="pdialog-kind"></p>
687
+ <p class="msg" id="pdialog-msg"></p>
688
+ <p class="realm" id="pdialog-realm" hidden></p>
689
+ <input id="pdialog-text" type="text" autocomplete="off" spellcheck="false" hidden>
690
+ <input id="pdialog-user" type="text" autocomplete="off" spellcheck="false" hidden>
691
+ <input id="pdialog-pass" type="password" autocomplete="off" hidden>
692
+ <div class="actions"><button type="button" id="pdialog-no" class="secondary"></button><button type="button" id="pdialog-yes" class="primary"></button></div>
693
+ <p class="hint" id="pdialog-hint" hidden></p>
694
+ </div>
546
695
  <div id="strips">
547
696
  <div id="blocked" class="strip" hidden><p><span id="blocked-label" class="label"></span> <span id="blocked-host"></span></p><button type="button" id="allow" class="primary"></button></div>
548
697
  <div id="dialog" class="strip" hidden><p><span id="dialog-label" class="label"></span> <span id="dialog-text"></span></p></div>
698
+ <div id="permission" class="strip" hidden><p><span id="permission-origin"></span> <span id="permission-label" class="label"></span> <span id="permission-name"></span></p><button type="button" id="permission-allow" class="primary"></button></div>
699
+ <div id="phonehint" class="strip" hidden><p id="phonehint-text"></p><button type="button" id="phonehint-go" class="primary"></button></div>
549
700
  <div id="notice" class="strip" role="alert" hidden><p><span id="notice-text"></span></p></div>
550
701
  </div>
551
702
  </div>
@@ -717,10 +868,231 @@ function panelScriptLoader(file = new URL("../ui/panel.js", import.meta.url)) {
717
868
  }
718
869
 
719
870
  // src/tools.ts
720
- import { ToolError as ToolError3 } from "@capybara-hq/plugin-sdk";
721
- var SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
722
- var WAIT_MAX_MS = 6e4;
871
+ import {
872
+ ToolError as ToolError4
873
+ } from "@capybara-hq/plugin-sdk";
874
+
875
+ // src/wait.ts
876
+ import {
877
+ ToolError as ToolError3
878
+ } from "@capybara-hq/plugin-sdk";
879
+ var WAIT_INLINE_MAX_MS = 6e4;
880
+ var WAIT_MAX_MS = 864e5;
723
881
  var WAIT_DEFAULT_MS = 1e4;
882
+ var WATCH_POLL_TIMEOUT_MS = 4e3;
883
+ var CHECK_NOW_MS = 500;
884
+ var WATCH_END_TIMEOUT_MS = 1e4;
885
+ var LONG_WAIT_NEEDS_CONDITION = "A wait longer than 60000 ms needs a condition: pass one of text, ref, urlContains, navigation or download. To continue later without one, finish and let the user or a scheduled task start a new run.";
886
+ var DEVICE_STOPPED_WHILE_WAITING = "The device stopped while waiting (it was suspended or reached its running limit); the page state is gone. Call browser_wait again if still needed.";
887
+ var WATCHED_TAB_CLOSED = "The tab being watched was closed; check the tabs with browser_tabs.";
888
+ var WAIT_LOST = "The browser lost track of the wait; the condition does not hold now. Call browser_wait again if still needed.";
889
+ var str2 = (v) => typeof v === "string" && v !== "" ? v : void 0;
890
+ function conditionsOf(i) {
891
+ const out = [];
892
+ const text = str2(i.text);
893
+ if (text !== void 0) out.push({ text });
894
+ const ref = str2(i.ref);
895
+ if (ref !== void 0) out.push({ ref });
896
+ const urlContains = str2(i.urlContains);
897
+ if (urlContains !== void 0) out.push({ urlContains });
898
+ if (i.navigation === true) out.push({ navigation: true });
899
+ if (i.download === true) out.push({ download: true });
900
+ return out;
901
+ }
902
+ function describeCondition(c) {
903
+ if ("text" in c) return `the text ${JSON.stringify(c.text)} appeared`;
904
+ if ("ref" in c) return `element ${c.ref} appeared`;
905
+ if ("urlContains" in c) return `the URL contains ${JSON.stringify(c.urlContains)}`;
906
+ if ("navigation" in c) return "a navigation finished";
907
+ return "a download finished";
908
+ }
909
+ function pendingCondition(c) {
910
+ if ("text" in c) return `the text ${JSON.stringify(c.text)} appeared`;
911
+ if ("ref" in c) return `element ${c.ref} appeared`;
912
+ if ("urlContains" in c) return `the URL contained ${JSON.stringify(c.urlContains)}`;
913
+ if ("navigation" in c) return "a navigation";
914
+ return "a download finished";
915
+ }
916
+ function formTitle(c) {
917
+ const cut = (s) => s.length <= 60 ? s : `${s.slice(0, 59)}…`;
918
+ const p = WAIT_FORM.titlePrefix;
919
+ if ("text" in c)
920
+ return {
921
+ zh: `${p.zh}${WAIT_FORM.text.zh}“${cut(c.text)}”`,
922
+ en: `${p.en}${WAIT_FORM.text.en}"${cut(c.text)}"`
923
+ };
924
+ if ("ref" in c)
925
+ return { zh: `${p.zh}${WAIT_FORM.ref.zh}${c.ref}`, en: `${p.en}${WAIT_FORM.ref.en}${c.ref}` };
926
+ if ("urlContains" in c)
927
+ return {
928
+ zh: `${p.zh}${WAIT_FORM.urlContains.zh}“${cut(c.urlContains)}”`,
929
+ en: `${p.en}${WAIT_FORM.urlContains.en}"${cut(c.urlContains)}"`
930
+ };
931
+ const k = "navigation" in c ? WAIT_FORM.navigation : WAIT_FORM.download;
932
+ return { zh: `${p.zh}${k.zh}`, en: `${p.en}${k.en}` };
933
+ }
934
+ function formatDuration(ms) {
935
+ const s = Math.max(0, Math.round(ms / 1e3));
936
+ if (s < 60) return `${s} s`;
937
+ const m = Math.floor(s / 60);
938
+ if (m < 60) return s % 60 === 0 ? `${m} min` : `${m} min ${s % 60} s`;
939
+ const h = Math.floor(m / 60);
940
+ return m % 60 === 0 ? `${h} h` : `${h} h ${m % 60} min`;
941
+ }
942
+ function watchIdOf(call) {
943
+ const key = call.idempotencyKey;
944
+ if (typeof key !== "string" || key.length < 32)
945
+ throw new ToolError3(
946
+ "browser_wait cannot park this wait: the call has no idempotency key. Retry with a wait of at most 60000 ms."
947
+ );
948
+ return key.slice(0, 32);
949
+ }
950
+ function watchOf(reply) {
951
+ const w = reply.watch;
952
+ const states = ["pending", "met", "ended", "unknown"];
953
+ return typeof w === "object" && w !== null && states.includes(String(w.state)) ? w : { state: "unknown" };
954
+ }
955
+ function inlineWait(i, timeoutMs) {
956
+ const c = conditionsOf(i)[0];
957
+ return {
958
+ op: "wait",
959
+ timeoutMs,
960
+ ...c === void 0 ? {} : c
961
+ };
962
+ }
963
+ function resultWith(reply, line) {
964
+ return toResult({ ...reply, text: [line, reply.text].filter((x) => x).join("\n") });
965
+ }
966
+ function waitHandler(deps) {
967
+ return async (input, call) => {
968
+ const i = typeof input === "object" && input !== null ? input : {};
969
+ const conditions = conditionsOf(i);
970
+ if (conditions.length > 1)
971
+ throw new ToolError3(
972
+ "browser_wait takes at most one condition (text, ref, urlContains, navigation or download); pass one and retry."
973
+ );
974
+ const asked = typeof i.timeoutMs === "number" && Number.isFinite(i.timeoutMs) ? i.timeoutMs : WAIT_DEFAULT_MS;
975
+ const timeoutMs = Math.max(0, Math.min(WAIT_MAX_MS, Math.floor(asked)));
976
+ const resumed = call.resume?.state;
977
+ if (call.resume !== void 0 && resumed?.watchId !== void 0)
978
+ return resume(deps, call, resumed);
979
+ if (timeoutMs <= WAIT_INLINE_MAX_MS) {
980
+ const req = inlineWait(i, timeoutMs);
981
+ return toResult(await runRequest(deps, call, req, timeoutMs + REQUEST_TIMEOUT_MS));
982
+ }
983
+ const condition = conditions[0];
984
+ if (condition === void 0) throw new ToolError3(LONG_WAIT_NEEDS_CONDITION);
985
+ const watchId = watchIdOf(call);
986
+ const started = await runRequest(deps, call, {
987
+ op: "watch_start",
988
+ watchId,
989
+ condition,
990
+ remainingMs: timeoutMs
991
+ });
992
+ const state = { watchId, startedAt: (/* @__PURE__ */ new Date()).toISOString(), condition };
993
+ if (watchOf(started).state !== "pending") return resume(deps, call, state);
994
+ const asking = {
995
+ kind: "input_required",
996
+ form: {
997
+ title: formTitle(condition),
998
+ fields: [
999
+ {
1000
+ key: "end",
1001
+ label: WAIT_FORM.end,
1002
+ schema: { type: "string", enum: ["end"] },
1003
+ required: true,
1004
+ choices: [{ value: "end", label: WAIT_FORM.endButton }]
1005
+ }
1006
+ ]
1007
+ },
1008
+ state,
1009
+ watch: { deadlineMs: timeoutMs }
1010
+ };
1011
+ return asking;
1012
+ };
1013
+ }
1014
+ function waitWatcher(deps) {
1015
+ return async (ctx) => {
1016
+ const state = ctx.state;
1017
+ if (typeof state?.watchId !== "string") return "settle";
1018
+ let reply;
1019
+ try {
1020
+ reply = await requestIfRunning(
1021
+ deps,
1022
+ ctx,
1023
+ { op: "watch_poll", watchId: state.watchId },
1024
+ WATCH_POLL_TIMEOUT_MS
1025
+ );
1026
+ } catch (e) {
1027
+ if (deviceAccessErrorCode(e) === "not_running") return "settle";
1028
+ throw e;
1029
+ }
1030
+ return watchOf(reply).state === "pending" ? "pending" : "settle";
1031
+ };
1032
+ }
1033
+ async function resume(deps, call, state) {
1034
+ const elapsed = formatDuration(Date.now() - Date.parse(state.startedAt));
1035
+ const c = state.condition;
1036
+ let reply;
1037
+ try {
1038
+ reply = await requestIfRunning(
1039
+ deps,
1040
+ call,
1041
+ { op: "watch_end", watchId: state.watchId },
1042
+ WATCH_END_TIMEOUT_MS
1043
+ );
1044
+ } catch (e) {
1045
+ if (deviceAccessErrorCode(e) === "not_running")
1046
+ throw new ToolError3(DEVICE_STOPPED_WHILE_WAITING);
1047
+ throw e;
1048
+ }
1049
+ const watch = watchOf(reply);
1050
+ if (watch.state === "met") {
1051
+ const at = watch.at === void 0 ? Date.now() : Date.parse(watch.at);
1052
+ const waited = formatDuration(at - Date.parse(state.startedAt));
1053
+ const detail = watch.detail === void 0 ? "" : ` (${watch.detail})`;
1054
+ return resultWith(reply, `Waited ${waited}: ${describeCondition(c)}${detail}.`);
1055
+ }
1056
+ if (watch.state === "ended" && watch.reason === "dialog")
1057
+ return resultWith(
1058
+ reply,
1059
+ `The page opened a dialog while waiting.${watch.detail === void 0 ? "" : ` Dialog: ${JSON.stringify(watch.detail)}.`}`
1060
+ );
1061
+ if (watch.state === "ended" && watch.reason === "tab_closed")
1062
+ throw new ToolError3(WATCHED_TAB_CLOSED);
1063
+ if (watch.state === "unknown") {
1064
+ if (!("download" in c) && !("navigation" in c)) {
1065
+ const now = await requestIfRunning(
1066
+ deps,
1067
+ call,
1068
+ { op: "wait", timeoutMs: CHECK_NOW_MS, ...c },
1069
+ CHECK_NOW_MS + REQUEST_TIMEOUT_MS
1070
+ ).catch(() => void 0);
1071
+ if (now !== void 0) return resultWith(now, `Waited ${elapsed}: ${describeCondition(c)}.`);
1072
+ }
1073
+ throw new ToolError3(WAIT_LOST);
1074
+ }
1075
+ const outcome = call.resume?.outcome ?? "expired";
1076
+ if (watch.state === "ended" && watch.reason === "deadline")
1077
+ throw new ToolError3(
1078
+ `${capitalize(pendingCondition(c))} did not happen within ${elapsed}. Check the page with browser_snapshot, then retry or call browser_wait.`
1079
+ );
1080
+ if (outcome === "answered")
1081
+ throw new ToolError3(
1082
+ `The user ended the wait before ${pendingCondition(c)}; ask the user how to continue.`
1083
+ );
1084
+ if (outcome === "woken")
1085
+ throw new ToolError3(
1086
+ `The wait was interrupted after ${elapsed} before ${pendingCondition(c)} (the browser service could not be checked). Call browser_wait again if still needed.`
1087
+ );
1088
+ throw new ToolError3(
1089
+ `${capitalize(pendingCondition(c))} did not happen within ${elapsed}. Check the page with browser_snapshot, then retry or call browser_wait.`
1090
+ );
1091
+ }
1092
+ var capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
1093
+
1094
+ // src/tools.ts
1095
+ var SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
724
1096
  var REF = {
725
1097
  type: "string",
726
1098
  description: 'An element ref from the latest browser_snapshot, e.g. "e12".'
@@ -968,35 +1340,43 @@ var TYPE_AT = {
968
1340
  var WAIT = {
969
1341
  name: "browser_wait",
970
1342
  title: "Wait",
971
- 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.",
1343
+ description: "Wait until a text appears on the page, an element ref appears, the URL contains a string, a navigation finishes or a download finishes, or until the time cap passes. Pass at most one condition. A wait of 60000 ms or less runs in the call. A longer wait needs a condition: it parks the run without using turns and returns when the condition holds or the time passes, so prefer one long wait over repeated short ones; the user can end it early. A long wait also ends when the device reaches its running limit (often 2 hours) or the input timeout; in a scheduled task it holds the task's next runs back. 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.",
972
1344
  inputSchema: {
973
1345
  type: "object",
974
1346
  properties: {
975
1347
  text: { type: "string", description: "Wait for this text on the page." },
976
1348
  ref: REF,
1349
+ urlContains: {
1350
+ type: "string",
1351
+ description: `Wait until the active tab's URL contains this string, e.g. "/orders/paid".`
1352
+ },
977
1353
  navigation: { type: "boolean", description: "Wait for the next navigation to finish." },
1354
+ download: {
1355
+ type: "boolean",
1356
+ description: "Wait for the next download to finish saving into the workspace."
1357
+ },
978
1358
  timeoutMs: {
979
1359
  type: "integer",
980
1360
  minimum: 0,
981
1361
  maximum: WAIT_MAX_MS,
982
- description: `The time cap in milliseconds (default ${WAIT_DEFAULT_MS}).`
1362
+ description: `The time cap in milliseconds (default ${WAIT_DEFAULT_MS}); over 60000 needs a condition.`
983
1363
  }
984
1364
  },
985
1365
  additionalProperties: false
986
1366
  },
987
- keyArgs: ["text", "timeoutMs"],
1367
+ keyArgs: ["text", "urlContains", "timeoutMs"],
988
1368
  defaultPolicy: "allow",
989
1369
  // any tool may start the device first (see TOOL_TIMEOUT_MS)
990
1370
  timeoutMs: TOOL_TIMEOUT_MS
991
1371
  };
992
1372
  var obj = (input) => typeof input === "object" && input !== null ? input : {};
993
- var str = (v) => typeof v === "string" ? v : void 0;
1373
+ var str3 = (v) => typeof v === "string" ? v : void 0;
994
1374
  var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
995
1375
  function defined(o) {
996
1376
  return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
997
1377
  }
998
1378
  function need(v, field, tool) {
999
- if (v === void 0) throw new ToolError3(`${tool} needs ${field}; pass it and retry.`);
1379
+ if (v === void 0) throw new ToolError4(`${tool} needs ${field}; pass it and retry.`);
1000
1380
  return v;
1001
1381
  }
1002
1382
  var namesTab = (a) => a === "switch" || a === "close" || a === "adopt";
@@ -1010,23 +1390,23 @@ function registerBrowserTools(ctx, deps) {
1010
1390
  ctx.tools.register(
1011
1391
  NAVIGATE,
1012
1392
  handler(deps, (i) => {
1013
- const url = str(i.url);
1014
- const action = str(i.action);
1393
+ const url = str3(i.url);
1394
+ const action = str3(i.action);
1015
1395
  if (url === void 0 === (action === void 0))
1016
- throw new ToolError3("browser_navigate needs either a url or an action; pass exactly one.");
1396
+ throw new ToolError4("browser_navigate needs either a url or an action; pass exactly one.");
1017
1397
  return defined({ op: "navigate", url, action });
1018
1398
  })
1019
1399
  );
1020
1400
  ctx.tools.register(
1021
1401
  TABS,
1022
1402
  handler(deps, (i) => {
1023
- const action = need(str(i.action), "an action", "browser_tabs");
1024
- const tabId = str(i.tabId);
1403
+ const action = need(str3(i.action), "an action", "browser_tabs");
1404
+ const tabId = str3(i.tabId);
1025
1405
  if (namesTab(action) && (tabId === void 0 || tabId === ""))
1026
- throw new ToolError3(
1406
+ throw new ToolError4(
1027
1407
  `browser_tabs needs a tabId for ${action}; call browser_tabs with action list for the tab ids, then retry.`
1028
1408
  );
1029
- return defined({ op: "tabs", action, tabId, url: str(i.url) });
1409
+ return defined({ op: "tabs", action, tabId, url: str3(i.url) });
1030
1410
  })
1031
1411
  );
1032
1412
  ctx.tools.register(
@@ -1047,7 +1427,7 @@ function registerBrowserTools(ctx, deps) {
1047
1427
  try {
1048
1428
  return toResult(await shot(SCREENSHOT_MAX_BYTES));
1049
1429
  } catch (e) {
1050
- if (!(e instanceof ToolError3) || !e.message.startsWith(REPLY_TOO_LARGE_MESSAGE)) throw e;
1430
+ if (!(e instanceof ToolError4) || !e.message.startsWith(REPLY_TOO_LARGE_MESSAGE)) throw e;
1051
1431
  return toResult(await shot(Math.floor(SCREENSHOT_MAX_BYTES / 2)));
1052
1432
  }
1053
1433
  });
@@ -1055,7 +1435,7 @@ function registerBrowserTools(ctx, deps) {
1055
1435
  CLICK,
1056
1436
  handler(deps, (i) => ({
1057
1437
  op: "click",
1058
- ref: need(str(i.ref), "a ref", "browser_click")
1438
+ ref: need(str3(i.ref), "a ref", "browser_click")
1059
1439
  }))
1060
1440
  );
1061
1441
  ctx.tools.register(
@@ -1064,8 +1444,8 @@ function registerBrowserTools(ctx, deps) {
1064
1444
  deps,
1065
1445
  (i) => defined({
1066
1446
  op: "type",
1067
- ref: need(str(i.ref), "a ref", "browser_type"),
1068
- text: need(str(i.text), "text", "browser_type"),
1447
+ ref: need(str3(i.ref), "a ref", "browser_type"),
1448
+ text: need(str3(i.text), "text", "browser_type"),
1069
1449
  submit: typeof i.submit === "boolean" ? i.submit : void 0
1070
1450
  })
1071
1451
  )
@@ -1074,7 +1454,7 @@ function registerBrowserTools(ctx, deps) {
1074
1454
  SELECT,
1075
1455
  handler(deps, (i) => ({
1076
1456
  op: "select",
1077
- ref: need(str(i.ref), "a ref", "browser_select"),
1457
+ ref: need(str3(i.ref), "a ref", "browser_select"),
1078
1458
  values: Array.isArray(i.values) ? i.values.filter((v) => typeof v === "string") : []
1079
1459
  }))
1080
1460
  );
@@ -1082,7 +1462,7 @@ function registerBrowserTools(ctx, deps) {
1082
1462
  PRESS,
1083
1463
  handler(deps, (i) => ({
1084
1464
  op: "press",
1085
- key: need(str(i.key), "a key", "browser_press")
1465
+ key: need(str3(i.key), "a key", "browser_press")
1086
1466
  }))
1087
1467
  );
1088
1468
  ctx.tools.register(
@@ -1091,7 +1471,7 @@ function registerBrowserTools(ctx, deps) {
1091
1471
  deps,
1092
1472
  (i) => defined({
1093
1473
  op: "scroll",
1094
- ref: str(i.ref),
1474
+ ref: str3(i.ref),
1095
1475
  dy: need(num(i.dy), "dy", "browser_scroll")
1096
1476
  })
1097
1477
  )
@@ -1100,15 +1480,15 @@ function registerBrowserTools(ctx, deps) {
1100
1480
  HOVER,
1101
1481
  handler(deps, (i) => ({
1102
1482
  op: "hover",
1103
- ref: need(str(i.ref), "a ref", "browser_hover")
1483
+ ref: need(str3(i.ref), "a ref", "browser_hover")
1104
1484
  }))
1105
1485
  );
1106
1486
  ctx.tools.register(
1107
1487
  UPLOAD,
1108
1488
  handler(deps, (i) => ({
1109
1489
  op: "upload",
1110
- ref: need(str(i.ref), "a ref", "browser_upload"),
1111
- path: need(str(i.path), "a path", "browser_upload")
1490
+ ref: need(str3(i.ref), "a ref", "browser_upload"),
1491
+ path: need(str3(i.path), "a path", "browser_upload")
1112
1492
  }))
1113
1493
  );
1114
1494
  ctx.tools.register(
@@ -1125,33 +1505,17 @@ function registerBrowserTools(ctx, deps) {
1125
1505
  op: "type_at",
1126
1506
  x: need(num(i.x), "x", "browser_type_at"),
1127
1507
  y: need(num(i.y), "y", "browser_type_at"),
1128
- text: need(str(i.text), "text", "browser_type_at")
1508
+ text: need(str3(i.text), "text", "browser_type_at")
1129
1509
  }))
1130
1510
  );
1131
- ctx.tools.register(
1132
- WAIT,
1133
- handler(
1134
- deps,
1135
- (i) => defined({
1136
- op: "wait",
1137
- text: str(i.text),
1138
- ref: str(i.ref),
1139
- navigation: i.navigation === true ? true : void 0,
1140
- timeoutMs: Math.max(
1141
- 0,
1142
- Math.min(WAIT_MAX_MS, Math.floor(num(i.timeoutMs) ?? WAIT_DEFAULT_MS))
1143
- )
1144
- }),
1145
- (r) => (r.op === "wait" ? r.timeoutMs : 0) + REQUEST_TIMEOUT_MS
1146
- )
1147
- );
1511
+ ctx.tools.register(WAIT, waitHandler(deps), { watch: waitWatcher(deps) });
1148
1512
  }
1149
1513
 
1150
1514
  // src/index.ts
1151
1515
  var index_default = defineExtension({
1152
1516
  name: "browser",
1153
- version: "0.1.0-rc.11",
1154
- sdk: "^0.1.0-rc.75",
1517
+ version: "0.1.0-rc.12",
1518
+ sdk: "^0.1.0-rc.83",
1155
1519
  provides: [],
1156
1520
  ui: [
1157
1521
  {
@@ -1179,7 +1543,8 @@ var index_default = defineExtension({
1179
1543
  "browser_click_at",
1180
1544
  "browser_type_at",
1181
1545
  "browser_wait",
1182
- "browser_handoff"
1546
+ "browser_handoff",
1547
+ "browser_dialog"
1183
1548
  ],
1184
1549
  http: [
1185
1550
  { method: "GET", path: "/ui/browser", access: "public" },
@@ -1203,6 +1568,7 @@ var index_default = defineExtension({
1203
1568
  const deps = { deviceAccess, serviceSpec: serviceSpecLoader(), log: ctx.log };
1204
1569
  registerBrowserTools(ctx, deps);
1205
1570
  registerHandoffTool(ctx, deps);
1571
+ registerDialogTool(ctx, deps);
1206
1572
  registerRoutes(ctx, { deviceAccess, panelScript: panelScriptLoader() });
1207
1573
  }
1208
1574
  });