@parcha/pi-browser 0.1.0-beta.33 → 0.1.0-beta.331

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
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,9 +46,6 @@ 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. */
@@ -242,7 +237,6 @@ async function create(c, scope, overrides, presetTag) {
242
237
  const unsupported = profileRefusal(spec, provider.caps) ?? navigationRefusal(spec, provider);
243
238
  if (unsupported)
244
239
  throw new BrowserFailureError(unsupported);
245
- // 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.
246
240
  const plan = await planRestore(c.vault, config.vault, provider, spec);
247
241
  const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now(), honours: provider.caps.settings });
248
242
  const row = rowOf(scope.cid, record);
@@ -287,9 +281,6 @@ async function create(c, scope, overrides, presetTag) {
287
281
  const live = { ...record, state: "live", resourceId: ref.id };
288
282
  try {
289
283
  const driver = await connect(c, scope, provider, ref, plan.afterAttach, plan.vaulted, plan.holdBack);
290
- // 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.
291
- if (plan.fresh)
292
- await c.held.capture(ref.tag);
293
284
  await emit(c, scope.cid, config.label, live, "launched", provider);
294
285
  return { record: live, driver };
295
286
  }
@@ -655,15 +646,19 @@ async function releasePlane(c, conversation, reason, context, still = () => true
655
646
  const mine = () => c.held.tags().filter((tag) => c.owned.get(tag)?.cid === conversation.id);
656
647
  // Kept before anything closes: the browser is still there, and a release that is cancelled (a call since) only made one capture more.
657
648
  await Promise.all(leasesOf(c, conversation.id).map((tag) => captureSession(c, tag)));
658
- // Closing a driver needs nothing from the store, so a release other than idle's starts closing the conversation's
659
- // drivers first and never waits for the commit to do it; the commit runs alongside, so the release task starts as
660
- // 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.
661
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);
662
653
  const tags = await conversation.commit(async (tx) => {
663
654
  const state = await tx.doc(c.Sessions, conversation.id);
664
655
  const record = still() ? currentRecord(state, PLANE) : null;
665
656
  if (!record || !releasable(record, reason))
666
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 [];
667
662
  // A person driving or watching the session through the live view keeps it from an idle release (#1098); it is
668
663
  // released one idle window after they leave.
669
664
  kept.gate = reason === "idle" ? personOn(c.options.gates ?? drivingGates, record.tag) : null;
@@ -709,6 +704,26 @@ async function releasePlane(c, conversation, reason, context, still = () => true
709
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));
710
705
  }
711
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
+ }
712
727
  async function chargeCall(c, api, context) {
713
728
  if (currentRecord(await api.snapshot(c.Sessions, api.conversationId, context), PLANE)?.state !== "live")
714
729
  return null;
@@ -727,7 +742,7 @@ const withSessionTime = (own, charged) => {
727
742
  };
728
743
  function toolsFor(c, impls) {
729
744
  return browserToolsFor(c.options.signIns ?? !!c.options.sessionVault)
730
- .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 }))
731
746
  .map((contract) => defineTool({
732
747
  name: contract.name,
733
748
  description: contract.description,
@@ -739,8 +754,7 @@ function toolsFor(c, impls) {
739
754
  c.idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
740
755
  try {
741
756
  const workspace = c.options.workspace?.(api.conversationId);
742
- const files = c.options.files ?? (workspace === undefined ? undefined : workspaceFiles(workspace));
743
- 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 };
744
758
  // Inside an async function, so a host tool that throws before it returns a promise is caught too.
745
759
  const out = await (async () => impls[contract.name](args, portFor(c, api, context), call))().catch((error) => {
746
760
  // A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
@@ -770,75 +784,10 @@ function sectionFor(c, names) {
770
784
  return undefined;
771
785
  const config = await input.read.snapshot(c.Config, input.conversationId, context);
772
786
  const offered = (tool) => input.agent.tools.some((t) => t.name === tool && names.has(tool));
773
- 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");
774
788
  },
775
789
  };
776
790
  }
777
- function childConversation(c, api, context) {
778
- return async (task) => {
779
- const config = await api.snapshot(c.Config, api.conversationId, context);
780
- const childTools = (await api.agent(context)).tools.filter((tool) => CHILD_TOOLS.has(tool.name));
781
- // One child per request, recorded in the commit that creates it: a replay or a repeated call finds it again, and
782
- // its submission is deduplicated by request_id.
783
- const id = await api.commit(async (tx) => {
784
- const children = await tx.doc(c.Children, api.conversationId);
785
- const key = `${task.site}:${task.requestId}`;
786
- const known = children.byRequest[key];
787
- if (known !== undefined)
788
- return known;
789
- const child = await tx.createConversation({ ownership: { kind: "task", taskId: api.taskId } });
790
- await configure(tx, child.id, { tools: childTools, instructions: null });
791
- Object.assign(await tx.doc(c.Config, child.id), config ?? UNCONFIGURED);
792
- children.byRequest[key] = child.id;
793
- return child.id;
794
- }, context);
795
- const child = await api.conversation(id, context);
796
- if (!child)
797
- throw new Error("the child conversation is gone");
798
- // Children on a provider whose sessions share one browser would drive the same pages, so there they take turns. One
799
- // whose provider cannot be looked up waits its turn too: its own browser calls ask the factory again.
800
- const shared = await providerOf(c, api, id, PLANE, context).then((provider) => provider.caps.sharedBrowser === true, () => true);
801
- // The turn covers the report and the release too: on a shared browser the next child attaches only once this one has let go.
802
- const run = async () => {
803
- try {
804
- const settled = await (await child.submit({ type: "input", content: task.prompt, requestId: task.requestId }, context)).wait(context);
805
- const report = await api.commit(async (tx) => {
806
- for (const entry of (await tx.scanEntries({ conversationId: id, order: "descending" }, 50)).items) {
807
- for (const message of [...(entry.model ?? [])].reverse()) {
808
- if (message.role !== "assistant")
809
- continue;
810
- const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
811
- if (text)
812
- return text;
813
- }
814
- }
815
- return "";
816
- }, context);
817
- if (settled.status !== "done" || !report)
818
- throw new Error("the child finished without a report");
819
- return report;
820
- }
821
- finally {
822
- await releasePlane(c, { id, commit: (change, ctx) => api.commit(change, ctx) }, "close", context).catch(() => undefined);
823
- }
824
- };
825
- return await (shared ? c.childTurns(run) : run());
826
- };
827
- }
828
- function siteTool(c, sites) {
829
- const contract = useWebsiteContract(sites.listing);
830
- return defineTool({
831
- name: contract.name,
832
- description: contract.description,
833
- parameters: contract.parameters,
834
- replay: contract.replay,
835
- executionMode: contract.executionMode,
836
- execute: async (args, api, context) => {
837
- const out = await useWebsite(args, sites.port, sites.listing, { signal: context.abortSignal ?? new AbortController().signal, runChild: childConversation(c, api, context) });
838
- return { ...forModel(redactContent(out.content, c.redact)), ...(out.isError ? { isError: true } : {}) };
839
- },
840
- });
841
- }
842
791
  /** A Session that a storage error failed ends `{ kind: "failed" }` (`closed`, pi-durable's SessionEnd), and close begins
843
792
  * at once (`subscribeClose`). */
844
793
  function endingOf(harness) {
@@ -859,7 +808,6 @@ export function createBrowserExtension(options) {
859
808
  const redact = createRedactor(() => [...providerKeyValues(process.env, options.redact?.values), ...tracked]);
860
809
  const vault = vaultRuntime(options, (secret) => { tracked.add(secret); }, (message) => process.emitWarning(`pi-browser: ${redact(message)}`, { code: "PI_BROWSER_VAULT" }));
861
810
  const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED), checkpointWhen: () => false });
862
- const Children = defineDoc({ kind: `${name}.children`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ byRequest: {} }), checkpointWhen: () => false });
863
811
  // A fork starts with no sessions: it never shares a live browser.
864
812
  const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: emptySessions, checkpointWhen: () => false });
865
813
  const readers = { options, redact, Config };
@@ -872,16 +820,16 @@ export function createBrowserExtension(options) {
872
820
  const listPriced = options.prices?.sessionUsdPerHour === undefined && prices.sessionUsdPerHour !== null;
873
821
  const meter = (spent, at, final = false) => {
874
822
  const charged = sessionCharge(spent, at, prices, priceState, final);
875
- 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 }) };
876
824
  };
877
825
  const bill = async (tx, conversationId, record, at, final, call) => {
878
826
  const before = record.spent;
879
827
  if (before.final)
880
828
  return null;
881
- const { spent, usage } = meter(before, at, final);
829
+ const { spent, usage, overbookedS } = meter(before, at, final);
882
830
  record.spent = spent;
883
831
  const seconds = Math.round((spent.seconds - before.seconds) * 1000) / 1000;
884
- 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);
885
833
  return usage;
886
834
  };
887
835
  const leaving = new Map();
@@ -902,9 +850,16 @@ export function createBrowserExtension(options) {
902
850
  handoff: options.handoff,
903
851
  handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
904
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
+ },
905
860
  });
906
861
  const c = {
907
- ...readers, name, Sessions, Children, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, serial: keyedSerializer(), childTurns: oneAtATime(), guards: new Map(), owned, failed: false, stops: new Map(), 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(),
908
863
  idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
909
864
  };
910
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
@@ -913,12 +868,12 @@ export function createBrowserExtension(options) {
913
868
  // pi checks a call's arguments against the tool's schema before execute, so each implementation receives its own shape.
914
869
  const tools = toolsFor(c, own);
915
870
  const names = new Set(tools.map((tool) => tool.name));
916
- const siteTools = options.sites ? [siteTool(c, options.sites)] : [];
917
871
  return {
918
- extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [sectionFor(c, names)], tasks: [store.ReleaseTask, store.HandoffTask] }),
919
- docs: { Config, Sessions, Inventory: store.Inventory, Children },
920
- 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,
921
875
  release: (conversation, reason, context) => releasePlane(c, conversation, reason, context),
876
+ charge: (conversation, context) => chargeOpen(c, conversation, context),
922
877
  async reconcile(harness, isActive, context) {
923
878
  c.opened = { harness, context };
924
879
  c.ending = endingOf(harness);
@@ -955,5 +910,24 @@ export function createBrowserExtension(options) {
955
910
  c.owned.clear();
956
911
  },
957
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
+ },
958
932
  };
959
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,5 +1,7 @@
1
- export { createLiveView, type LiveViewHost, type LiveViewOptions, type TakeAnswer } 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
5
  export { viewerAssets } from "./viewer.js";
6
+ export { acceptWebSocket, type WsConn, type WsOptions } from "./ws.js";
7
+ export { newToken, newViewerId, tokenMatches } from "./token.js";
@@ -3,3 +3,7 @@ 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
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";
@@ -140,7 +140,7 @@ export declare function decodeFrame(message: Uint8Array): {
140
140
  /** What stream.ts gives the server: one session's page, shown and driven over its browser's DevTools socket. */
141
141
  export type StreamHandlers = {
142
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
143
- * (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. */
144
144
  frame(jpeg: Buffer, page: {
145
145
  w: number;
146
146
  h: number;
@@ -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) => {
@@ -8,6 +8,23 @@ export type LiveViewOptions = {
8
8
  /** Where the host mounts `handle` and `upgrade`, e.g. `https://host.example/live`. Its origin is the viewer's own origin, which an upgrade's Origin
9
9
  * header must equal. Absent: the live view starts its own server on 127.0.0.1 (never 0.0.0.0), on an ephemeral port, at the first `open`. */
10
10
  baseUrl?: string;
11
+ /** With no `baseUrl`: the address its own server listens on, and the host the viewer's link names, for a host whose
12
+ * viewer is reached from another machine (its own proxy, never a person's browser directly). Absent: loopback for
13
+ * both. A host that listens off loopback gives `admit` too. `fd`, in place of `bind`: a socket already listening that
14
+ * this process was handed (its parent made it, and knows its address), served as it is; the link names `host` and
15
+ * that socket's own port. The process listens on it once: a later live view given the same `fd` takes it over from
16
+ * the one before (whose links then answer 404), and a close leaves it listening, answering 404, for the next. */
17
+ listen?: {
18
+ readonly bind: string;
19
+ readonly host: string;
20
+ } | {
21
+ readonly fd: number;
22
+ readonly host: string;
23
+ };
24
+ /** Asked of every page request and upgrade before anything else is read of it: false is a 403. The host's own check
25
+ * that the request comes from its own proxy (a signed header, say). Absent: every request is asked only what it is
26
+ * asked today. */
27
+ admit?: (req: IncomingMessage) => boolean;
11
28
  /** The screencast and input (stream.ts); the default is the package's own. A test passes a fake. */
12
29
  stream?: StreamFactory;
13
30
  /** The person/model mutex. Absent, the package's own process-wide registry (`drivingGates`, core/driving.ts), the one the toolset's model calls use, so a
@@ -58,8 +75,13 @@ export type LiveViewHost = {
58
75
  open(tag: string, cdpUrl: string): Promise<LiveView>;
59
76
  /** The view `open` gave for a tag, or null: for a caller that must not start anything (`liveViewProvider` asks before it attaches). */
60
77
  known(tag: string): LiveView | null;
61
- /** True while a person is driving this session (viewer input within the gate's idle window): the frame recorder holds its capture meanwhile. */
78
+ /** True while a person is driving this session (viewer input within the gate's idle window). */
62
79
  driving(tag: string): boolean;
80
+ /** The host watches the session's screen with or without a viewer (serve's run video): one screencast per session, the
81
+ * viewer's and the watchers' alike, never a second. Each frame reaches `watcher.frame` and is acked by the viewer's send,
82
+ * or at once with none; `ended` once if the browser's socket ends unasked (a release ends the watch with no call). The
83
+ * answer stops watching; null when the session has no view. */
84
+ watch(tag: string, watcher: Watcher): (() => void) | null;
63
85
  /** The token is dead, the viewer's socket closed, the stream and the gate ended. Idempotent. */
64
86
  release(tag: string): Promise<void>;
65
87
  /** What the host holds, for diagnostics and tests: the sessions with a viewer URL and the opens in flight. Neither grows with the sessions it once released. */
@@ -70,4 +92,12 @@ export type LiveViewHost = {
70
92
  /** Releases every session and stops the server it started, if any. */
71
93
  close(): Promise<void>;
72
94
  };
95
+ /** A host's watch of a session's frames (LiveViewHost.watch). */
96
+ export type Watcher = {
97
+ frame(jpeg: Buffer, page: {
98
+ w: number;
99
+ h: number;
100
+ }): void;
101
+ ended(): void;
102
+ };
73
103
  export declare function createLiveView(options: LiveViewOptions): LiveViewHost;