@parcha/pi-browser 0.0.0-stage → 0.1.0-beta.14
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.
- package/CHANGELOG.md +23 -0
- package/LICENSE +202 -0
- package/NOTICE +33 -0
- package/README.md +348 -2
- package/dist/coding-agent-local.d.ts +16 -0
- package/dist/coding-agent-local.js +138 -0
- package/dist/coding-agent.d.ts +79 -0
- package/dist/coding-agent.js +448 -0
- package/dist/core/contract.d.ts +26 -0
- package/dist/core/contract.js +154 -0
- package/dist/core/custody.d.ts +117 -0
- package/dist/core/custody.js +126 -0
- package/dist/core/decisions.d.ts +43 -0
- package/dist/core/decisions.js +4 -0
- package/dist/core/downloads.d.ts +35 -0
- package/dist/core/downloads.js +131 -0
- package/dist/core/effects.d.ts +63 -0
- package/dist/core/effects.js +256 -0
- package/dist/core/evidence.d.ts +43 -0
- package/dist/core/evidence.js +6 -0
- package/dist/core/failures.d.ts +36 -0
- package/dist/core/failures.js +68 -0
- package/dist/core/find.d.ts +32 -0
- package/dist/core/find.js +179 -0
- package/dist/core/guard.d.ts +6 -0
- package/dist/core/guard.js +25 -0
- package/dist/core/host.d.ts +328 -0
- package/dist/core/host.js +2 -0
- package/dist/core/images.d.ts +37 -0
- package/dist/core/images.js +60 -0
- package/dist/core/lease.d.ts +16 -0
- package/dist/core/lease.js +30 -0
- package/dist/core/receipts.d.ts +19 -0
- package/dist/core/receipts.js +22 -0
- package/dist/core/redact.d.ts +13 -0
- package/dist/core/redact.js +83 -0
- package/dist/core/session-control.d.ts +25 -0
- package/dist/core/session-control.js +75 -0
- package/dist/core/sites.d.ts +33 -0
- package/dist/core/sites.js +102 -0
- package/dist/core/tools.d.ts +72 -0
- package/dist/core/tools.js +200 -0
- package/dist/core/uri.d.ts +11 -0
- package/dist/core/uri.js +37 -0
- package/dist/core/usage.d.ts +19 -0
- package/dist/core/usage.js +44 -0
- package/dist/core/web.d.ts +98 -0
- package/dist/core/web.js +327 -0
- package/dist/driver/extension-worker.d.ts +6 -0
- package/dist/driver/extension-worker.js +121 -0
- package/dist/driver/stagehand.d.ts +25 -0
- package/dist/driver/stagehand.js +91 -0
- package/dist/durable-result.d.ts +6 -0
- package/dist/durable-result.js +2 -0
- package/dist/durable.d.ts +79 -0
- package/dist/durable.js +582 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +20 -0
- package/dist/providers/browserbase-net.d.ts +13 -0
- package/dist/providers/browserbase-net.js +96 -0
- package/dist/providers/browserbase.d.ts +152 -0
- package/dist/providers/browserbase.js +262 -0
- package/dist/providers/cdp-call.d.ts +6 -0
- package/dist/providers/cdp-call.js +25 -0
- package/dist/providers/cdp.d.ts +55 -0
- package/dist/providers/cdp.js +423 -0
- package/dist/providers/http.d.ts +2 -0
- package/dist/providers/http.js +21 -0
- package/dist/providers/kernel.d.ts +49 -0
- package/dist/providers/kernel.js +246 -0
- package/dist/providers/shared.d.ts +47 -0
- package/dist/providers/shared.js +82 -0
- package/dist/recorder/credential.d.ts +9 -0
- package/dist/recorder/credential.js +49 -0
- package/dist/recorder/follow.d.ts +26 -0
- package/dist/recorder/follow.js +138 -0
- package/dist/recorder/frames.d.ts +80 -0
- package/dist/recorder/frames.js +309 -0
- package/dist/recorder/index.d.ts +4 -0
- package/dist/recorder/index.js +7 -0
- package/dist/recorder/jpeg.d.ts +8 -0
- package/dist/recorder/jpeg.js +70 -0
- package/dist/recorder/track.d.ts +107 -0
- package/dist/recorder/track.js +259 -0
- package/dist/store.d.ts +56 -0
- package/dist/store.js +196 -0
- package/dist/testing/backend.d.ts +231 -0
- package/dist/testing/backend.js +414 -0
- package/dist/testing/driver.d.ts +28 -0
- package/dist/testing/driver.js +32 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.js +4 -0
- package/dist/testing/pages.d.ts +3 -0
- package/dist/testing/pages.js +10 -0
- package/dist/testing/sentinels.d.ts +29 -0
- package/dist/testing/sentinels.js +38 -0
- package/dist/vendor/stagehand-facade/contract.d.ts +348 -0
- package/dist/vendor/stagehand-facade/contract.js +155 -0
- package/dist/vendor/stagehand-facade/runtime.d.ts +90 -0
- package/dist/vendor/stagehand-facade/runtime.js +1640 -0
- package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +15 -0
- package/dist/vendor/stagehand-facade/screenshot-transport.js +51 -0
- package/dist/vendor/stagehand-facade/tools.d.ts +31 -0
- package/dist/vendor/stagehand-facade/tools.js +139 -0
- package/dist/web.d.ts +41 -0
- package/dist/web.js +38 -0
- package/package.json +123 -4
- package/src/vendor/stagehand-facade/UPSTREAM.json +24 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { Context } from "@earendil-works/chord";
|
|
2
|
+
import { type Conversation, type ConversationDocToken, type ConversationId, type Extension, type Harness, type SessionDocToken, type ToolRegistration } from "@earendil-works/pi-durable";
|
|
3
|
+
import { type DriverFactory } from "./core/custody.js";
|
|
4
|
+
import type { Decisions } from "./core/decisions.js";
|
|
5
|
+
import type { EvidenceSink } from "./core/evidence.js";
|
|
6
|
+
import { EffectObserver } from "./core/effects.js";
|
|
7
|
+
import { type BrowserToolImpls, type PageDriver } from "./core/tools.js";
|
|
8
|
+
import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionRow, SessionsState, SiteInfo, SiteRunPort } from "./core/host.js";
|
|
9
|
+
export type { BrowserToolArgs, BrowserToolImpls, PageDriver, ToolCall, ToolImpl } from "./core/tools.js";
|
|
10
|
+
export type { DriverFactory, DriverOptions } from "./core/custody.js";
|
|
11
|
+
export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = {
|
|
12
|
+
/** Default "browser"; a second plane installs a second extension under another name. */
|
|
13
|
+
name?: string;
|
|
14
|
+
/** Called per use: the provider for this conversation's plane. Holds the credentials in its closure; nothing it
|
|
15
|
+
* returns is committed. */
|
|
16
|
+
provider: (target: {
|
|
17
|
+
conversationId: ConversationId;
|
|
18
|
+
plane: string;
|
|
19
|
+
config: BrowserConfig;
|
|
20
|
+
}) => BrowserProvider | Promise<BrowserProvider>;
|
|
21
|
+
driver: DriverFactory<D>;
|
|
22
|
+
/** Implementations by contract name, over the package's own; a contract tool with no implementation is not listed. */
|
|
23
|
+
tools?: Partial<BrowserToolImpls<D>>;
|
|
24
|
+
evidence: EvidenceSink;
|
|
25
|
+
/** Where `browser_downloads` writes files; absent, the tool is not listed. */
|
|
26
|
+
workspace?: (conversationId: ConversationId) => string;
|
|
27
|
+
/** `use_website`'s sites; absent, the tool is not listed. `listing` is the port's `list()`, read once at host setup:
|
|
28
|
+
* the tool's description renders from it. Each local child runs in a conversation this call owns. */
|
|
29
|
+
sites?: {
|
|
30
|
+
port: SiteRunPort;
|
|
31
|
+
listing: readonly SiteInfo[];
|
|
32
|
+
};
|
|
33
|
+
/** Live view and session status; a throw here never fails a call. */
|
|
34
|
+
onSession?: (row: SessionRow, change: SessionChange) => void | Promise<void>;
|
|
35
|
+
/** A session runs without the effect observer its policy asked for; a throw here never fails a call. */
|
|
36
|
+
onObserver?: (row: ObserverRow) => void | Promise<void>;
|
|
37
|
+
prices?: Partial<PriceTable>;
|
|
38
|
+
/** Exact strings to scrub from every output besides the built-in shapes, read at each use. */
|
|
39
|
+
redact?: {
|
|
40
|
+
values: () => readonly string[];
|
|
41
|
+
};
|
|
42
|
+
section?: {
|
|
43
|
+
addendum?: string;
|
|
44
|
+
};
|
|
45
|
+
decisions?: Decisions;
|
|
46
|
+
/** How long a create may still land at the provider after its caller stopped waiting; default 60 s. */
|
|
47
|
+
createDeadlineMs?: number;
|
|
48
|
+
/** How the request observer attaches (default `EffectObserver.open`); a seam for tests that have no Chrome. */
|
|
49
|
+
openObserver?: typeof EffectObserver.open;
|
|
50
|
+
};
|
|
51
|
+
export type BrowserExtensionHandle = {
|
|
52
|
+
/** Install once per Harness, before `resume()`; select per conversation. */
|
|
53
|
+
extension: Extension;
|
|
54
|
+
/** `Children`: the conversation each `use_website` request ran its child in, by `<site>:<request_id>`. */
|
|
55
|
+
docs: {
|
|
56
|
+
Config: ConversationDocToken<BrowserConfig>;
|
|
57
|
+
Sessions: ConversationDocToken<SessionsState>;
|
|
58
|
+
Inventory: SessionDocToken<{
|
|
59
|
+
rows: Record<string, InventoryRow>;
|
|
60
|
+
}>;
|
|
61
|
+
Children: ConversationDocToken<{
|
|
62
|
+
byRequest: Record<string, number>;
|
|
63
|
+
}>;
|
|
64
|
+
};
|
|
65
|
+
tools: readonly ToolRegistration[];
|
|
66
|
+
/** Shutdown path (pi has no conversation-end event): commits `releasing` and a release task; it does not wait. */
|
|
67
|
+
release(conversation: Conversation, reason: ReleaseReason, context: Context): Promise<void>;
|
|
68
|
+
/** At run open, after install and before resume: every open lease is reconciled with its provider. */
|
|
69
|
+
reconcile(harness: Harness, isActive: (conversationId: ConversationId) => boolean, context: Context): Promise<ReconcileReport>;
|
|
70
|
+
/** Shutdown is release, `waitForIdle`, `drain`, close: resolves when none of this extension's release tasks is live. */
|
|
71
|
+
drain(harness: Harness, context: Context, signal?: AbortSignal): Promise<void>;
|
|
72
|
+
/** Drop in-memory driver attachments and idle timers (process exit); never releases. */
|
|
73
|
+
close(): Promise<void>;
|
|
74
|
+
/** How many conversations the extension still holds in-memory state for: a repeat guard, an idle timer or a queued call. */
|
|
75
|
+
retained(): number;
|
|
76
|
+
};
|
|
77
|
+
export { createWebExtension, type WebExtensionOptions } from "./web.js";
|
|
78
|
+
export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
|
|
79
|
+
export declare function createBrowserExtension<D extends PageDriver>(options: BrowserExtensionOptions<D>): BrowserExtensionHandle;
|
package/dist/durable.js
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
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, custodyTools, newSessionRecord, notices, NAVIGATION_CAP, relaunchRefusal, SESSION_REPLACED, sessionSpec } from "./core/custody.js";
|
|
5
|
+
import { forModel } from "./durable-result.js";
|
|
6
|
+
import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
|
|
7
|
+
import { browserFailure, classifyBrowserError } from "./core/failures.js";
|
|
8
|
+
import { pageTools } from "./core/tools.js";
|
|
9
|
+
import { useWebsite, useWebsiteContract } from "./core/sites.js";
|
|
10
|
+
import { leaseTag } from "./core/lease.js";
|
|
11
|
+
import { createRedactor, redactDeep, scrubPageUrl } from "./core/redact.js";
|
|
12
|
+
import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, providerKeyValues } from "./core/session-control.js";
|
|
13
|
+
import { custodyStore, now } from "./store.js";
|
|
14
|
+
import { resolvePrices, sessionCharge } from "./core/usage.js";
|
|
15
|
+
export { createWebExtension } from "./web.js";
|
|
16
|
+
export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
|
|
17
|
+
const PLANE = "default";
|
|
18
|
+
const UNCONFIGURED = { label: "", run: "", policy: DEFAULT_BROWSER_POLICY };
|
|
19
|
+
const NOT_CONFIGURED = new BrowserFailureError(browserFailure("browser_unavailable", "This conversation has no browser configuration, so no browser can be launched here; use web_fetch or another source."));
|
|
20
|
+
const emptySessions = () => ({ current: {}, sessions: [], notice: null });
|
|
21
|
+
async function drainReleases(name, harness, context, signal) {
|
|
22
|
+
signal?.throwIfAborted();
|
|
23
|
+
const drained = (async () => {
|
|
24
|
+
for (;;) {
|
|
25
|
+
const live = (await harness.inspect(context)).tasks.filter((task) => task.record.kind === `${name}.release`);
|
|
26
|
+
if (!live.length)
|
|
27
|
+
return;
|
|
28
|
+
await Promise.all(live.map((task) => harness.waitForTask(task.record.id, context)));
|
|
29
|
+
}
|
|
30
|
+
})();
|
|
31
|
+
if (!signal)
|
|
32
|
+
return drained;
|
|
33
|
+
const done = new AbortController();
|
|
34
|
+
try {
|
|
35
|
+
await Promise.race([drained, new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true, signal: done.signal }))]);
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
done.abort();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const open = (record) => record?.state === "live" || record?.state === "creating";
|
|
42
|
+
// A child gets the browser and web tools only, never use_website, so it cannot start children of its own.
|
|
43
|
+
const CHILD_TOOLS = new Set([...BROWSER_TOOL_NAMES, ...WEB_TOOL_NAMES]);
|
|
44
|
+
class Attachments {
|
|
45
|
+
drivers = new Map();
|
|
46
|
+
observers = new Map();
|
|
47
|
+
driver(tag) {
|
|
48
|
+
return this.drivers.get(tag);
|
|
49
|
+
}
|
|
50
|
+
observer(tag) {
|
|
51
|
+
return this.observers.get(tag);
|
|
52
|
+
}
|
|
53
|
+
attach(tag, driver, observer) {
|
|
54
|
+
this.observers.set(tag, observer);
|
|
55
|
+
this.drivers.set(tag, driver);
|
|
56
|
+
}
|
|
57
|
+
async detach(tag) {
|
|
58
|
+
const driver = this.drivers.get(tag);
|
|
59
|
+
this.drivers.delete(tag);
|
|
60
|
+
this.observers.get(tag)?.close();
|
|
61
|
+
this.observers.delete(tag);
|
|
62
|
+
if (driver)
|
|
63
|
+
await closeDriver(driver);
|
|
64
|
+
}
|
|
65
|
+
/** Let go of a dead driver connection and nothing else: a healthy observer stays attached, so a page that sends
|
|
66
|
+
* something before the next call is still held. When the observer is dead too, both go. */
|
|
67
|
+
async detachDriver(tag) {
|
|
68
|
+
if (this.observers.get(tag)?.closed)
|
|
69
|
+
return this.detach(tag);
|
|
70
|
+
const driver = this.drivers.get(tag);
|
|
71
|
+
this.drivers.delete(tag);
|
|
72
|
+
if (driver)
|
|
73
|
+
await closeDriver(driver);
|
|
74
|
+
}
|
|
75
|
+
tags() {
|
|
76
|
+
return [...new Set([...this.drivers.keys(), ...this.observers.keys()])];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function configOf(c, read, cid, context) {
|
|
80
|
+
const config = await read.snapshot(c.Config, cid, context);
|
|
81
|
+
if (!config?.run)
|
|
82
|
+
throw NOT_CONFIGURED;
|
|
83
|
+
return config;
|
|
84
|
+
}
|
|
85
|
+
async function providerOf(c, read, cid, plane, context) {
|
|
86
|
+
return c.options.provider({ conversationId: cid, plane, config: await configOf(c, read, cid, context) });
|
|
87
|
+
}
|
|
88
|
+
const rowOf = (cid, record) => ({ tag: record.tag, conversationId: cid, plane: record.plane, provider: record.provider, resourceId: record.resourceId, state: record.state });
|
|
89
|
+
async function emitObserver(c, row) {
|
|
90
|
+
try {
|
|
91
|
+
await c.options.onObserver?.(row);
|
|
92
|
+
}
|
|
93
|
+
catch { }
|
|
94
|
+
}
|
|
95
|
+
async function emit(c, cid, label, record, change, provider) {
|
|
96
|
+
if (!c.options.onSession)
|
|
97
|
+
return;
|
|
98
|
+
try {
|
|
99
|
+
const ref = record.resourceId === null ? null : { id: record.resourceId, tag: record.tag };
|
|
100
|
+
const view = change !== "released" && ref && provider?.liveView ? await provider.liveView(ref) : null;
|
|
101
|
+
// 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
|
|
102
|
+
// scrubbed, since its query can carry a credential.
|
|
103
|
+
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) })) };
|
|
104
|
+
await c.options.onSession({ conversationId: cid, label, session: record, liveView }, change);
|
|
105
|
+
}
|
|
106
|
+
catch { }
|
|
107
|
+
}
|
|
108
|
+
async function stateOf(c, scope) {
|
|
109
|
+
return (await scope.read.snapshot(c.Sessions, scope.cid, scope.context)) ?? emptySessions();
|
|
110
|
+
}
|
|
111
|
+
const failure = (error, scope) => error instanceof BrowserFailureError ? error : new BrowserFailureError(classifyBrowserError(error, false, { aborted: scope.signal.aborted }));
|
|
112
|
+
async function attachLive(c, scope, record) {
|
|
113
|
+
const held = c.held.driver(record.tag);
|
|
114
|
+
// An observer whose socket closed holds nothing: driver and observer are attached again together.
|
|
115
|
+
if (held && !c.held.observer(record.tag)?.closed)
|
|
116
|
+
return held;
|
|
117
|
+
if (held)
|
|
118
|
+
await c.held.detach(record.tag);
|
|
119
|
+
const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
|
|
120
|
+
const ref = { id: record.resourceId, tag: record.tag };
|
|
121
|
+
try {
|
|
122
|
+
return await connect(c, scope, provider, ref);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (!(await markEnded(c, scope, record, provider)))
|
|
126
|
+
throw failure(error, scope);
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async function connect(c, scope, provider, ref) {
|
|
131
|
+
const config = await configOf(c, scope.read, scope.cid, scope.context);
|
|
132
|
+
const { actions: policy, batchTimeoutMs } = config.policy;
|
|
133
|
+
const target = await provider.attach(ref, scope.signal);
|
|
134
|
+
const driver = await c.options.driver(target, scope.signal, { batchTimeoutMs });
|
|
135
|
+
let unattached = null;
|
|
136
|
+
// A healthy observer that outlived its driver's connection is kept, not opened a second time.
|
|
137
|
+
const kept = c.held.observer(ref.tag);
|
|
138
|
+
const open = c.options.openObserver ?? EffectObserver.open.bind(EffectObserver);
|
|
139
|
+
const observer = kept && !kept.closed ? kept : policy ? await open(target, policy === "allow" ? null : effectDecider(policy, c.options.decisions), batchTimeoutMs).catch((error) => { unattached = error; return null; }) : null;
|
|
140
|
+
// A policy that holds requests never degrades to browsing without the hold.
|
|
141
|
+
if (policy && policy !== "allow" && !observer) {
|
|
142
|
+
await closeDriver(driver);
|
|
143
|
+
throw new BrowserFailureError(browserFailure("browser_unavailable", "The browser's request observer could not attach, and this run's action policy needs it to hold requests; the browser is not used without it.", { retryable: true }));
|
|
144
|
+
}
|
|
145
|
+
c.held.attach(ref.tag, driver, observer);
|
|
146
|
+
if (policy === "allow" && !observer)
|
|
147
|
+
await emitObserver(c, { conversationId: scope.cid, label: config.label, tag: ref.tag, session_id: ref.id, policy, code: observerFailure(unattached) });
|
|
148
|
+
return driver;
|
|
149
|
+
}
|
|
150
|
+
async function markEnded(c, scope, record, provider) {
|
|
151
|
+
const status = await provider.status({ id: record.resourceId, tag: record.tag }, scope.signal).catch(() => "running");
|
|
152
|
+
if (status !== "gone" && status !== "stopped")
|
|
153
|
+
return false;
|
|
154
|
+
await scope.commit((tx) => c.store.move(tx, rowOf(scope.cid, record), { state: "released", reason: "ended", at: now() }));
|
|
155
|
+
await c.held.detach(record.tag);
|
|
156
|
+
await c.store.emitReleased(scope.cid, record.tag, scope.read, scope.context);
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
async function settleCreating(c, scope, record) {
|
|
160
|
+
const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
|
|
161
|
+
try {
|
|
162
|
+
await c.store.bindByTag(provider, rowOf(scope.cid, record), scope.commit, scope.signal);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
throw failure(error, scope);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async function create(c, scope, overrides, presetTag) {
|
|
169
|
+
const config = await configOf(c, scope.read, scope.cid, scope.context);
|
|
170
|
+
const provider = await c.options.provider({ conversationId: scope.cid, plane: scope.plane, config });
|
|
171
|
+
const tag = presetTag ?? leaseTag("ar", config.run, scope.cid, (await stateOf(c, scope)).sessions.length + 1);
|
|
172
|
+
const spec = sessionSpec(config, tag, overrides);
|
|
173
|
+
const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now(), honours: provider.caps.settings });
|
|
174
|
+
const row = rowOf(scope.cid, record);
|
|
175
|
+
await scope.commit(async (tx) => {
|
|
176
|
+
const state = await tx.doc(c.Sessions, scope.cid);
|
|
177
|
+
state.sessions.push(record);
|
|
178
|
+
state.current[scope.plane] = state.sessions.length - 1;
|
|
179
|
+
await c.store.begin(tx, row);
|
|
180
|
+
});
|
|
181
|
+
// An answer lost on the way back is not a session that never started: it is settled by its tag.
|
|
182
|
+
const ref = await provider.create(spec, scope.signal).then(async (made) => { await scope.commit((tx) => c.store.move(tx, row, { state: "live", resourceId: made.id, at: now() })); return made; }, async (error) => (await c.store.bindByTag(provider, row, scope.commit, scope.signal, await provider.findByTag(tag, scope.signal).catch(() => []))) ?? Promise.reject(failure(error, scope)));
|
|
183
|
+
const live = { ...record, state: "live", resourceId: ref.id };
|
|
184
|
+
try {
|
|
185
|
+
const driver = await connect(c, scope, provider, ref);
|
|
186
|
+
await emit(c, scope.cid, config.label, live, "launched", provider);
|
|
187
|
+
return { record: live, driver };
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
throw failure(error, scope);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async function acquire(c, scope) {
|
|
194
|
+
let note = null;
|
|
195
|
+
for (let turn = 0; turn < 4; turn += 1) {
|
|
196
|
+
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
197
|
+
if (record?.state === "live") {
|
|
198
|
+
const driver = await attachLive(c, scope, record);
|
|
199
|
+
if (driver)
|
|
200
|
+
return { record, driver, note };
|
|
201
|
+
note = notices.ended(record.lastUrl);
|
|
202
|
+
}
|
|
203
|
+
else if (record?.state === "creating") {
|
|
204
|
+
await settleCreating(c, scope, record);
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
return { ...(await create(c, scope, {})), note };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
throw new Error(`browser custody for conversation ${scope.cid} did not settle`);
|
|
211
|
+
}
|
|
212
|
+
/** Custody's notice is kept in the call's memo before it is cleared, so a call rerun after a crash still tells it. */
|
|
213
|
+
async function attached(c, scope, record, driver, note) {
|
|
214
|
+
const state = await stateOf(c, scope);
|
|
215
|
+
const notice = await scope.keep("notice", [note, state.notice].filter(Boolean).join(" "));
|
|
216
|
+
if (state.notice !== null)
|
|
217
|
+
await scope.commit(async (tx) => { (await tx.doc(c.Sessions, scope.cid)).notice = null; });
|
|
218
|
+
const fresh = state.sessions.find((r) => r.tag === record.tag) ?? record;
|
|
219
|
+
const interrupted = await cutOf(c, scope, journalOf(state, scope.plane));
|
|
220
|
+
const recorded = Boolean((await providerOf(c, scope.read, scope.cid, scope.plane, scope.context)).recordings);
|
|
221
|
+
return { driver, tag: record.tag, sessionId: fresh.resourceId, record: fresh, notice: notice || null, interrupted, recorded, effects: c.held.observer(record.tag) ?? null };
|
|
222
|
+
}
|
|
223
|
+
async function releaseRecord(c, scope, record, reason) {
|
|
224
|
+
await scope.commit((tx) => c.store.requestRelease(tx, rowOf(scope.cid, record), reason, now()));
|
|
225
|
+
await c.held.detach(record.tag);
|
|
226
|
+
}
|
|
227
|
+
const editState = (c, scope, edit) => scope.commit(async (tx) => edit(await tx.doc(c.Sessions, scope.cid)));
|
|
228
|
+
const journalOf = (state, plane) => [...state.sessions].reverse().find((r) => r.plane === plane && r.pendingEffect !== null)?.pendingEffect ?? null;
|
|
229
|
+
const clearJournal = (c, scope, callId) => editState(c, scope, (state) => { for (const record of state.sessions)
|
|
230
|
+
if (record.plane === scope.plane && record.pendingEffect?.callId === callId)
|
|
231
|
+
record.pendingEffect = null; });
|
|
232
|
+
/** Whether a journaled action's own answer was committed as a success: its result, found by pi's typed tool-result
|
|
233
|
+
* entry. The scan covers only the entry's conversation from where it was journaled on, never the whole history. */
|
|
234
|
+
async function answered(scope, pending) {
|
|
235
|
+
const after = pending.after;
|
|
236
|
+
if (after === undefined)
|
|
237
|
+
return false;
|
|
238
|
+
return scope.commit(async (tx) => {
|
|
239
|
+
let cursor;
|
|
240
|
+
do {
|
|
241
|
+
const page = await tx.scanEntries({ conversationId: scope.cid, minEntryId: after, order: "ascending" }, 100, cursor);
|
|
242
|
+
for (const entry of page.items) {
|
|
243
|
+
const message = ToolResultEntry.is(entry) ? entry.model?.[0] : undefined;
|
|
244
|
+
if (message?.role === "toolResult" && message.toolCallId === pending.callId)
|
|
245
|
+
return message.isError !== true;
|
|
246
|
+
}
|
|
247
|
+
cursor = page.next;
|
|
248
|
+
} while (cursor !== undefined);
|
|
249
|
+
return false;
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
/** The cut a call answers for. In this process an entry is in flight or answered, never cut; one an earlier process
|
|
253
|
+
* wrote is a cut unless its action finished and pi committed its answer, which only then is looked up. */
|
|
254
|
+
async function cutOf(c, scope, pending) {
|
|
255
|
+
if (!pending || pending.incarnation === c.incarnation)
|
|
256
|
+
return null;
|
|
257
|
+
if (!pending.finished || pending.told || !(await answered(scope, pending)))
|
|
258
|
+
return pending;
|
|
259
|
+
await clearJournal(c, scope, pending.callId);
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
async function relaunchOn(c, scope, api, slot, overrides) {
|
|
263
|
+
const config = await configOf(c, scope.read, scope.cid, scope.context);
|
|
264
|
+
const refusal = relaunchRefusal(config.policy, overrides);
|
|
265
|
+
if (refusal)
|
|
266
|
+
throw new BrowserFailureError(refusal);
|
|
267
|
+
// The relaunch's session is chosen in a memo before its create commits: a rerun runs on it or says
|
|
268
|
+
// session_replaced, never a second launch; a memo with no record yet is an uncommitted create and goes ahead.
|
|
269
|
+
const find = async (tag) => (await stateOf(c, scope)).sessions.find((r) => r.tag === tag);
|
|
270
|
+
const launched = await api.memo(slot, scope.context);
|
|
271
|
+
let mine = await find(launched);
|
|
272
|
+
if (mine) {
|
|
273
|
+
if (mine.state === "creating") {
|
|
274
|
+
await settleCreating(c, scope, mine);
|
|
275
|
+
mine = await find(launched);
|
|
276
|
+
}
|
|
277
|
+
const driver = mine?.state === "live" ? await attachLive(c, scope, mine) : null;
|
|
278
|
+
if (!mine || !driver)
|
|
279
|
+
throw new BrowserFailureError(SESSION_REPLACED);
|
|
280
|
+
return attached(c, scope, mine, driver, null);
|
|
281
|
+
}
|
|
282
|
+
const state = await stateOf(c, scope);
|
|
283
|
+
const tag = launched ?? await api.memo(slot, leaseTag("ar", config.run, scope.cid, state.sessions.length + 1), scope.context);
|
|
284
|
+
const old = currentRecord(state, scope.plane);
|
|
285
|
+
if (old && open(old) && old.tag !== tag)
|
|
286
|
+
await releaseRecord(c, scope, old, "relaunch");
|
|
287
|
+
const made = await create(c, scope, overrides, tag);
|
|
288
|
+
return attached(c, scope, made.record, made.driver, null);
|
|
289
|
+
}
|
|
290
|
+
function portFor(c, api, context) {
|
|
291
|
+
const memo = (slot) => `${c.name}:${slot}:${PLANE}`;
|
|
292
|
+
const scope = { cid: api.conversationId, plane: PLANE, context, read: api, signal: context.abortSignal ?? new AbortController().signal, commit: (change) => api.commit(change, context), keep: async (slot, value) => {
|
|
293
|
+
// An earlier attempt's text comes first; an empty one is never memoized, so it cannot shadow a later notice.
|
|
294
|
+
const prior = await api.memo(memo(slot), context);
|
|
295
|
+
if (prior !== undefined)
|
|
296
|
+
return [prior, value].filter(Boolean).join(" ");
|
|
297
|
+
return value ? api.memo(memo(slot), value, context) : "";
|
|
298
|
+
} };
|
|
299
|
+
const key = `${scope.cid}:${scope.plane}`;
|
|
300
|
+
return {
|
|
301
|
+
session: () => c.serial.run(key, async () => {
|
|
302
|
+
const ran = await api.memo(memo("ran"), context);
|
|
303
|
+
if (ran !== undefined) {
|
|
304
|
+
const record = (await stateOf(c, scope)).sessions.find((r) => r.tag === ran);
|
|
305
|
+
const driver = record?.state === "live" ? await attachLive(c, scope, record) : null;
|
|
306
|
+
if (!record || !driver)
|
|
307
|
+
throw new BrowserFailureError(SESSION_REPLACED);
|
|
308
|
+
return attached(c, scope, record, driver, null);
|
|
309
|
+
}
|
|
310
|
+
const { record, driver, note } = await acquire(c, scope);
|
|
311
|
+
await api.memo(memo("ran"), record.tag, context);
|
|
312
|
+
return attached(c, scope, record, driver, note);
|
|
313
|
+
}),
|
|
314
|
+
relaunch: (overrides) => c.serial.run(key, () => relaunchOn(c, scope, api, memo("relaunch"), overrides)),
|
|
315
|
+
release: () => c.serial.run(key, async () => {
|
|
316
|
+
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
317
|
+
if (!record || !open(record))
|
|
318
|
+
return { released: record?.state === "releasing", sessionId: record?.resourceId ?? null };
|
|
319
|
+
await releaseRecord(c, scope, record, "tool");
|
|
320
|
+
return { released: true, sessionId: record.resourceId };
|
|
321
|
+
}),
|
|
322
|
+
dispatching: (effect) => scope.commit(async (tx) => {
|
|
323
|
+
const record = currentRecord(await tx.doc(c.Sessions, scope.cid), scope.plane);
|
|
324
|
+
if (!record)
|
|
325
|
+
return;
|
|
326
|
+
const newest = (await tx.scanEntries({ conversationId: scope.cid, order: "descending" }, 1)).items[0]?.id;
|
|
327
|
+
record.pendingEffect = { ...effect, url: effect.url === null ? null : scrubPageUrl(effect.url, c.redact), at: now(), sent: [], incarnation: c.incarnation, ...(newest === undefined ? {} : { after: newest }) };
|
|
328
|
+
}),
|
|
329
|
+
journal: (row) => editState(c, scope, (state) => {
|
|
330
|
+
const pending = currentRecord(state, scope.plane)?.pendingEffect;
|
|
331
|
+
if (!pending)
|
|
332
|
+
return;
|
|
333
|
+
const sent = pending.sent ?? (pending.sent = []);
|
|
334
|
+
const scrubbed = { ...row, origin: c.redact(row.origin), path: c.redact(row.path) };
|
|
335
|
+
const at = sent.findIndex((r) => r.requestId === row.requestId);
|
|
336
|
+
if (at === -1)
|
|
337
|
+
sent.push(scrubbed);
|
|
338
|
+
else
|
|
339
|
+
sent[at] = scrubbed;
|
|
340
|
+
}),
|
|
341
|
+
mark: (step, callId) => editState(c, scope, (state) => {
|
|
342
|
+
const pending = state.sessions.find((r) => r.plane === scope.plane && r.pendingEffect?.callId === callId)?.pendingEffect;
|
|
343
|
+
if (pending)
|
|
344
|
+
pending[step] = true;
|
|
345
|
+
}),
|
|
346
|
+
settle: (callId) => clearJournal(c, scope, callId),
|
|
347
|
+
navigated: async (page) => {
|
|
348
|
+
// A page URL can carry a credential in any query value, its fragment or its userinfo: scrubbed before it is
|
|
349
|
+
// committed or reported.
|
|
350
|
+
const url = scrubPageUrl(page, c.redact);
|
|
351
|
+
await editState(c, scope, (state) => {
|
|
352
|
+
const record = currentRecord(state, scope.plane);
|
|
353
|
+
if (!record)
|
|
354
|
+
return;
|
|
355
|
+
record.navigation.push({ at: now(), url });
|
|
356
|
+
if (record.navigation.length > NAVIGATION_CAP)
|
|
357
|
+
record.navigation.splice(0, record.navigation.length - NAVIGATION_CAP);
|
|
358
|
+
record.lastUrl = url;
|
|
359
|
+
});
|
|
360
|
+
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
361
|
+
if (record)
|
|
362
|
+
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));
|
|
363
|
+
},
|
|
364
|
+
dropped: () => c.serial.run(key, async () => {
|
|
365
|
+
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
366
|
+
if (record)
|
|
367
|
+
await c.held.detachDriver(record.tag);
|
|
368
|
+
}),
|
|
369
|
+
ended: async () => {
|
|
370
|
+
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
371
|
+
if (record?.state !== "live")
|
|
372
|
+
return false;
|
|
373
|
+
return markEnded(c, scope, record, await providerOf(c, scope.read, scope.cid, scope.plane, scope.context));
|
|
374
|
+
},
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
/** A plane nobody calls for its idle window is released, never mid-call. A dead process's timers die with it, and the
|
|
378
|
+
* provider's own idle bound takes over. */
|
|
379
|
+
async function releaseIdle(c, cid, fired, idleMs) {
|
|
380
|
+
const conversation = c.opened && await c.opened.harness.conversation(cid, c.opened.context);
|
|
381
|
+
if (!conversation)
|
|
382
|
+
return;
|
|
383
|
+
// Only the still-current timer releases, checked inside the commit: a call since, even one that ran while the
|
|
384
|
+
// lookup above waited, replaced it.
|
|
385
|
+
await releasePlane(c, conversation, "idle", c.opened.context, () => c.idle.isCurrent(cid, fired), Math.round(idleMs / 1000));
|
|
386
|
+
}
|
|
387
|
+
/** A release the model did not ask for (idle, close) commits its notice with it, so whichever call next attaches a
|
|
388
|
+
* session tells it, even when the call that opened the replacement failed or died. */
|
|
389
|
+
async function releasePlane(c, conversation, reason, context, still = () => true, idleS = 0) {
|
|
390
|
+
const key = `${conversation.id}:${PLANE}`;
|
|
391
|
+
const released = await c.serial.run(key, async () => {
|
|
392
|
+
const tags = await conversation.commit(async (tx) => {
|
|
393
|
+
const state = await tx.doc(c.Sessions, conversation.id);
|
|
394
|
+
const record = still() ? currentRecord(state, PLANE) : null;
|
|
395
|
+
if (!record || !open(record))
|
|
396
|
+
return [];
|
|
397
|
+
await c.store.requestRelease(tx, rowOf(conversation.id, record), reason, now());
|
|
398
|
+
if (reason === "idle" || reason === "close")
|
|
399
|
+
c.store.addNotice(state, notices.released(reason, record.lastUrl, idleS));
|
|
400
|
+
return [record.tag];
|
|
401
|
+
}, context);
|
|
402
|
+
for (const tag of tags)
|
|
403
|
+
await c.held.detach(tag);
|
|
404
|
+
return tags.length > 0;
|
|
405
|
+
});
|
|
406
|
+
if (reason === "close") {
|
|
407
|
+
c.idle.forget(conversation.id);
|
|
408
|
+
c.guards.delete(conversation.id);
|
|
409
|
+
}
|
|
410
|
+
else if (released)
|
|
411
|
+
c.idle.cancel(conversation.id);
|
|
412
|
+
}
|
|
413
|
+
async function chargeCall(c, api, context) {
|
|
414
|
+
if (currentRecord(await api.snapshot(c.Sessions, api.conversationId, context), PLANE)?.state !== "live")
|
|
415
|
+
return null;
|
|
416
|
+
return api.commit(async (tx) => {
|
|
417
|
+
const record = currentRecord(await tx.doc(c.Sessions, api.conversationId), PLANE);
|
|
418
|
+
if (record?.state !== "live")
|
|
419
|
+
return null;
|
|
420
|
+
const { spent, usage } = c.meter(record.spent, now());
|
|
421
|
+
record.spent = spent;
|
|
422
|
+
return usage;
|
|
423
|
+
}, context);
|
|
424
|
+
}
|
|
425
|
+
const withSessionTime = (own, charged) => {
|
|
426
|
+
if (!charged)
|
|
427
|
+
return own;
|
|
428
|
+
const ownCost = (own?.cost ?? {});
|
|
429
|
+
return { ...charged.usage, ...own, cost: { ...charged.usage.cost, ...ownCost, total: charged.usage.cost.total + (ownCost.total ?? 0) } };
|
|
430
|
+
};
|
|
431
|
+
function toolsFor(c, impls) {
|
|
432
|
+
return BROWSER_TOOLS
|
|
433
|
+
.filter((contract) => impls[contract.name] && (contract.listedWhen !== "downloads" || c.options.workspace))
|
|
434
|
+
.map((contract) => defineTool({
|
|
435
|
+
name: contract.name,
|
|
436
|
+
description: contract.description,
|
|
437
|
+
parameters: contract.parameters,
|
|
438
|
+
replay: contract.replay,
|
|
439
|
+
executionMode: contract.executionMode,
|
|
440
|
+
execute: async (args, api, context) => {
|
|
441
|
+
const config = await api.snapshot(c.Config, api.conversationId, context);
|
|
442
|
+
c.idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
|
|
443
|
+
try {
|
|
444
|
+
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 };
|
|
445
|
+
// Inside an async function, so a host tool that throws before it returns a promise is caught too.
|
|
446
|
+
const out = await (async () => impls[contract.name](args, portFor(c, api, context), call))().catch((error) => {
|
|
447
|
+
// A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
|
|
448
|
+
const typed = error instanceof BrowserFailureError ? error.failure : classifyBrowserError(error, contract.effect === "effect", { aborted: context.abortSignal?.aborted === true });
|
|
449
|
+
return { content: [{ type: "text", text: JSON.stringify(typed) }], isError: true };
|
|
450
|
+
});
|
|
451
|
+
// A charge that cannot be committed now is carried by the next one.
|
|
452
|
+
const usage = withSessionTime(out.usage, await chargeCall(c, api, context).catch(() => null));
|
|
453
|
+
return {
|
|
454
|
+
...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: c.redact(item.text) } : item)),
|
|
455
|
+
...(out.isError ? { isError: true } : {}),
|
|
456
|
+
...(out.details ? { details: redactDeep(out.details, c.redact) } : {}),
|
|
457
|
+
...(usage ? { usage: usage } : {}),
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
finally {
|
|
461
|
+
c.idle.activity(api.conversationId, -1);
|
|
462
|
+
}
|
|
463
|
+
},
|
|
464
|
+
}));
|
|
465
|
+
}
|
|
466
|
+
function sectionFor(c, names) {
|
|
467
|
+
return {
|
|
468
|
+
key: c.name,
|
|
469
|
+
async render(input, context) {
|
|
470
|
+
if (!input.agent.tools.some((tool) => names.has(tool.name)))
|
|
471
|
+
return undefined;
|
|
472
|
+
const config = await input.read.snapshot(c.Config, input.conversationId, context);
|
|
473
|
+
return [browserSection({ idleReleaseS: config?.policy.idleReleaseS ?? UNCONFIGURED.policy.idleReleaseS }), c.options.section?.addendum].filter(Boolean).join("\n\n");
|
|
474
|
+
},
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
function childConversation(c, api, context) {
|
|
478
|
+
return async (task) => {
|
|
479
|
+
const config = await api.snapshot(c.Config, api.conversationId, context);
|
|
480
|
+
const childTools = (await api.agent(context)).tools.filter((tool) => CHILD_TOOLS.has(tool.name));
|
|
481
|
+
// One child per request, recorded in the commit that creates it: a replay or a repeated call finds it again, and
|
|
482
|
+
// its submission is deduplicated by request_id.
|
|
483
|
+
const id = await api.commit(async (tx) => {
|
|
484
|
+
const children = await tx.doc(c.Children, api.conversationId);
|
|
485
|
+
const key = `${task.site}:${task.requestId}`;
|
|
486
|
+
const known = children.byRequest[key];
|
|
487
|
+
if (known !== undefined)
|
|
488
|
+
return known;
|
|
489
|
+
const child = await tx.createConversation({ ownership: { kind: "task", taskId: api.taskId } });
|
|
490
|
+
await configure(tx, child.id, { tools: childTools, instructions: null });
|
|
491
|
+
Object.assign(await tx.doc(c.Config, child.id), config ?? UNCONFIGURED);
|
|
492
|
+
children.byRequest[key] = child.id;
|
|
493
|
+
return child.id;
|
|
494
|
+
}, context);
|
|
495
|
+
const child = await api.conversation(id, context);
|
|
496
|
+
if (!child)
|
|
497
|
+
throw new Error("the child conversation is gone");
|
|
498
|
+
try {
|
|
499
|
+
const settled = await (await child.submit({ type: "input", content: task.prompt, requestId: task.requestId }, context)).wait(context);
|
|
500
|
+
const report = await api.commit(async (tx) => {
|
|
501
|
+
for (const entry of (await tx.scanEntries({ conversationId: id, order: "descending" }, 50)).items) {
|
|
502
|
+
for (const message of [...(entry.model ?? [])].reverse()) {
|
|
503
|
+
if (message.role !== "assistant")
|
|
504
|
+
continue;
|
|
505
|
+
const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
|
|
506
|
+
if (text)
|
|
507
|
+
return text;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return "";
|
|
511
|
+
}, context);
|
|
512
|
+
if (settled.status !== "done" || !report)
|
|
513
|
+
throw new Error("the child finished without a report");
|
|
514
|
+
return report;
|
|
515
|
+
}
|
|
516
|
+
finally {
|
|
517
|
+
await releasePlane(c, { id, commit: (change, ctx) => api.commit(change, ctx) }, "close", context).catch(() => undefined);
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
function siteTool(c, sites) {
|
|
522
|
+
const contract = useWebsiteContract(sites.listing);
|
|
523
|
+
return defineTool({
|
|
524
|
+
name: contract.name,
|
|
525
|
+
description: contract.description,
|
|
526
|
+
parameters: contract.parameters,
|
|
527
|
+
replay: contract.replay,
|
|
528
|
+
executionMode: contract.executionMode,
|
|
529
|
+
execute: async (args, api, context) => {
|
|
530
|
+
const out = await useWebsite(args, sites.port, sites.listing, { signal: context.abortSignal ?? new AbortController().signal, runChild: childConversation(c, api, context) });
|
|
531
|
+
return { ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: c.redact(item.text) } : item)), ...(out.isError ? { isError: true } : {}) };
|
|
532
|
+
},
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
export function createBrowserExtension(options) {
|
|
536
|
+
const name = options.name ?? "browser";
|
|
537
|
+
const redact = createRedactor(() => providerKeyValues(process.env, options.redact?.values));
|
|
538
|
+
const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED) });
|
|
539
|
+
const Children = defineDoc({ kind: `${name}.children`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ byRequest: {} }) });
|
|
540
|
+
// A fork starts with no sessions: it never shares a live browser.
|
|
541
|
+
const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: emptySessions });
|
|
542
|
+
const readers = { options, redact, Config };
|
|
543
|
+
/** Class name and redacted message only: a vendor SDK's error text can repeat the request's credentials. */
|
|
544
|
+
const scrubbed = (error) => Object.assign(new Error(redact(error instanceof Error ? error.message : String(error))), { name: error instanceof Error ? error.name : "Error" });
|
|
545
|
+
const prices = resolvePrices(options.prices);
|
|
546
|
+
const priceState = prices.sessionUsdPerHour === null ? "unpriced" : "priced";
|
|
547
|
+
const meter = (spent, at, final = false) => {
|
|
548
|
+
const charged = sessionCharge(spent, at, prices, priceState, final);
|
|
549
|
+
return { spent: { ...charged.spent, state: charged.usage.state }, usage: charged.usage };
|
|
550
|
+
};
|
|
551
|
+
const store = custodyStore({
|
|
552
|
+
name, Config, Sessions, meter, scrubbed, createDeadlineMs: options.createDeadlineMs ?? CREATE_DEADLINE_MS,
|
|
553
|
+
providerOf: (read, cid, plane, context) => providerOf(readers, read, cid, plane, context),
|
|
554
|
+
emit: (cid, label, record, change) => emit(readers, cid, label, record, change),
|
|
555
|
+
});
|
|
556
|
+
const c = {
|
|
557
|
+
...readers, name, Sessions, Children, store, meter, held: new Attachments(), serial: keyedSerializer(), guards: new Map(), opened: null, incarnation: randomUUID(),
|
|
558
|
+
idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
|
|
559
|
+
};
|
|
560
|
+
const own = { ...custodyTools, ...pageTools({ guards: c.guards }), ...options.tools };
|
|
561
|
+
// pi checks a call's arguments against the tool's schema before execute, so each implementation receives its own shape.
|
|
562
|
+
const tools = toolsFor(c, own);
|
|
563
|
+
const names = new Set(tools.map((tool) => tool.name));
|
|
564
|
+
const siteTools = options.sites ? [siteTool(c, options.sites)] : [];
|
|
565
|
+
return {
|
|
566
|
+
extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [sectionFor(c, names)], tasks: [store.ReleaseTask] }),
|
|
567
|
+
docs: { Config, Sessions, Inventory: store.Inventory, Children },
|
|
568
|
+
tools: [...tools, ...siteTools],
|
|
569
|
+
release: (conversation, reason, context) => releasePlane(c, conversation, reason, context),
|
|
570
|
+
async reconcile(harness, isActive, context) {
|
|
571
|
+
c.opened = { harness, context };
|
|
572
|
+
return store.reconcileAll(harness, isActive, context);
|
|
573
|
+
},
|
|
574
|
+
drain: (harness, context, signal) => drainReleases(name, harness, context, signal),
|
|
575
|
+
async close() {
|
|
576
|
+
c.idle.clear();
|
|
577
|
+
// A session whose driver was let go and not yet replaced still has its observer attached: close both kinds.
|
|
578
|
+
await Promise.all(c.held.tags().map((tag) => c.held.detach(tag)));
|
|
579
|
+
},
|
|
580
|
+
retained: () => new Set([...c.guards.keys(), ...c.idle.keys(), ...c.serial.keys().map((key) => Number(key.slice(0, key.indexOf(":"))))]).size,
|
|
581
|
+
};
|
|
582
|
+
}
|