@parcha/pi-browser 0.1.0-beta.21 → 0.1.0-beta.26

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 (58) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +38 -7
  3. package/dist/coding-agent-local.js +7 -6
  4. package/dist/coding-agent.js +32 -28
  5. package/dist/core/clip.js +2 -2
  6. package/dist/core/contract.d.ts +7 -0
  7. package/dist/core/contract.js +3 -0
  8. package/dist/core/custody.d.ts +13 -4
  9. package/dist/core/custody.js +23 -6
  10. package/dist/core/downloads.js +2 -2
  11. package/dist/core/driving.d.ts +6 -0
  12. package/dist/core/driving.js +8 -0
  13. package/dist/core/failures.d.ts +13 -3
  14. package/dist/core/failures.js +22 -15
  15. package/dist/core/host.d.ts +6 -0
  16. package/dist/core/redact.d.ts +9 -0
  17. package/dist/core/redact.js +9 -0
  18. package/dist/core/sites.js +2 -1
  19. package/dist/core/tools.d.ts +2 -2
  20. package/dist/core/tools.js +7 -10
  21. package/dist/core/web.d.ts +1 -6
  22. package/dist/core/web.js +8 -4
  23. package/dist/driver/extension-worker.js +149 -118
  24. package/dist/driver/page-driver.d.ts +2 -1
  25. package/dist/driver/sealed.d.ts +16 -0
  26. package/dist/driver/sealed.js +47 -0
  27. package/dist/driver/stagehand.js +7 -43
  28. package/dist/durable/journal.d.ts +31 -0
  29. package/dist/durable/journal.js +105 -0
  30. package/dist/{durable-result.d.ts → durable/result.d.ts} +1 -1
  31. package/dist/{store.d.ts → durable/store.d.ts} +2 -2
  32. package/dist/{store.js → durable/store.js} +1 -1
  33. package/dist/{web.d.ts → durable/web.d.ts} +4 -4
  34. package/dist/{web.js → durable/web.js} +5 -5
  35. package/dist/durable.d.ts +2 -2
  36. package/dist/durable.js +42 -135
  37. package/dist/live-view/provider.d.ts +1 -1
  38. package/dist/live-view/provider.js +1 -1
  39. package/dist/live-view/server.d.ts +2 -2
  40. package/dist/live-view/server.js +1 -3
  41. package/dist/providers/assigned.js +2 -3
  42. package/dist/providers/browserbase-net.d.ts +0 -1
  43. package/dist/providers/browserbase-net.js +0 -1
  44. package/dist/providers/browserbase.js +5 -4
  45. package/dist/providers/cdp.js +38 -43
  46. package/dist/providers/chrome-args.d.ts +18 -0
  47. package/dist/providers/chrome-args.js +66 -0
  48. package/dist/providers/chrome-stderr.d.ts +21 -0
  49. package/dist/providers/chrome-stderr.js +108 -0
  50. package/dist/providers/http.d.ts +4 -1
  51. package/dist/providers/http.js +5 -8
  52. package/dist/providers/kernel.d.ts +10 -1
  53. package/dist/providers/kernel.js +1 -1
  54. package/dist/providers/profiles.js +6 -6
  55. package/dist/providers/shared.d.ts +9 -0
  56. package/dist/providers/shared.js +5 -1
  57. package/package.json +7 -3
  58. /package/dist/{durable-result.js → durable/result.js} +0 -0
@@ -0,0 +1,47 @@
1
+ // The steps of attaching a sealed Stagehand that can fail on their own: naming where a failed step went, stopping a
2
+ // cancelled attach, and creating the instance once more when the extension is still running an earlier attach's init.
3
+ import { BrowserFailureError } from "../core/custody.js";
4
+ import { browserFailure } from "../core/failures.js";
5
+ /** What Stagehand's extension answers an init while another is still running in it. */
6
+ export const INIT_IN_PROGRESS = "Stagehand initialization is already in progress";
7
+ /** Stagehand's own init deadline: an init the extension is still running has ended by then. */
8
+ export const IN_FLIGHT_INIT_MS = 60_000;
9
+ /** The extension refused an init because another is still running in it (its JSON-RPC error, as Stagehand's cause). */
10
+ export const initInProgress = (error) => {
11
+ const cause = error?.cause;
12
+ return !!cause && typeof cause === "object" && typeof cause.code === "number" && cause.message === INIT_IN_PROGRESS;
13
+ };
14
+ /** A failed attach step names where it went: Stagehand reports a failed open as "[object Object]", and the socket's error
15
+ * has no address. */
16
+ export const attachStep = (host) => (step) => step.catch((error) => {
17
+ throw new Error(`attaching to the browser at ${host} failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
18
+ });
19
+ /** A cancelled call never starts an init of its own, however the wait ended. */
20
+ export function throwIfCancelled(signal) {
21
+ if (signal?.aborted)
22
+ throw signal.reason instanceof Error ? signal.reason : Object.assign(new Error("the attach was cancelled"), { name: "AbortError" });
23
+ }
24
+ /** The sealed Stagehand, created once more when the extension is still running an earlier attach's init: an attach that
25
+ * gave up (a dropped connection, a deadline) left its init running there, and `waitForThatInit` (a close, which queues
26
+ * behind that init, so its reply means the init has ended) waits it out first. A second refusal is the browser still
27
+ * busy, retryable. */
28
+ export async function createSealed(create, waitForThatInit, host, signal) {
29
+ try {
30
+ return await create();
31
+ }
32
+ catch (error) {
33
+ if (!initInProgress(error))
34
+ throw error;
35
+ }
36
+ throwIfCancelled(signal);
37
+ await waitForThatInit();
38
+ throwIfCancelled(signal);
39
+ try {
40
+ return await create();
41
+ }
42
+ catch (again) {
43
+ if (!initInProgress(again))
44
+ throw again;
45
+ throw new BrowserFailureError(browserFailure("browser_unavailable", `The browser at ${host} is still finishing an earlier connection after ${IN_FLIGHT_INIT_MS / 1_000} s. Call again in a moment, or call browser_relaunch for a fresh session.`, { retryable: true }));
46
+ }
47
+ }
@@ -1,9 +1,6 @@
1
- // Stagehand is created sealed: no inference leaves through it (act, extract and observe are refused), nothing is cached
2
- // server side, and the driver never ends the browser: custody releases it through the provider.
3
- import { BrowserFailureError } from "../core/custody.js";
4
- import { browserFailure } from "../core/failures.js";
5
1
  import { installedExtension } from "./extension-worker.js";
6
2
  import { pageDriver } from "./page-driver.js";
3
+ import { attachStep, createSealed, IN_FLIGHT_INIT_MS, INIT_IN_PROGRESS } from "./sealed.js";
7
4
  /** A closed loopback port, so no span leaves the host: Stagehand 4.1.0 cannot turn its trace exporter off. */
8
5
  export const STAGEHAND_TELEMETRY = { traces: { endpoint: "http://127.0.0.1:9/v1/traces" } };
9
6
  export const STAGEHAND_INFERENCE_REFUSED = "Stagehand inference is off in this harness: act, extract and observe are unavailable. Drive the page with run code or snapshot IDs.";
@@ -14,50 +11,17 @@ export const SEALED_STAGEHAND = {
14
11
  telemetry: STAGEHAND_TELEMETRY,
15
12
  };
16
13
  /** What Stagehand's extension answers an init while another is still running in it. */
17
- export const STAGEHAND_INIT_IN_PROGRESS = "Stagehand initialization is already in progress";
18
- /** Stagehand's own init deadline: an init the extension is still running has ended by then. */
19
- const IN_FLIGHT_INIT_MS = 60_000;
20
- const initInProgress = (error) => {
21
- const cause = error?.cause;
22
- return !!cause && typeof cause === "object" && typeof cause.code === "number" && cause.message === STAGEHAND_INIT_IN_PROGRESS;
23
- };
14
+ export const STAGEHAND_INIT_IN_PROGRESS = INIT_IN_PROGRESS;
24
15
  /** The batch deadline comes from `DriverOptions`; a caller that passes none gets the facade's 60 s. */
25
16
  export function stagehandDriver() {
26
17
  return async (target, signal, options) => {
27
18
  const { localBrowser, Stagehand } = await import("@browserbasehq/stagehand");
28
- // An id the provider supplies names a held extension too, so its worker is reset as well.
29
- // A failed open names where it went: Stagehand reports it as "[object Object]" and the socket's error has no
30
- // address.
31
19
  const host = new URL(target.dial?.url ?? target.sdkCdpUrl).host;
32
- const named = (step) => step.catch((error) => { throw new Error(`attaching to the browser at ${host} failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); });
33
- const extensionId = await named(installedExtension(target.sdkCdpUrl, signal, target.extensionId));
34
- const browser = await named(localBrowser.connect({ cdpUrl: target.sdkCdpUrl, ...(extensionId ? { extensionId } : {}) }));
35
- let stagehand;
36
- try {
37
- stagehand = await Stagehand.create({ browser, ...SEALED_STAGEHAND });
38
- }
39
- catch (error) {
40
- if (!initInProgress(error))
41
- throw error;
42
- // A cancelled call never starts an init of its own, however the wait ended.
43
- const stopIfCancelled = () => {
44
- if (signal?.aborted)
45
- throw signal.reason instanceof Error ? signal.reason : Object.assign(new Error("the attach was cancelled"), { name: "AbortError" });
46
- };
47
- stopIfCancelled();
48
- // An attach that gave up (a dropped connection, a deadline) left its init running in the extension. A close
49
- // queues behind that init, so its reply means the init has ended; this attach then inits once more.
50
- await named(installedExtension(target.sdkCdpUrl, signal, extensionId ?? undefined, IN_FLIGHT_INIT_MS));
51
- stopIfCancelled();
52
- try {
53
- stagehand = await Stagehand.create({ browser, ...SEALED_STAGEHAND });
54
- }
55
- catch (again) {
56
- if (!initInProgress(again))
57
- throw again;
58
- throw new BrowserFailureError(browserFailure("browser_unavailable", `The browser at ${host} is still finishing an earlier connection after ${IN_FLIGHT_INIT_MS / 1_000} s. Call again in a moment, or call browser_relaunch for a fresh session.`, { retryable: true }));
59
- }
60
- }
20
+ const step = attachStep(host);
21
+ // An id the provider supplies names a held extension too, so its worker is reset as well.
22
+ const extensionId = await step(installedExtension(target.sdkCdpUrl, signal, target.extensionId));
23
+ const browser = await step(localBrowser.connect({ cdpUrl: target.sdkCdpUrl, ...(extensionId ? { extensionId } : {}) }));
24
+ const stagehand = await createSealed(() => Stagehand.create({ browser, ...SEALED_STAGEHAND }), () => step(installedExtension(target.sdkCdpUrl, signal, extensionId ?? undefined, IN_FLIGHT_INIT_MS)), host, signal);
61
25
  return pageDriver(stagehand, { batchMs: options?.batchTimeoutMs ?? 60_000 });
62
26
  };
63
27
  }
@@ -0,0 +1,31 @@
1
+ import { type ConversationDocToken, type ConversationId, type Tx } from "@earendil-works/pi-durable";
2
+ import type { PendingEffect, SessionsState } from "../core/host.js";
3
+ /** What the journal reads of custody: the conversation's sessions and this process's incarnation. */
4
+ type Journal = {
5
+ Sessions: ConversationDocToken<SessionsState>;
6
+ incarnation: string;
7
+ };
8
+ /** What the journal reads of a tool call: its conversation and plane, and a commit. */
9
+ type JournalScope = {
10
+ cid: ConversationId;
11
+ plane: string;
12
+ commit<T>(change: (tx: Tx) => Promise<T>): Promise<T>;
13
+ };
14
+ export declare const journalOf: (state: SessionsState, plane: string) => PendingEffect | null;
15
+ /** The entry with this call's id in a journal chain: the entry itself or one it carries as `prior`. */
16
+ export declare const inChain: (entry: PendingEffect | null | undefined, callId: string) => PendingEffect | undefined;
17
+ /** Settles one entry of a journal chain; the entries it carried stay. */
18
+ export declare const clearJournal: (c: Journal, scope: JournalScope, callId: string) => Promise<void>;
19
+ /** The entries of a journal chain whose warning is still owed, as a chain: each an earlier process wrote that is a cut (not
20
+ * finished with a saved answer) and has not been told by a saved answer. An entry of this process is never a cut, and a told
21
+ * one whose telling answer was saved was delivered. */
22
+ export declare function owed(c: Journal, scope: JournalScope, entry: PendingEffect | null | undefined): Promise<PendingEffect | null>;
23
+ /** A journaled action's own answer as pi committed it: true for a success, false for an error, null for none yet. */
24
+ export declare function answerOf(scope: JournalScope, pending: PendingEffect): Promise<boolean | null>;
25
+ /** Every cut in a journal chain, oldest first. An entry a later action replaced counts only while its warning is still owed:
26
+ * once a saved answer told it, the later action replaced it, as it would have with no chain. */
27
+ export declare function cutsOf(c: Journal, scope: JournalScope, entry: PendingEffect | null | undefined, newest?: boolean): Promise<PendingEffect[]>;
28
+ /** The cut a call answers for: the oldest whose warning is still owed (an entry a later action replaced before the telling
29
+ * of it was saved comes first), else the newest. */
30
+ export declare const cutOf: (cuts: PendingEffect[]) => PendingEffect | null;
31
+ export {};
@@ -0,0 +1,105 @@
1
+ // The effect journal of the pi-durable adapter: an effectful action is journaled before it runs, and an entry an earlier process
2
+ // wrote and never settled is a cut, which the next call tells the model about once. These read and settle the journal; custody
3
+ // (durable.ts) writes it.
4
+ import { ToolResultEntry } from "@earendil-works/pi-durable";
5
+ export const journalOf = (state, plane) => [...state.sessions].reverse().find((r) => r.plane === plane && r.pendingEffect !== null)?.pendingEffect ?? null;
6
+ /** The entry with this call's id in a journal chain: the entry itself or one it carries as `prior`. */
7
+ export const inChain = (entry, callId) => {
8
+ for (let e = entry; e; e = e.prior)
9
+ if (e.callId === callId)
10
+ return e;
11
+ return undefined;
12
+ };
13
+ /** Settles one entry of a journal chain; the entries it carried stay. */
14
+ export const clearJournal = (c, scope, callId) => scope.commit(async (tx) => {
15
+ const state = await tx.doc(c.Sessions, scope.cid);
16
+ for (const record of state.sessions) {
17
+ if (record.plane !== scope.plane || !record.pendingEffect)
18
+ continue;
19
+ if (record.pendingEffect.callId === callId) {
20
+ record.pendingEffect = record.pendingEffect.prior ?? null;
21
+ continue;
22
+ }
23
+ for (let e = record.pendingEffect; e.prior; e = e.prior) {
24
+ if (e.prior.callId !== callId)
25
+ continue;
26
+ if (e.prior.prior)
27
+ e.prior = e.prior.prior;
28
+ else
29
+ delete e.prior;
30
+ break;
31
+ }
32
+ }
33
+ });
34
+ /** The entries of a journal chain whose warning is still owed, as a chain: each an earlier process wrote that is a cut (not
35
+ * finished with a saved answer) and has not been told by a saved answer. An entry of this process is never a cut, and a told
36
+ * one whose telling answer was saved was delivered. */
37
+ export async function owed(c, scope, entry) {
38
+ if (!entry)
39
+ return null;
40
+ const rest = await owed(c, scope, entry.prior);
41
+ const { prior: _carried, ...own } = entry;
42
+ const delivered = entry.incarnation === c.incarnation
43
+ || (entry.told === true && (await toldSaved(scope, entry)))
44
+ || (entry.finished === true && !entry.told && (await answered(scope, entry)));
45
+ return delivered ? rest : { ...own, ...(rest ? { prior: rest } : {}) };
46
+ }
47
+ /** A journaled action's own answer as pi committed it: true for a success, false for an error, null for none yet. */
48
+ export async function answerOf(scope, pending) {
49
+ const message = await savedAnswer(scope, pending.after, pending.callId);
50
+ return message === null ? null : message.isError !== true;
51
+ }
52
+ /** Whether the call that told a cut had its answer saved, carrying the cut's facts. One killed between the told mark and pi's
53
+ * commit told nobody, and the cut is told again. */
54
+ async function toldSaved(scope, pending) {
55
+ if (!pending.toldBy)
56
+ return false;
57
+ const message = await savedAnswer(scope, pending.after, pending.toldBy);
58
+ return message?.details?.pendingEffect?.callId === pending.callId;
59
+ }
60
+ /** A call's saved tool result, found by pi's typed tool-result entry. The scan covers only the cut's conversation from where
61
+ * it was journaled on, never the whole history. */
62
+ async function savedAnswer(scope, after, callId) {
63
+ if (after === undefined)
64
+ return null;
65
+ return scope.commit(async (tx) => {
66
+ let cursor;
67
+ do {
68
+ const page = await tx.scanEntries({ conversationId: scope.cid, minEntryId: after, order: "ascending" }, 100, cursor);
69
+ for (const entry of page.items) {
70
+ const message = ToolResultEntry.is(entry) ? entry.model?.[0] : undefined;
71
+ if (message?.role === "toolResult" && message.toolCallId === callId)
72
+ return message;
73
+ }
74
+ cursor = page.next;
75
+ } while (cursor !== undefined);
76
+ return null;
77
+ });
78
+ }
79
+ /** Whether a journaled action's own answer was committed as a success. */
80
+ const answered = async (scope, pending) => (await answerOf(scope, pending)) === true;
81
+ /** One journal entry as a cut. In this process an entry is in flight or answered, never cut; one an earlier process wrote is
82
+ * a cut unless its action finished and pi committed its answer, which only then is looked up. It counts as told only once
83
+ * the telling call's answer, carrying its facts, was saved. */
84
+ async function oneCut(c, scope, entry) {
85
+ if (entry.incarnation === c.incarnation)
86
+ return null;
87
+ const { prior: _carried, ...own } = entry;
88
+ const pending = own.told && !(await toldSaved(scope, own)) ? { ...own, told: false } : own;
89
+ if (!pending.finished || pending.told || !(await answered(scope, pending)))
90
+ return pending;
91
+ await clearJournal(c, scope, pending.callId);
92
+ return null;
93
+ }
94
+ /** Every cut in a journal chain, oldest first. An entry a later action replaced counts only while its warning is still owed:
95
+ * once a saved answer told it, the later action replaced it, as it would have with no chain. */
96
+ export async function cutsOf(c, scope, entry, newest = true) {
97
+ if (!entry)
98
+ return [];
99
+ const older = await cutsOf(c, scope, entry.prior, false);
100
+ const own = await oneCut(c, scope, entry);
101
+ return own && (newest || !own.told) ? [...older, own] : older;
102
+ }
103
+ /** The cut a call answers for: the oldest whose warning is still owed (an entry a later action replaced before the telling
104
+ * of it was saved comes first), else the newest. */
105
+ export const cutOf = (cuts) => cuts.find((cut) => !cut.told) ?? cuts.at(-1) ?? null;
@@ -1,4 +1,4 @@
1
- import type { ToolOutput } from "./core/custody.js";
1
+ import type { ToolOutput } from "../core/custody.js";
2
2
  /** pi-durable 1.0 and 1.1 read a tool result's `content`; 1.2 reads `output` and treats a result that lacks it as empty. The model's text goes under both keys. */
3
3
  export declare const forModel: (content: ToolOutput["content"]) => {
4
4
  content: ToolOutput["content"];
@@ -1,7 +1,7 @@
1
1
  import type { Context } from "@earendil-works/chord";
2
2
  import { type ConversationDocToken, type ConversationId, type DocumentReader, type Harness, type TaskId, type Tx } from "@earendil-works/pi-durable";
3
- import type { BrowserConfig, BrowserProvider, HandoffOutcome, HandoffPort, InventoryRow, ReconcileReport, ReleaseReason, SessionChange, SessionRecord, SessionsState } from "./core/host.js";
4
- import type { LeaseRef, LeaseState } from "./core/lease.js";
3
+ import type { BrowserConfig, BrowserProvider, HandoffOutcome, HandoffPort, InventoryRow, ReconcileReport, ReleaseReason, SessionChange, SessionRecord, SessionsState } from "../core/host.js";
4
+ import type { LeaseRef, LeaseState } from "../core/lease.js";
5
5
  export declare const now: () => string;
6
6
  /** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
7
7
  export declare const RELEASE_ATTEMPTS = 6;
@@ -1,5 +1,5 @@
1
1
  import { defineDoc, defineTask } from "@earendil-works/pi-durable";
2
- import { backoffMs, moveRecord, notices } from "./core/custody.js";
2
+ import { backoffMs, moveRecord, notices } from "../core/custody.js";
3
3
  export const now = () => new Date().toISOString();
4
4
  const iso = (ms) => new Date(ms).toISOString();
5
5
  const cidOf = (row) => row.conversationId;
@@ -1,8 +1,8 @@
1
1
  import { defineExtension, type ConversationId, type ToolRegistration } from "@earendil-works/pi-durable";
2
- import type { Decisions } from "./core/decisions.js";
3
- import type { EvidenceSink } from "./core/evidence.js";
4
- import type { FetchRequest, FetchResult, PriceTable, SearchRequest, SearchResult } from "./core/host.js";
5
- import { type RenderedPage, type WebBackup, type WebToolsOptions } from "./core/web.js";
2
+ import type { Decisions } from "../core/decisions.js";
3
+ import type { EvidenceSink } from "../core/evidence.js";
4
+ import type { FetchRequest, FetchResult, PriceTable, SearchRequest, SearchResult } from "../core/host.js";
5
+ import { type RenderedPage, type WebBackup, type WebToolsOptions } from "../core/web.js";
6
6
  export type WebExtensionOptions = {
7
7
  providers: {
8
8
  /** Names the source in `via` (`<name>_fetch`, `<name>_search`); default "provider". */
@@ -1,9 +1,9 @@
1
1
  import { defineExtension, defineTool } from "@earendil-works/pi-durable";
2
- import { WEB_TOOLS } from "./core/contract.js";
3
- import { providerKeyValues } from "./core/session-control.js";
4
- import { toolUsage } from "./core/usage.js";
5
- import { createWebTools } from "./core/web.js";
6
- import { forModel } from "./durable-result.js";
2
+ import { WEB_TOOLS } from "../core/contract.js";
3
+ import { providerKeyValues } from "../core/session-control.js";
4
+ import { toolUsage } from "../core/usage.js";
5
+ import { createWebTools } from "../core/web.js";
6
+ import { forModel } from "./result.js";
7
7
  export function createWebExtension(options) {
8
8
  const tools = createWebTools({
9
9
  name: options.providers.name ?? "provider",
package/dist/durable.d.ts CHANGED
@@ -93,6 +93,6 @@ export type BrowserExtensionHandle = {
93
93
  /** How many conversations the extension still holds in-memory state for: a repeat guard, an idle timer or a queued call. */
94
94
  retained(): number;
95
95
  };
96
- export { createWebExtension, type WebExtensionOptions } from "./web.js";
97
- export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
96
+ export { createWebExtension, type WebExtensionOptions } from "./durable/web.js";
97
+ export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./durable/store.js";
98
98
  export declare function createBrowserExtension<D extends PageDriver>(options: BrowserExtensionOptions<D>): BrowserExtensionHandle;
package/dist/durable.js CHANGED
@@ -1,23 +1,24 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { configure, defineDoc, defineExtension, defineTool, ToolResultEntry } from "@earendil-works/pi-durable";
3
- import { BROWSER_TOOL_NAMES, BROWSER_TOOLS, browserSection, 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, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
5
- import { forModel } from "./durable-result.js";
2
+ import { configure, defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
3
+ import { BROWSER_TOOL_NAMES, BROWSER_TOOLS, browserSection, 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";
5
+ import { forModel } from "./durable/result.js";
6
6
  import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
7
7
  import { browserFailure, classifyBrowserError } from "./core/failures.js";
8
8
  import { workspaceFiles } from "./core/files.js";
9
9
  import { drivingGuarded } from "./core/driving-guard.js";
10
- import { drivingGates, keptFor, personOn, rearmWhenLeft } from "./core/driving.js";
10
+ import { drivingGates, keptReason, personOn, rearmWhenLeft } from "./core/driving.js";
11
11
  import { pageTools } from "./core/tools.js";
12
12
  import { useWebsite, useWebsiteContract } from "./core/sites.js";
13
13
  import { leaseTag } from "./core/lease.js";
14
- import { createRedactor, redactDeep, scrubPageUrl } from "./core/redact.js";
14
+ import { createRedactor, hostLiveView, redactContent, redactDeep, scrubPageUrl } from "./core/redact.js";
15
15
  import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, oneAtATime, providerKeyValues } from "./core/session-control.js";
16
- import { custodyStore, now } from "./store.js";
16
+ import { custodyStore, now } from "./durable/store.js";
17
+ import { answerOf, clearJournal, cutOf, cutsOf, inChain, journalOf, owed } from "./durable/journal.js";
17
18
  import { withinDeadline } from "./core/unanswered.js";
18
19
  import { resolvePrices, sessionCharge, withEstimate } from "./core/usage.js";
19
- export { createWebExtension } from "./web.js";
20
- export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
20
+ export { createWebExtension } from "./durable/web.js";
21
+ export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./durable/store.js";
21
22
  const PLANE = "default";
22
23
  const UNCONFIGURED = { label: "", run: "", policy: DEFAULT_BROWSER_POLICY };
23
24
  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 }));
@@ -97,6 +98,9 @@ async function configOf(c, read, cid, context) {
97
98
  async function providerOf(c, read, cid, plane, context) {
98
99
  return c.options.provider({ conversationId: cid, plane, config: await configOf(c, read, cid, context) });
99
100
  }
101
+ /** The two lookups for the conversation and plane a tool call runs in. */
102
+ const scopeConfig = (c, scope) => configOf(c, scope.read, scope.cid, scope.context);
103
+ const scopeProvider = (c, scope) => providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
100
104
  const rowOf = (cid, record) => ({ tag: record.tag, conversationId: cid, plane: record.plane, provider: record.provider, resourceId: record.resourceId, state: record.state });
101
105
  async function emitObserver(c, row) {
102
106
  try {
@@ -124,9 +128,7 @@ async function emit(c, cid, label, record, change, provider) {
124
128
  try {
125
129
  const ref = record.resourceId === null ? null : { id: record.resourceId, tag: record.tag };
126
130
  const view = change !== "released" && ref && provider?.liveView ? await provider.liveView(ref) : null;
127
- // The live view's own URLs go to the host as they are (it needs their token); a browsed page's URL and title are
128
- // scrubbed, since its query can carry a credential.
129
- const liveView = view && { ...view, pages: view.pages.map((page) => ({ ...page, url: page.url === null ? null : scrubPageUrl(page.url, c.redact), title: page.title === null ? null : c.redact(page.title) })) };
131
+ const liveView = view && hostLiveView(view, c.redact);
130
132
  await c.options.onSession({ conversationId: cid, label, session: record, liveView }, change);
131
133
  }
132
134
  catch { }
@@ -138,13 +140,22 @@ const failure = (error, scope, redact) => error instanceof BrowserFailureError ?
138
140
  /** `bound`, when given, limits the attach beside the call's own signal (a reconnect's budget); the check for a session the
139
141
  * provider ended keeps the call's own. */
140
142
  async function attachLive(c, scope, record, bound) {
143
+ // A live session reused, resumed by another process or kept across a change of policy, meets the navigation check a new one
144
+ // meets at create: a policy its provider cannot enforce is refused, and so is an allow list the session was not started under,
145
+ // never browsed under because the session already existed.
146
+ const navigation = (await scopeConfig(c, scope)).policy.navigation;
147
+ if (navigation) {
148
+ const refusal = navigationRefusal({ navigation }, await scopeProvider(c, scope), { applied: record.settings.navigationAllow });
149
+ if (refusal)
150
+ throw new BrowserFailureError(refusal);
151
+ }
141
152
  const held = c.held.driver(record.tag);
142
153
  // An observer whose socket closed holds nothing: driver and observer are attached again together.
143
154
  if (held && !c.held.observer(record.tag)?.closed)
144
155
  return held;
145
156
  if (held)
146
157
  await c.held.detach(record.tag);
147
- const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
158
+ const provider = await scopeProvider(c, scope);
148
159
  const ref = { id: record.resourceId, tag: record.tag };
149
160
  try {
150
161
  return await connect(c, bound ? { ...scope, signal: AbortSignal.any([scope.signal, bound]) } : scope, provider, ref);
@@ -156,7 +167,7 @@ async function attachLive(c, scope, record, bound) {
156
167
  }
157
168
  }
158
169
  async function connect(c, scope, provider, ref) {
159
- const config = await configOf(c, scope.read, scope.cid, scope.context);
170
+ const config = await scopeConfig(c, scope);
160
171
  const { actions: policy, batchTimeoutMs } = config.policy;
161
172
  c.owned.set(ref.tag, { cid: scope.cid, provider, ref });
162
173
  const target = await provider.attach(ref, scope.signal);
@@ -186,11 +197,11 @@ async function markEnded(c, scope, record, provider) {
186
197
  return true;
187
198
  }
188
199
  async function refuseHeld(c, scope, record) {
189
- if (record?.state === "held" && !(await markEnded(c, scope, record, await providerOf(c, scope.read, scope.cid, scope.plane, scope.context))))
200
+ if (record?.state === "held" && !(await markEnded(c, scope, record, await scopeProvider(c, scope))))
190
201
  throw waiting(record);
191
202
  }
192
203
  async function settleCreating(c, scope, record) {
193
- const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
204
+ const provider = await scopeProvider(c, scope);
194
205
  try {
195
206
  await c.store.bindByTag(provider, rowOf(scope.cid, record), scope.commit, scope.signal);
196
207
  }
@@ -199,11 +210,11 @@ async function settleCreating(c, scope, record) {
199
210
  }
200
211
  }
201
212
  async function create(c, scope, overrides, presetTag) {
202
- const config = await configOf(c, scope.read, scope.cid, scope.context);
213
+ const config = await scopeConfig(c, scope);
203
214
  const provider = await c.options.provider({ conversationId: scope.cid, plane: scope.plane, config });
204
215
  const tag = presetTag ?? leaseTag("ar", config.run, scope.cid, (await stateOf(c, scope)).sessions.length + 1);
205
216
  const spec = sessionSpec(config, tag, overrides);
206
- const unsupported = profileRefusal(spec, provider.caps);
217
+ const unsupported = profileRefusal(spec, provider.caps) ?? navigationRefusal(spec, provider);
207
218
  if (unsupported)
208
219
  throw new BrowserFailureError(unsupported);
209
220
  const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now(), honours: provider.caps.settings });
@@ -270,7 +281,7 @@ async function attached(c, scope, record, driver, note) {
270
281
  const fresh = state.sessions.find((r) => r.tag === record.tag) ?? record;
271
282
  const cuts = await cutsOf(c, scope, journalOf(state, scope.plane));
272
283
  const interrupted = cutOf(cuts);
273
- const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
284
+ const provider = await scopeProvider(c, scope);
274
285
  const fence = fresh.fence ?? 0;
275
286
  return { driver: fenced(driver, fence, () => c.fences.get(record.tag)), tag: record.tag, sessionId: fresh.resourceId, record: fresh, notice: notice || null, interrupted, cuts, recorded: Boolean(provider.recordings), effects: c.held.observer(record.tag) ?? null, fence, downloads: provider.downloads ?? null, replaced: replacedOf(state, scope.plane, fresh) };
276
287
  }
@@ -292,114 +303,14 @@ async function releaseRecord(c, scope, record, reason) {
292
303
  await c.held.detach(record.tag);
293
304
  }
294
305
  const editState = (c, scope, edit) => scope.commit(async (tx) => edit(await tx.doc(c.Sessions, scope.cid)));
295
- const journalOf = (state, plane) => [...state.sessions].reverse().find((r) => r.plane === plane && r.pendingEffect !== null)?.pendingEffect ?? null;
296
- /** The entry with this call's id in a journal chain: the entry itself or one it carries as `prior`. */
297
- const inChain = (entry, callId) => {
298
- for (let e = entry; e; e = e.prior)
299
- if (e.callId === callId)
300
- return e;
301
- return undefined;
302
- };
303
- /** Settles one entry of a journal chain; the entries it carried stay. */
304
- const clearJournal = (c, scope, callId) => editState(c, scope, (state) => {
305
- for (const record of state.sessions) {
306
- if (record.plane !== scope.plane || !record.pendingEffect)
307
- continue;
308
- if (record.pendingEffect.callId === callId) {
309
- record.pendingEffect = record.pendingEffect.prior ?? null;
310
- continue;
311
- }
312
- for (let e = record.pendingEffect; e.prior; e = e.prior) {
313
- if (e.prior.callId !== callId)
314
- continue;
315
- if (e.prior.prior)
316
- e.prior = e.prior.prior;
317
- else
318
- delete e.prior;
319
- break;
320
- }
321
- }
322
- });
323
- /** The entries of a journal chain whose warning is still owed, as a chain: each an earlier process wrote that is a cut (not
324
- * finished with a saved answer) and has not been told by a saved answer. An entry of this process is never a cut, and a told
325
- * one whose telling answer was saved was delivered. */
326
- async function owed(c, scope, entry) {
327
- if (!entry)
328
- return null;
329
- const rest = await owed(c, scope, entry.prior);
330
- const { prior: _carried, ...own } = entry;
331
- const delivered = entry.incarnation === c.incarnation
332
- || (entry.told === true && (await toldSaved(scope, entry)))
333
- || (entry.finished === true && !entry.told && (await answered(scope, entry)));
334
- return delivered ? rest : { ...own, ...(rest ? { prior: rest } : {}) };
335
- }
336
- /** A journaled action's own answer as pi committed it: true for a success, false for an error, null for none yet. */
337
- async function answerOf(scope, pending) {
338
- const message = await savedAnswer(scope, pending.after, pending.callId);
339
- return message === null ? null : message.isError !== true;
340
- }
341
- /** Whether the call that told a cut had its answer saved, carrying the cut's facts. One killed between the told mark and pi's
342
- * commit told nobody, and the cut is told again. */
343
- async function toldSaved(scope, pending) {
344
- if (!pending.toldBy)
345
- return false;
346
- const message = await savedAnswer(scope, pending.after, pending.toldBy);
347
- return message?.details?.pendingEffect?.callId === pending.callId;
348
- }
349
- /** A call's saved tool result, found by pi's typed tool-result entry. The scan covers only the cut's conversation from where
350
- * it was journaled on, never the whole history. */
351
- async function savedAnswer(scope, after, callId) {
352
- if (after === undefined)
353
- return null;
354
- return scope.commit(async (tx) => {
355
- let cursor;
356
- do {
357
- const page = await tx.scanEntries({ conversationId: scope.cid, minEntryId: after, order: "ascending" }, 100, cursor);
358
- for (const entry of page.items) {
359
- const message = ToolResultEntry.is(entry) ? entry.model?.[0] : undefined;
360
- if (message?.role === "toolResult" && message.toolCallId === callId)
361
- return message;
362
- }
363
- cursor = page.next;
364
- } while (cursor !== undefined);
365
- return null;
366
- });
367
- }
368
- /** Whether a journaled action's own answer was committed as a success. */
369
- const answered = async (scope, pending) => (await answerOf(scope, pending)) === true;
370
- /** One journal entry as a cut. In this process an entry is in flight or answered, never cut; one an earlier process wrote is
371
- * a cut unless its action finished and pi committed its answer, which only then is looked up. It counts as told only once
372
- * the telling call's answer, carrying its facts, was saved. */
373
- async function oneCut(c, scope, entry) {
374
- if (entry.incarnation === c.incarnation)
375
- return null;
376
- const { prior: _carried, ...own } = entry;
377
- const pending = own.told && !(await toldSaved(scope, own)) ? { ...own, told: false } : own;
378
- if (!pending.finished || pending.told || !(await answered(scope, pending)))
379
- return pending;
380
- await clearJournal(c, scope, pending.callId);
381
- return null;
382
- }
383
- /** Every cut in a journal chain, oldest first. An entry a later action replaced counts only while its warning is still owed:
384
- * once a saved answer told it, the later action replaced it, as it would have with no chain. */
385
- async function cutsOf(c, scope, entry, newest = true) {
386
- if (!entry)
387
- return [];
388
- const older = await cutsOf(c, scope, entry.prior, false);
389
- const own = await oneCut(c, scope, entry);
390
- return own && (newest || !own.told) ? [...older, own] : older;
391
- }
392
- /** The cut a call answers for: the oldest whose warning is still owed (an entry a later action replaced before the telling
393
- * of it was saved comes first), else the newest. */
394
- const cutOf = (cuts) => cuts.find((cut) => !cut.told) ?? cuts.at(-1) ?? null;
395
306
  async function relaunchOn(c, scope, api, slot, overrides) {
396
- const config = await configOf(c, scope.read, scope.cid, scope.context);
307
+ const config = await scopeConfig(c, scope);
397
308
  const refusal = relaunchRefusal(config.policy, overrides);
398
309
  if (refusal)
399
310
  throw new BrowserFailureError(refusal);
400
311
  await refuseHeld(c, scope, currentRecord(await stateOf(c, scope), scope.plane));
401
312
  // A session the host assigned is the only one: refused before anything is released.
402
- if ((await providerOf(c, scope.read, scope.cid, scope.plane, scope.context)).caps.fixedSession)
313
+ if ((await scopeProvider(c, scope)).caps.fixedSession)
403
314
  throw new BrowserFailureError(FIXED_SESSION_RELAUNCH);
404
315
  // The relaunch's session is chosen in a memo before its create commits: a rerun runs on it or says
405
316
  // session_replaced, never a second launch; a memo with no record yet is an uncommitted create and goes ahead.
@@ -528,18 +439,13 @@ function portFor(c, api, context) {
528
439
  });
529
440
  const record = currentRecord(await stateOf(c, scope), scope.plane);
530
441
  if (record)
531
- await emit(c, scope.cid, (await configOf(c, scope.read, scope.cid, scope.context)).label, record, "updated", await providerOf(c, scope.read, scope.cid, scope.plane, scope.context));
442
+ await emit(c, scope.cid, (await scopeConfig(c, scope)).label, record, "updated", await scopeProvider(c, scope));
532
443
  },
533
444
  unreachable: () => c.serial.run(key, async () => {
534
445
  const record = currentRecord(await stateOf(c, scope), scope.plane);
535
- // A session held for a person is theirs: custody never releases it on its own.
536
- if (record?.state === "held")
537
- return { released: false, lastUrl: record.lastUrl, kept: "held" };
538
- if (!record || !open(record))
446
+ if (!record || (record.state !== "held" && !open(record)))
539
447
  return { released: false, lastUrl: record?.lastUrl ?? null };
540
- // A session a person drives or watches through the live view is theirs: custody never releases it on its own.
541
- const person = personOn(c.options.gates ?? drivingGates, record.tag);
542
- const kept = person && keptFor(person);
448
+ const kept = keptReason(record, c.options.gates ?? drivingGates);
543
449
  if (kept)
544
450
  return { released: false, lastUrl: record.lastUrl, kept };
545
451
  await scope.commit(async (tx) => {
@@ -583,7 +489,7 @@ function portFor(c, api, context) {
583
489
  const record = currentRecord(await stateOf(c, scope), scope.plane);
584
490
  if (record?.state !== "live" && record?.state !== "held")
585
491
  return false;
586
- return markEnded(c, scope, record, await providerOf(c, scope.read, scope.cid, scope.plane, scope.context));
492
+ return markEnded(c, scope, record, await scopeProvider(c, scope));
587
493
  },
588
494
  handoff: async (ask) => {
589
495
  const person = c.options.handoff;
@@ -597,8 +503,9 @@ function portFor(c, api, context) {
597
503
  if (interactionId === undefined) {
598
504
  const { tag, sessionId } = await port.hold(ask.requestId);
599
505
  const asked = await (async () => {
600
- const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
601
- const liveView = provider.liveView ? await provider.liveView({ id: sessionId, tag }).catch(() => null) : null;
506
+ const provider = await scopeProvider(c, scope);
507
+ const view = provider.liveView ? await provider.liveView({ id: sessionId, tag }).catch(() => null) : null;
508
+ const liveView = view && hostLiveView(view, c.redact);
602
509
  return person.request({ requestId: ask.requestId, sessionTag: tag, sessionId, liveView, instruction: ask.instruction, completionCondition: ask.completionCondition }, scope.signal);
603
510
  })().catch(async (error) => { await port.resume(null); throw failure(error, scope, c.redact); });
604
511
  if ("refused" in asked) {
@@ -751,7 +658,7 @@ const withSessionTime = (own, charged) => {
751
658
  };
752
659
  function toolsFor(c, impls) {
753
660
  return BROWSER_TOOLS
754
- .filter((contract) => impls[contract.name] && (contract.listedWhen !== "downloads" || c.options.workspace) && (contract.listedWhen !== "upload" || c.options.files || c.options.workspace) && (contract.listedWhen !== "handoff" || c.options.handoff))
661
+ .filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!(c.options.files || c.options.workspace), handoff: !!c.options.handoff }))
755
662
  .map((contract) => defineTool({
756
663
  name: contract.name,
757
664
  description: contract.description,
@@ -774,7 +681,7 @@ function toolsFor(c, impls) {
774
681
  // A charge that cannot be committed now is carried by the next one.
775
682
  const usage = withSessionTime(out.usage, await chargeCall(c, api, context).catch(() => null));
776
683
  return {
777
- ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: c.redact(item.text) } : item)),
684
+ ...forModel(redactContent(out.content, c.redact)),
778
685
  ...(out.isError ? { isError: true } : {}),
779
686
  ...(out.details ? { details: redactDeep(out.details, c.redact) } : {}),
780
687
  ...(usage ? { usage: usage } : {}),
@@ -859,7 +766,7 @@ function siteTool(c, sites) {
859
766
  executionMode: contract.executionMode,
860
767
  execute: async (args, api, context) => {
861
768
  const out = await useWebsite(args, sites.port, sites.listing, { signal: context.abortSignal ?? new AbortController().signal, runChild: childConversation(c, api, context) });
862
- return { ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: c.redact(item.text) } : item)), ...(out.isError ? { isError: true } : {}) };
769
+ return { ...forModel(redactContent(out.content, c.redact)), ...(out.isError ? { isError: true } : {}) };
863
770
  },
864
771
  });
865
772
  }