@parcha/pi-browser 0.1.0-beta.34 → 0.1.0-beta.340

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 (78) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/NOTICE +6 -1
  3. package/README.md +70 -60
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +12 -30
  6. package/dist/core/custody.d.ts +6 -0
  7. package/dist/core/custody.js +15 -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 +1 -1
  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 +23 -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.js +3 -3
  39. package/dist/driver/page-driver.js +7 -3
  40. package/dist/driver/stagehand.d.ts +3 -1
  41. package/dist/driver/stagehand.js +4 -2
  42. package/dist/durable/store.d.ts +14 -3
  43. package/dist/durable/store.js +204 -51
  44. package/dist/durable.d.ts +32 -16
  45. package/dist/durable.js +68 -95
  46. package/dist/index.d.ts +3 -3
  47. package/dist/index.js +5 -3
  48. package/dist/live-view/index.d.ts +3 -1
  49. package/dist/live-view/index.js +4 -0
  50. package/dist/live-view/protocol.d.ts +1 -1
  51. package/dist/live-view/server.d.ts +30 -0
  52. package/dist/live-view/server.js +152 -25
  53. package/dist/providers/cdp.js +2 -2
  54. package/dist/providers/profiles.d.ts +1 -15
  55. package/dist/providers/profiles.js +1 -64
  56. package/dist/providers/shared.d.ts +1 -47
  57. package/dist/providers/shared.js +1 -82
  58. package/dist/providers/worker-extension.d.ts +14 -1
  59. package/dist/providers/worker-extension.js +69 -3
  60. package/dist/testing/backend.d.ts +6 -24
  61. package/dist/testing/backend.js +7 -30
  62. package/dist/vault-session.d.ts +4 -7
  63. package/dist/vault-session.js +26 -81
  64. package/dist/vendor/browser-use-pi/page.d.ts +3 -12
  65. package/dist/vendor/browser-use-pi/page.js +6 -19
  66. package/package.json +9 -22
  67. package/dist/core/sites.d.ts +0 -33
  68. package/dist/core/sites.js +0 -104
  69. package/dist/durable/web.d.ts +0 -47
  70. package/dist/durable/web.js +0 -41
  71. package/dist/providers/browserbase-net.d.ts +0 -12
  72. package/dist/providers/browserbase-net.js +0 -95
  73. package/dist/providers/browserbase.d.ts +0 -169
  74. package/dist/providers/browserbase.js +0 -319
  75. package/dist/providers/kernel.d.ts +0 -58
  76. package/dist/providers/kernel.js +0 -291
  77. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  78. /package/dist/{providers → core}/cdp-call.js +0 -0
package/dist/durable.js CHANGED
@@ -1,24 +1,21 @@
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";
23
20
  export { HANDOFF_POLL_MS } from "./core/custody.js";
24
21
  const PLANE = "default";
@@ -49,9 +46,6 @@ async function drainReleases(name, harness, context, signal) {
49
46
  const open = (record) => record?.state === "live" || record?.state === "creating";
50
47
  const releasable = (record, reason) => open(record) || (record?.state === "held" && reason !== "idle");
51
48
  const waiting = (record) => new BrowserFailureError(waitingForHuman(record.handoff));
52
- // A child gets the browser and web tools only: never use_website, so it cannot start children of its own, and never
53
- // browser_upload or browser_downloads, since its report is all that crosses back (invariant 10) and a site run has no files.
54
- const CHILD_TOOLS = new Set([...BROWSER_TOOL_NAMES, ...WEB_TOOL_NAMES].filter((name) => name !== "browser_upload" && name !== "browser_downloads"));
55
49
  /** How long a release the store could not record may take at the provider. */
56
50
  const DIRECT_RELEASE_MS = 30_000;
57
51
  /** How long close waits to learn whether a Session that began closing failed. */
@@ -243,7 +237,6 @@ async function create(c, scope, overrides, presetTag) {
243
237
  const unsupported = profileRefusal(spec, provider.caps) ?? navigationRefusal(spec, provider);
244
238
  if (unsupported)
245
239
  throw new BrowserFailureError(unsupported);
246
- // 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.
247
240
  const plan = await planRestore(c.vault, config.vault, provider, spec);
248
241
  const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now(), honours: provider.caps.settings });
249
242
  const row = rowOf(scope.cid, record);
@@ -288,9 +281,6 @@ async function create(c, scope, overrides, presetTag) {
288
281
  const live = { ...record, state: "live", resourceId: ref.id };
289
282
  try {
290
283
  const driver = await connect(c, scope, provider, ref, plan.afterAttach, plan.vaulted, plan.holdBack);
291
- // 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.
292
- if (plan.fresh)
293
- await c.held.capture(ref.tag);
294
284
  await emit(c, scope.cid, config.label, live, "launched", provider);
295
285
  return { record: live, driver };
296
286
  }
@@ -656,15 +646,19 @@ async function releasePlane(c, conversation, reason, context, still = () => true
656
646
  const mine = () => c.held.tags().filter((tag) => c.owned.get(tag)?.cid === conversation.id);
657
647
  // Kept before anything closes: the browser is still there, and a release that is cancelled (a call since) only made one capture more.
658
648
  await Promise.all(leasesOf(c, conversation.id).map((tag) => captureSession(c, tag)));
659
- // Closing a driver needs nothing from the store, so a release other than idle's starts closing the conversation's
660
- // drivers first and never waits for the commit to do it; the commit runs alongside, so the release task starts as
661
- // 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.
662
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);
663
653
  const tags = await conversation.commit(async (tx) => {
664
654
  const state = await tx.doc(c.Sessions, conversation.id);
665
655
  const record = still() ? currentRecord(state, PLANE) : null;
666
656
  if (!record || !releasable(record, reason))
667
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 [];
668
662
  // A person driving or watching the session through the live view keeps it from an idle release (#1098); it is
669
663
  // released one idle window after they leave.
670
664
  kept.gate = reason === "idle" ? personOn(c.options.gates ?? drivingGates, record.tag) : null;
@@ -710,6 +704,26 @@ async function releasePlane(c, conversation, reason, context, still = () => true
710
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));
711
705
  }
712
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
+ }
713
727
  async function chargeCall(c, api, context) {
714
728
  if (currentRecord(await api.snapshot(c.Sessions, api.conversationId, context), PLANE)?.state !== "live")
715
729
  return null;
@@ -728,7 +742,7 @@ const withSessionTime = (own, charged) => {
728
742
  };
729
743
  function toolsFor(c, impls) {
730
744
  return browserToolsFor(c.options.signIns ?? !!c.options.sessionVault)
731
- .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 }))
732
746
  .map((contract) => defineTool({
733
747
  name: contract.name,
734
748
  description: contract.description,
@@ -740,8 +754,7 @@ function toolsFor(c, impls) {
740
754
  c.idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
741
755
  try {
742
756
  const workspace = c.options.workspace?.(api.conversationId);
743
- const files = c.options.files ?? (workspace === undefined ? undefined : workspaceFiles(workspace));
744
- 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 };
745
758
  // Inside an async function, so a host tool that throws before it returns a promise is caught too.
746
759
  const out = await (async () => impls[contract.name](args, portFor(c, api, context), call))().catch((error) => {
747
760
  // A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
@@ -771,75 +784,10 @@ function sectionFor(c, names) {
771
784
  return undefined;
772
785
  const config = await input.read.snapshot(c.Config, input.conversationId, context);
773
786
  const offered = (tool) => input.agent.tools.some((t) => t.name === tool && names.has(tool));
774
- 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");
775
788
  },
776
789
  };
777
790
  }
778
- function childConversation(c, api, context) {
779
- return async (task) => {
780
- const config = await api.snapshot(c.Config, api.conversationId, context);
781
- const childTools = (await api.agent(context)).tools.filter((tool) => CHILD_TOOLS.has(tool.name));
782
- // One child per request, recorded in the commit that creates it: a replay or a repeated call finds it again, and
783
- // its submission is deduplicated by request_id.
784
- const id = await api.commit(async (tx) => {
785
- const children = await tx.doc(c.Children, api.conversationId);
786
- const key = `${task.site}:${task.requestId}`;
787
- const known = children.byRequest[key];
788
- if (known !== undefined)
789
- return known;
790
- const child = await tx.createConversation({ ownership: { kind: "task", taskId: api.taskId } });
791
- await configure(tx, child.id, { tools: childTools, instructions: null });
792
- Object.assign(await tx.doc(c.Config, child.id), config ?? UNCONFIGURED);
793
- children.byRequest[key] = child.id;
794
- return child.id;
795
- }, context);
796
- const child = await api.conversation(id, context);
797
- if (!child)
798
- throw new Error("the child conversation is gone");
799
- // Children on a provider whose sessions share one browser would drive the same pages, so there they take turns. One
800
- // whose provider cannot be looked up waits its turn too: its own browser calls ask the factory again.
801
- const shared = await providerOf(c, api, id, PLANE, context).then((provider) => provider.caps.sharedBrowser === true, () => true);
802
- // The turn covers the report and the release too: on a shared browser the next child attaches only once this one has let go.
803
- const run = async () => {
804
- try {
805
- const settled = await (await child.submit({ type: "input", content: task.prompt, requestId: task.requestId }, context)).wait(context);
806
- const report = await api.commit(async (tx) => {
807
- for (const entry of (await tx.scanEntries({ conversationId: id, order: "descending" }, 50)).items) {
808
- for (const message of [...(entry.model ?? [])].reverse()) {
809
- if (message.role !== "assistant")
810
- continue;
811
- const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
812
- if (text)
813
- return text;
814
- }
815
- }
816
- return "";
817
- }, context);
818
- if (settled.status !== "done" || !report)
819
- throw new Error("the child finished without a report");
820
- return report;
821
- }
822
- finally {
823
- await releasePlane(c, { id, commit: (change, ctx) => api.commit(change, ctx) }, "close", context).catch(() => undefined);
824
- }
825
- };
826
- return await (shared ? c.childTurns(run) : run());
827
- };
828
- }
829
- function siteTool(c, sites) {
830
- const contract = useWebsiteContract(sites.listing);
831
- return defineTool({
832
- name: contract.name,
833
- description: contract.description,
834
- parameters: contract.parameters,
835
- replay: contract.replay,
836
- executionMode: contract.executionMode,
837
- execute: async (args, api, context) => {
838
- const out = await useWebsite(args, sites.port, sites.listing, { signal: context.abortSignal ?? new AbortController().signal, runChild: childConversation(c, api, context) });
839
- return { ...forModel(redactContent(out.content, c.redact)), ...(out.isError ? { isError: true } : {}) };
840
- },
841
- });
842
- }
843
791
  /** A Session that a storage error failed ends `{ kind: "failed" }` (`closed`, pi-durable's SessionEnd), and close begins
844
792
  * at once (`subscribeClose`). */
845
793
  function endingOf(harness) {
@@ -860,7 +808,6 @@ export function createBrowserExtension(options) {
860
808
  const redact = createRedactor(() => [...providerKeyValues(process.env, options.redact?.values), ...tracked]);
861
809
  const vault = vaultRuntime(options, (secret) => { tracked.add(secret); }, (message) => process.emitWarning(`pi-browser: ${redact(message)}`, { code: "PI_BROWSER_VAULT" }));
862
810
  const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED), checkpointWhen: () => false });
863
- const Children = defineDoc({ kind: `${name}.children`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ byRequest: {} }), checkpointWhen: () => false });
864
811
  // A fork starts with no sessions: it never shares a live browser.
865
812
  const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: emptySessions, checkpointWhen: () => false });
866
813
  const readers = { options, redact, Config };
@@ -873,16 +820,16 @@ export function createBrowserExtension(options) {
873
820
  const listPriced = options.prices?.sessionUsdPerHour === undefined && prices.sessionUsdPerHour !== null;
874
821
  const meter = (spent, at, final = false) => {
875
822
  const charged = sessionCharge(spent, at, prices, priceState, final);
876
- 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 }) };
877
824
  };
878
825
  const bill = async (tx, conversationId, record, at, final, call) => {
879
826
  const before = record.spent;
880
827
  if (before.final)
881
828
  return null;
882
- const { spent, usage } = meter(before, at, final);
829
+ const { spent, usage, overbookedS } = meter(before, at, final);
883
830
  record.spent = spent;
884
831
  const seconds = Math.round((spent.seconds - before.seconds) * 1000) / 1000;
885
- 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);
886
833
  return usage;
887
834
  };
888
835
  const leaving = new Map();
@@ -903,9 +850,16 @@ export function createBrowserExtension(options) {
903
850
  handoff: options.handoff,
904
851
  handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
905
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
+ },
906
860
  });
907
861
  const c = {
908
- ...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(),
909
863
  idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
910
864
  };
911
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
@@ -914,12 +868,12 @@ export function createBrowserExtension(options) {
914
868
  // pi checks a call's arguments against the tool's schema before execute, so each implementation receives its own shape.
915
869
  const tools = toolsFor(c, own);
916
870
  const names = new Set(tools.map((tool) => tool.name));
917
- const siteTools = options.sites ? [siteTool(c, options.sites)] : [];
918
871
  return {
919
- extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [sectionFor(c, names)], tasks: [store.ReleaseTask, store.HandoffTask] }),
920
- docs: { Config, Sessions, Inventory: store.Inventory, Children },
921
- 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,
922
875
  release: (conversation, reason, context) => releasePlane(c, conversation, reason, context),
876
+ charge: (conversation, context) => chargeOpen(c, conversation, context),
923
877
  async reconcile(harness, isActive, context) {
924
878
  c.opened = { harness, context };
925
879
  c.ending = endingOf(harness);
@@ -956,5 +910,24 @@ export function createBrowserExtension(options) {
956
910
  c.owned.clear();
957
911
  },
958
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
+ },
959
932
  };
960
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;
@@ -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
@@ -60,6 +77,11 @@ export type LiveViewHost = {
60
77
  known(tag: string): LiveView | null;
61
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;