@parcha/pi-browser 0.1.0-beta.31 → 0.1.0-beta.310

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 (125) hide show
  1. package/CHANGELOG.md +232 -0
  2. package/NOTICE +39 -4
  3. package/README.md +122 -236
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +27 -36
  6. package/dist/core/custody.d.ts +19 -2
  7. package/dist/core/custody.js +28 -6
  8. package/dist/core/downloads.d.ts +44 -3
  9. package/dist/core/downloads.js +94 -58
  10. package/dist/core/driving-guard.d.ts +20 -0
  11. package/dist/core/driving-guard.js +190 -23
  12. package/dist/core/driving.d.ts +56 -2
  13. package/dist/core/driving.js +189 -10
  14. package/dist/core/effects.d.ts +80 -6
  15. package/dist/core/effects.js +374 -41
  16. package/dist/core/evidence.d.ts +1 -1
  17. package/dist/core/failures.d.ts +15 -1
  18. package/dist/core/failures.js +7 -0
  19. package/dist/core/files.d.ts +20 -2
  20. package/dist/core/files.js +161 -10
  21. package/dist/core/host.d.ts +29 -77
  22. package/dist/core/images.d.ts +32 -4
  23. package/dist/core/images.js +81 -16
  24. package/dist/core/lease.d.ts +2 -1
  25. package/dist/core/page-scan.d.ts +81 -2
  26. package/dist/core/page-scan.js +487 -13
  27. package/dist/core/public-fetch.d.ts +70 -9
  28. package/dist/core/public-fetch.js +348 -51
  29. package/dist/core/read-page-worker.js +5 -4
  30. package/dist/core/read-page.d.ts +23 -8
  31. package/dist/core/read-page.js +64 -20
  32. package/dist/core/redact.d.ts +0 -2
  33. package/dist/core/redact.js +0 -32
  34. package/dist/core/session-control.d.ts +0 -2
  35. package/dist/core/session-control.js +0 -5
  36. package/dist/core/tools.d.ts +46 -1
  37. package/dist/core/tools.js +88 -12
  38. package/dist/core/usage.d.ts +4 -3
  39. package/dist/core/usage.js +5 -4
  40. package/dist/core/vault.d.ts +0 -10
  41. package/dist/core/vault.js +0 -13
  42. package/dist/core/web.d.ts +2 -111
  43. package/dist/core/web.js +0 -443
  44. package/dist/driver/cdp.d.ts +6 -0
  45. package/dist/driver/cdp.js +245 -0
  46. package/dist/driver/page-driver.js +110 -7
  47. package/dist/driver/sealed.d.ts +4 -12
  48. package/dist/driver/sealed.js +23 -37
  49. package/dist/driver/stagehand.d.ts +12 -15
  50. package/dist/driver/stagehand.js +21 -17
  51. package/dist/durable/result.d.ts +1 -2
  52. package/dist/durable/result.js +2 -2
  53. package/dist/durable/store.d.ts +17 -3
  54. package/dist/durable/store.js +231 -64
  55. package/dist/durable.d.ts +47 -17
  56. package/dist/durable.js +106 -105
  57. package/dist/index.d.ts +3 -3
  58. package/dist/index.js +5 -3
  59. package/dist/live-view/index.d.ts +4 -1
  60. package/dist/live-view/index.js +5 -0
  61. package/dist/live-view/protocol.d.ts +39 -7
  62. package/dist/live-view/protocol.js +2 -0
  63. package/dist/live-view/provider.d.ts +2 -2
  64. package/dist/live-view/provider.js +2 -2
  65. package/dist/live-view/server.d.ts +55 -2
  66. package/dist/live-view/server.js +282 -35
  67. package/dist/live-view/stream.js +16 -3
  68. package/dist/live-view/viewer.js +106 -13
  69. package/dist/providers/cdp.d.ts +0 -1
  70. package/dist/providers/cdp.js +35 -13
  71. package/dist/providers/chrome-args.d.ts +3 -0
  72. package/dist/providers/chrome-args.js +13 -2
  73. package/dist/providers/profiles.d.ts +1 -15
  74. package/dist/providers/profiles.js +1 -64
  75. package/dist/providers/shared.d.ts +1 -47
  76. package/dist/providers/shared.js +1 -82
  77. package/dist/providers/worker-extension.d.ts +20 -1
  78. package/dist/providers/worker-extension.js +86 -7
  79. package/dist/testing/backend.d.ts +6 -24
  80. package/dist/testing/backend.js +7 -30
  81. package/dist/vault-session.d.ts +4 -7
  82. package/dist/vault-session.js +26 -81
  83. package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
  84. package/dist/vendor/browser-use-pi/ax.js +642 -0
  85. package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
  86. package/dist/vendor/browser-use-pi/cdp.js +106 -0
  87. package/dist/vendor/browser-use-pi/page.d.ts +29 -0
  88. package/dist/vendor/browser-use-pi/page.js +99 -0
  89. package/package.json +15 -46
  90. package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
  91. package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
  92. package/dist/coding-agent-local.d.ts +0 -12
  93. package/dist/coding-agent-local.js +0 -72
  94. package/dist/coding-agent.d.ts +0 -134
  95. package/dist/coding-agent.js +0 -641
  96. package/dist/core/sites.d.ts +0 -33
  97. package/dist/core/sites.js +0 -104
  98. package/dist/driver/extension-worker.d.ts +0 -9
  99. package/dist/driver/extension-worker.js +0 -185
  100. package/dist/durable/web.d.ts +0 -47
  101. package/dist/durable/web.js +0 -41
  102. package/dist/providers/assigned.d.ts +0 -18
  103. package/dist/providers/assigned.js +0 -75
  104. package/dist/providers/browserbase-net.d.ts +0 -12
  105. package/dist/providers/browserbase-net.js +0 -95
  106. package/dist/providers/browserbase.d.ts +0 -169
  107. package/dist/providers/browserbase.js +0 -319
  108. package/dist/providers/kernel.d.ts +0 -58
  109. package/dist/providers/kernel.js +0 -291
  110. package/dist/recorder/credential.d.ts +0 -9
  111. package/dist/recorder/credential.js +0 -49
  112. package/dist/recorder/follow.d.ts +0 -36
  113. package/dist/recorder/follow.js +0 -163
  114. package/dist/recorder/frames.d.ts +0 -87
  115. package/dist/recorder/frames.js +0 -377
  116. package/dist/recorder/index.d.ts +0 -4
  117. package/dist/recorder/index.js +0 -7
  118. package/dist/recorder/jpeg.d.ts +0 -8
  119. package/dist/recorder/jpeg.js +0 -70
  120. package/dist/recorder/track.d.ts +0 -107
  121. package/dist/recorder/track.js +0 -280
  122. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
  123. package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
  124. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  125. /package/dist/{providers → core}/cdp-call.js +0 -0
package/dist/durable.js CHANGED
@@ -1,25 +1,23 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { configure, defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
3
- import { BROWSER_TOOL_NAMES, browserSection, browserToolsFor, listedFor, WEB_TOOL_NAMES } from "./core/contract.js";
4
- import { BrowserFailureError, closeDriver, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
2
+ import { defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
3
+ import { browserSection, browserToolsFor, listedFor } from "./core/contract.js";
4
+ import { BrowserFailureError, closeDriver, DRIVER_ACK_BEFORE_KILL_MS, settledWithin, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
5
5
  import { forModel } from "./durable/result.js";
6
6
  import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
7
7
  import { browserFailure, classifyBrowserError, isRefusal } from "./core/failures.js";
8
- import { workspaceFiles } from "./core/files.js";
9
8
  import { drivingGuarded } from "./core/driving-guard.js";
10
9
  import { drivingGates, keptFor, keptReason, personOn, rearmWhenLeft } from "./core/driving.js";
11
10
  import { captureFor, planRestore, untilQuiet, vaultRuntime } from "./vault-session.js";
12
11
  import { pageTools } from "./core/tools.js";
13
- import { useWebsite, useWebsiteContract } from "./core/sites.js";
14
12
  import { leaseTag } from "./core/lease.js";
15
13
  import { createRedactor, hostLiveView, redactContent, redactDeep, scrubPageUrl } from "./core/redact.js";
16
- import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, oneAtATime, providerKeyValues } from "./core/session-control.js";
14
+ import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, providerKeyValues } from "./core/session-control.js";
17
15
  import { custodyStore, now } from "./durable/store.js";
18
16
  import { answerOf, clearJournal, cutOf, cutsOf, inChain, journalOf, owed } from "./durable/journal.js";
19
17
  import { withinDeadline } from "./core/unanswered.js";
20
18
  import { resolvePrices, sessionCharge, withEstimate } from "./core/usage.js";
21
- export { createWebExtension } from "./durable/web.js";
22
19
  export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./durable/store.js";
20
+ export { HANDOFF_POLL_MS } from "./core/custody.js";
23
21
  const PLANE = "default";
24
22
  const UNCONFIGURED = { label: "", run: "", policy: DEFAULT_BROWSER_POLICY };
25
23
  const HANDOFF_ENDED = new BrowserFailureError(browserFailure("session_ended", "The browser session left the person's hands before their answer could be waited on. Your next browser call opens a fresh session; take a snapshot there before acting.", { retryable: true }));
@@ -48,13 +46,13 @@ async function drainReleases(name, harness, context, signal) {
48
46
  const open = (record) => record?.state === "live" || record?.state === "creating";
49
47
  const releasable = (record, reason) => open(record) || (record?.state === "held" && reason !== "idle");
50
48
  const waiting = (record) => new BrowserFailureError(waitingForHuman(record.handoff));
51
- // A child gets the browser and web tools only: never use_website, so it cannot start children of its own, and never
52
- // browser_upload or browser_downloads, since its report is all that crosses back (invariant 10) and a site run has no files.
53
- const CHILD_TOOLS = new Set([...BROWSER_TOOL_NAMES, ...WEB_TOOL_NAMES].filter((name) => name !== "browser_upload" && name !== "browser_downloads"));
54
49
  /** How long a release the store could not record may take at the provider. */
55
50
  const DIRECT_RELEASE_MS = 30_000;
56
51
  /** How long close waits to learn whether a Session that began closing failed. */
57
52
  const FAILED_END_MS = 5_000;
53
+ /** How long close, with no drain before it, waits for this process's close releases to reach the provider, as a direct
54
+ * release may take. */
55
+ const CLOSE_STOP_MS = DIRECT_RELEASE_MS;
58
56
  class Attachments {
59
57
  drivers = new Map();
60
58
  observers = new Map();
@@ -239,7 +237,6 @@ async function create(c, scope, overrides, presetTag) {
239
237
  const unsupported = profileRefusal(spec, provider.caps) ?? navigationRefusal(spec, provider);
240
238
  if (unsupported)
241
239
  throw new BrowserFailureError(unsupported);
242
- // The vault may name a context or profile for the provider; the record stored below is made from the spec WITHOUT it, so no context id reaches the store.
243
240
  const plan = await planRestore(c.vault, config.vault, provider, spec);
244
241
  const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now(), honours: provider.caps.settings });
245
242
  const row = rowOf(scope.cid, record);
@@ -249,6 +246,17 @@ async function create(c, scope, overrides, presetTag) {
249
246
  state.current[scope.plane] = state.sessions.length - 1;
250
247
  await c.store.begin(tx, row);
251
248
  });
249
+ // The host's barrier, with the record in the store: nothing is created at the provider until it is through.
250
+ if (c.options.beforeCreate) {
251
+ try {
252
+ await c.options.beforeCreate({ conversationId: scope.cid, tag, commit: scope.commit });
253
+ }
254
+ catch (error) {
255
+ await scope.commit((tx) => c.store.move(tx, row, { state: "released", reason: "create_failed", at: now() })).catch(() => undefined);
256
+ await c.store.emitReleased(scope.cid, tag, scope.read, scope.context).catch(() => undefined);
257
+ throw failure(error, scope, c.redact);
258
+ }
259
+ }
252
260
  // An answer lost on the way back is not a session that never started: it is settled by its tag.
253
261
  const ref = await provider.create(plan.spec, scope.signal).then(async (made) => {
254
262
  // Owned before it is recorded: a store that cannot record it still lets close release it.
@@ -273,9 +281,6 @@ async function create(c, scope, overrides, presetTag) {
273
281
  const live = { ...record, state: "live", resourceId: ref.id };
274
282
  try {
275
283
  const driver = await connect(c, scope, provider, ref, plan.afterAttach, plan.vaulted, plan.holdBack);
276
- // A context made for this session is given to the vault now, so a restart that loses the provider's memory of it still finds it.
277
- if (plan.fresh)
278
- await c.held.capture(ref.tag);
279
284
  await emit(c, scope.cid, config.label, live, "launched", provider);
280
285
  return { record: live, driver };
281
286
  }
@@ -572,7 +577,7 @@ function portFor(c, api, context) {
572
577
  for (;;) {
573
578
  const { state } = await api.waitForTask(task, context);
574
579
  if (state.outcome.status === "completed" && state.outcome.result) {
575
- const { outcome } = state.outcome.result;
580
+ const { outcome, reason } = state.outcome.result;
576
581
  // A sign-in just happened and the person has handed back: kept now, so a crash after it does not lose it.
577
582
  const current = currentRecord(await stateOf(c, scope), scope.plane);
578
583
  if (current)
@@ -581,7 +586,7 @@ function portFor(c, api, context) {
581
586
  if ((await stateOf(c, scope)).notice?.includes(told)) {
582
587
  await editState(c, scope, (sessions) => { sessions.notice = sessions.notice?.replace(told, "").replace(/\s+/g, " ").trim() || null; });
583
588
  }
584
- return { outcome };
589
+ return { outcome, ...(reason ? { reason } : {}) };
585
590
  }
586
591
  const next = await find();
587
592
  if (next === undefined || next === task)
@@ -641,15 +646,19 @@ async function releasePlane(c, conversation, reason, context, still = () => true
641
646
  const mine = () => c.held.tags().filter((tag) => c.owned.get(tag)?.cid === conversation.id);
642
647
  // Kept before anything closes: the browser is still there, and a release that is cancelled (a call since) only made one capture more.
643
648
  await Promise.all(leasesOf(c, conversation.id).map((tag) => captureSession(c, tag)));
644
- // Closing a driver needs nothing from the store, so a release other than idle's starts closing the conversation's
645
- // drivers first and never waits for the commit to do it; the commit runs alongside, so the release task starts as
646
- // early as before. An idle release leaves it to the commit, which can find a call since or a person on the live view.
649
+ // Ack-then-kill, "close" only (a new reason gets the wait by decision, not by default): its drivers' close gets DRIVER_ACK_BEFORE_KILL_MS to answer before the commit that ends the session.
647
650
  const closing = reason === "idle" ? Promise.resolve() : Promise.all(mine().map((tag) => c.held.detach(tag)));
651
+ if (reason === "close")
652
+ await settledWithin(closing, DRIVER_ACK_BEFORE_KILL_MS);
648
653
  const tags = await conversation.commit(async (tx) => {
649
654
  const state = await tx.doc(c.Sessions, conversation.id);
650
655
  const record = still() ? currentRecord(state, PLANE) : null;
651
656
  if (!record || !releasable(record, reason))
652
657
  return [];
658
+ // A run waiting for its person's answer keeps the session from an idle release; letting the keep go starts the idle
659
+ // window again (keepForPerson).
660
+ if (reason === "idle" && c.waiting.has(record.tag))
661
+ return [];
653
662
  // A person driving or watching the session through the live view keeps it from an idle release (#1098); it is
654
663
  // released one idle window after they leave.
655
664
  kept.gate = reason === "idle" ? personOn(c.options.gates ?? drivingGates, record.tag) : null;
@@ -657,11 +666,17 @@ async function releasePlane(c, conversation, reason, context, still = () => true
657
666
  if (kept.gate)
658
667
  return [];
659
668
  await c.store.requestRelease(tx, rowOf(conversation.id, record), reason, now());
669
+ if (reason === "close" && !c.stops.has(record.tag)) {
670
+ let stop = () => { };
671
+ const stopped = new Promise((resolve) => { stop = resolve; });
672
+ c.stops.set(record.tag, { stopped, stop, drained: false });
673
+ }
660
674
  if (reason === "idle" || reason === "close")
661
675
  c.store.addNotice(state, notices.released(reason, record.lastUrl, idleS));
662
676
  return [record.tag];
663
677
  }, context).catch(async (error) => {
664
678
  c.failed = true;
679
+ c.stops.delete(kept.tag);
665
680
  await closing;
666
681
  for (const tag of mine())
667
682
  await c.held.detach(tag);
@@ -689,6 +704,26 @@ async function releasePlane(c, conversation, reason, context, still = () => true
689
704
  c.leaving.set(tag, rearmWhenLeft(kept.gate, () => c.idle.keys().includes(conversation.id), () => { c.leaving.delete(tag); c.idle.activity(conversation.id, 0); }, idleS * 1000));
690
705
  }
691
706
  }
707
+ /** The open sessions' time through now, not final, in one commit (BrowserExtensionHandle.charge): no lock is taken, so a
708
+ * release under way (its record `releasing`) never holds it back. A record with no session id (its create under way, or
709
+ * its answer lost and the session not yet found by its tag) has nothing at the provider to bill yet: its release's charge
710
+ * bills the whole session once it is found. One already charged through now has no time to charge, and gets no $0 one. */
711
+ async function chargeOpen(c, conversation, context) {
712
+ return conversation.commit(async (tx) => {
713
+ const state = await tx.doc(c.Sessions, conversation.id);
714
+ const at = now();
715
+ let charged = 0;
716
+ for (const record of state.sessions) {
717
+ if ((record.state !== "live" && record.state !== "held" && record.state !== "releasing") || record.resourceId === null || record.spent.final)
718
+ continue;
719
+ if (Date.parse(record.spent.chargedThrough) >= Date.parse(at))
720
+ continue;
721
+ if (await c.bill(tx, conversation.id, record, at, false))
722
+ charged += 1;
723
+ }
724
+ return charged;
725
+ }, context);
726
+ }
692
727
  async function chargeCall(c, api, context) {
693
728
  if (currentRecord(await api.snapshot(c.Sessions, api.conversationId, context), PLANE)?.state !== "live")
694
729
  return null;
@@ -707,7 +742,7 @@ const withSessionTime = (own, charged) => {
707
742
  };
708
743
  function toolsFor(c, impls) {
709
744
  return browserToolsFor(c.options.signIns ?? !!c.options.sessionVault)
710
- .filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!(c.options.files || c.options.workspace), handoff: !!c.options.handoff }))
745
+ .filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!c.options.files, handoff: !!c.options.handoff }))
711
746
  .map((contract) => defineTool({
712
747
  name: contract.name,
713
748
  description: contract.description,
@@ -719,8 +754,7 @@ function toolsFor(c, impls) {
719
754
  c.idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
720
755
  try {
721
756
  const workspace = c.options.workspace?.(api.conversationId);
722
- const files = c.options.files ?? (workspace === undefined ? undefined : workspaceFiles(workspace));
723
- const call = { callId: api.callId, conversationId: api.conversationId, signal: context.abortSignal, label: config?.label ?? "", redact: c.redact, evidence: c.options.evidence, classifyPage: c.options.decisions?.classifyPage, workspace, files };
757
+ const call = { callId: api.callId, conversationId: api.conversationId, signal: context.abortSignal, label: config?.label ?? "", redact: c.redact, evidence: c.options.evidence, classifyPage: c.options.decisions?.classifyPage, workspace, files: c.options.files };
724
758
  // Inside an async function, so a host tool that throws before it returns a promise is caught too.
725
759
  const out = await (async () => impls[contract.name](args, portFor(c, api, context), call))().catch((error) => {
726
760
  // A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
@@ -750,82 +784,15 @@ function sectionFor(c, names) {
750
784
  return undefined;
751
785
  const config = await input.read.snapshot(c.Config, input.conversationId, context);
752
786
  const offered = (tool) => input.agent.tools.some((t) => t.name === tool && names.has(tool));
753
- return [browserSection({ idleReleaseS: config?.policy.idleReleaseS ?? UNCONFIGURED.policy.idleReleaseS }, { downloads: offered("browser_downloads"), upload: offered("browser_upload") }), c.options.section?.addendum].filter(Boolean).join("\n\n");
787
+ return [browserSection({ idleReleaseS: config?.policy.idleReleaseS ?? UNCONFIGURED.policy.idleReleaseS }, { downloads: offered("browser_downloads"), upload: offered("browser_upload"), signedIn: c.options.signIns ?? !!c.options.sessionVault }), c.options.section?.addendum].filter(Boolean).join("\n\n");
754
788
  },
755
789
  };
756
790
  }
757
- function childConversation(c, api, context) {
758
- return async (task) => {
759
- const config = await api.snapshot(c.Config, api.conversationId, context);
760
- const childTools = (await api.agent(context)).tools.filter((tool) => CHILD_TOOLS.has(tool.name));
761
- // One child per request, recorded in the commit that creates it: a replay or a repeated call finds it again, and
762
- // its submission is deduplicated by request_id.
763
- const id = await api.commit(async (tx) => {
764
- const children = await tx.doc(c.Children, api.conversationId);
765
- const key = `${task.site}:${task.requestId}`;
766
- const known = children.byRequest[key];
767
- if (known !== undefined)
768
- return known;
769
- const child = await tx.createConversation({ ownership: { kind: "task", taskId: api.taskId } });
770
- await configure(tx, child.id, { tools: childTools, instructions: null });
771
- Object.assign(await tx.doc(c.Config, child.id), config ?? UNCONFIGURED);
772
- children.byRequest[key] = child.id;
773
- return child.id;
774
- }, context);
775
- const child = await api.conversation(id, context);
776
- if (!child)
777
- throw new Error("the child conversation is gone");
778
- // Children on a provider whose sessions share one browser would drive the same pages, so there they take turns. One
779
- // whose provider cannot be looked up waits its turn too: its own browser calls ask the factory again.
780
- const shared = await providerOf(c, api, id, PLANE, context).then((provider) => provider.caps.sharedBrowser === true, () => true);
781
- // The turn covers the report and the release too: on a shared browser the next child attaches only once this one has let go.
782
- const run = async () => {
783
- try {
784
- const settled = await (await child.submit({ type: "input", content: task.prompt, requestId: task.requestId }, context)).wait(context);
785
- const report = await api.commit(async (tx) => {
786
- for (const entry of (await tx.scanEntries({ conversationId: id, order: "descending" }, 50)).items) {
787
- for (const message of [...(entry.model ?? [])].reverse()) {
788
- if (message.role !== "assistant")
789
- continue;
790
- const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
791
- if (text)
792
- return text;
793
- }
794
- }
795
- return "";
796
- }, context);
797
- if (settled.status !== "done" || !report)
798
- throw new Error("the child finished without a report");
799
- return report;
800
- }
801
- finally {
802
- await releasePlane(c, { id, commit: (change, ctx) => api.commit(change, ctx) }, "close", context).catch(() => undefined);
803
- }
804
- };
805
- return await (shared ? c.childTurns(run) : run());
806
- };
807
- }
808
- function siteTool(c, sites) {
809
- const contract = useWebsiteContract(sites.listing);
810
- return defineTool({
811
- name: contract.name,
812
- description: contract.description,
813
- parameters: contract.parameters,
814
- replay: contract.replay,
815
- executionMode: contract.executionMode,
816
- execute: async (args, api, context) => {
817
- const out = await useWebsite(args, sites.port, sites.listing, { signal: context.abortSignal ?? new AbortController().signal, runChild: childConversation(c, api, context) });
818
- return { ...forModel(redactContent(out.content, c.redact)), ...(out.isError ? { isError: true } : {}) };
819
- },
820
- });
821
- }
822
- /** pi-durable 1.2 on: a Session that a storage error failed ends with reason "failed" (`closed`), and close begins at
823
- * once (`subscribeClose`). Before 1.2 a Session has no such end, and a failed commit poisons it with no sign. */
791
+ /** A Session that a storage error failed ends `{ kind: "failed" }` (`closed`, pi-durable's SessionEnd), and close begins
792
+ * at once (`subscribeClose`). */
824
793
  function endingOf(harness) {
825
794
  const closed = harness.closed;
826
- if (typeof closed?.then !== "function")
827
- return null;
828
- const ending = { closing: false, failed: closed.then((end) => end.reason === "failed", () => false) };
795
+ const ending = { closing: false, failed: closed.then((end) => end.kind === "failed", () => false) };
829
796
  try {
830
797
  harness.subscribeClose(() => { ending.closing = true; });
831
798
  }
@@ -840,10 +807,9 @@ export function createBrowserExtension(options) {
840
807
  const tracked = new Set();
841
808
  const redact = createRedactor(() => [...providerKeyValues(process.env, options.redact?.values), ...tracked]);
842
809
  const vault = vaultRuntime(options, (secret) => { tracked.add(secret); }, (message) => process.emitWarning(`pi-browser: ${redact(message)}`, { code: "PI_BROWSER_VAULT" }));
843
- const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED) });
844
- const Children = defineDoc({ kind: `${name}.children`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ byRequest: {} }) });
810
+ const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED), checkpointWhen: () => false });
845
811
  // A fork starts with no sessions: it never shares a live browser.
846
- const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: emptySessions });
812
+ const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: emptySessions, checkpointWhen: () => false });
847
813
  const readers = { options, redact, Config };
848
814
  /** Class name and redacted message only: a vendor SDK's error text can repeat the request's credentials. */
849
815
  const scrubbed = (error) => Object.assign(new Error(redact(error instanceof Error ? error.message : String(error))), { name: error instanceof Error ? error.name : "Error" });
@@ -854,16 +820,16 @@ export function createBrowserExtension(options) {
854
820
  const listPriced = options.prices?.sessionUsdPerHour === undefined && prices.sessionUsdPerHour !== null;
855
821
  const meter = (spent, at, final = false) => {
856
822
  const charged = sessionCharge(spent, at, prices, priceState, final);
857
- return { spent: { ...withEstimate(spent, charged.spent, listPriced), state: charged.usage.state }, usage: charged.usage };
823
+ return { spent: { ...withEstimate(spent, charged.spent, listPriced), state: charged.usage.state }, usage: charged.usage, ...(charged.overbookedS === undefined ? {} : { overbookedS: charged.overbookedS }) };
858
824
  };
859
825
  const bill = async (tx, conversationId, record, at, final, call) => {
860
826
  const before = record.spent;
861
827
  if (before.final)
862
828
  return null;
863
- const { spent, usage } = meter(before, at, final);
829
+ const { spent, usage, overbookedS } = meter(before, at, final);
864
830
  record.spent = spent;
865
831
  const seconds = Math.round((spent.seconds - before.seconds) * 1000) / 1000;
866
- await options.onCharge?.({ conversationId, tag: record.tag, provider: record.provider, at, seconds, usd: usage.usage.cost.total, final, state: usage.state }, tx, call);
832
+ await options.onCharge?.({ conversationId, tag: record.tag, provider: record.provider, at, seconds, usd: usage.usage.cost.total, final, state: usage.state, ...(overbookedS === undefined ? {} : { overbookedS }) }, tx, call);
867
833
  return usage;
868
834
  };
869
835
  const leaving = new Map();
@@ -883,9 +849,17 @@ export function createBrowserExtension(options) {
883
849
  },
884
850
  handoff: options.handoff,
885
851
  handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
852
+ stopped: (tag) => { c.stops.get(tag)?.stop(); c.stops.delete(tag); },
853
+ raced: async (row, ids, made) => {
854
+ const madeAt = Object.fromEntries(ids.flatMap((id) => (made[id] ? [[id, made[id]]] : [])));
855
+ try {
856
+ await options.onRaceReleased?.({ conversationId: row.conversationId, tag: row.tag, ids, ...(Object.keys(madeAt).length ? { madeAt } : {}) });
857
+ }
858
+ catch { /* the host's booking never fails the release */ }
859
+ },
886
860
  });
887
861
  const c = {
888
- ...readers, name, Sessions, Children, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, serial: keyedSerializer(), childTurns: oneAtATime(), guards: new Map(), owned, failed: false, ending: null, opened: null, incarnation: randomUUID(),
862
+ ...readers, name, Sessions, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, waiting: new Map(), serial: keyedSerializer(), guards: new Map(), owned, failed: false, stops: new Map(), ending: null, opened: null, incarnation: randomUUID(),
889
863
  idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
890
864
  };
891
865
  // Every browser tool is a model call on its session's driving gate: refused while a person drives the live view, and the viewer's input is held while it runs. The host's own
@@ -894,12 +868,12 @@ export function createBrowserExtension(options) {
894
868
  // pi checks a call's arguments against the tool's schema before execute, so each implementation receives its own shape.
895
869
  const tools = toolsFor(c, own);
896
870
  const names = new Set(tools.map((tool) => tool.name));
897
- const siteTools = options.sites ? [siteTool(c, options.sites)] : [];
898
871
  return {
899
- extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [sectionFor(c, names)], tasks: [store.ReleaseTask, store.HandoffTask] }),
900
- docs: { Config, Sessions, Inventory: store.Inventory, Children },
901
- tools: [...tools, ...siteTools],
872
+ extension: defineExtension({ name, tools, sections: [sectionFor(c, names)], tasks: [store.ReleaseTask, store.HandoffTask] }),
873
+ docs: { Config, Sessions, Inventory: store.Inventory },
874
+ tools,
902
875
  release: (conversation, reason, context) => releasePlane(c, conversation, reason, context),
876
+ charge: (conversation, context) => chargeOpen(c, conversation, context),
903
877
  async reconcile(harness, isActive, context) {
904
878
  c.opened = { harness, context };
905
879
  c.ending = endingOf(harness);
@@ -912,7 +886,9 @@ export function createBrowserExtension(options) {
912
886
  }
913
887
  return report;
914
888
  },
915
- drain: (harness, context, signal) => drainReleases(name, harness, context, signal),
889
+ // The releases recorded so far are the drain's, however it ends (the host's signal may cut it short); a later one is not.
890
+ drain: (harness, context, signal) => { for (const wait of c.stops.values())
891
+ wait.drained = true; return drainReleases(name, harness, context, signal); },
916
892
  async close() {
917
893
  c.idle.clear();
918
894
  c.fences.clear();
@@ -921,6 +897,12 @@ export function createBrowserExtension(options) {
921
897
  c.leaving.clear();
922
898
  // A session whose driver was let go and not yet replaced still has its observer attached: close both kinds.
923
899
  await Promise.all(c.held.tags().map((tag) => c.held.detach(tag)));
900
+ // Closing the Harness cancels a release task that has not released yet. A host that closes with no drain after its
901
+ // close releases (the crash-and-resume example) gets them at the provider all the same: close waits for their tasks,
902
+ // at most CLOSE_STOP_MS, rather than counting on a slow driver close to have given them time. One a drain covered is
903
+ // not waited for again (the host bounded that wait itself); a Harness that runs no task leaves them to the next run.
904
+ await Promise.all([...c.stops.values()].filter((wait) => !wait.drained).map((wait) => settleWithin(wait.stopped, CLOSE_STOP_MS, undefined)));
905
+ c.stops.clear();
924
906
  // A store that failed runs no release task again, so what this process still holds is released at the provider.
925
907
  // Over a healthy store it is kept, for the next run to resume or reconcile.
926
908
  if (c.failed || (c.ending?.closing && await settleWithin(c.ending.failed, FAILED_END_MS, false)))
@@ -928,5 +910,24 @@ export function createBrowserExtension(options) {
928
910
  c.owned.clear();
929
911
  },
930
912
  retained: () => new Set([...c.guards.keys(), ...c.idle.keys(), ...c.serial.keys().map((key) => Number(key.slice(0, key.indexOf(":"))))]).size,
913
+ keepForPerson(tag) {
914
+ c.waiting.set(tag, (c.waiting.get(tag) ?? 0) + 1);
915
+ let kept = true;
916
+ return () => {
917
+ if (!kept)
918
+ return;
919
+ kept = false;
920
+ const left = (c.waiting.get(tag) ?? 1) - 1;
921
+ if (left > 0) {
922
+ c.waiting.set(tag, left);
923
+ return;
924
+ }
925
+ c.waiting.delete(tag);
926
+ // The idle window starts again from now, for a session still owned here.
927
+ const cid = c.owned.get(tag)?.cid;
928
+ if (cid !== undefined && c.idle.keys().includes(cid))
929
+ c.idle.activity(cid, 0);
930
+ };
931
+ },
931
932
  };
932
933
  }
package/dist/index.d.ts CHANGED
@@ -13,13 +13,13 @@ export * from "./core/host.js";
13
13
  export * from "./core/images.js";
14
14
  export * from "./core/lease.js";
15
15
  export * from "./core/page-classifier.js";
16
- export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch, type PublicAnswer, type PublicFetchOptions } from "./core/public-fetch.js";
17
- export { READ_DEADLINE_MS, READ_MAX_CHARS, readPage, type PageRead, type ReadPageOptions } from "./core/read-page.js";
16
+ export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicCheck, publicDownload, publicFetch, publicUpload, type PublicAnswer, type PublicFetchOptions, type PublicFile, type PublicUpload } from "./core/public-fetch.js";
17
+ export { PageReadOutOfMemory, READ_DEADLINE_MS, READ_LINKS_MAX, READ_LINKS_MAX_CHARS, READ_MAX_CHARS, READ_WORKER_HEAP_MB, readPage, type PageRead, type ReadPageOptions } from "./core/read-page.js";
18
18
  export * from "./core/receipts.js";
19
19
  export * from "./core/redact.js";
20
- export * from "./core/sites.js";
21
20
  export { DEFAULT_BROWSER_POLICY } from "./core/session-control.js";
22
21
  export * from "./core/tools.js";
23
22
  export * from "./core/usage.js";
24
23
  export * from "./core/web.js";
25
24
  export * from "./core/vault.js";
25
+ export { cdpCall, type CdpSession } from "./core/cdp-call.js";
package/dist/index.js CHANGED
@@ -14,13 +14,15 @@ export * from "./core/host.js";
14
14
  export * from "./core/images.js";
15
15
  export * from "./core/lease.js";
16
16
  export * from "./core/page-classifier.js";
17
- export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch } from "./core/public-fetch.js";
18
- export { READ_DEADLINE_MS, READ_MAX_CHARS, readPage } from "./core/read-page.js";
17
+ export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicCheck, publicDownload, publicFetch, publicUpload } from "./core/public-fetch.js";
18
+ export { PageReadOutOfMemory, READ_DEADLINE_MS, READ_LINKS_MAX, READ_LINKS_MAX_CHARS, READ_MAX_CHARS, READ_WORKER_HEAP_MB, readPage } from "./core/read-page.js";
19
19
  export * from "./core/receipts.js";
20
20
  export * from "./core/redact.js";
21
- export * from "./core/sites.js";
22
21
  export { DEFAULT_BROWSER_POLICY } from "./core/session-control.js";
23
22
  export * from "./core/tools.js";
24
23
  export * from "./core/usage.js";
25
24
  export * from "./core/web.js";
26
25
  export * from "./core/vault.js";
26
+ // One CDP call over its own socket, kept open for a setting that lasts as long as it (Browser.setDownloadBehavior): what a
27
+ // host holding a vendor's browser for the tool needs beside the driver.
28
+ export { cdpCall } from "./core/cdp-call.js";
@@ -1,4 +1,7 @@
1
- export { createLiveView, type LiveViewHost, type LiveViewOptions } from "./server.js";
1
+ export { createLiveView, type LiveViewHost, type LiveViewOptions, type TakeAnswer, type Watcher } from "./server.js";
2
2
  export { liveViewProvider } from "./provider.js";
3
3
  export * from "./protocol.js";
4
4
  export { createDrivingGates, drivingGates, personDrivingFailure, PERSON_DRIVING, withModelCall, type DrivingOptions } from "../core/driving.js";
5
+ export { viewerAssets } from "./viewer.js";
6
+ export { acceptWebSocket, type WsConn, type WsOptions } from "./ws.js";
7
+ export { newToken, newViewerId, tokenMatches } from "./token.js";
@@ -2,3 +2,8 @@ export { createLiveView } from "./server.js";
2
2
  export { liveViewProvider } from "./provider.js";
3
3
  export * from "./protocol.js";
4
4
  export { createDrivingGates, drivingGates, personDrivingFailure, PERSON_DRIVING, withModelCall } from "../core/driving.js";
5
+ export { viewerAssets } from "./viewer.js";
6
+ // The WebSocket server and the viewer's credentials, for another live view built on this protocol (serve's computer
7
+ // viewer, computer-live.ts): the same handshake, frames and token checks.
8
+ export { acceptWebSocket } from "./ws.js";
9
+ export { newToken, newViewerId, tokenMatches } from "./token.js";
@@ -1,5 +1,5 @@
1
- import type { DriveState, DrivingGate, DrivingGates } from "../core/driving.js";
2
- export type { DriveState, DrivingGate, DrivingGates };
1
+ import type { DriveState, DrivingGate, DrivingGates, HoldEnd } from "../core/driving.js";
2
+ export type { DriveState, DrivingGate, DrivingGates, HoldEnd };
3
3
  /** The viewer's first message, and nothing else is accepted before it. The token is read from the URL fragment by the viewer's script and
4
4
  * never travels in a path, a query or a header. */
5
5
  export type Hello = {
@@ -56,12 +56,37 @@ export type DialogAnswer = {
56
56
  accept: boolean;
57
57
  promptText?: string;
58
58
  };
59
- export type ClientMessage = Hello | InputMessage | NavMessage | DialogAnswer;
59
+ /** A take-over viewer's hands (LiveViewOptions.takeOver): `take` asks to hold the browser, `give` hands it back. */
60
+ export type HandsMessage = {
61
+ type: "take";
62
+ } | {
63
+ type: "give";
64
+ };
65
+ export type ClientMessage = Hello | InputMessage | NavMessage | DialogAnswer | HandsMessage;
60
66
  export type ServerMessage =
61
- /** Sent once, after a valid hello. */
67
+ /** Sent once, after a valid hello. `readOnly`: the viewer watches and never drives (LiveViewOptions.readOnly); `takeOver`: it drives only while
68
+ * it holds the browser (LiveViewOptions.takeOver), and `held` says whether it does now; neither: it may drive. */
62
69
  {
63
70
  type: "ready";
64
71
  drive: DriveState;
72
+ readOnly?: true;
73
+ takeOver?: true;
74
+ held?: boolean;
75
+ }
76
+ /** A take-over viewer's hold began (`held: true`), or ended (`held: false`, why, and the host's words when it gave them: a spend cap's). */
77
+ | {
78
+ type: "hold";
79
+ held: true;
80
+ } | {
81
+ type: "hold";
82
+ held: false;
83
+ reason: HoldEnd;
84
+ message?: string;
85
+ }
86
+ /** A `take` the host refused, in its words (a spend cap with no room for the person's time). Nothing changed. */
87
+ | {
88
+ type: "take_refused";
89
+ message: string;
65
90
  } | {
66
91
  type: "status";
67
92
  drive: DriveState;
@@ -71,6 +96,10 @@ export type ServerMessage =
71
96
  type: "page";
72
97
  url: string;
73
98
  title: string;
99
+ }
100
+ /** The browser has no page to show (one that starts with none, or whose last page closed): until a page opens there is nothing to draw. */
101
+ | {
102
+ type: "no_page";
74
103
  } | {
75
104
  type: "dialog";
76
105
  kind: "alert" | "confirm" | "prompt" | "beforeunload";
@@ -82,7 +111,7 @@ export type ServerMessage =
82
111
  /** One input or nav message was not delivered, and why. */
83
112
  | {
84
113
  type: "held";
85
- reason: "agent_acting" | "no_page" | "bad_message" | "busy";
114
+ reason: "agent_acting" | "no_page" | "bad_message" | "busy" | "read_only" | "not_taken" | "taking";
86
115
  } | {
87
116
  type: "refused";
88
117
  reason: RefusalReason;
@@ -111,7 +140,7 @@ export declare function decodeFrame(message: Uint8Array): {
111
140
  /** What stream.ts gives the server: one session's page, shown and driven over its browser's DevTools socket. */
112
141
  export type StreamHandlers = {
113
142
  /** The latest frame only. `ack` tells the browser to send the next: call it after the frame was sent to the viewer, or at once to drop it
114
- * (the viewer is slow). No frame is kept after the handler returns, and none is ever written anywhere. */
143
+ * (the viewer is slow). No frame is kept after the handler returns, and the stream writes none anywhere. */
115
144
  frame(jpeg: Buffer, page: {
116
145
  w: number;
117
146
  h: number;
@@ -120,6 +149,8 @@ export type StreamHandlers = {
120
149
  url: string;
121
150
  title: string;
122
151
  }): void;
152
+ /** The browser has no page to follow: none when the stream starts, or its last one closed. A page that opens next is announced by `page`. */
153
+ noPage?(): void;
123
154
  dialog(dialog: {
124
155
  kind: "alert" | "confirm" | "prompt" | "beforeunload";
125
156
  message: string;
@@ -130,7 +161,8 @@ export type StreamHandlers = {
130
161
  };
131
162
  export type Stream = {
132
163
  input(message: InputMessage): Promise<void>;
133
- nav(message: NavMessage): Promise<void>;
164
+ /** `live` is false once the command was let go (handed back, and the agent's call went on): a nav of several steps checks it before each. */
165
+ nav(message: NavMessage, live?: () => boolean): Promise<void>;
134
166
  dialog(answer: DialogAnswer): Promise<void>;
135
167
  close(): void;
136
168
  };
@@ -75,6 +75,8 @@ export function parseClientMessage(raw) {
75
75
  if (m.action === "back" || m.action === "reload")
76
76
  return { type: "nav", action: m.action };
77
77
  return m.action === "url" && word(m.url, LIMITS.url) && viewerMayOpen(m.url) ? { type: "nav", action: "url", url: m.url } : null;
78
+ case "take":
79
+ case "give": return Object.keys(m).length === 1 ? { type: m.type } : null;
78
80
  case "dialog":
79
81
  if (typeof m.accept !== "boolean" || (m.promptText !== undefined && (typeof m.promptText !== "string" || m.promptText.length > LIMITS.promptText)))
80
82
  return null;
@@ -1,6 +1,6 @@
1
1
  import type { BrowserProvider } from "../core/host.js";
2
2
  import type { LiveViewHost } from "./server.js";
3
3
  /** The provider with a live view: `liveView(ref)` reports the viewer's URL (to the host only: its `onSession` and a handoff's `request`), and a release kills the
4
- * token before the provider's own release runs, so a session that is going away cannot be driven. Wrap the cdp provider with it, as the frame recorder
5
- * wraps a provider with `watch`; the provider's own methods are untouched. */
4
+ * token before the provider's own release runs, so a session that is going away cannot be driven. Wrap the cdp provider with it; the provider's own
5
+ * methods are untouched. */
6
6
  export declare function liveViewProvider(provider: BrowserProvider, host: LiveViewHost): BrowserProvider;
@@ -1,6 +1,6 @@
1
1
  /** The provider with a live view: `liveView(ref)` reports the viewer's URL (to the host only: its `onSession` and a handoff's `request`), and a release kills the
2
- * token before the provider's own release runs, so a session that is going away cannot be driven. Wrap the cdp provider with it, as the frame recorder
3
- * wraps a provider with `watch`; the provider's own methods are untouched. */
2
+ * token before the provider's own release runs, so a session that is going away cannot be driven. Wrap the cdp provider with it; the provider's own
3
+ * methods are untouched. */
4
4
  export function liveViewProvider(provider, host) {
5
5
  const wrapped = Object.create(provider);
6
6
  wrapped.liveView = async (ref) => {