@parcha/pi-browser 0.1.0-beta.29 → 0.1.0-beta.31
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 +18 -0
- package/README.md +13 -2
- package/dist/coding-agent.js +3 -2
- package/dist/core/contract.d.ts +9 -0
- package/dist/core/contract.js +14 -2
- package/dist/core/failures.d.ts +2 -0
- package/dist/core/failures.js +8 -1
- package/dist/core/host.d.ts +13 -0
- package/dist/durable/store.d.ts +7 -1
- package/dist/durable/store.js +70 -20
- package/dist/durable.d.ts +13 -2
- package/dist/durable.js +31 -9
- package/dist/providers/browserbase.js +7 -2
- package/dist/providers/kernel.js +7 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.31 (2026-11-06)
|
|
6
|
+
|
|
7
|
+
- A model granted both web_fetch and the browser is now told which one has cookies. Asked to "Open https://httpbin.org/cookies", a pi run picked web_fetch, which has no cookies, and answered with an empty page; it picked the browser only when told to. The tool descriptions the model reads now say:
|
|
8
|
+
- **web_fetch** has no cookies, sign-ins or session: it reads one page cold, so a page behind a sign-in, or one that depends on an earlier page, needs the browser tool, where this run has it. That holds for serve's web_fetch on every harness and for pi-browser's.
|
|
9
|
+
- **The browser's `run`** keeps this agent's saved sign-ins and cookies, for anything behind a sign-in or a page that depends on an earlier one. It says this only on a run that has a saved sign-in: in serve, a run handed its agent's sign-in; in pi-browser, a host that passes `signIns: true` or a session vault. Without one it says only that the browser keeps cookies across pages, which stays true for a local Chrome, which keeps no saved sign-in.
|
|
10
|
+
- **pi-browser** adds `browserToolsFor(signIns)` (the browser's contracts with `run`'s words for that plane), `BROWSER_KEEPS` (the two sentences), and the durable extension's `signIns` option.
|
|
11
|
+
|
|
12
|
+
## 0.1.0-beta.30 (2026-11-05)
|
|
13
|
+
|
|
14
|
+
- Browser minutes count in a run's spend. Each charge of a `browser` session's time is booked as a tool cost, so it is a `Tool cost` line on the run's timeline, part of its `cost.usd`, and `/usage`'s new `browser_time` meter (dollars, and seconds for runs that have ended); capabilities list `browser_time` in `usage.meters`. Under `max_cost_usd`, the browser's time is held before it runs: a browser call that the cap cannot hold is not made, the model gets the cap's words, and the run's session is released, so no browser minute passes the cap.
|
|
15
|
+
- Prices by provider: Browserbase $0.12 an hour with a 60 s minimum, Kernel (headless) about $0.06 an hour by the second, a local Chrome $0. `AGENTRUN_BROWSER_USD_PER_HOUR_<PROVIDER>` (`_BROWSERBASE`, `_KERNEL`, `_CDP`) sets a provider's own price in US dollars an hour. A provider with no price books its time as an unknown cost, and under a cap its calls are refused.
|
|
16
|
+
- Each browser call is held at what its session ran since its last charge plus two stretches of session time; a stretch is the provider's minimum, pi-browser's 180 s idle window and 30 s for a release to be confirmed (270 s, $0.009, at Browserbase). A session keeps one stretch held until its release is booked.
|
|
17
|
+
- pi-browser: `createBrowserExtension` takes `onCharge(charge, tx, call?)`, called with each session charge (`SessionCharge`: `seconds`, `usd`, `final`, `tag`, `provider`, `state`) in the commit that writes it on the session's record, at each browser call and at the release, or when custody gives up releasing a session. A session found by its tag (its create's answer lost) is billed at its release. A session kept across a reopen has its idle release armed at reconcile, so one no call uses is released an idle window later.
|
|
18
|
+
- A browser session the provider refuses to create (HTTP 401 or 403: a bad key, or a session type the account may not start) now ends released with `create_failed` as soon as the call fails, and the run's end no longer waits on it. Before, the refusal was treated like a create whose answer was lost: the record sat in `releasing` and a background release waited out the create deadline (60 s by default), so a run with a refused key read final about a minute after it completed. Every other failed create (a timeout, a 5xx, a dropped connection) still waits out the deadline, so a session that lands late is still released.
|
|
19
|
+
- A saving profile, or a Browserbase kept context, whose create the provider refuses with 401 or 403 is free for the next saving session at once. Before, the profile stayed claimed for the life of the process (the lookup that would have freed it failed on the same bad key), so every later saving create on it was refused.
|
|
20
|
+
- `isRefusal(error)` is exported: true when a browser provider refused a call with 401 or 403.
|
|
21
|
+
- A browser session found by its tag (its create's answer was lost) is billed at its release even when the release is tried again. Before, a release that stopped the session but could not confirm it started its next attempt without the ids it had found, and a provider's tag lookup lists running sessions only, so the next attempt found nothing and the session's time was never billed or told to the host (`onCharge`). The ids a release finds are now kept across its attempts, handed on to a task that takes over from an aborted one, and used for the session's final charge, also when the release gives up and the session ends lost. The ids a lookup finds are kept even when the release that follows fails, since the stop may have landed before the provider's answer was lost. A reopen's reconcile that stops a lost session found by its tag and then fails keeps the id on the session's record, so the next reconcile releases and bills it.
|
|
22
|
+
|
|
5
23
|
## 0.1.0-beta.29 (2026-11-04)
|
|
6
24
|
|
|
7
25
|
- `createPageClassifier(options)` builds `decisions.classifyPage` over a host's typed-question judge (`PageJudge`, declared here so the package imports no DSL; the DSL's `runJudge` and Jev's runner are assignable to it). It asks one request a page within the run's page budget (`pageBudget`, `PageBudget`, `PAGE_GUARD_MAX_PAGES`). It marks injection at `INJECTION_THRESHOLD` and a wall or content at `PAGE_WALL_THRESHOLD`. It never rejects: a page it cannot judge is `unjudged`, with the reason in its `guard` record. A probability outside 0 to 1 is the wrong shape. A page whose wall it cannot place keeps its injection score, and the snippet screen and `pageNotice` check that score before the wall: a page at or over the threshold is withheld or marked as an injection whatever its wall.
|
package/README.md
CHANGED
|
@@ -203,7 +203,8 @@ the call's own while the provider can still be tried.
|
|
|
203
203
|
`web_fetch` and `web_search` results carry their price as pi usage (the Browserbase provider's list prices; a search
|
|
204
204
|
source's answer at the usage it reports, else the list search price). Session
|
|
205
205
|
minutes are charged by the session meter (`core/usage.ts`, wired into custody): every session tool's result carries the
|
|
206
|
-
time since the last charge, and each released session's record carries its total.
|
|
206
|
+
time since the last charge, and each released session's record carries its total. A host that books session time as spend
|
|
207
|
+
passes `onCharge` (below), which hears each charge in the commit that bills it.
|
|
207
208
|
|
|
208
209
|
|
|
209
210
|
## Failures
|
|
@@ -395,12 +396,21 @@ await browser.reconcile(harness, () => true, context); // settles what a dead
|
|
|
395
396
|
- `decisions`: `classifyPage` and `rankChunks`, answered with your judge. Absent, no page is classified and no find is ranked.
|
|
396
397
|
- `redact.values`: exact strings to scrub besides the built-in shapes.
|
|
397
398
|
- `section.addendum`: your text after the package's prompt section.
|
|
399
|
+
- `signIns`: `true` when the plane's sessions open on the agent's saved sign-ins (your kept profile or context). `run`'s
|
|
400
|
+
description then tells the model the browser keeps them, for a page behind a sign-in; without it, it says only that the
|
|
401
|
+
browser keeps cookies across pages. Absent, it is whether a `sessionVault` is given.
|
|
398
402
|
- `workspace`: where `browser_downloads` writes, and where `browser_upload` reads when `files` is absent. Absent, `browser_downloads` is not listed, and `browser_upload` is listed only if `files` is given.
|
|
399
403
|
- `files`: a `WorkspaceFiles` that resolves `browser_upload` paths. Given, `browser_upload` is listed without a `workspace`.
|
|
400
404
|
- `handoff`: a `HandoffPort` that reaches a person (`request`, then `outcome` polled until done, cancelled or expired;
|
|
401
405
|
when a request expires is the port's to decide). Absent, `browser_request_handoff` is not listed.
|
|
402
406
|
- `prices`: your session price (for example from `BROWSERBASE_USD_PER_MINUTE`). It prices the session meter, so each session
|
|
403
407
|
tool's result and each released session's record carry dollars. Without it the minutes are recorded unpriced.
|
|
408
|
+
- `onCharge(charge, tx, call?)`: each charge of a session's time, `{ conversationId, tag, provider, at, seconds, usd,
|
|
409
|
+
final, state }`, called in the commit that writes it on the session's record, so a host that books it in `tx` books
|
|
410
|
+
exactly what the record bills: at a browser call (`call.callId`), what the session ran since its last charge; at its
|
|
411
|
+
release, or when custody gives up releasing it (`lost`) (`final`), the rest, topped up to `prices.sessionMinimumS`. A session already billed in full is never charged
|
|
412
|
+
again. `state` is `priced`, or `unpriced`/`invalid` with `usd` 0 (no price, not $0). It must not throw: a throw fails the
|
|
413
|
+
commit, and a call's charge is then carried by the session's next one.
|
|
404
414
|
|
|
405
415
|
Per conversation, the host writes a `BrowserConfig` (`label`, `run`, and the policy: proxies, verified, captcha, geolocation,
|
|
406
416
|
region, a raw context id, the session timeout, the idle release and the batch timeout; `DEFAULT_BROWSER_POLICY` holds the
|
|
@@ -412,7 +422,8 @@ is still made at the provider, and the record is left for the next run's reconci
|
|
|
412
422
|
`handle.close()` releases every session the process still holds, and over a healthy store it releases nothing. At run open,
|
|
413
423
|
after the extensions are installed and
|
|
414
424
|
before anything resumes, it calls `handle.reconcile(harness, isActive, ctx)`, and every session a dead process left is bound,
|
|
415
|
-
kept or released.
|
|
425
|
+
kept or released. A kept session's idle release is armed then, so one no call uses is released an idle window after the
|
|
426
|
+
reopen. The host wraps the tools (`handle.tools`) with its own policy: pause, call records, a result cap, media for
|
|
416
427
|
the route.
|
|
417
428
|
|
|
418
429
|
A policy's `navigation` is a restriction the host relies on, so a session that would not hold to it is never started. No
|
package/dist/coding-agent.js
CHANGED
|
@@ -4,7 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises";
|
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
7
|
-
import { BROWSER_TOOLS, WEB_TOOLS, browserSection, listedFor } from "./core/contract.js";
|
|
7
|
+
import { BROWSER_TOOLS, WEB_TOOLS, browserSection, browserToolsFor, listedFor } from "./core/contract.js";
|
|
8
8
|
import { BrowserFailureError, closeDriver, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, loadedNoPage, moveRecord, newSessionRecord, notices, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, sessionSpec, waitingForHuman, backoffMs, NO_HANDOFF, } from "./core/custody.js";
|
|
9
9
|
import { browserFailure, classifyBrowserError } from "./core/failures.js";
|
|
10
10
|
import { workspaceFiles } from "./core/files.js";
|
|
@@ -629,7 +629,8 @@ export function createBrowserExtension(options = {}) {
|
|
|
629
629
|
},
|
|
630
630
|
});
|
|
631
631
|
}
|
|
632
|
-
|
|
632
|
+
// A session vault keeps sign-ins, and run says so; without one it claims cookies across pages only.
|
|
633
|
+
for (const contract of browserToolsFor(!!options.sessionVault))
|
|
633
634
|
if (listedFor(contract, { downloads: fileTools, upload: fileTools, handoff: !!options.handoff }))
|
|
634
635
|
registerTool(pi, contract, runtimeOf);
|
|
635
636
|
registerTool(pi, WEB_TOOLS.find((tool) => tool.name === "web_fetch"), runtimeOf);
|
package/dist/core/contract.d.ts
CHANGED
|
@@ -16,6 +16,12 @@ export type ToolContract = {
|
|
|
16
16
|
readonly evidence: "none" | "receipt" | "image" | "files" | "urls";
|
|
17
17
|
readonly listedWhen: "always" | "downloads" | "upload" | "fetch" | "search" | "sites" | "handoff";
|
|
18
18
|
};
|
|
19
|
+
/** What the browser keeps, as `run`'s description tells the model when it picks between the browser and web_fetch:
|
|
20
|
+
* cookies across pages always, its agent's saved sign-ins only on a plane that has them (a local Chrome keeps none). */
|
|
21
|
+
export declare const BROWSER_KEEPS: Readonly<{
|
|
22
|
+
cookies: "It keeps cookies across pages: use it for a page that depends on an earlier one, or one that sets cookies.";
|
|
23
|
+
signIns: "It keeps this agent's saved sign-ins and cookies: use it for anything behind a sign-in, or a page that depends on an earlier one.";
|
|
24
|
+
}>;
|
|
19
25
|
/** A hit's snippet is clipped to this many characters, whitespace collapsed, so ten hits stay a few kilobytes. */
|
|
20
26
|
export declare const WEB_SEARCH_SNIPPET_MAX = 500;
|
|
21
27
|
/** Whether a host lists a browser tool: one that is always offered, or one whose capability the host has (a workspace to copy downloads
|
|
@@ -27,6 +33,9 @@ export declare const listedFor: (contract: ToolContract, offers: {
|
|
|
27
33
|
}) => boolean;
|
|
28
34
|
export declare const BROWSER_TOOLS: readonly ToolContract[];
|
|
29
35
|
export declare const WEB_TOOLS: readonly ToolContract[];
|
|
36
|
+
/** The browser's contracts as a plane's model reads them: `run` says the plane keeps its agent's saved sign-ins where it
|
|
37
|
+
* has them (a host's kept profile, or a session vault), and only cookies where it has none. */
|
|
38
|
+
export declare const browserToolsFor: (signIns: boolean) => readonly ToolContract[];
|
|
30
39
|
export declare const BROWSER_TOOL_NAMES: readonly string[];
|
|
31
40
|
export declare const WEB_TOOL_NAMES: readonly string[];
|
|
32
41
|
/** Depends only on configuration, never live state, so every request renders the same text and keeps the prompt cache. */
|
package/dist/core/contract.js
CHANGED
|
@@ -16,10 +16,18 @@ const snapshot = {
|
|
|
16
16
|
parameters: object({ includeIframes: { type: "boolean", default: true } }),
|
|
17
17
|
effect: "read", replay: "safe", executionMode: "sequential", evidence: "none", listedWhen: "always",
|
|
18
18
|
};
|
|
19
|
+
/** What the browser keeps, as `run`'s description tells the model when it picks between the browser and web_fetch:
|
|
20
|
+
* cookies across pages always, its agent's saved sign-ins only on a plane that has them (a local Chrome keeps none). */
|
|
21
|
+
export const BROWSER_KEEPS = Object.freeze({
|
|
22
|
+
cookies: "It keeps cookies across pages: use it for a page that depends on an earlier one, or one that sets cookies.",
|
|
23
|
+
signIns: "It keeps this agent's saved sign-ins and cookies: use it for anything behind a sign-in, or a page that depends on an earlier one.",
|
|
24
|
+
});
|
|
25
|
+
const runDescription = (signIns) => `Browse and automate websites in the persistent Stagehand browser. ${signIns ? BROWSER_KEEPS.signIns : BROWSER_KEEPS.cookies} ` +
|
|
26
|
+
'Navigate with JavaScript such as await page.goto("https://example.com"); there is no separate navigate or start tool. Execute either a JavaScript workflow against the Stagehand Playwright facade or a batch of actions using IDs from the latest snapshot. Code is the body of an async function with page, context and browser in scope: `return` the value you want back. Provide exactly one of code or actions. Each action must use "op" (never "kind") and "id" (never "ref"). Copy the bracketed snapshot ID as a string. Examples: {"actions":[{"op":"click","id":"1-42"}]}, {"actions":[{"op":"fill","id":"2-14","value":"Miami"}]}, {"actions":[{"op":"select","id":"3-9","values":"Lowest price"}]}.';
|
|
19
27
|
const run = {
|
|
20
28
|
name: "run",
|
|
21
29
|
label: "Browser: run",
|
|
22
|
-
description:
|
|
30
|
+
description: runDescription(false),
|
|
23
31
|
// No top-level oneOf for "exactly one of code or actions": AI-SDK-based clients reject it, so the tool enforces it.
|
|
24
32
|
parameters: object({
|
|
25
33
|
code: { type: "string", minLength: 1 },
|
|
@@ -133,7 +141,8 @@ const webFetch = {
|
|
|
133
141
|
name: "web_fetch",
|
|
134
142
|
label: "Web fetch",
|
|
135
143
|
description: "Fetch one URL as clean markdown without a browser session: fast and cheap, and it handles most static and many dynamic pages. " +
|
|
136
|
-
"
|
|
144
|
+
"It has no cookies, sign-ins or session: it reads one page cold. " +
|
|
145
|
+
"Use it for reading articles, filings, registries, PDFs-as-pages. If it returns blocked or empty content, or the page is behind a sign-in or depends on an earlier page, drive it with run/snapshot instead. " +
|
|
137
146
|
"A page it returns is filed as evidence: that read, not a search result, is what a claim cites. " +
|
|
138
147
|
"The result is persisted as evidence with its URL: a query value that is in the URL you asked for stays in it, any other value of the final URL is replaced by a redaction marker (the word redacted in square brackets).",
|
|
139
148
|
parameters: object({
|
|
@@ -159,6 +168,9 @@ const webSearch = {
|
|
|
159
168
|
export const listedFor = (contract, offers) => contract.listedWhen === "always" || (contract.listedWhen === "downloads" && offers.downloads) || (contract.listedWhen === "upload" && offers.upload) || (contract.listedWhen === "handoff" && offers.handoff);
|
|
160
169
|
export const BROWSER_TOOLS = Object.freeze([snapshot, run, screenshot, browserRead, browserRelease, browserRelaunch, browserRequestHandoff, browserDownloads, browserUpload]);
|
|
161
170
|
export const WEB_TOOLS = Object.freeze([webFetch, webSearch]);
|
|
171
|
+
/** The browser's contracts as a plane's model reads them: `run` says the plane keeps its agent's saved sign-ins where it
|
|
172
|
+
* has them (a host's kept profile, or a session vault), and only cookies where it has none. */
|
|
173
|
+
export const browserToolsFor = (signIns) => signIns ? Object.freeze(BROWSER_TOOLS.map((contract) => (contract === run ? { ...contract, description: runDescription(true) } : contract))) : BROWSER_TOOLS;
|
|
162
174
|
export const BROWSER_TOOL_NAMES = Object.freeze(BROWSER_TOOLS.map((tool) => tool.name));
|
|
163
175
|
export const WEB_TOOL_NAMES = Object.freeze(WEB_TOOLS.map((tool) => tool.name));
|
|
164
176
|
/** Depends only on configuration, never live state, so every request renders the same text and keeps the prompt cache. */
|
package/dist/core/failures.d.ts
CHANGED
|
@@ -47,4 +47,6 @@ export type TransportFact = {
|
|
|
47
47
|
};
|
|
48
48
|
/** A throw site's `transport` record, else class name, `code` and `status` down the cause chain; first found wins. */
|
|
49
49
|
export declare function transportFactOf(error: unknown): TransportFact;
|
|
50
|
+
/** The provider refused the call (401 or 403): its own answer that it did nothing. */
|
|
51
|
+
export declare function isRefusal(error: unknown): boolean;
|
|
50
52
|
export declare function classifyBrowserError(error: unknown, effectful: boolean, facts?: FailureFacts): BrowserFailure;
|
package/dist/core/failures.js
CHANGED
|
@@ -62,13 +62,20 @@ function withCause(own, cause) {
|
|
|
62
62
|
const tag = typeof code === "number" || (typeof code === "string" && code) ? ` (code ${code})` : "";
|
|
63
63
|
return `${own}${text}${tag}`;
|
|
64
64
|
}
|
|
65
|
+
/** The HTTP status an error carries. Stagehand wraps SDK failures with { cause }: the status may live on the cause. */
|
|
66
|
+
const statusOf = (error, fact = transportFactOf(error)) => fact.status ?? Number(field(error, "statusCode") ?? field(field(error, "cause"), "statusCode") ?? NaN);
|
|
67
|
+
/** The provider refused the call (401 or 403): its own answer that it did nothing. */
|
|
68
|
+
export function isRefusal(error) {
|
|
69
|
+
const status = statusOf(error);
|
|
70
|
+
return status === 401 || status === 403;
|
|
71
|
+
}
|
|
65
72
|
export function classifyBrowserError(error, effectful, facts = {}) {
|
|
66
73
|
// Stagehand wraps SDK failures with { cause }: the HTTP status and the real message live on the cause.
|
|
67
74
|
const cause = field(error, "cause");
|
|
68
75
|
const own = error instanceof Error ? error.message : String(error);
|
|
69
76
|
const message = (facts.redact ?? ((text) => text))(withCause(own, cause));
|
|
70
77
|
const fact = transportFactOf(error);
|
|
71
|
-
const status =
|
|
78
|
+
const status = statusOf(error, fact);
|
|
72
79
|
const effect = effectful ? "possibly_effected" : "none";
|
|
73
80
|
const detail = message.slice(0, 2_000);
|
|
74
81
|
if (facts.aborted || fact.errorName === "AbortError")
|
package/dist/core/host.d.ts
CHANGED
|
@@ -405,5 +405,18 @@ export type PriceTable = {
|
|
|
405
405
|
fetchProxiedUsd: number;
|
|
406
406
|
searchUsd: number;
|
|
407
407
|
};
|
|
408
|
+
/** One charge of a session's time, as its record bills it: `seconds` and `usd` since the session's last charge, through `at`,
|
|
409
|
+
* or, `final`, at its release, topped up to the provider's minimum. `state` says whether `usd` is a price (`priced`) or
|
|
410
|
+
* the time went unpriced (`unpriced`, `invalid`: `usd` is 0 and is no charge). */
|
|
411
|
+
export type SessionCharge = {
|
|
412
|
+
conversationId: number;
|
|
413
|
+
tag: string;
|
|
414
|
+
provider: string;
|
|
415
|
+
at: string;
|
|
416
|
+
seconds: number;
|
|
417
|
+
usd: number;
|
|
418
|
+
final: boolean;
|
|
419
|
+
state: PriceState;
|
|
420
|
+
};
|
|
408
421
|
/** Browserbase list prices as of 2026-10-06: the Developer overage rate, one-minute minimum. */
|
|
409
422
|
export declare const LIST_PRICES: PriceTable;
|
package/dist/durable/store.d.ts
CHANGED
|
@@ -14,13 +14,17 @@ type Move = {
|
|
|
14
14
|
notice?: "kept" | "lost";
|
|
15
15
|
handoff?: string;
|
|
16
16
|
};
|
|
17
|
+
/** `found`: the ids an earlier attempt (or a task this one succeeds) released under the row's tag, kept until the release
|
|
18
|
+
* is billed: a provider's tag lookup lists running sessions only, so a later attempt no longer finds one it stopped. */
|
|
17
19
|
type ReleaseInput = {
|
|
18
20
|
row: InventoryRow;
|
|
19
21
|
notBefore?: number;
|
|
22
|
+
found?: string[];
|
|
20
23
|
};
|
|
21
24
|
type ReleaseState = {
|
|
22
25
|
phase: "release";
|
|
23
26
|
attempt: number;
|
|
27
|
+
found?: string[];
|
|
24
28
|
} | {
|
|
25
29
|
phase: "confirm";
|
|
26
30
|
attempt: number;
|
|
@@ -45,13 +49,15 @@ export type StoreDeps = {
|
|
|
45
49
|
meter(spent: SessionRecord["spent"], at: string, final?: boolean): {
|
|
46
50
|
spent: SessionRecord["spent"];
|
|
47
51
|
};
|
|
52
|
+
/** The release's charge (or a lost session's), written on `record` in the commit `tx` and told to the host (durable.ts). */
|
|
53
|
+
bill(tx: Tx, conversationId: ConversationId, record: SessionRecord, at: string, final: true): Promise<unknown>;
|
|
48
54
|
scrubbed(error: unknown): Error;
|
|
49
55
|
createDeadlineMs: number;
|
|
50
56
|
handoff?: HandoffPort;
|
|
51
57
|
/** A handoff's session came back under `fence`. */
|
|
52
58
|
handedBack?(tag: string, fence: number): void;
|
|
53
59
|
};
|
|
54
|
-
export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, scrubbed, createDeadlineMs, handoff, handedBack }: StoreDeps): {
|
|
60
|
+
export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack }: StoreDeps): {
|
|
55
61
|
Inventory: import("@earendil-works/pi-durable").SessionDocToken<{
|
|
56
62
|
rows: Record<string, InventoryRow>;
|
|
57
63
|
}>;
|
package/dist/durable/store.js
CHANGED
|
@@ -6,7 +6,7 @@ const cidOf = (row) => row.conversationId;
|
|
|
6
6
|
/** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
|
|
7
7
|
export const RELEASE_ATTEMPTS = 6;
|
|
8
8
|
export const CONFIRM_POLLS = 5;
|
|
9
|
-
export function custodyStore({ name, Config, Sessions, providerOf, emit, meter, scrubbed, createDeadlineMs, handoff, handedBack }) {
|
|
9
|
+
export function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack }) {
|
|
10
10
|
const Inventory = defineDoc({ kind: `${name}.inventory`, version: 1, scope: "session", initial: () => ({ rows: {} }) });
|
|
11
11
|
/** One state change: the record and the open-session inventory move in the same commit. */
|
|
12
12
|
async function move(tx, row, next) {
|
|
@@ -21,8 +21,10 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
21
21
|
if (!record)
|
|
22
22
|
return;
|
|
23
23
|
moveRecord(record, next);
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
// A session custody gave up releasing (lost) is billed in full too, what it ran and its minimum, so a host lets go of
|
|
25
|
+
// what it held for it; a later release finds it billed and adds nothing.
|
|
26
|
+
if ((next.state === "released" || next.state === "lost") && record.resourceId !== null)
|
|
27
|
+
await bill(tx, cidOf(row), record, next.at, true);
|
|
26
28
|
if (next.notice) {
|
|
27
29
|
for (const stale of [notices.kept(record.lastUrl), notices.lost(record.lastUrl)])
|
|
28
30
|
state.notice = state.notice?.replace(stale, "").replace(/\s+/g, " ").trim() || null;
|
|
@@ -41,8 +43,11 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
41
43
|
/** A create no tag lookup finds may still land (a crashed or fenced holder's call in flight): the release task looks
|
|
42
44
|
* again by tag after the create deadline and releases whatever landed. */
|
|
43
45
|
const unknownCreate = (tx, row, at) => requestRelease(tx, row, "create_failed", at, Date.now() + createDeadlineMs);
|
|
44
|
-
|
|
46
|
+
/** `found` hears the ids before any is released: a release that stops a session and then fails (its status check after
|
|
47
|
+
* the stop) leaves the session known only to its caller, since the provider's tag lookup lists running sessions only. */
|
|
48
|
+
async function releaseAll(row, provider, signal, found = () => { }) {
|
|
45
49
|
const ids = [...new Set([row.resourceId, ...(await provider.findByTag(row.tag, signal)).map((ref) => ref.id)].filter((id) => id !== null))];
|
|
50
|
+
await found(ids);
|
|
46
51
|
for (const id of ids)
|
|
47
52
|
await provider.release({ id, tag: row.tag }, signal);
|
|
48
53
|
return ids;
|
|
@@ -53,7 +58,14 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
53
58
|
return true;
|
|
54
59
|
return false;
|
|
55
60
|
};
|
|
56
|
-
|
|
61
|
+
/** The ids released under `row`'s tag once none of them runs; null while one does. */
|
|
62
|
+
const releasedIds = async (provider, row, signal, found) => {
|
|
63
|
+
const ids = await releaseAll(row, provider, signal, found);
|
|
64
|
+
return (await anyRunning(provider, row, ids, signal)) ? null : ids;
|
|
65
|
+
};
|
|
66
|
+
/** A session found by its tag (its create's answer lost: the record has no id) is billed at its release too: the
|
|
67
|
+
* provider ran it. A create the provider refused found nothing, and is billed nothing. */
|
|
68
|
+
const foundId = (row, ids) => (row.resourceId === null && ids?.length ? { resourceId: ids[0] } : {});
|
|
57
69
|
/** Its error goes to the host's report, scrubbed, and `fallback` stands in; an abort is rethrown. */
|
|
58
70
|
async function step(runtime, run, fallback) {
|
|
59
71
|
try {
|
|
@@ -83,17 +95,19 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
83
95
|
if (record && spent)
|
|
84
96
|
await emit(cid, config?.label ?? "", { ...record, state: "released", endedAt: record.endedAt ?? at, spent }, "released");
|
|
85
97
|
}
|
|
86
|
-
|
|
87
|
-
|
|
98
|
+
const union = (...lists) => [...new Set(lists.flatMap((ids) => ids ?? []))];
|
|
99
|
+
/** The row stays in the inventory until a run open's reconcile sees nothing under its tag running. `found` goes on to
|
|
100
|
+
* the next attempt, and bills a lost one. */
|
|
101
|
+
async function retry(runtime, row, attempt, context, found) {
|
|
88
102
|
if (attempt + 1 >= RELEASE_ATTEMPTS) {
|
|
89
103
|
await runtime.commit(async (tx) => {
|
|
90
|
-
await move(tx, row, { state: "lost", reason: "lost", at: iso(runtime.now()) });
|
|
104
|
+
await move(tx, row, { state: "lost", reason: "lost", at: iso(runtime.now()), ...foundId(row, found) });
|
|
91
105
|
return { status: "terminal", outcome: { status: "failed", error: { code: "release_failed", message: `${row.tag}: not released after ${RELEASE_ATTEMPTS} attempts` } } };
|
|
92
106
|
}, context);
|
|
93
107
|
return;
|
|
94
108
|
}
|
|
95
109
|
await runtime.sleep(runtime.now() + backoffMs(attempt), context);
|
|
96
|
-
await runtime.commit(() => ({ status: "running", checkpoint: { phase: "release", attempt: attempt + 1 } }), context);
|
|
110
|
+
await runtime.commit(() => ({ status: "running", checkpoint: { phase: "release", attempt: attempt + 1, ...(found.length ? { found } : {}) } }), context);
|
|
97
111
|
}
|
|
98
112
|
const ReleaseTask = defineTask({
|
|
99
113
|
name: `${name}.release`,
|
|
@@ -103,11 +117,25 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
103
117
|
release: async (task, runtime, context) => {
|
|
104
118
|
const { row, notBefore } = task.input;
|
|
105
119
|
const { attempt } = task.state.checkpoint;
|
|
120
|
+
const found = union(task.input.found, task.state.checkpoint.found);
|
|
106
121
|
if (attempt === 0 && notBefore && runtime.now() < notBefore)
|
|
107
122
|
await runtime.sleep(notBefore, context);
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
123
|
+
let seen = [];
|
|
124
|
+
// Ids the lookup found that the task does not hold yet are committed before any stop is sent: an attempt cut
|
|
125
|
+
// between its stop and its next commit (the task's abort) leaves them for the abort handler, whose own lookup
|
|
126
|
+
// no longer lists a stopped session.
|
|
127
|
+
const keep = async (ids) => {
|
|
128
|
+
seen = ids;
|
|
129
|
+
const known = union(found, ids);
|
|
130
|
+
if (known.length > found.length)
|
|
131
|
+
await runtime.commit(() => ({ status: "running", checkpoint: { phase: "release", attempt, found: known } }), context);
|
|
132
|
+
};
|
|
133
|
+
const released = await step(runtime, async () => releaseAll(row, await providerOf(runtime, cidOf(row), row.plane, context), runtime.signal, keep), null);
|
|
134
|
+
// What the lookup found goes on to the next attempt even when its release failed: the stop may have landed.
|
|
135
|
+
if (!released)
|
|
136
|
+
return retry(runtime, row, attempt, context, union(found, seen));
|
|
137
|
+
// Confirmed together: what this attempt released and what earlier ones did.
|
|
138
|
+
const ids = union(found, released);
|
|
111
139
|
await runtime.commit(() => ({ status: "running", checkpoint: { phase: "confirm", attempt, ids, polls: 0 } }), context);
|
|
112
140
|
},
|
|
113
141
|
confirm: async (task, runtime, context) => {
|
|
@@ -120,13 +148,13 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
120
148
|
return;
|
|
121
149
|
}
|
|
122
150
|
if (running)
|
|
123
|
-
return retry(runtime, row, attempt, context);
|
|
151
|
+
return retry(runtime, row, attempt, context, ids);
|
|
124
152
|
// The host hears the release before the task's last commit, so at least once, with the bill that commit
|
|
125
153
|
// records.
|
|
126
154
|
const at = iso(runtime.now());
|
|
127
155
|
await emitReleased(cidOf(row), row.tag, runtime, context, at);
|
|
128
156
|
await runtime.commit(async (tx) => {
|
|
129
|
-
await move(tx, row, { state: "released", at });
|
|
157
|
+
await move(tx, row, { state: "released", at, ...foundId(row, ids) });
|
|
130
158
|
return { status: "terminal", outcome: { status: "completed", result: { released: ids.length } } };
|
|
131
159
|
}, context);
|
|
132
160
|
},
|
|
@@ -135,15 +163,17 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
135
163
|
// to a successor task in the same commit.
|
|
136
164
|
abort: async (task, runtime, context) => {
|
|
137
165
|
const { row, notBefore } = task.input;
|
|
138
|
-
|
|
166
|
+
const checkpoint = task.state.checkpoint;
|
|
167
|
+
let found = union(task.input.found, checkpoint.phase === "confirm" ? checkpoint.ids : checkpoint.found);
|
|
168
|
+
let stopped = null;
|
|
139
169
|
// Before the create deadline nothing found is proof of nothing: the successor keeps the delayed lookup.
|
|
140
170
|
if (!(notBefore && runtime.now() < notBefore))
|
|
141
|
-
stopped = await providerOf(runtime, cidOf(row), row.plane, context).then((provider) =>
|
|
171
|
+
stopped = await providerOf(runtime, cidOf(row), row.plane, context).then((provider) => releasedIds(provider, row, context.abortSignal, (ids) => void (found = union(found, ids)))).catch(() => null);
|
|
142
172
|
await runtime.commit(async (tx) => {
|
|
143
173
|
if (stopped)
|
|
144
|
-
await move(tx, row, { state: "released", at: iso(runtime.now()) });
|
|
174
|
+
await move(tx, row, { state: "released", at: iso(runtime.now()), ...foundId(row, union(found, stopped)) });
|
|
145
175
|
else
|
|
146
|
-
await tx.createTask(ReleaseTask, task.input, { ownership: { kind: "conversation" }, conversationId: cidOf(row), background: true });
|
|
176
|
+
await tx.createTask(ReleaseTask, { ...task.input, ...(found.length ? { found } : {}) }, { ownership: { kind: "conversation" }, conversationId: cidOf(row), background: true });
|
|
147
177
|
return { status: "terminal", outcome: { status: "aborted", reason: stopped ? "released by the abort handler" : "release handed to a successor task" } };
|
|
148
178
|
}, context);
|
|
149
179
|
},
|
|
@@ -230,11 +260,31 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
230
260
|
try {
|
|
231
261
|
const provider = await providerOf(harness, cidOf(row), row.plane, context);
|
|
232
262
|
if (row.state === "lost") {
|
|
233
|
-
|
|
263
|
+
let seen = [];
|
|
264
|
+
const ids = await releasedIds(provider, row, undefined, (found) => void (seen = found)).catch(async (error) => {
|
|
265
|
+
// The stop may have landed before the provider's answer was lost, and its tag lookup lists running sessions
|
|
266
|
+
// only: a session known only by its tag keeps the id found on its row and record, for the next reconcile to
|
|
267
|
+
// release and bill.
|
|
268
|
+
const id = row.resourceId === null ? seen[0] : undefined;
|
|
269
|
+
if (id !== undefined) {
|
|
270
|
+
await commit(async (tx) => {
|
|
271
|
+
const rows = (await tx.doc(Inventory)).rows;
|
|
272
|
+
if (rows[row.tag])
|
|
273
|
+
rows[row.tag] = { ...rows[row.tag], resourceId: id };
|
|
274
|
+
const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
|
|
275
|
+
if (record && record.resourceId === null)
|
|
276
|
+
record.resourceId = id;
|
|
277
|
+
}).catch(() => undefined);
|
|
278
|
+
}
|
|
279
|
+
throw error;
|
|
280
|
+
});
|
|
281
|
+
await (ids ? outcome("released", async (tx) => {
|
|
234
282
|
delete (await tx.doc(Inventory)).rows[row.tag];
|
|
235
283
|
const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
|
|
284
|
+
if (record && record.resourceId === null && ids.length)
|
|
285
|
+
record.resourceId = ids[0];
|
|
236
286
|
if (record && record.resourceId !== null)
|
|
237
|
-
|
|
287
|
+
await bill(tx, cidOf(row), record, at, true);
|
|
238
288
|
}) : outcome("lost"));
|
|
239
289
|
continue;
|
|
240
290
|
}
|
package/dist/durable.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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";
|
|
2
|
+
import { type Conversation, type ConversationDocToken, type ConversationId, type Extension, type Harness, type SessionDocToken, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
|
|
3
3
|
import { type DriverFactory } from "./core/custody.js";
|
|
4
4
|
import type { Decisions } from "./core/decisions.js";
|
|
5
5
|
import type { EvidenceSink } from "./core/evidence.js";
|
|
@@ -7,12 +7,15 @@ import { EffectObserver } from "./core/effects.js";
|
|
|
7
7
|
import { type VaultOptions } from "./vault-session.js";
|
|
8
8
|
import type { DrivingGates } from "./live-view/protocol.js";
|
|
9
9
|
import { type BrowserToolImpls, type PageDriver } from "./core/tools.js";
|
|
10
|
-
import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionRow, SessionsState, SiteInfo, SiteRunPort, HandoffPort, WorkspaceFiles } from "./core/host.js";
|
|
10
|
+
import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionCharge, SessionRow, SessionsState, SiteInfo, SiteRunPort, HandoffPort, WorkspaceFiles } from "./core/host.js";
|
|
11
11
|
export type { BrowserToolArgs, BrowserToolImpls, PageDriver, ToolCall, ToolImpl } from "./core/tools.js";
|
|
12
12
|
export type { DriverFactory, DriverOptions } from "./core/custody.js";
|
|
13
13
|
export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOptions & {
|
|
14
14
|
/** Default "browser"; a second plane installs a second extension under another name. */
|
|
15
15
|
name?: string;
|
|
16
|
+
/** The plane's sessions open on its agent's saved sign-ins (a host's kept profile): `run` tells the model so, for a page
|
|
17
|
+
* behind a sign-in. Default: whether a `sessionVault` is given. Without either, it claims cookies across pages only. */
|
|
18
|
+
signIns?: boolean;
|
|
16
19
|
/** Called per use: the provider for this conversation's plane. Holds the credentials in its closure; nothing it
|
|
17
20
|
* returns is committed. */
|
|
18
21
|
provider: (target: {
|
|
@@ -44,6 +47,14 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOp
|
|
|
44
47
|
/** A session runs without the effect observer its policy asked for; a throw here never fails a call. */
|
|
45
48
|
onObserver?: (row: ObserverRow) => void | Promise<void>;
|
|
46
49
|
prices?: Partial<PriceTable>;
|
|
50
|
+
/** Each charge of a session's time, called in the commit that writes it on the session's record (`tx`), so a host that
|
|
51
|
+
* books it in that commit books what the record bills, once: at a browser call (`call`), what the session ran since its
|
|
52
|
+
* last charge; at its release, or when custody gives up releasing it (`final`, no `call`), what it ran since, topped up
|
|
53
|
+
* to the provider's minimum. Never for a session already billed in full. It must not throw: a throw fails that commit,
|
|
54
|
+
* and a call's charge is then carried by the session's next one. */
|
|
55
|
+
onCharge?: (charge: SessionCharge, tx: Tx, call?: {
|
|
56
|
+
callId: string;
|
|
57
|
+
}) => void | Promise<void>;
|
|
47
58
|
/** Exact strings to scrub from every output besides the built-in shapes, read at each use. */
|
|
48
59
|
redact?: {
|
|
49
60
|
values: () => readonly string[];
|
package/dist/durable.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { configure, defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
3
|
-
import { BROWSER_TOOL_NAMES,
|
|
3
|
+
import { BROWSER_TOOL_NAMES, browserSection, browserToolsFor, listedFor, WEB_TOOL_NAMES } from "./core/contract.js";
|
|
4
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
5
|
import { forModel } from "./durable/result.js";
|
|
6
6
|
import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
|
|
7
|
-
import { browserFailure, classifyBrowserError } from "./core/failures.js";
|
|
7
|
+
import { browserFailure, classifyBrowserError, isRefusal } from "./core/failures.js";
|
|
8
8
|
import { workspaceFiles } from "./core/files.js";
|
|
9
9
|
import { drivingGuarded } from "./core/driving-guard.js";
|
|
10
10
|
import { drivingGates, keptFor, keptReason, personOn, rearmWhenLeft } from "./core/driving.js";
|
|
@@ -256,6 +256,13 @@ async function create(c, scope, overrides, presetTag) {
|
|
|
256
256
|
await scope.commit((tx) => c.store.move(tx, row, { state: "live", resourceId: made.id, at: now() }));
|
|
257
257
|
return made;
|
|
258
258
|
}, async (error) => {
|
|
259
|
+
// A 401 or 403 is the provider's own answer that nothing was made: the record ends at once, with no lookup by tag
|
|
260
|
+
// and no release delayed for a create that might still land.
|
|
261
|
+
if (isRefusal(error)) {
|
|
262
|
+
await scope.commit((tx) => c.store.move(tx, row, { state: "released", reason: "create_failed", at: now() }));
|
|
263
|
+
await c.store.emitReleased(scope.cid, tag, scope.read, scope.context);
|
|
264
|
+
throw failure(error, scope, c.redact);
|
|
265
|
+
}
|
|
259
266
|
const found = await provider.findByTag(tag, scope.signal).catch(() => []);
|
|
260
267
|
// The session found by its tag is the one kept (bindByTag releases the others first), and it is owned before it is
|
|
261
268
|
// recorded, as a create's own answer is: a store that cannot record it still lets close release it.
|
|
@@ -689,9 +696,7 @@ async function chargeCall(c, api, context) {
|
|
|
689
696
|
const record = currentRecord(await tx.doc(c.Sessions, api.conversationId), PLANE);
|
|
690
697
|
if (record?.state !== "live")
|
|
691
698
|
return null;
|
|
692
|
-
|
|
693
|
-
record.spent = spent;
|
|
694
|
-
return usage;
|
|
699
|
+
return c.bill(tx, api.conversationId, record, now(), false, { callId: api.callId });
|
|
695
700
|
}, context);
|
|
696
701
|
}
|
|
697
702
|
const withSessionTime = (own, charged) => {
|
|
@@ -701,7 +706,7 @@ const withSessionTime = (own, charged) => {
|
|
|
701
706
|
return { ...charged.usage, ...own, cost: { ...charged.usage.cost, ...ownCost, total: charged.usage.cost.total + (ownCost.total ?? 0) } };
|
|
702
707
|
};
|
|
703
708
|
function toolsFor(c, impls) {
|
|
704
|
-
return
|
|
709
|
+
return browserToolsFor(c.options.signIns ?? !!c.options.sessionVault)
|
|
705
710
|
.filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!(c.options.files || c.options.workspace), handoff: !!c.options.handoff }))
|
|
706
711
|
.map((contract) => defineTool({
|
|
707
712
|
name: contract.name,
|
|
@@ -851,10 +856,20 @@ export function createBrowserExtension(options) {
|
|
|
851
856
|
const charged = sessionCharge(spent, at, prices, priceState, final);
|
|
852
857
|
return { spent: { ...withEstimate(spent, charged.spent, listPriced), state: charged.usage.state }, usage: charged.usage };
|
|
853
858
|
};
|
|
859
|
+
const bill = async (tx, conversationId, record, at, final, call) => {
|
|
860
|
+
const before = record.spent;
|
|
861
|
+
if (before.final)
|
|
862
|
+
return null;
|
|
863
|
+
const { spent, usage } = meter(before, at, final);
|
|
864
|
+
record.spent = spent;
|
|
865
|
+
const seconds = Math.round((spent.seconds - before.seconds) * 1000) / 1000;
|
|
866
|
+
await options.onCharge?.({ conversationId, tag: record.tag, provider: record.provider, at, seconds, usd: usage.usage.cost.total, final, state: usage.state }, tx, call);
|
|
867
|
+
return usage;
|
|
868
|
+
};
|
|
854
869
|
const leaving = new Map();
|
|
855
870
|
const owned = new Map();
|
|
856
871
|
const store = custodyStore({
|
|
857
|
-
name, Config, Sessions, meter, scrubbed, createDeadlineMs: options.createDeadlineMs ?? CREATE_DEADLINE_MS,
|
|
872
|
+
name, Config, Sessions, meter, bill, scrubbed, createDeadlineMs: options.createDeadlineMs ?? CREATE_DEADLINE_MS,
|
|
858
873
|
providerOf: (read, cid, plane, context) => providerOf(readers, read, cid, plane, context),
|
|
859
874
|
emit: (cid, label, record, change) => {
|
|
860
875
|
// A released session's poll ends with it, whatever released it, and nothing is left to release directly.
|
|
@@ -870,7 +885,7 @@ export function createBrowserExtension(options) {
|
|
|
870
885
|
handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
|
|
871
886
|
});
|
|
872
887
|
const c = {
|
|
873
|
-
...readers, name, Sessions, Children, store,
|
|
888
|
+
...readers, name, Sessions, Children, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, serial: keyedSerializer(), childTurns: oneAtATime(), guards: new Map(), owned, failed: false, ending: null, opened: null, incarnation: randomUUID(),
|
|
874
889
|
idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
|
|
875
890
|
};
|
|
876
891
|
// 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
|
|
@@ -888,7 +903,14 @@ export function createBrowserExtension(options) {
|
|
|
888
903
|
async reconcile(harness, isActive, context) {
|
|
889
904
|
c.opened = { harness, context };
|
|
890
905
|
c.ending = endingOf(harness);
|
|
891
|
-
|
|
906
|
+
const report = await store.reconcileAll(harness, isActive, context);
|
|
907
|
+
// A session kept across a reopen has had no call here to arm its idle release: armed now, so one the run no longer
|
|
908
|
+
// uses is released an idle window after the reopen, not at the provider's session timeout.
|
|
909
|
+
for (const row of Object.values((await harness.snapshot(store.Inventory, context))?.rows ?? {}).filter((r) => report.kept.includes(r.tag))) {
|
|
910
|
+
const cid = row.conversationId;
|
|
911
|
+
c.idle.activity(cid, 0, ((await harness.snapshot(Config, cid, context))?.policy.idleReleaseS ?? 0) * 1000);
|
|
912
|
+
}
|
|
913
|
+
return report;
|
|
892
914
|
},
|
|
893
915
|
drain: (harness, context, signal) => drainReleases(name, harness, context, signal),
|
|
894
916
|
async close() {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Credentials come from the host's env and live in this module's memory only: a ref is `{ id, tag }`, and the connect
|
|
2
2
|
// URL (it carries a signing key) is held here, found again by `retrieve` after a restart.
|
|
3
3
|
import { createReadStream } from "node:fs";
|
|
4
|
+
import { isRefusal } from "../core/failures.js";
|
|
4
5
|
import { fetchUsage, resolvePrices, searchUsage } from "../core/usage.js";
|
|
5
6
|
import { cdpCall } from "./cdp-call.js";
|
|
6
7
|
import { applyBrowserbaseNoProxy, bindConnectDial, installWebSocketWrapper, rewriteConnectUrl, unbindConnectDial } from "./browserbase-net.js";
|
|
@@ -154,8 +155,12 @@ export function browserbaseProvider(options = {}) {
|
|
|
154
155
|
throw error;
|
|
155
156
|
}
|
|
156
157
|
// At most once: an SDK retry of a create the server already served would open a second paid browser. A failed send keeps
|
|
157
|
-
// the profile's claim until findByTag has looked: the session may exist.
|
|
158
|
-
const created = await (await client()).sessions.create(body, { maxRetries: 0, signal })
|
|
158
|
+
// the profile's claim until findByTag has looked: the session may exist. A refusal (401, 403) made none, so it frees the claim.
|
|
159
|
+
const created = await (await client()).sessions.create(body, { maxRetries: 0, signal }).catch((error) => {
|
|
160
|
+
if (isRefusal(error))
|
|
161
|
+
freeWriter(spec.tag);
|
|
162
|
+
throw error;
|
|
163
|
+
});
|
|
159
164
|
connectUrls.set(held(created.id), created.connectUrl);
|
|
160
165
|
noteWriter(spec.tag, running({ id: created.id, tag: spec.tag }), () => sleep(options.profileSettleMs ?? 5_000));
|
|
161
166
|
return { id: created.id, tag: spec.tag };
|
package/dist/providers/kernel.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// No error carries the key, the URL or Kernel's text: only the call, the status and the code.
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { isRefusal } from "../core/failures.js";
|
|
5
6
|
import { directFetch } from "./http.js";
|
|
6
7
|
import { claimWriter, freeWriter, isWriter, noteWriter } from "./profiles.js";
|
|
7
8
|
import { accountKey, assertTag, defaultSleep, DEFAULT_CONFIRM, extensionArchive, kernelHoldings, nonEmpty, releaseAndConfirm, tagValue, untilAborted, uploadOnce } from "./shared.js";
|
|
@@ -192,8 +193,12 @@ export function kernelProvider(options = {}) {
|
|
|
192
193
|
throw error;
|
|
193
194
|
}
|
|
194
195
|
// At most once: a lost answer is found again by its tag (findByTag), never by a second create. A failed send keeps the
|
|
195
|
-
// profile's claim until findByTag has looked: the browser may exist.
|
|
196
|
-
const created = await call("POST", "/browsers", { body, signal })
|
|
196
|
+
// profile's claim until findByTag has looked: the browser may exist. A refusal (401, 403) made none, so it frees the claim.
|
|
197
|
+
const created = await call("POST", "/browsers", { body, signal }).catch((error) => {
|
|
198
|
+
if (isRefusal(error))
|
|
199
|
+
freeWriter(spec.tag);
|
|
200
|
+
throw error;
|
|
201
|
+
});
|
|
197
202
|
const id = nonEmpty(created.json?.session_id);
|
|
198
203
|
const url = nonEmpty(created.json?.cdp_ws_url);
|
|
199
204
|
if (created.status === 404 || !id || !url)
|