@parcha/pi-browser 0.1.0-beta.30 → 0.1.0-beta.301
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 +239 -0
- package/NOTICE +39 -4
- package/README.md +125 -236
- package/dist/core/contract.d.ts +17 -5
- package/dist/core/contract.js +36 -33
- package/dist/core/custody.d.ts +19 -2
- package/dist/core/custody.js +28 -6
- package/dist/core/downloads.d.ts +44 -3
- package/dist/core/downloads.js +94 -58
- package/dist/core/driving-guard.d.ts +20 -0
- package/dist/core/driving-guard.js +190 -23
- package/dist/core/driving.d.ts +56 -2
- package/dist/core/driving.js +189 -10
- package/dist/core/effects.d.ts +80 -6
- package/dist/core/effects.js +374 -41
- package/dist/core/evidence.d.ts +1 -1
- package/dist/core/failures.d.ts +15 -1
- package/dist/core/failures.js +7 -0
- package/dist/core/files.d.ts +20 -2
- package/dist/core/files.js +161 -10
- package/dist/core/host.d.ts +29 -77
- package/dist/core/images.d.ts +32 -4
- package/dist/core/images.js +81 -16
- package/dist/core/lease.d.ts +2 -1
- package/dist/core/page-scan.d.ts +81 -2
- package/dist/core/page-scan.js +487 -13
- package/dist/core/public-fetch.d.ts +70 -9
- package/dist/core/public-fetch.js +348 -51
- package/dist/core/read-page-worker.js +5 -4
- package/dist/core/read-page.d.ts +23 -8
- package/dist/core/read-page.js +64 -20
- package/dist/core/redact.d.ts +0 -2
- package/dist/core/redact.js +0 -32
- package/dist/core/session-control.d.ts +0 -2
- package/dist/core/session-control.js +0 -5
- package/dist/core/tools.d.ts +46 -1
- package/dist/core/tools.js +88 -12
- package/dist/core/usage.d.ts +4 -3
- package/dist/core/usage.js +5 -4
- package/dist/core/vault.d.ts +0 -10
- package/dist/core/vault.js +0 -13
- package/dist/core/web.d.ts +2 -111
- package/dist/core/web.js +0 -443
- package/dist/driver/cdp.d.ts +6 -0
- package/dist/driver/cdp.js +245 -0
- package/dist/driver/page-driver.js +110 -7
- package/dist/driver/sealed.d.ts +4 -12
- package/dist/driver/sealed.js +23 -37
- package/dist/driver/stagehand.d.ts +12 -15
- package/dist/driver/stagehand.js +21 -17
- package/dist/durable/result.d.ts +1 -2
- package/dist/durable/result.js +2 -2
- package/dist/durable/store.d.ts +17 -3
- package/dist/durable/store.js +231 -64
- package/dist/durable.d.ts +50 -17
- package/dist/durable.js +107 -106
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -3
- package/dist/live-view/index.d.ts +4 -1
- package/dist/live-view/index.js +5 -0
- package/dist/live-view/protocol.d.ts +39 -7
- package/dist/live-view/protocol.js +2 -0
- package/dist/live-view/provider.d.ts +2 -2
- package/dist/live-view/provider.js +2 -2
- package/dist/live-view/server.d.ts +55 -2
- package/dist/live-view/server.js +282 -35
- package/dist/live-view/stream.js +16 -3
- package/dist/live-view/viewer.js +106 -13
- package/dist/providers/cdp.d.ts +0 -1
- package/dist/providers/cdp.js +35 -13
- package/dist/providers/chrome-args.d.ts +3 -0
- package/dist/providers/chrome-args.js +13 -2
- package/dist/providers/profiles.d.ts +1 -15
- package/dist/providers/profiles.js +1 -64
- package/dist/providers/shared.d.ts +1 -47
- package/dist/providers/shared.js +1 -82
- package/dist/providers/worker-extension.d.ts +20 -1
- package/dist/providers/worker-extension.js +86 -7
- package/dist/testing/backend.d.ts +6 -24
- package/dist/testing/backend.js +7 -30
- package/dist/vault-session.d.ts +4 -7
- package/dist/vault-session.js +26 -81
- package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
- package/dist/vendor/browser-use-pi/ax.js +642 -0
- package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
- package/dist/vendor/browser-use-pi/cdp.js +106 -0
- package/dist/vendor/browser-use-pi/page.d.ts +29 -0
- package/dist/vendor/browser-use-pi/page.js +99 -0
- package/package.json +15 -46
- package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
- package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
- package/dist/coding-agent-local.d.ts +0 -12
- package/dist/coding-agent-local.js +0 -72
- package/dist/coding-agent.d.ts +0 -134
- package/dist/coding-agent.js +0 -640
- package/dist/core/sites.d.ts +0 -33
- package/dist/core/sites.js +0 -104
- package/dist/driver/extension-worker.d.ts +0 -9
- package/dist/driver/extension-worker.js +0 -185
- package/dist/durable/web.d.ts +0 -47
- package/dist/durable/web.js +0 -41
- package/dist/providers/assigned.d.ts +0 -18
- package/dist/providers/assigned.js +0 -75
- package/dist/providers/browserbase-net.d.ts +0 -12
- package/dist/providers/browserbase-net.js +0 -95
- package/dist/providers/browserbase.d.ts +0 -169
- package/dist/providers/browserbase.js +0 -319
- package/dist/providers/kernel.d.ts +0 -58
- package/dist/providers/kernel.js +0 -291
- package/dist/recorder/credential.d.ts +0 -9
- package/dist/recorder/credential.js +0 -49
- package/dist/recorder/follow.d.ts +0 -36
- package/dist/recorder/follow.js +0 -163
- package/dist/recorder/frames.d.ts +0 -87
- package/dist/recorder/frames.js +0 -377
- package/dist/recorder/index.d.ts +0 -4
- package/dist/recorder/index.js +0 -7
- package/dist/recorder/jpeg.d.ts +0 -8
- package/dist/recorder/jpeg.js +0 -70
- package/dist/recorder/track.d.ts +0 -107
- package/dist/recorder/track.js +0 -280
- package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
- package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
- /package/dist/{providers → core}/cdp-call.d.ts +0 -0
- /package/dist/{providers → core}/cdp-call.js +0 -0
package/dist/durable/store.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Context } from "@earendil-works/chord";
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
2
|
import { type ConversationDocToken, type ConversationId, type DocumentReader, type Harness, type TaskId, type Tx } from "@earendil-works/pi-durable";
|
|
3
3
|
import type { BrowserConfig, BrowserProvider, HandoffOutcome, HandoffPort, InventoryRow, ReconcileReport, ReleaseReason, SessionChange, SessionRecord, SessionsState } from "../core/host.js";
|
|
4
4
|
import type { LeaseRef, LeaseState } from "../core/lease.js";
|
|
@@ -6,6 +6,7 @@ export declare const now: () => string;
|
|
|
6
6
|
/** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
|
|
7
7
|
export declare const RELEASE_ATTEMPTS = 6;
|
|
8
8
|
export declare const CONFIRM_POLLS = 5;
|
|
9
|
+
/** `owed` adds to the row's owed ids, `told` takes those told off it (InventoryRow.owed). */
|
|
9
10
|
type Move = {
|
|
10
11
|
state: LeaseState;
|
|
11
12
|
resourceId?: string;
|
|
@@ -13,6 +14,8 @@ type Move = {
|
|
|
13
14
|
at: string;
|
|
14
15
|
notice?: "kept" | "lost";
|
|
15
16
|
handoff?: string;
|
|
17
|
+
owed?: string[];
|
|
18
|
+
told?: string[];
|
|
16
19
|
};
|
|
17
20
|
/** `found`: the ids an earlier attempt (or a task this one succeeds) released under the row's tag, kept until the release
|
|
18
21
|
* is billed: a provider's tag lookup lists running sessions only, so a later attempt no longer finds one it stopped. */
|
|
@@ -39,7 +42,10 @@ export type HandoffInput = {
|
|
|
39
42
|
};
|
|
40
43
|
type HandoffResult = {
|
|
41
44
|
outcome: HandoffOutcome;
|
|
45
|
+
reason?: string;
|
|
42
46
|
};
|
|
47
|
+
/** When the provider made each session a tag lookup found, by id (InventoryRow.made). */
|
|
48
|
+
type Made = Record<string, string>;
|
|
43
49
|
export type StoreDeps = {
|
|
44
50
|
name: string;
|
|
45
51
|
Config: ConversationDocToken<BrowserConfig>;
|
|
@@ -56,8 +62,14 @@ export type StoreDeps = {
|
|
|
56
62
|
handoff?: HandoffPort;
|
|
57
63
|
/** A handoff's session came back under `fence`. */
|
|
58
64
|
handedBack?(tag: string, fence: number): void;
|
|
65
|
+
/** A release task (an attempt, or its abort handler) had the provider release `tag`'s session, and the provider answered. */
|
|
66
|
+
stopped?(tag: string): void;
|
|
67
|
+
/** A release by `row`'s tag ended sessions besides the row's own (`ids`, each confirmed no longer running): a create
|
|
68
|
+
* retried behind the provider, or a create race, left them. Their time is on no record (durable.ts, onRaceReleased).
|
|
69
|
+
* `made`: when the provider made each, where a tag lookup said (InventoryRow.made). */
|
|
70
|
+
raced?(row: InventoryRow, ids: string[], made: Made): Promise<void>;
|
|
59
71
|
};
|
|
60
|
-
export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack }: StoreDeps): {
|
|
72
|
+
export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook, raced }: StoreDeps): {
|
|
61
73
|
Inventory: import("@earendil-works/pi-durable").SessionDocToken<{
|
|
62
74
|
rows: Record<string, InventoryRow>;
|
|
63
75
|
}>;
|
|
@@ -66,7 +78,9 @@ export declare function custodyStore({ name, Config, Sessions, providerOf, emit,
|
|
|
66
78
|
begin: (tx: Tx, row: InventoryRow) => Promise<void>;
|
|
67
79
|
requestRelease: (tx: Tx, row: InventoryRow, reason: ReleaseReason, at: string, notBefore?: number) => Promise<void>;
|
|
68
80
|
bindByTag: (provider: BrowserProvider, row: InventoryRow, commit: (change: (tx: Tx) => Promise<void>) => Promise<unknown>, signal?: AbortSignal, found?: LeaseRef[]) => Promise<LeaseRef | null>;
|
|
69
|
-
emitReleased: (cid: ConversationId, tag: string, read: DocumentReader, context: Context, at?: string
|
|
81
|
+
emitReleased: (cid: ConversationId, tag: string, read: DocumentReader, context: Context, at?: string, found?: {
|
|
82
|
+
resourceId?: string;
|
|
83
|
+
}) => Promise<void>;
|
|
70
84
|
ReleaseTask: import("@earendil-works/pi-durable").Task<ReleaseInput, ReleaseState, {
|
|
71
85
|
released: number;
|
|
72
86
|
}, object>;
|
package/dist/durable/store.js
CHANGED
|
@@ -1,21 +1,37 @@
|
|
|
1
1
|
import { defineDoc, defineTask } from "@earendil-works/pi-durable";
|
|
2
|
-
import { backoffMs, moveRecord, notices } from "../core/custody.js";
|
|
2
|
+
import { backoffMs, HANDOFF_POLL_MS, moveRecord, notices } from "../core/custody.js";
|
|
3
3
|
export const now = () => new Date().toISOString();
|
|
4
4
|
const iso = (ms) => new Date(ms).toISOString();
|
|
5
5
|
const cidOf = (row) => row.conversationId;
|
|
6
|
+
/** Waits `ms`, or until `signal` aborts. */
|
|
7
|
+
const pause = (ms, signal) => new Promise((resolve) => {
|
|
8
|
+
const done = () => { clearTimeout(timer); signal?.removeEventListener("abort", done); resolve(); };
|
|
9
|
+
const timer = setTimeout(done, ms);
|
|
10
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
11
|
+
});
|
|
6
12
|
/** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
|
|
7
13
|
export const RELEASE_ATTEMPTS = 6;
|
|
8
14
|
export const CONFIRM_POLLS = 5;
|
|
9
|
-
|
|
10
|
-
|
|
15
|
+
const madeOf = (refs) => Object.fromEntries(refs.flatMap((ref) => (ref.madeAt ? [[ref.id, ref.madeAt]] : [])));
|
|
16
|
+
/** `made` without the ids `told`; undefined when none is left. */
|
|
17
|
+
const madeLeft = (made, told = []) => {
|
|
18
|
+
const left = Object.entries(made ?? {}).filter(([id]) => !told.includes(id));
|
|
19
|
+
return left.length ? Object.fromEntries(left) : undefined;
|
|
20
|
+
};
|
|
21
|
+
export function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook, raced }) {
|
|
22
|
+
const Inventory = defineDoc({ kind: `${name}.inventory`, version: 1, scope: "session", initial: () => ({ rows: {} }), checkpointWhen: () => false });
|
|
11
23
|
/** One state change: the record and the open-session inventory move in the same commit. */
|
|
12
24
|
async function move(tx, row, next) {
|
|
13
25
|
const inventory = await tx.doc(Inventory);
|
|
14
|
-
|
|
15
|
-
|
|
26
|
+
const owed = union(inventory.rows[row.tag]?.owed, next.owed).filter((id) => !next.told?.includes(id));
|
|
27
|
+
const made = madeLeft(inventory.rows[row.tag]?.made, next.told);
|
|
28
|
+
const { owed: _stale, made: _staleMade, ...fields } = row;
|
|
29
|
+
// A lost one stays: custody gave up releasing it, not looking for it (reconcile releases it again at run open). So
|
|
30
|
+
// does a released one that still owes a raced call: the reconcile confirms those sessions' stop and tells them.
|
|
31
|
+
if (next.state === "released" && !owed.length)
|
|
16
32
|
delete inventory.rows[row.tag];
|
|
17
33
|
else
|
|
18
|
-
inventory.rows[row.tag] = { ...
|
|
34
|
+
inventory.rows[row.tag] = { ...fields, state: next.state === "released" ? "lost" : next.state, resourceId: next.resourceId ?? row.resourceId, ...(owed.length ? { owed } : {}), ...(made ? { made } : {}) };
|
|
19
35
|
const state = await tx.doc(Sessions, cidOf(row));
|
|
20
36
|
const record = state.sessions.find((r) => r.tag === row.tag);
|
|
21
37
|
if (!record)
|
|
@@ -36,9 +52,33 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
36
52
|
const addNotice = (state, text) => { if (!state.notice?.includes(text))
|
|
37
53
|
state.notice = [state.notice, text].filter(Boolean).join(" "); };
|
|
38
54
|
const begin = async (tx, row) => { (await tx.doc(Inventory)).rows[row.tag] = { ...row, state: "creating", resourceId: null }; };
|
|
55
|
+
/** Saves `ids` on the row as owed, and when the provider made each (`made`), before any stop is sent to them. */
|
|
56
|
+
const owe = async (tx, row, ids, made = {}) => {
|
|
57
|
+
const rows = (await tx.doc(Inventory)).rows;
|
|
58
|
+
const at = rows[row.tag] ?? row;
|
|
59
|
+
rows[row.tag] = { ...at, owed: union(at.owed, ids), ...madeOn(at, made) };
|
|
60
|
+
};
|
|
61
|
+
/** The row's `made` with `made` added, as fields to spread on it. */
|
|
62
|
+
const madeOn = (at, made) => {
|
|
63
|
+
const all = madeLeft({ ...at.made, ...made });
|
|
64
|
+
return all ? { made: all } : {};
|
|
65
|
+
};
|
|
66
|
+
/** Saves when the provider made the sessions a release found (`made`) on the row, before any stop is sent to them. */
|
|
67
|
+
const noteMade = async (tx, row, made) => {
|
|
68
|
+
const rows = (await tx.doc(Inventory)).rows;
|
|
69
|
+
const at = rows[row.tag];
|
|
70
|
+
if (at && Object.keys(made).length)
|
|
71
|
+
rows[row.tag] = { ...at, ...madeOn(at, made) };
|
|
72
|
+
};
|
|
73
|
+
/** When the provider made the row's sessions, as its row holds it now, with `seen` (this process's lookups) over it. */
|
|
74
|
+
const madeFor = async (read, row, context, seen = {}) => ({ ...(await read.snapshot(Inventory, context))?.rows?.[row.tag]?.made, ...seen });
|
|
75
|
+
/** The release confirms the row's owed sessions with its own and tells them (they go in as `found`). A row with no id
|
|
76
|
+
* yet leaves them to the reconcile: its release takes the first id it finds as its own. */
|
|
39
77
|
async function requestRelease(tx, row, reason, at, notBefore) {
|
|
78
|
+
const owed = row.resourceId === null ? [] : (await tx.doc(Inventory)).rows[row.tag]?.owed ?? [];
|
|
40
79
|
await move(tx, row, { state: "releasing", reason, at });
|
|
41
|
-
|
|
80
|
+
const { owed: _stale, made: _staleMade, ...fields } = row;
|
|
81
|
+
await tx.createTask(ReleaseTask, { row: { ...fields, state: "releasing" }, ...(notBefore ? { notBefore } : {}), ...(owed.length ? { found: owed } : {}) }, { ownership: { kind: "conversation" }, conversationId: cidOf(row), background: true });
|
|
42
82
|
}
|
|
43
83
|
/** A create no tag lookup finds may still land (a crashed or fenced holder's call in flight): the release task looks
|
|
44
84
|
* again by tag after the create deadline and releases whatever landed. */
|
|
@@ -46,12 +86,28 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
46
86
|
/** `found` hears the ids before any is released: a release that stops a session and then fails (its status check after
|
|
47
87
|
* the stop) leaves the session known only to its caller, since the provider's tag lookup lists running sessions only. */
|
|
48
88
|
async function releaseAll(row, provider, signal, found = () => { }) {
|
|
49
|
-
const
|
|
50
|
-
|
|
89
|
+
const refs = await provider.findByTag(row.tag, signal);
|
|
90
|
+
const ids = [...new Set([row.resourceId, ...refs.map((ref) => ref.id)].filter((id) => id !== null))];
|
|
91
|
+
await found(ids, madeOf(refs));
|
|
51
92
|
for (const id of ids)
|
|
52
93
|
await provider.release({ id, tag: row.tag }, signal);
|
|
53
94
|
return ids;
|
|
54
95
|
}
|
|
96
|
+
/** The sessions among `ids` besides `row`'s own. `ids` are what its release found, every attempt's, oldest first (the
|
|
97
|
+
* task's checkpoint keeps them): its own is its id, or for a create whose answer was lost the first its tag found
|
|
98
|
+
* (foundId), whose record bills it. */
|
|
99
|
+
const othersOf = (row, ids) => {
|
|
100
|
+
const own = row.resourceId ?? ids[0];
|
|
101
|
+
return ids.filter((id) => id !== own);
|
|
102
|
+
};
|
|
103
|
+
/** The host hears the sessions besides `row`'s own among `ids` (raced) once their stop is confirmed, `ids` every id the
|
|
104
|
+
* release found: one whose release stopped it and then failed (its status read) is found by no later lookup, so it is
|
|
105
|
+
* told from the ids its release kept, once, by the step that confirms the release. */
|
|
106
|
+
const tellRaced = async (row, ids, made) => {
|
|
107
|
+
const extras = othersOf(row, ids);
|
|
108
|
+
if (extras.length)
|
|
109
|
+
await raced?.(row, extras, await made());
|
|
110
|
+
};
|
|
55
111
|
const anyRunning = async (provider, row, ids, signal) => {
|
|
56
112
|
for (const id of ids)
|
|
57
113
|
if (["pending", "running"].includes(await provider.status({ id, tag: row.tag }, signal)))
|
|
@@ -78,36 +134,79 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
78
134
|
return fallback;
|
|
79
135
|
}
|
|
80
136
|
}
|
|
137
|
+
/** Releases `extras` and returns those a status read confirms stopped, read again (backoffMs) up to CONFIRM_POLLS times
|
|
138
|
+
* while a read fails or a stop that was sent is still under way; one still running after a release that failed is
|
|
139
|
+
* not read again. One not returned stays owed on the row. */
|
|
140
|
+
async function stopExtras(provider, row, extras, signal) {
|
|
141
|
+
const open = new Map();
|
|
142
|
+
for (const extra of extras)
|
|
143
|
+
open.set(extra.id, await provider.release(extra, signal).then(() => true, () => false));
|
|
144
|
+
const stopped = new Set();
|
|
145
|
+
for (let poll = 0; open.size && poll < CONFIRM_POLLS && !signal?.aborted; poll += 1) {
|
|
146
|
+
if (poll)
|
|
147
|
+
await pause(backoffMs(poll - 1), signal);
|
|
148
|
+
for (const [id, sent] of [...open]) {
|
|
149
|
+
const state = await provider.status({ id, tag: row.tag }, signal).catch(() => null);
|
|
150
|
+
if (state === null)
|
|
151
|
+
continue;
|
|
152
|
+
if (!["pending", "running"].includes(state))
|
|
153
|
+
(stopped.add(id), open.delete(id));
|
|
154
|
+
else if (!sent)
|
|
155
|
+
open.delete(id);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return extras.map((extra) => extra.id).filter((id) => stopped.has(id));
|
|
159
|
+
}
|
|
81
160
|
/** A create whose answer never came, settled by its tag: the first session found is kept and committed `live`; extras
|
|
82
|
-
* (a create retried behind the provider's API) are released
|
|
161
|
+
* (a create retried behind the provider's API) are saved on the row as owed, then released, and told as raced once
|
|
162
|
+
* their stop is confirmed. One no read confirms here stays owed, for the session's own release or the reconcile. */
|
|
83
163
|
async function bindByTag(provider, row, commit, signal, found) {
|
|
84
164
|
const refs = found ?? await provider.findByTag(row.tag, signal);
|
|
85
|
-
|
|
86
|
-
|
|
165
|
+
const extras = refs.slice(1);
|
|
166
|
+
if (extras.length)
|
|
167
|
+
await commit((tx) => owe(tx, row, extras.map((ref) => ref.id), madeOf(extras)));
|
|
168
|
+
const stopped = await stopExtras(provider, row, extras, signal);
|
|
169
|
+
if (stopped.length)
|
|
170
|
+
await raced?.(row, stopped, madeOf(extras));
|
|
87
171
|
const kept = refs[0] ?? null;
|
|
88
|
-
await commit((tx) => kept ? move(tx, row, { state: "live", resourceId: kept.id, at: now() }) : unknownCreate(tx, row, now()));
|
|
172
|
+
await commit((tx) => kept ? move(tx, row, { state: "live", resourceId: kept.id, at: now(), told: stopped }) : unknownCreate(tx, row, now()));
|
|
89
173
|
return kept;
|
|
90
174
|
}
|
|
91
|
-
|
|
175
|
+
/** `found`: the id a release task's lookup found for a record that has none yet, which the commit after this one
|
|
176
|
+
* records; the host hears the session with it, and with the bill that commit makes. */
|
|
177
|
+
async function emitReleased(cid, tag, read, context, at = now(), found = {}) {
|
|
92
178
|
const [state, config] = await Promise.all([read.snapshot(Sessions, cid, context), read.snapshot(Config, cid, context)]);
|
|
93
|
-
const
|
|
179
|
+
const stored = state?.sessions.find((r) => r.tag === tag);
|
|
180
|
+
const record = stored && stored.resourceId === null && found.resourceId ? { ...stored, resourceId: found.resourceId } : stored;
|
|
94
181
|
const spent = record && record.resourceId !== null ? meter(record.spent, at, true).spent : record?.spent;
|
|
95
182
|
if (record && spent)
|
|
96
183
|
await emit(cid, config?.label ?? "", { ...record, state: "released", endedAt: record.endedAt ?? at, spent }, "released");
|
|
97
184
|
}
|
|
98
185
|
const union = (...lists) => [...new Set(lists.flatMap((ids) => ids ?? []))];
|
|
99
186
|
/** 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
|
|
187
|
+
* the next attempt, and bills a lost one; of a lost one's other sessions, each the provider says no longer runs is
|
|
188
|
+
* told (raced), and the rest stay owed on the row for the reconcile. */
|
|
101
189
|
async function retry(runtime, row, attempt, context, found) {
|
|
102
190
|
if (attempt + 1 >= RELEASE_ATTEMPTS) {
|
|
191
|
+
const ended = await step(runtime, async () => {
|
|
192
|
+
const provider = await providerOf(runtime, cidOf(row), row.plane, context);
|
|
193
|
+
const out = [];
|
|
194
|
+
for (const id of othersOf(row, found))
|
|
195
|
+
if (!(await anyRunning(provider, row, [id], runtime.signal)))
|
|
196
|
+
out.push(id);
|
|
197
|
+
return out;
|
|
198
|
+
}, []);
|
|
199
|
+
if (ended.length)
|
|
200
|
+
await raced?.(row, ended, await madeFor(runtime, row, context));
|
|
103
201
|
await runtime.commit(async (tx) => {
|
|
104
|
-
await move(tx, row, { state: "lost", reason: "lost", at: iso(runtime.now()), ...foundId(row, found) });
|
|
202
|
+
await move(tx, row, { state: "lost", reason: "lost", at: iso(runtime.now()), ...foundId(row, found), owed: othersOf(row, found), told: ended });
|
|
105
203
|
return { status: "terminal", outcome: { status: "failed", error: { code: "release_failed", message: `${row.tag}: not released after ${RELEASE_ATTEMPTS} attempts` } } };
|
|
106
204
|
}, context);
|
|
107
205
|
return;
|
|
108
206
|
}
|
|
109
|
-
|
|
110
|
-
|
|
207
|
+
// pi 1.5: the wait is a durable sleep. Its deadline is computed once on the Harness clock and stored with the sleep
|
|
208
|
+
// (the task's `until`), so a process that dies while it sleeps resumes at that same deadline, never a new one.
|
|
209
|
+
await runtime.sleepUntil(runtime.now() + backoffMs(attempt), { phase: "release", attempt: attempt + 1, ...(found.length ? { found } : {}) }, context);
|
|
111
210
|
}
|
|
112
211
|
const ReleaseTask = defineTask({
|
|
113
212
|
name: `${name}.release`,
|
|
@@ -118,22 +217,29 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
118
217
|
const { row, notBefore } = task.input;
|
|
119
218
|
const { attempt } = task.state.checkpoint;
|
|
120
219
|
const found = union(task.input.found, task.state.checkpoint.found);
|
|
220
|
+
// The create deadline from the task's input (durable): sleep to it, then this phase runs again at the same
|
|
221
|
+
// checkpoint, past the deadline.
|
|
121
222
|
if (attempt === 0 && notBefore && runtime.now() < notBefore)
|
|
122
|
-
|
|
223
|
+
return runtime.sleepUntil(notBefore, task.state.checkpoint, context);
|
|
123
224
|
let seen = [];
|
|
124
225
|
// Ids the lookup found that the task does not hold yet are committed before any stop is sent: an attempt cut
|
|
125
226
|
// between its stop and its next commit (the task's abort) leaves them for the abort handler, whose own lookup
|
|
126
227
|
// no longer lists a stopped session.
|
|
127
|
-
const keep = async (ids) => {
|
|
228
|
+
const keep = async (ids, made) => {
|
|
128
229
|
seen = ids;
|
|
129
230
|
const known = union(found, ids);
|
|
130
|
-
if (known.length > found.length)
|
|
131
|
-
await runtime.commit(() =>
|
|
231
|
+
if (known.length > found.length) {
|
|
232
|
+
await runtime.commit(async (tx) => {
|
|
233
|
+
await noteMade(tx, row, made);
|
|
234
|
+
return { status: "running", checkpoint: { phase: "release", attempt, found: known } };
|
|
235
|
+
}, context);
|
|
236
|
+
}
|
|
132
237
|
};
|
|
133
238
|
const released = await step(runtime, async () => releaseAll(row, await providerOf(runtime, cidOf(row), row.plane, context), runtime.signal, keep), null);
|
|
134
239
|
// What the lookup found goes on to the next attempt even when its release failed: the stop may have landed.
|
|
135
240
|
if (!released)
|
|
136
241
|
return retry(runtime, row, attempt, context, union(found, seen));
|
|
242
|
+
stoppedHook?.(row.tag);
|
|
137
243
|
// Confirmed together: what this attempt released and what earlier ones did.
|
|
138
244
|
const ids = union(found, released);
|
|
139
245
|
await runtime.commit(() => ({ status: "running", checkpoint: { phase: "confirm", attempt, ids, polls: 0 } }), context);
|
|
@@ -143,18 +249,18 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
143
249
|
const { attempt, ids, polls } = task.state.checkpoint;
|
|
144
250
|
const running = await step(runtime, async () => anyRunning(await providerOf(runtime, cidOf(row), row.plane, context), row, ids, runtime.signal), true);
|
|
145
251
|
if (running && polls + 1 < CONFIRM_POLLS) {
|
|
146
|
-
await runtime.
|
|
147
|
-
await runtime.commit(() => ({ status: "running", checkpoint: { phase: "confirm", attempt, ids, polls: polls + 1 } }), context);
|
|
252
|
+
await runtime.sleepUntil(runtime.now() + backoffMs(polls), { phase: "confirm", attempt, ids, polls: polls + 1 }, context);
|
|
148
253
|
return;
|
|
149
254
|
}
|
|
150
255
|
if (running)
|
|
151
256
|
return retry(runtime, row, attempt, context, ids);
|
|
152
|
-
// The host hears the release before the task's last commit, so at
|
|
153
|
-
// records.
|
|
257
|
+
// The host hears the release, and the other sessions it ended (tellRaced), before the task's last commit, so at
|
|
258
|
+
// least once, with the bill that commit records.
|
|
154
259
|
const at = iso(runtime.now());
|
|
155
|
-
await emitReleased(cidOf(row), row.tag, runtime, context, at);
|
|
260
|
+
await emitReleased(cidOf(row), row.tag, runtime, context, at, foundId(row, ids));
|
|
261
|
+
await tellRaced(row, ids, () => madeFor(runtime, row, context));
|
|
156
262
|
await runtime.commit(async (tx) => {
|
|
157
|
-
await move(tx, row, { state: "released", at, ...foundId(row, ids) });
|
|
263
|
+
await move(tx, row, { state: "released", at, ...foundId(row, ids), told: othersOf(row, ids) });
|
|
158
264
|
return { status: "terminal", outcome: { status: "completed", result: { released: ids.length } } };
|
|
159
265
|
}, context);
|
|
160
266
|
},
|
|
@@ -166,20 +272,39 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
166
272
|
const checkpoint = task.state.checkpoint;
|
|
167
273
|
let found = union(task.input.found, checkpoint.phase === "confirm" ? checkpoint.ids : checkpoint.found);
|
|
168
274
|
let stopped = null;
|
|
169
|
-
|
|
275
|
+
let confirmed = [];
|
|
276
|
+
let seen = {};
|
|
277
|
+
// Before the create deadline nothing found is proof of nothing: the successor keeps the delayed lookup. The ids
|
|
278
|
+
// earlier attempts found that no lookup lists now are read once each; one not confirmed stays owed on the row.
|
|
170
279
|
if (!(notBefore && runtime.now() < notBefore))
|
|
171
|
-
stopped = await providerOf(runtime, cidOf(row), row.plane, context).then(
|
|
280
|
+
stopped = await providerOf(runtime, cidOf(row), row.plane, context).then(async (provider) => {
|
|
281
|
+
const ids = await releasedIds(provider, row, context.abortSignal, (ids, made) => void ((found = union(found, ids)), (seen = { ...seen, ...made })));
|
|
282
|
+
if (ids)
|
|
283
|
+
for (const id of found)
|
|
284
|
+
if (ids.includes(id) || !(await anyRunning(provider, row, [id], context.abortSignal).catch(() => true)))
|
|
285
|
+
confirmed.push(id);
|
|
286
|
+
return ids;
|
|
287
|
+
}).catch(() => null);
|
|
288
|
+
const others = stopped ? othersOf(row, union(found, stopped)) : [];
|
|
289
|
+
const told = others.filter((id) => stopped?.includes(id) || confirmed.includes(id));
|
|
290
|
+
if (stopped)
|
|
291
|
+
stoppedHook?.(row.tag);
|
|
292
|
+
if (told.length)
|
|
293
|
+
await raced?.(row, told, await madeFor(runtime, row, context, seen));
|
|
172
294
|
await runtime.commit(async (tx) => {
|
|
173
295
|
if (stopped)
|
|
174
|
-
await
|
|
296
|
+
await noteMade(tx, row, seen);
|
|
297
|
+
if (stopped)
|
|
298
|
+
await move(tx, row, { state: "released", at: iso(runtime.now()), ...foundId(row, union(found, stopped)), owed: others, told });
|
|
175
299
|
else
|
|
176
300
|
await tx.createTask(ReleaseTask, { ...task.input, ...(found.length ? { found } : {}) }, { ownership: { kind: "conversation" }, conversationId: cidOf(row), background: true });
|
|
177
301
|
return { status: "terminal", outcome: { status: "aborted", reason: stopped ? "released by the abort handler" : "release handed to a successor task" } };
|
|
178
302
|
}, context);
|
|
179
303
|
},
|
|
180
304
|
});
|
|
181
|
-
/** Polls the port until it answers,
|
|
182
|
-
* this request.
|
|
305
|
+
/** Polls the port until it answers, every HANDOFF_POLL_MS while the answer is pending, then gives the session back with
|
|
306
|
+
* the outcome's notice, if it is still held for this request. `attempt` counts the reads in a row that failed, which
|
|
307
|
+
* back off (backoffMs); a read that answers "pending" starts it again. */
|
|
183
308
|
const HandoffTask = defineTask({
|
|
184
309
|
name: `${name}.handoff`,
|
|
185
310
|
version: 1,
|
|
@@ -201,6 +326,7 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
201
326
|
if (over)
|
|
202
327
|
return;
|
|
203
328
|
let answer = "pending";
|
|
329
|
+
let failed = false;
|
|
204
330
|
try {
|
|
205
331
|
if (handoff)
|
|
206
332
|
answer = await handoff.outcome(interactionId, runtime.signal);
|
|
@@ -209,13 +335,20 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
209
335
|
if (runtime.signal.aborted)
|
|
210
336
|
throw error;
|
|
211
337
|
runtime.report(scrubbed(error));
|
|
338
|
+
failed = true;
|
|
339
|
+
}
|
|
340
|
+
// A person's answer can come at any moment: while it is pending, it is asked again at a short fixed interval, so
|
|
341
|
+
// a hand-back resumes the agent within one poll. A read that failed backs off instead.
|
|
342
|
+
if (failed) {
|
|
343
|
+
await runtime.sleepUntil(runtime.now() + backoffMs(attempt), { phase: "poll", attempt: attempt + 1 }, context);
|
|
344
|
+
return;
|
|
212
345
|
}
|
|
213
346
|
if (answer === "pending") {
|
|
214
|
-
await runtime.
|
|
215
|
-
await runtime.commit(() => ({ status: "running", checkpoint: { phase: "poll", attempt: attempt + 1 } }), context);
|
|
347
|
+
await runtime.sleepUntil(runtime.now() + HANDOFF_POLL_MS, { phase: "poll", attempt: 0 }, context);
|
|
216
348
|
return;
|
|
217
349
|
}
|
|
218
|
-
const outcome = answer;
|
|
350
|
+
const outcome = typeof answer === "string" ? answer : answer.outcome;
|
|
351
|
+
const reason = typeof answer === "string" ? undefined : answer.reason;
|
|
219
352
|
await runtime.commit(async (tx) => {
|
|
220
353
|
const state = await tx.doc(Sessions, cidOf(row));
|
|
221
354
|
const record = state.sessions.find((r) => r.tag === row.tag);
|
|
@@ -224,7 +357,7 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
224
357
|
addNotice(state, notices.handedBack(outcome, completionCondition));
|
|
225
358
|
handedBack?.(row.tag, record.fence ?? 0);
|
|
226
359
|
}
|
|
227
|
-
return { status: "terminal", outcome: { status: "completed", result: { outcome } } };
|
|
360
|
+
return { status: "terminal", outcome: { status: "completed", result: { outcome, ...(reason ? { reason } : {}) } } };
|
|
228
361
|
}, context);
|
|
229
362
|
},
|
|
230
363
|
},
|
|
@@ -248,6 +381,65 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
248
381
|
} while (cursor);
|
|
249
382
|
return undefined;
|
|
250
383
|
}
|
|
384
|
+
/** A lost row at run open: the sessions besides its own that its tag lists are saved as owed, then its own and those
|
|
385
|
+
* are released, and its own and every owed one read once each. The others a read confirms stopped are told (raced) though another's release failed; the rest stay owed.
|
|
386
|
+
* The row goes, its record billed, once every release answered and every session is confirmed stopped; a release
|
|
387
|
+
* that failed leaves it for the next reconcile (unreachable). A session known only by its tag (no id on the row) is
|
|
388
|
+
* the first its tag lists, kept on the row and record before any stop is sent, as its tag lookup lists running
|
|
389
|
+
* sessions only. */
|
|
390
|
+
async function reconcileLost(provider, row, commit, outcome, at) {
|
|
391
|
+
const refs = await provider.findByTag(row.tag);
|
|
392
|
+
const listed = refs.map((ref) => ref.id);
|
|
393
|
+
const made = { ...row.made, ...madeOf(refs) };
|
|
394
|
+
const own = row.resourceId ?? listed[0] ?? null;
|
|
395
|
+
const others = union(listed, row.owed).filter((id) => id !== own);
|
|
396
|
+
if (others.some((id) => !row.owed?.includes(id)) || own !== row.resourceId) {
|
|
397
|
+
await commit(async (tx) => {
|
|
398
|
+
await owe(tx, row, others, made);
|
|
399
|
+
const rows = (await tx.doc(Inventory)).rows;
|
|
400
|
+
if (own !== null && rows[row.tag]?.resourceId === null)
|
|
401
|
+
rows[row.tag].resourceId = own;
|
|
402
|
+
const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
|
|
403
|
+
if (own !== null && record && record.resourceId === null)
|
|
404
|
+
record.resourceId = own;
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
let answered = true;
|
|
408
|
+
for (const id of union(own === null ? [] : [own], listed))
|
|
409
|
+
if (!(await provider.release({ id, tag: row.tag }).then(() => true, () => false)))
|
|
410
|
+
answered = false;
|
|
411
|
+
const stopped = [];
|
|
412
|
+
for (const id of union(own === null ? [] : [own], others))
|
|
413
|
+
if (!(await anyRunning(provider, row, [id]).catch(() => true)))
|
|
414
|
+
stopped.push(id);
|
|
415
|
+
const told = others.filter((id) => stopped.includes(id));
|
|
416
|
+
if (told.length)
|
|
417
|
+
await raced?.(row, told, made);
|
|
418
|
+
const done = answered && (own === null || stopped.includes(own)) && told.length === others.length;
|
|
419
|
+
if (done) {
|
|
420
|
+
await outcome("released", async (tx) => {
|
|
421
|
+
delete (await tx.doc(Inventory)).rows[row.tag];
|
|
422
|
+
const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
|
|
423
|
+
if (record && record.resourceId !== null)
|
|
424
|
+
await bill(tx, cidOf(row), record, at, true);
|
|
425
|
+
});
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (told.length) {
|
|
429
|
+
await commit(async (tx) => {
|
|
430
|
+
const rows = (await tx.doc(Inventory)).rows;
|
|
431
|
+
const at = rows[row.tag];
|
|
432
|
+
if (!at)
|
|
433
|
+
return;
|
|
434
|
+
const { made: _told, ...fields } = at;
|
|
435
|
+
const left = madeLeft(at.made, told);
|
|
436
|
+
rows[row.tag] = { ...fields, owed: (at.owed ?? []).filter((id) => !told.includes(id)), ...(left ? { made: left } : {}) };
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
if (!answered)
|
|
440
|
+
throw new Error(`${row.tag}: a release failed`);
|
|
441
|
+
await outcome("lost");
|
|
442
|
+
}
|
|
251
443
|
async function reconcileAll(harness, isActive, context) {
|
|
252
444
|
const report = { released: [], kept: [], lost: [], unreachable: [] };
|
|
253
445
|
for (const row of Object.values((await harness.snapshot(Inventory, context))?.rows ?? {})) {
|
|
@@ -260,32 +452,7 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
|
|
|
260
452
|
try {
|
|
261
453
|
const provider = await providerOf(harness, cidOf(row), row.plane, context);
|
|
262
454
|
if (row.state === "lost") {
|
|
263
|
-
|
|
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) => {
|
|
282
|
-
delete (await tx.doc(Inventory)).rows[row.tag];
|
|
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];
|
|
286
|
-
if (record && record.resourceId !== null)
|
|
287
|
-
await bill(tx, cidOf(row), record, at, true);
|
|
288
|
-
}) : outcome("lost"));
|
|
455
|
+
await reconcileLost(provider, row, commit, outcome, at);
|
|
289
456
|
continue;
|
|
290
457
|
}
|
|
291
458
|
let live = row;
|