@parcha/pi-browser 0.1.0-beta.32 → 0.1.0-beta.321

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 (109) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/NOTICE +36 -1
  3. package/README.md +91 -231
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +26 -35
  6. package/dist/core/custody.d.ts +12 -0
  7. package/dist/core/custody.js +21 -3
  8. package/dist/core/downloads.d.ts +37 -3
  9. package/dist/core/downloads.js +81 -57
  10. package/dist/core/driving-guard.d.ts +1 -1
  11. package/dist/core/driving-guard.js +18 -3
  12. package/dist/core/evidence.d.ts +1 -1
  13. package/dist/core/files.d.ts +20 -2
  14. package/dist/core/files.js +161 -10
  15. package/dist/core/host.d.ts +18 -75
  16. package/dist/core/images.d.ts +32 -4
  17. package/dist/core/images.js +81 -16
  18. package/dist/core/lease.d.ts +2 -1
  19. package/dist/core/page-scan.d.ts +81 -2
  20. package/dist/core/page-scan.js +487 -13
  21. package/dist/core/public-fetch.d.ts +70 -9
  22. package/dist/core/public-fetch.js +348 -51
  23. package/dist/core/read-page-worker.js +5 -4
  24. package/dist/core/read-page.d.ts +23 -8
  25. package/dist/core/read-page.js +64 -20
  26. package/dist/core/redact.d.ts +0 -2
  27. package/dist/core/redact.js +0 -32
  28. package/dist/core/session-control.d.ts +0 -2
  29. package/dist/core/session-control.js +0 -5
  30. package/dist/core/tools.d.ts +32 -1
  31. package/dist/core/tools.js +46 -4
  32. package/dist/core/usage.d.ts +4 -3
  33. package/dist/core/usage.js +5 -4
  34. package/dist/core/vault.d.ts +0 -10
  35. package/dist/core/vault.js +0 -13
  36. package/dist/core/web.d.ts +2 -111
  37. package/dist/core/web.js +0 -443
  38. package/dist/driver/cdp.d.ts +6 -0
  39. package/dist/driver/cdp.js +245 -0
  40. package/dist/driver/page-driver.js +36 -6
  41. package/dist/driver/stagehand.d.ts +3 -1
  42. package/dist/driver/stagehand.js +4 -2
  43. package/dist/durable/store.d.ts +14 -3
  44. package/dist/durable/store.js +217 -55
  45. package/dist/durable.d.ts +33 -16
  46. package/dist/durable.js +69 -95
  47. package/dist/index.d.ts +3 -3
  48. package/dist/index.js +5 -3
  49. package/dist/live-view/index.d.ts +3 -1
  50. package/dist/live-view/index.js +4 -0
  51. package/dist/live-view/protocol.d.ts +1 -1
  52. package/dist/live-view/provider.d.ts +2 -2
  53. package/dist/live-view/provider.js +2 -2
  54. package/dist/live-view/server.d.ts +31 -1
  55. package/dist/live-view/server.js +152 -25
  56. package/dist/providers/cdp.js +2 -2
  57. package/dist/providers/chrome-args.d.ts +3 -0
  58. package/dist/providers/chrome-args.js +13 -2
  59. package/dist/providers/profiles.d.ts +1 -15
  60. package/dist/providers/profiles.js +1 -64
  61. package/dist/providers/shared.d.ts +1 -47
  62. package/dist/providers/shared.js +1 -82
  63. package/dist/providers/worker-extension.d.ts +14 -1
  64. package/dist/providers/worker-extension.js +69 -3
  65. package/dist/testing/backend.d.ts +6 -24
  66. package/dist/testing/backend.js +7 -30
  67. package/dist/vault-session.d.ts +4 -7
  68. package/dist/vault-session.js +26 -81
  69. package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
  70. package/dist/vendor/browser-use-pi/ax.js +642 -0
  71. package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
  72. package/dist/vendor/browser-use-pi/cdp.js +106 -0
  73. package/dist/vendor/browser-use-pi/page.d.ts +29 -0
  74. package/dist/vendor/browser-use-pi/page.js +99 -0
  75. package/package.json +14 -45
  76. package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
  77. package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
  78. package/dist/coding-agent-local.d.ts +0 -12
  79. package/dist/coding-agent-local.js +0 -72
  80. package/dist/coding-agent.d.ts +0 -135
  81. package/dist/coding-agent.js +0 -641
  82. package/dist/core/sites.d.ts +0 -33
  83. package/dist/core/sites.js +0 -104
  84. package/dist/durable/web.d.ts +0 -47
  85. package/dist/durable/web.js +0 -41
  86. package/dist/providers/assigned.d.ts +0 -18
  87. package/dist/providers/assigned.js +0 -75
  88. package/dist/providers/browserbase-net.d.ts +0 -12
  89. package/dist/providers/browserbase-net.js +0 -95
  90. package/dist/providers/browserbase.d.ts +0 -169
  91. package/dist/providers/browserbase.js +0 -319
  92. package/dist/providers/kernel.d.ts +0 -58
  93. package/dist/providers/kernel.js +0 -291
  94. package/dist/recorder/credential.d.ts +0 -9
  95. package/dist/recorder/credential.js +0 -49
  96. package/dist/recorder/follow.d.ts +0 -36
  97. package/dist/recorder/follow.js +0 -163
  98. package/dist/recorder/frames.d.ts +0 -87
  99. package/dist/recorder/frames.js +0 -377
  100. package/dist/recorder/index.d.ts +0 -4
  101. package/dist/recorder/index.js +0 -7
  102. package/dist/recorder/jpeg.d.ts +0 -8
  103. package/dist/recorder/jpeg.js +0 -70
  104. package/dist/recorder/track.d.ts +0 -107
  105. package/dist/recorder/track.js +0 -280
  106. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
  107. package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
  108. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  109. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -0,0 +1,245 @@
1
+ import { refusedError } from "../core/custody.js";
2
+ import { openDial } from "../core/dial.js";
3
+ import { AxHelpers, UnknownIdError } from "../vendor/browser-use-pi/ax.js";
4
+ import { CDP, CDPConnectionClosedError } from "../vendor/browser-use-pi/cdp.js";
5
+ import { Page } from "../vendor/browser-use-pi/page.js";
6
+ import { NAVIGATED_SNAPSHOT_ERROR, NO_HYDRATED_SNAPSHOT_ERROR, STALE_SNAPSHOT_ID_ERROR } from "../core/failures.js";
7
+ /** The package's stale-snapshot words, as the Stagehand driver says them: plain errors, so a failure reads them as a stale snapshot. */
8
+ const stale = (message) => new Error(message);
9
+ const staleSnapshotIdError = (id) => STALE_SNAPSHOT_ID_ERROR.replace("${id}", id);
10
+ /** What `run` with code is told on this browser. */
11
+ export const CDP_CODE_REFUSED = 'run code is not available on this browser (the agent\'s browser computer): send actions instead, each an op with a snapshot id and a value, for example {"actions":[{"op":"click","id":"0-42"}]}, and navigate with {"actions":[{"op":"goto","url":"https://example.com"}]}. Read the page with browser_read.';
12
+ /** How long one CDP command may take before the action is said to be unanswered. */
13
+ const COMMAND_MS = 30_000;
14
+ /**
15
+ * One element's box once it is scrolled into view, in CSS pixels from the top page's viewport corner, or how many a
16
+ * selector matches. An element in a same-origin iframe (an id from the snapshot) gets each enclosing frame's
17
+ * content-box offset added, and the viewport is the top page's, as the screenshot's clip is.
18
+ */
19
+ const LOCATE_JS = `function(selector){
20
+ let top = (this && this.ownerDocument ? this.ownerDocument : document).defaultView;
21
+ while (top.frameElement) top = top.parent;
22
+ const viewport = { width: top.innerWidth, height: top.innerHeight };
23
+ const found = selector === null ? null : selector === undefined ? this : document.querySelectorAll(selector);
24
+ if (found === null) return { viewport };
25
+ const list = found instanceof NodeList ? [...found] : [found.nodeType === 1 ? found : found.parentElement];
26
+ if (list.length !== 1 || !list[0]) return { viewport, matches: list.filter(Boolean).length };
27
+ list[0].scrollIntoView({ block: 'center', inline: 'center' });
28
+ const r = list[0].getBoundingClientRect();
29
+ let x = r.x, y = r.y;
30
+ for (let w = list[0].ownerDocument.defaultView; w && w.frameElement; w = w.parent) {
31
+ const f = w.frameElement, fr = f.getBoundingClientRect(), cs = getComputedStyle(f);
32
+ x += fr.x + f.clientLeft + parseFloat(cs.paddingLeft);
33
+ y += fr.y + f.clientTop + parseFloat(cs.paddingTop);
34
+ }
35
+ return { viewport, matches: 1, box: { x, y, width: r.width, height: r.height } };
36
+ }`;
37
+ /** The browser's tabs, in the browser's order (DevTools' own pages left out). */
38
+ async function tabsOf(cdp) {
39
+ const { targetInfos } = await cdp.send("Target.getTargets");
40
+ return targetInfos.filter((t) => t.type === "page" && !t.url.startsWith("devtools://"));
41
+ }
42
+ /** A blank tab opened for the driver, when the browser has none. */
43
+ async function blankTab(cdp) {
44
+ return (await cdp.send("Target.createTarget", { url: "about:blank" })).targetId;
45
+ }
46
+ /** The raw-CDP page driver: snapshot ids and actions only. */
47
+ export function cdpDriver() {
48
+ return async (target, signal) => {
49
+ signal?.throwIfAborted();
50
+ const cdp = await CDP.open(openDial(target), COMMAND_MS);
51
+ let page;
52
+ /** Every tab the driver has seen, so one that appears later is known as new. */
53
+ const seen = new Set();
54
+ /** The tab that opened each tab the driver followed, to go back to when that one closes. */
55
+ const openers = new Map();
56
+ /** Whether the last run moved to another tab (movedTab). */
57
+ let movedTab = false;
58
+ try {
59
+ const tabs = await tabsOf(cdp);
60
+ for (const t of tabs)
61
+ seen.add(t.targetId);
62
+ // The browser's first tab, or a blank one opened for the driver when it has none.
63
+ page = await Page.attach(cdp, tabs[0]?.targetId ?? (await blankTab(cdp)));
64
+ seen.add(page.targetId);
65
+ }
66
+ catch (error) {
67
+ cdp.close();
68
+ throw error;
69
+ }
70
+ const ax = new AxHelpers(() => page, () => cdp);
71
+ /**
72
+ * Drives the tab the driven tab opened (a popup, or a link that opens a new tab), or, when the driven tab has closed,
73
+ * the tab that opened it (else the browser's last, else a blank one). The old tab's snapshot ids are dropped, so an
74
+ * action by id fails as a stale snapshot until the next snapshot. Answers the line that says so, or nothing when
75
+ * the driven tab stays.
76
+ */
77
+ const follow = async () => {
78
+ const tabs = await tabsOf(cdp);
79
+ const opened = tabs.filter((t) => !seen.has(t.targetId) && t.openerId === page.targetId).at(-1);
80
+ for (const t of tabs)
81
+ seen.add(t.targetId);
82
+ let next = opened?.targetId;
83
+ if (!next && !tabs.some((t) => t.targetId === page.targetId)) {
84
+ const back = openers.get(page.targetId);
85
+ next = tabs.find((t) => t.targetId === back)?.targetId ?? tabs.at(-1)?.targetId ?? (await blankTab(cdp));
86
+ seen.add(next);
87
+ }
88
+ if (!next)
89
+ return undefined;
90
+ const old = page;
91
+ page = await Page.attach(cdp, next);
92
+ if (opened)
93
+ openers.set(next, old.targetId);
94
+ ax.forget();
95
+ await cdp.send("Target.detachFromTarget", { sessionId: old.sessionId }).catch(() => undefined);
96
+ await ax.settle({ capMs: 3000 }).catch(() => undefined);
97
+ const { targetInfo } = await cdp.send("Target.getTargetInfo", { targetId: next });
98
+ const now = opened ? "the page opened a new tab; now driving it" : "the tab closed; now driving another";
99
+ return `[tab] ${now}: ${targetInfo.url}.`;
100
+ };
101
+ /** The latest snapshot's ids hold: there is one, the page still shows its document, and every id is in it. */
102
+ const check = async (actions, checked = false) => {
103
+ if (actions.every((a) => a.op === "goto"))
104
+ return;
105
+ if (!ax.hydrated || !ax.taken)
106
+ throw stale(NO_HYDRATED_SNAPSHOT_ERROR);
107
+ if (!checked) {
108
+ // A probe the page can't answer is a navigated page; a dropped connection is said as one, not as a stale snapshot.
109
+ const now = await ax.probe().catch((error) => {
110
+ if (error instanceof CDPConnectionClosedError)
111
+ throw error;
112
+ return undefined;
113
+ });
114
+ if (!now || now.doc !== ax.taken.doc)
115
+ throw stale(NAVIGATED_SNAPSHOT_ERROR);
116
+ }
117
+ for (const action of actions) {
118
+ if (action.op === "goto")
119
+ break; // what follows a goto is on the next page: its ids are checked when it runs
120
+ try {
121
+ ax.nodeOf(action.id);
122
+ }
123
+ catch {
124
+ throw stale(staleSnapshotIdError(action.id));
125
+ }
126
+ }
127
+ };
128
+ const runOne = async (action) => {
129
+ switch (action.op) {
130
+ case "goto": {
131
+ const before = await ax.probe().catch(() => undefined);
132
+ await page.goto(action.url);
133
+ // The page's ids were the old document's: the next action by id fails as a stale snapshot.
134
+ ax.forget();
135
+ const settled = await ax.settle({ capMs: 3000 });
136
+ return `[ok] goto ${action.url} -> ${await ax.change(before, settled.probe)}`;
137
+ }
138
+ case "click":
139
+ return ax.click(action.id);
140
+ case "hover":
141
+ return ax.hover(action.id);
142
+ case "fill":
143
+ return ax.fill(action.id, action.value);
144
+ case "type":
145
+ return ax.type(action.id, action.text, action.delay);
146
+ case "press":
147
+ return ax.press(action.id, action.key);
148
+ case "select":
149
+ return ax.select(action.id, action.values);
150
+ default:
151
+ throw refusedError(`run takes the ops goto, click, hover, fill, type, press and select, not ${JSON.stringify(action.op)}`);
152
+ }
153
+ };
154
+ return {
155
+ // A snapshot is of the tab the agent is on now: a tab the page opened since, or the one left when it closed.
156
+ snapshot: async (options = {}) => {
157
+ const moved = await follow();
158
+ const shot = await ax.snapshot(options.includeIframes === undefined ? {} : { includeIframes: options.includeIframes });
159
+ return moved ? `${moved}\n${shot}` : shot;
160
+ },
161
+ run: async ({ code, actions, checked, rest: after = 0 }) => {
162
+ movedTab = false;
163
+ if (code !== undefined)
164
+ throw refusedError(CDP_CODE_REFUSED);
165
+ if (!actions?.length)
166
+ throw refusedError("run requires exactly one of code or actions");
167
+ await check(actions, checked === true);
168
+ const lines = [];
169
+ for (const [i, action] of actions.entries()) {
170
+ try {
171
+ lines.push(await runOne(action));
172
+ }
173
+ catch (error) {
174
+ // An id after a goto in the same run names nothing of the new page: a stale snapshot.
175
+ if (error instanceof UnknownIdError)
176
+ throw stale(staleSnapshotIdError(error.id));
177
+ if (!lines.length)
178
+ throw error;
179
+ // What ran is said with what failed: the actions before it took effect.
180
+ throw new Error(`${lines.join("\n")}\n${error instanceof Error ? error.message : String(error)}`, { cause: error });
181
+ }
182
+ // An action that opened a tab (or closed this one) moves the driver there; the rest name the old tab's ids.
183
+ // The action already took effect, so a failure to look is not its failure.
184
+ const moved = await follow().catch(() => undefined);
185
+ if (moved) {
186
+ movedTab = true;
187
+ lines.push(`${moved} Take a snapshot before acting by id.`);
188
+ // This run's actions after this one, and the batch's that the guard would send after them.
189
+ const rest = actions.length - i - 1 + after;
190
+ if (rest)
191
+ lines.push(`[stopped] ${rest} more action${rest === 1 ? "" : "s"} not run: they name the old tab's snapshot ids.`);
192
+ break;
193
+ }
194
+ }
195
+ return lines.join("\n");
196
+ },
197
+ movedTab: () => movedTab,
198
+ checkActions: (actions) => check(actions),
199
+ url: async () => {
200
+ const { targetInfo } = await cdp.send("Target.getTargetInfo", { targetId: page.targetId });
201
+ return targetInfo.url;
202
+ },
203
+ forgetSnapshots: () => ax.forget(),
204
+ locate: async (place) => {
205
+ if (place?.id !== undefined) {
206
+ let node;
207
+ try {
208
+ node = ax.nodeOf(place.id);
209
+ }
210
+ catch {
211
+ throw stale(ax.hydrated ? staleSnapshotIdError(place.id) : NO_HYDRATED_SNAPSHOT_ERROR);
212
+ }
213
+ const { object } = await page.cdp("DOM.resolveNode", { backendNodeId: node });
214
+ if (!object.objectId)
215
+ return { viewport: await page.evaluate(() => ({ width: innerWidth, height: innerHeight })), matches: 0 };
216
+ try {
217
+ const answer = await page.cdp("Runtime.callFunctionOn", { objectId: object.objectId, functionDeclaration: LOCATE_JS, arguments: [{ value: undefined }], returnByValue: true });
218
+ return answer.result.value;
219
+ }
220
+ finally {
221
+ await page.cdp("Runtime.releaseObject", { objectId: object.objectId }).catch(() => { });
222
+ }
223
+ }
224
+ const selector = place?.selector ?? null;
225
+ return page.evaluate(`(${LOCATE_JS}).call(document, ${JSON.stringify(selector)})`);
226
+ },
227
+ screenshot: async (options) => {
228
+ const data = await page.screenshot(options);
229
+ return { data, mimeType: options.type === "jpeg" ? "image/jpeg" : "image/png" };
230
+ },
231
+ // One evaluate reads all four, so they are one document's.
232
+ page: () => page.evaluate(() => ({
233
+ url: location.href,
234
+ title: document.title,
235
+ text: document.body ? document.body.innerText : "",
236
+ html: document.documentElement ? document.documentElement.outerHTML : "",
237
+ })),
238
+ // The browser keeps running: custody releases it through the provider.
239
+ close: async () => {
240
+ await cdp.send("Target.detachFromTarget", { sessionId: page.sessionId }).catch(() => undefined);
241
+ cdp.close();
242
+ },
243
+ };
244
+ };
245
+ }
@@ -133,6 +133,25 @@ export function pageDriver(stagehand, deadlines) {
133
133
  kept().set(page.pageId, { ...current, url: snapshot.url });
134
134
  }
135
135
  };
136
+ /** A batch with a goto: the actions one at a time, a goto through the facade's page (http, https or about:blank only), each
137
+ * other action by its id as the facade runs it, so an id after a goto meets the new page and fails as a stale snapshot. */
138
+ const withGoto = async (actions, checked) => {
139
+ if (!actions.some((action) => action.op === "goto"))
140
+ return checked ? afterChecked(actions) : facade.runActions(actions);
141
+ let completed = 0;
142
+ let url = "";
143
+ for (const action of actions) {
144
+ if (action.op === "goto") {
145
+ if (!/^(https?:\/\/|about:blank$)/i.test(action.url))
146
+ throw new Error(`goto takes an http or https URL (or about:blank), not ${JSON.stringify(action.url.slice(0, 100))}`);
147
+ url = await facade.run(`await page.goto(${JSON.stringify(action.url)}); return page.url();`);
148
+ }
149
+ else
150
+ url = (await facade.runActions([action])).url;
151
+ completed++;
152
+ }
153
+ return { completed, url };
154
+ };
136
155
  return {
137
156
  snapshot: async (snapshotOptions) => {
138
157
  const tree = await reads.snapshot(snapshotOptions);
@@ -142,19 +161,26 @@ export function pageDriver(stagehand, deadlines) {
142
161
  snapshotDocuments.set(page.pageId, { xpathById: taken.xpathById, document: documentOf(page) });
143
162
  return tree;
144
163
  },
145
- run: (input) => input.actions !== undefined ? (input.checked ? afterChecked(input.actions) : facade.runActions(input.actions)) : facade.run(input.code ?? ""),
164
+ run: (input) => input.actions !== undefined ? withGoto(input.actions, input.checked === true) : facade.run(input.code ?? ""),
146
165
  // As the facade's own batch checks a run's actions before it sends any (runActionsNow): the active page's snapshot,
147
- // the page still at its address, and every id in it. Read from the facade's snapshots, as forgetSnapshots does.
166
+ // the page still at its address, and every id in it. Read from the facade's snapshots, as forgetSnapshots does. A
167
+ // batch of gotos alone names no id, so it needs no snapshot, as the raw-CDP driver's check holds too.
148
168
  checkActions: async (actions) => {
169
+ if (actions.every((action) => action.op === "goto"))
170
+ return;
149
171
  const page = await active();
150
172
  const snapshot = facade.snapshotsByPage.get(page.pageId);
151
173
  if (!snapshot)
152
174
  throw new Error(NO_HYDRATED_SNAPSHOT_ERROR);
153
175
  if ((await page.url()) !== snapshot.url)
154
176
  throw new Error(NAVIGATED_SNAPSHOT_ERROR);
155
- for (const action of actions)
177
+ for (const action of actions) {
178
+ // What follows a goto is on the next page: its ids are checked when it runs.
179
+ if (action.op === "goto")
180
+ break;
156
181
  if (!snapshot.xpathById[action.id])
157
182
  throw new Error(staleSnapshotIdError(action.id));
183
+ }
158
184
  },
159
185
  url: async () => documentUrl(stagehand, await active()),
160
186
  // The facade keeps each page's last snapshot's ids for its own actions; with none, an action by id fails NO_HYDRATED (a stale snapshot).
@@ -179,12 +205,16 @@ export function pageDriver(stagehand, deadlines) {
179
205
  selector = target.selector;
180
206
  return await facade.run(locateCode(selector));
181
207
  }),
208
+ // Stagehand's page.screenshot scales to its device's pixels or to one per CSS pixel, and only a clip: a scale below 1
209
+ // is a clip (the viewport's, when none is asked) at one image pixel per CSS pixel, which is no smaller than that on a
210
+ // display of one device pixel per CSS pixel. A full page it does not scale (captureWithinBudget takes the viewport).
182
211
  screenshot: async ({ type = "png", quality, fullPage, scale, clip }) => {
212
+ const css = scale !== undefined && scale < 1;
183
213
  // A clip is read from the viewport's corner, and the browser's own is from the document's: the scroll offset is added.
184
- const origin = clip ? await facade.run(`return await page.evaluate("({ x: scrollX, y: scrollY })");`) : null;
214
+ const view = clip || (css && !fullPage) ? await facade.run(`return await page.evaluate("({ x: scrollX, y: scrollY, width: innerWidth, height: innerHeight })");`) : null;
215
+ const region = view && (clip ? { ...clip, x: clip.x + view.x, y: clip.y + view.y } : view);
185
216
  const bytes = await (await active()).screenshot({
186
- type, ...(fullPage === undefined ? {} : { fullPage }), ...(scale === undefined ? {} : { scale }),
187
- ...(clip && origin ? { clip: { ...clip, x: clip.x + origin.x, y: clip.y + origin.y } } : {}),
217
+ type, ...(region ? { clip: region } : fullPage === undefined ? {} : { fullPage }), ...(css ? { scale: "css" } : {}),
188
218
  // CDP takes a quality for jpeg only, and only as an integer.
189
219
  ...(type === "jpeg" && quality !== undefined ? { quality: Math.round(quality) } : {}),
190
220
  });
@@ -12,7 +12,9 @@ export declare const SEALED_STAGEHAND: {
12
12
  };
13
13
  };
14
14
  type StagehandModule = Pick<typeof import("@browserbasehq/stagehand"), "localBrowser" | "Stagehand">;
15
- /** The batch deadline comes from `DriverOptions`; a caller that passes none gets the facade's 60 s. Stagehand allows one
15
+ /** The batch deadline a caller that passes none in `DriverOptions` gets: 60 s, the facade's. */
16
+ export declare const DEFAULT_BATCH_TIMEOUT_MS = 60000;
17
+ /** The batch deadline comes from `DriverOptions`; a caller that passes none gets `DEFAULT_BATCH_TIMEOUT_MS`. Stagehand allows one
16
18
  * client per browser: an attach that fails or is cancelled after it connected disconnects again, and only then fails, so
17
19
  * the next attach never meets its slot still taken (Stagehand bounds the disconnect: 10 s for the detach). `internals` is
18
20
  * for tests: the Stagehand module the driver uses. */
@@ -7,7 +7,9 @@ export const SEALED_STAGEHAND = {
7
7
  cache: false,
8
8
  model: { generate: async () => { throw new Error(STAGEHAND_INFERENCE_REFUSED); } },
9
9
  };
10
- /** The batch deadline comes from `DriverOptions`; a caller that passes none gets the facade's 60 s. Stagehand allows one
10
+ /** The batch deadline a caller that passes none in `DriverOptions` gets: 60 s, the facade's. */
11
+ export const DEFAULT_BATCH_TIMEOUT_MS = 60_000;
12
+ /** The batch deadline comes from `DriverOptions`; a caller that passes none gets `DEFAULT_BATCH_TIMEOUT_MS`. Stagehand allows one
11
13
  * client per browser: an attach that fails or is cancelled after it connected disconnects again, and only then fails, so
12
14
  * the next attach never meets its slot still taken (Stagehand bounds the disconnect: 10 s for the detach). `internals` is
13
15
  * for tests: the Stagehand module the driver uses. */
@@ -20,7 +22,7 @@ export function stagehandDriver(internals = {}) {
20
22
  const browser = await untilCancelled(attachStep(host)(connecting), signal, (late) => late.disconnect());
21
23
  try {
22
24
  const stagehand = await untilCancelled(Stagehand.create({ browser, ...SEALED_STAGEHAND }), signal, () => undefined);
23
- return pageDriver(stagehand, { batchMs: options?.batchTimeoutMs ?? 60_000 });
25
+ return pageDriver(stagehand, { batchMs: options?.batchTimeoutMs ?? DEFAULT_BATCH_TIMEOUT_MS });
24
26
  }
25
27
  catch (error) {
26
28
  await browser.disconnect().catch(() => undefined);
@@ -1,4 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type ConversationDocToken, type ConversationId, type DocumentReader, type Harness, type TaskId, type Tx } from "@earendil-works/pi-durable";
3
3
  import type { BrowserConfig, BrowserProvider, HandoffOutcome, HandoffPort, InventoryRow, ReconcileReport, ReleaseReason, SessionChange, SessionRecord, SessionsState } from "../core/host.js";
4
4
  import type { LeaseRef, LeaseState } from "../core/lease.js";
@@ -6,6 +6,7 @@ export declare const now: () => string;
6
6
  /** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
7
7
  export declare const RELEASE_ATTEMPTS = 6;
8
8
  export declare const CONFIRM_POLLS = 5;
9
+ /** `owed` adds to the row's owed ids, `told` takes those told off it (InventoryRow.owed). */
9
10
  type Move = {
10
11
  state: LeaseState;
11
12
  resourceId?: string;
@@ -13,6 +14,8 @@ type Move = {
13
14
  at: string;
14
15
  notice?: "kept" | "lost";
15
16
  handoff?: string;
17
+ owed?: string[];
18
+ told?: string[];
16
19
  };
17
20
  /** `found`: the ids an earlier attempt (or a task this one succeeds) released under the row's tag, kept until the release
18
21
  * is billed: a provider's tag lookup lists running sessions only, so a later attempt no longer finds one it stopped. */
@@ -41,6 +44,8 @@ type HandoffResult = {
41
44
  outcome: HandoffOutcome;
42
45
  reason?: string;
43
46
  };
47
+ /** When the provider made each session a tag lookup found, by id (InventoryRow.made). */
48
+ type Made = Record<string, string>;
44
49
  export type StoreDeps = {
45
50
  name: string;
46
51
  Config: ConversationDocToken<BrowserConfig>;
@@ -59,8 +64,12 @@ export type StoreDeps = {
59
64
  handedBack?(tag: string, fence: number): void;
60
65
  /** A release task (an attempt, or its abort handler) had the provider release `tag`'s session, and the provider answered. */
61
66
  stopped?(tag: string): void;
67
+ /** A release by `row`'s tag ended sessions besides the row's own (`ids`, each confirmed no longer running): a create
68
+ * retried behind the provider, or a create race, left them. Their time is on no record (durable.ts, onRaceReleased).
69
+ * `made`: when the provider made each, where a tag lookup said (InventoryRow.made). */
70
+ raced?(row: InventoryRow, ids: string[], made: Made): Promise<void>;
62
71
  };
63
- export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook }: StoreDeps): {
72
+ export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook, raced }: StoreDeps): {
64
73
  Inventory: import("@earendil-works/pi-durable").SessionDocToken<{
65
74
  rows: Record<string, InventoryRow>;
66
75
  }>;
@@ -69,7 +78,9 @@ export declare function custodyStore({ name, Config, Sessions, providerOf, emit,
69
78
  begin: (tx: Tx, row: InventoryRow) => Promise<void>;
70
79
  requestRelease: (tx: Tx, row: InventoryRow, reason: ReleaseReason, at: string, notBefore?: number) => Promise<void>;
71
80
  bindByTag: (provider: BrowserProvider, row: InventoryRow, commit: (change: (tx: Tx) => Promise<void>) => Promise<unknown>, signal?: AbortSignal, found?: LeaseRef[]) => Promise<LeaseRef | null>;
72
- emitReleased: (cid: ConversationId, tag: string, read: DocumentReader, context: Context, at?: string) => Promise<void>;
81
+ emitReleased: (cid: ConversationId, tag: string, read: DocumentReader, context: Context, at?: string, found?: {
82
+ resourceId?: string;
83
+ }) => Promise<void>;
73
84
  ReleaseTask: import("@earendil-works/pi-durable").Task<ReleaseInput, ReleaseState, {
74
85
  released: number;
75
86
  }, object>;