@parcha/pi-browser 0.1.0-beta.17 → 0.1.0-beta.19
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 +5 -0
- package/README.md +177 -39
- package/dist/coding-agent-local.js +2 -1
- package/dist/coding-agent.d.ts +42 -2
- package/dist/coding-agent.js +159 -21
- package/dist/core/clip.d.ts +31 -0
- package/dist/core/clip.js +49 -0
- package/dist/core/contract.d.ts +4 -1
- package/dist/core/contract.js +40 -7
- package/dist/core/custody.d.ts +79 -5
- package/dist/core/custody.js +66 -5
- package/dist/core/decisions.d.ts +4 -0
- package/dist/core/dial.d.ts +7 -0
- package/dist/core/dial.js +41 -0
- package/dist/core/downloads.d.ts +1 -0
- package/dist/core/downloads.js +17 -5
- package/dist/core/driving-guard.d.ts +13 -0
- package/dist/core/driving-guard.js +61 -0
- package/dist/core/driving.d.ts +61 -0
- package/dist/core/driving.js +156 -0
- package/dist/core/effects.js +33 -13
- package/dist/core/evidence.d.ts +3 -1
- package/dist/core/failures.d.ts +5 -1
- package/dist/core/failures.js +20 -4
- package/dist/core/files.d.ts +8 -0
- package/dist/core/files.js +74 -0
- package/dist/core/find.d.ts +3 -1
- package/dist/core/find.js +2 -1
- package/dist/core/guard.d.ts +9 -1
- package/dist/core/guard.js +7 -2
- package/dist/core/host.d.ts +49 -1
- package/dist/core/images.d.ts +10 -2
- package/dist/core/images.js +4 -4
- package/dist/core/lease.d.ts +1 -1
- package/dist/core/lease.js +2 -1
- package/dist/core/session-control.d.ts +2 -0
- package/dist/core/session-control.js +5 -0
- package/dist/core/tools.d.ts +70 -4
- package/dist/core/tools.js +288 -45
- package/dist/core/unanswered.d.ts +3 -0
- package/dist/core/unanswered.js +17 -0
- package/dist/core/usage.d.ts +2 -0
- package/dist/core/usage.js +6 -0
- package/dist/core/web.d.ts +1 -1
- package/dist/core/web.js +9 -7
- package/dist/driver/extension-worker.d.ts +4 -2
- package/dist/driver/extension-worker.js +16 -10
- package/dist/driver/page-driver.d.ts +8 -0
- package/dist/driver/page-driver.js +128 -0
- package/dist/driver/stagehand.d.ts +3 -1
- package/dist/driver/stagehand.js +40 -66
- package/dist/durable.d.ts +16 -4
- package/dist/durable.js +415 -82
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/live-view/index.d.ts +4 -0
- package/dist/live-view/index.js +4 -0
- package/dist/live-view/protocol.d.ts +152 -0
- package/dist/live-view/protocol.js +84 -0
- package/dist/live-view/provider.d.ts +6 -0
- package/dist/live-view/provider.js +23 -0
- package/dist/live-view/server.d.ts +50 -0
- package/dist/live-view/server.js +342 -0
- package/dist/live-view/stream.d.ts +7 -0
- package/dist/live-view/stream.js +388 -0
- package/dist/live-view/token.d.ts +6 -0
- package/dist/live-view/token.js +13 -0
- package/dist/live-view/viewer.d.ts +6 -0
- package/dist/live-view/viewer.js +350 -0
- package/dist/live-view/ws.d.ts +19 -0
- package/dist/live-view/ws.js +176 -0
- package/dist/providers/assigned.d.ts +18 -0
- package/dist/providers/assigned.js +76 -0
- package/dist/providers/cdp-call.js +12 -2
- package/dist/providers/cdp.js +37 -11
- package/dist/recorder/follow.d.ts +10 -0
- package/dist/recorder/follow.js +27 -2
- package/dist/recorder/frames.d.ts +7 -0
- package/dist/recorder/frames.js +73 -5
- package/dist/store.d.ts +22 -3
- package/dist/store.js +75 -4
- package/dist/testing/backend.d.ts +26 -0
- package/dist/testing/backend.js +21 -3
- package/dist/testing/driver.d.ts +18 -1
- package/dist/testing/driver.js +4 -0
- package/dist/web.js +2 -2
- package/package.json +10 -2
package/dist/durable.js
CHANGED
|
@@ -1,21 +1,26 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { configure, defineDoc, defineExtension, defineTool, ToolResultEntry } from "@earendil-works/pi-durable";
|
|
3
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, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec } from "./core/custody.js";
|
|
4
|
+
import { BrowserFailureError, closeDriver, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
|
|
5
5
|
import { forModel } from "./durable-result.js";
|
|
6
6
|
import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
|
|
7
7
|
import { browserFailure, classifyBrowserError } from "./core/failures.js";
|
|
8
|
+
import { workspaceFiles } from "./core/files.js";
|
|
9
|
+
import { drivingGuarded } from "./core/driving-guard.js";
|
|
10
|
+
import { drivingGates, keptFor, personOn, rearmWhenLeft } from "./core/driving.js";
|
|
8
11
|
import { pageTools } from "./core/tools.js";
|
|
9
12
|
import { useWebsite, useWebsiteContract } from "./core/sites.js";
|
|
10
13
|
import { leaseTag } from "./core/lease.js";
|
|
11
14
|
import { createRedactor, redactDeep, scrubPageUrl } from "./core/redact.js";
|
|
12
|
-
import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, providerKeyValues } from "./core/session-control.js";
|
|
15
|
+
import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, oneAtATime, providerKeyValues } from "./core/session-control.js";
|
|
13
16
|
import { custodyStore, now } from "./store.js";
|
|
14
|
-
import {
|
|
17
|
+
import { withinDeadline } from "./core/unanswered.js";
|
|
18
|
+
import { resolvePrices, sessionCharge, withEstimate } from "./core/usage.js";
|
|
15
19
|
export { createWebExtension } from "./web.js";
|
|
16
20
|
export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
|
|
17
21
|
const PLANE = "default";
|
|
18
22
|
const UNCONFIGURED = { label: "", run: "", policy: DEFAULT_BROWSER_POLICY };
|
|
23
|
+
const HANDOFF_ENDED = new BrowserFailureError(browserFailure("session_ended", "The browser session left the person's hands before their answer could be waited on. Your next browser call opens a fresh session; take a snapshot there before acting.", { retryable: true }));
|
|
19
24
|
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
25
|
const emptySessions = () => ({ current: {}, sessions: [], notice: null });
|
|
21
26
|
async function drainReleases(name, harness, context, signal) {
|
|
@@ -39,8 +44,15 @@ async function drainReleases(name, harness, context, signal) {
|
|
|
39
44
|
}
|
|
40
45
|
}
|
|
41
46
|
const open = (record) => record?.state === "live" || record?.state === "creating";
|
|
42
|
-
|
|
43
|
-
const
|
|
47
|
+
const releasable = (record, reason) => open(record) || (record?.state === "held" && reason !== "idle");
|
|
48
|
+
const waiting = (record) => new BrowserFailureError(waitingForHuman(record.handoff));
|
|
49
|
+
// A child gets the browser and web tools only: never use_website, so it cannot start children of its own, and never
|
|
50
|
+
// browser_upload or browser_downloads, since its report is all that crosses back (invariant 10) and a site run has no files.
|
|
51
|
+
const CHILD_TOOLS = new Set([...BROWSER_TOOL_NAMES, ...WEB_TOOL_NAMES].filter((name) => name !== "browser_upload" && name !== "browser_downloads"));
|
|
52
|
+
/** How long a release the store could not record may take at the provider. */
|
|
53
|
+
const DIRECT_RELEASE_MS = 30_000;
|
|
54
|
+
/** How long close waits to learn whether a Session that began closing failed. */
|
|
55
|
+
const FAILED_END_MS = 5_000;
|
|
44
56
|
class Attachments {
|
|
45
57
|
drivers = new Map();
|
|
46
58
|
observers = new Map();
|
|
@@ -122,8 +134,10 @@ async function emit(c, cid, label, record, change, provider) {
|
|
|
122
134
|
async function stateOf(c, scope) {
|
|
123
135
|
return (await scope.read.snapshot(c.Sessions, scope.cid, scope.context)) ?? emptySessions();
|
|
124
136
|
}
|
|
125
|
-
const failure = (error, scope) => error instanceof BrowserFailureError ? error : new BrowserFailureError(classifyBrowserError(error, false, { aborted: scope.signal.aborted }));
|
|
126
|
-
|
|
137
|
+
const failure = (error, scope, redact) => error instanceof BrowserFailureError ? error : new BrowserFailureError(classifyBrowserError(error, false, { aborted: scope.signal.aborted, redact }));
|
|
138
|
+
/** `bound`, when given, limits the attach beside the call's own signal (a reconnect's budget); the check for a session the
|
|
139
|
+
* provider ended keeps the call's own. */
|
|
140
|
+
async function attachLive(c, scope, record, bound) {
|
|
127
141
|
const held = c.held.driver(record.tag);
|
|
128
142
|
// An observer whose socket closed holds nothing: driver and observer are attached again together.
|
|
129
143
|
if (held && !c.held.observer(record.tag)?.closed)
|
|
@@ -133,17 +147,18 @@ async function attachLive(c, scope, record) {
|
|
|
133
147
|
const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
|
|
134
148
|
const ref = { id: record.resourceId, tag: record.tag };
|
|
135
149
|
try {
|
|
136
|
-
return await connect(c, scope, provider, ref);
|
|
150
|
+
return await connect(c, bound ? { ...scope, signal: AbortSignal.any([scope.signal, bound]) } : scope, provider, ref);
|
|
137
151
|
}
|
|
138
152
|
catch (error) {
|
|
139
153
|
if (!(await markEnded(c, scope, record, provider)))
|
|
140
|
-
throw failure(error, scope);
|
|
154
|
+
throw failure(error, scope, c.redact);
|
|
141
155
|
return null;
|
|
142
156
|
}
|
|
143
157
|
}
|
|
144
158
|
async function connect(c, scope, provider, ref) {
|
|
145
159
|
const config = await configOf(c, scope.read, scope.cid, scope.context);
|
|
146
160
|
const { actions: policy, batchTimeoutMs } = config.policy;
|
|
161
|
+
c.owned.set(ref.tag, { cid: scope.cid, provider, ref });
|
|
147
162
|
const target = await provider.attach(ref, scope.signal);
|
|
148
163
|
const driver = await c.options.driver(target, scope.signal, { batchTimeoutMs });
|
|
149
164
|
let unattached = null;
|
|
@@ -170,13 +185,17 @@ async function markEnded(c, scope, record, provider) {
|
|
|
170
185
|
await c.store.emitReleased(scope.cid, record.tag, scope.read, scope.context);
|
|
171
186
|
return true;
|
|
172
187
|
}
|
|
188
|
+
async function refuseHeld(c, scope, record) {
|
|
189
|
+
if (record?.state === "held" && !(await markEnded(c, scope, record, await providerOf(c, scope.read, scope.cid, scope.plane, scope.context))))
|
|
190
|
+
throw waiting(record);
|
|
191
|
+
}
|
|
173
192
|
async function settleCreating(c, scope, record) {
|
|
174
193
|
const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
|
|
175
194
|
try {
|
|
176
195
|
await c.store.bindByTag(provider, rowOf(scope.cid, record), scope.commit, scope.signal);
|
|
177
196
|
}
|
|
178
197
|
catch (error) {
|
|
179
|
-
throw failure(error, scope);
|
|
198
|
+
throw failure(error, scope, c.redact);
|
|
180
199
|
}
|
|
181
200
|
}
|
|
182
201
|
async function create(c, scope, overrides, presetTag) {
|
|
@@ -196,7 +215,19 @@ async function create(c, scope, overrides, presetTag) {
|
|
|
196
215
|
await c.store.begin(tx, row);
|
|
197
216
|
});
|
|
198
217
|
// An answer lost on the way back is not a session that never started: it is settled by its tag.
|
|
199
|
-
const ref = await provider.create(spec, scope.signal).then(async (made) => {
|
|
218
|
+
const ref = await provider.create(spec, scope.signal).then(async (made) => {
|
|
219
|
+
// Owned before it is recorded: a store that cannot record it still lets close release it.
|
|
220
|
+
c.owned.set(tag, { cid: scope.cid, provider, ref: made });
|
|
221
|
+
await scope.commit((tx) => c.store.move(tx, row, { state: "live", resourceId: made.id, at: now() }));
|
|
222
|
+
return made;
|
|
223
|
+
}, async (error) => {
|
|
224
|
+
const found = await provider.findByTag(tag, scope.signal).catch(() => []);
|
|
225
|
+
// The session found by its tag is the one kept (bindByTag releases the others first), and it is owned before it is
|
|
226
|
+
// recorded, as a create's own answer is: a store that cannot record it still lets close release it.
|
|
227
|
+
if (found[0])
|
|
228
|
+
c.owned.set(tag, { cid: scope.cid, provider, ref: found[0] });
|
|
229
|
+
return (await c.store.bindByTag(provider, row, scope.commit, scope.signal, found)) ?? Promise.reject(failure(error, scope, c.redact));
|
|
230
|
+
});
|
|
200
231
|
const live = { ...record, state: "live", resourceId: ref.id };
|
|
201
232
|
try {
|
|
202
233
|
const driver = await connect(c, scope, provider, ref);
|
|
@@ -204,15 +235,19 @@ async function create(c, scope, overrides, presetTag) {
|
|
|
204
235
|
return { record: live, driver };
|
|
205
236
|
}
|
|
206
237
|
catch (error) {
|
|
207
|
-
throw failure(error, scope);
|
|
238
|
+
throw failure(error, scope, c.redact);
|
|
208
239
|
}
|
|
209
240
|
}
|
|
210
|
-
async function acquire(c, scope) {
|
|
241
|
+
async function acquire(c, scope, bound) {
|
|
211
242
|
let note = null;
|
|
212
243
|
for (let turn = 0; turn < 4; turn += 1) {
|
|
213
244
|
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
214
|
-
if (record?.state === "
|
|
215
|
-
|
|
245
|
+
if (record?.state === "held") {
|
|
246
|
+
await refuseHeld(c, scope, record);
|
|
247
|
+
note = notices.ended(record.lastUrl);
|
|
248
|
+
}
|
|
249
|
+
else if (record?.state === "live") {
|
|
250
|
+
const driver = await attachLive(c, scope, record, bound);
|
|
216
251
|
if (driver)
|
|
217
252
|
return { record, driver, note };
|
|
218
253
|
note = notices.ended(record.lastUrl);
|
|
@@ -233,9 +268,24 @@ async function attached(c, scope, record, driver, note) {
|
|
|
233
268
|
if (state.notice !== null)
|
|
234
269
|
await scope.commit(async (tx) => { (await tx.doc(c.Sessions, scope.cid)).notice = null; });
|
|
235
270
|
const fresh = state.sessions.find((r) => r.tag === record.tag) ?? record;
|
|
236
|
-
const
|
|
237
|
-
const
|
|
238
|
-
|
|
271
|
+
const cuts = await cutsOf(c, scope, journalOf(state, scope.plane));
|
|
272
|
+
const interrupted = cutOf(cuts);
|
|
273
|
+
const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
|
|
274
|
+
const fence = fresh.fence ?? 0;
|
|
275
|
+
return { driver: fenced(driver, fence, () => c.fences.get(record.tag)), tag: record.tag, sessionId: fresh.resourceId, record: fresh, notice: notice || null, interrupted, cuts, recorded: Boolean(provider.recordings), effects: c.held.observer(record.tag) ?? null, fence, downloads: provider.downloads ?? null, replaced: replacedOf(state, scope.plane, fresh) };
|
|
276
|
+
}
|
|
277
|
+
/** The session the current one replaced after a release the model did not ask for, while the current one has loaded no
|
|
278
|
+
* page: the plane's last record before it that went live (a launch that failed in between never replaces it), released
|
|
279
|
+
* (or being released) for idle or close. */
|
|
280
|
+
function replacedOf(state, plane, current) {
|
|
281
|
+
if (!loadedNoPage(current))
|
|
282
|
+
return null;
|
|
283
|
+
const on = state.sessions.filter((r) => r.plane === plane);
|
|
284
|
+
const before = on.slice(0, on.findIndex((r) => r.tag === current.tag)).reverse().find((r) => r.releaseReason !== "create_failed");
|
|
285
|
+
if (!before || (before.state !== "releasing" && before.state !== "released"))
|
|
286
|
+
return null;
|
|
287
|
+
const reason = before.releaseReason;
|
|
288
|
+
return reason === "idle" || reason === "close" || reason === "lost" ? { reason, at: before.endedAt, lastUrl: before.lastUrl } : null;
|
|
239
289
|
}
|
|
240
290
|
async function releaseRecord(c, scope, record, reason) {
|
|
241
291
|
await scope.commit((tx) => c.store.requestRelease(tx, rowOf(scope.cid, record), reason, now()));
|
|
@@ -243,14 +293,62 @@ async function releaseRecord(c, scope, record, reason) {
|
|
|
243
293
|
}
|
|
244
294
|
const editState = (c, scope, edit) => scope.commit(async (tx) => edit(await tx.doc(c.Sessions, scope.cid)));
|
|
245
295
|
const journalOf = (state, plane) => [...state.sessions].reverse().find((r) => r.plane === plane && r.pendingEffect !== null)?.pendingEffect ?? null;
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
296
|
+
/** The entry with this call's id in a journal chain: the entry itself or one it carries as `prior`. */
|
|
297
|
+
const inChain = (entry, callId) => {
|
|
298
|
+
for (let e = entry; e; e = e.prior)
|
|
299
|
+
if (e.callId === callId)
|
|
300
|
+
return e;
|
|
301
|
+
return undefined;
|
|
302
|
+
};
|
|
303
|
+
/** Settles one entry of a journal chain; the entries it carried stay. */
|
|
304
|
+
const clearJournal = (c, scope, callId) => editState(c, scope, (state) => {
|
|
305
|
+
for (const record of state.sessions) {
|
|
306
|
+
if (record.plane !== scope.plane || !record.pendingEffect)
|
|
307
|
+
continue;
|
|
308
|
+
if (record.pendingEffect.callId === callId) {
|
|
309
|
+
record.pendingEffect = record.pendingEffect.prior ?? null;
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
for (let e = record.pendingEffect; e.prior; e = e.prior) {
|
|
313
|
+
if (e.prior.callId !== callId)
|
|
314
|
+
continue;
|
|
315
|
+
if (e.prior.prior)
|
|
316
|
+
e.prior = e.prior.prior;
|
|
317
|
+
else
|
|
318
|
+
delete e.prior;
|
|
319
|
+
break;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
/** The entries of a journal chain whose warning is still owed, as a chain: each an earlier process wrote that is a cut (not
|
|
324
|
+
* finished with a saved answer) and has not been told by a saved answer. An entry of this process is never a cut, and a told
|
|
325
|
+
* one whose telling answer was saved was delivered. */
|
|
326
|
+
async function owed(c, scope, entry) {
|
|
327
|
+
if (!entry)
|
|
328
|
+
return null;
|
|
329
|
+
const rest = await owed(c, scope, entry.prior);
|
|
330
|
+
const { prior: _carried, ...own } = entry;
|
|
331
|
+
const delivered = entry.incarnation === c.incarnation
|
|
332
|
+
|| (entry.told === true && (await toldSaved(scope, entry)))
|
|
333
|
+
|| (entry.finished === true && !entry.told && (await answered(scope, entry)));
|
|
334
|
+
return delivered ? rest : { ...own, ...(rest ? { prior: rest } : {}) };
|
|
335
|
+
}
|
|
336
|
+
/** A journaled action's own answer as pi committed it: true for a success, false for an error, null for none yet. */
|
|
252
337
|
async function answerOf(scope, pending) {
|
|
253
|
-
const
|
|
338
|
+
const message = await savedAnswer(scope, pending.after, pending.callId);
|
|
339
|
+
return message === null ? null : message.isError !== true;
|
|
340
|
+
}
|
|
341
|
+
/** Whether the call that told a cut had its answer saved, carrying the cut's facts. One killed between the told mark and pi's
|
|
342
|
+
* commit told nobody, and the cut is told again. */
|
|
343
|
+
async function toldSaved(scope, pending) {
|
|
344
|
+
if (!pending.toldBy)
|
|
345
|
+
return false;
|
|
346
|
+
const message = await savedAnswer(scope, pending.after, pending.toldBy);
|
|
347
|
+
return message?.details?.pendingEffect?.callId === pending.callId;
|
|
348
|
+
}
|
|
349
|
+
/** A call's saved tool result, found by pi's typed tool-result entry. The scan covers only the cut's conversation from where
|
|
350
|
+
* it was journaled on, never the whole history. */
|
|
351
|
+
async function savedAnswer(scope, after, callId) {
|
|
254
352
|
if (after === undefined)
|
|
255
353
|
return null;
|
|
256
354
|
return scope.commit(async (tx) => {
|
|
@@ -259,8 +357,8 @@ async function answerOf(scope, pending) {
|
|
|
259
357
|
const page = await tx.scanEntries({ conversationId: scope.cid, minEntryId: after, order: "ascending" }, 100, cursor);
|
|
260
358
|
for (const entry of page.items) {
|
|
261
359
|
const message = ToolResultEntry.is(entry) ? entry.model?.[0] : undefined;
|
|
262
|
-
if (message?.role === "toolResult" && message.toolCallId ===
|
|
263
|
-
return message
|
|
360
|
+
if (message?.role === "toolResult" && message.toolCallId === callId)
|
|
361
|
+
return message;
|
|
264
362
|
}
|
|
265
363
|
cursor = page.next;
|
|
266
364
|
} while (cursor !== undefined);
|
|
@@ -269,21 +367,40 @@ async function answerOf(scope, pending) {
|
|
|
269
367
|
}
|
|
270
368
|
/** Whether a journaled action's own answer was committed as a success. */
|
|
271
369
|
const answered = async (scope, pending) => (await answerOf(scope, pending)) === true;
|
|
272
|
-
/**
|
|
273
|
-
*
|
|
274
|
-
|
|
275
|
-
|
|
370
|
+
/** One journal entry as a cut. In this process an entry is in flight or answered, never cut; one an earlier process wrote is
|
|
371
|
+
* a cut unless its action finished and pi committed its answer, which only then is looked up. It counts as told only once
|
|
372
|
+
* the telling call's answer, carrying its facts, was saved. */
|
|
373
|
+
async function oneCut(c, scope, entry) {
|
|
374
|
+
if (entry.incarnation === c.incarnation)
|
|
276
375
|
return null;
|
|
376
|
+
const { prior: _carried, ...own } = entry;
|
|
377
|
+
const pending = own.told && !(await toldSaved(scope, own)) ? { ...own, told: false } : own;
|
|
277
378
|
if (!pending.finished || pending.told || !(await answered(scope, pending)))
|
|
278
379
|
return pending;
|
|
279
380
|
await clearJournal(c, scope, pending.callId);
|
|
280
381
|
return null;
|
|
281
382
|
}
|
|
383
|
+
/** Every cut in a journal chain, oldest first. An entry a later action replaced counts only while its warning is still owed:
|
|
384
|
+
* once a saved answer told it, the later action replaced it, as it would have with no chain. */
|
|
385
|
+
async function cutsOf(c, scope, entry, newest = true) {
|
|
386
|
+
if (!entry)
|
|
387
|
+
return [];
|
|
388
|
+
const older = await cutsOf(c, scope, entry.prior, false);
|
|
389
|
+
const own = await oneCut(c, scope, entry);
|
|
390
|
+
return own && (newest || !own.told) ? [...older, own] : older;
|
|
391
|
+
}
|
|
392
|
+
/** The cut a call answers for: the oldest whose warning is still owed (an entry a later action replaced before the telling
|
|
393
|
+
* of it was saved comes first), else the newest. */
|
|
394
|
+
const cutOf = (cuts) => cuts.find((cut) => !cut.told) ?? cuts.at(-1) ?? null;
|
|
282
395
|
async function relaunchOn(c, scope, api, slot, overrides) {
|
|
283
396
|
const config = await configOf(c, scope.read, scope.cid, scope.context);
|
|
284
397
|
const refusal = relaunchRefusal(config.policy, overrides);
|
|
285
398
|
if (refusal)
|
|
286
399
|
throw new BrowserFailureError(refusal);
|
|
400
|
+
await refuseHeld(c, scope, currentRecord(await stateOf(c, scope), scope.plane));
|
|
401
|
+
// A session the host assigned is the only one: refused before anything is released.
|
|
402
|
+
if ((await providerOf(c, scope.read, scope.cid, scope.plane, scope.context)).caps.fixedSession)
|
|
403
|
+
throw new BrowserFailureError(FIXED_SESSION_RELAUNCH);
|
|
287
404
|
// The relaunch's session is chosen in a memo before its create commits: a rerun runs on it or says
|
|
288
405
|
// session_replaced, never a second launch; a memo with no record yet is an uncommitted create and goes ahead.
|
|
289
406
|
const find = async (tag) => (await stateOf(c, scope)).sessions.find((r) => r.tag === tag);
|
|
@@ -317,24 +434,27 @@ function portFor(c, api, context) {
|
|
|
317
434
|
return value ? api.memo(memo(slot), value, context) : "";
|
|
318
435
|
} };
|
|
319
436
|
const key = `${scope.cid}:${scope.plane}`;
|
|
320
|
-
|
|
321
|
-
session: () => c.serial.run(key, async () => {
|
|
437
|
+
const port = {
|
|
438
|
+
session: (signal) => c.serial.run(key, async () => {
|
|
322
439
|
const ran = await api.memo(memo("ran"), context);
|
|
323
440
|
if (ran !== undefined) {
|
|
324
441
|
const record = (await stateOf(c, scope)).sessions.find((r) => r.tag === ran);
|
|
325
|
-
|
|
442
|
+
await refuseHeld(c, scope, record);
|
|
443
|
+
const driver = record?.state === "live" ? await attachLive(c, scope, record, signal) : null;
|
|
326
444
|
if (!record || !driver)
|
|
327
445
|
throw new BrowserFailureError(SESSION_REPLACED);
|
|
328
446
|
return attached(c, scope, record, driver, null);
|
|
329
447
|
}
|
|
330
|
-
const { record, driver, note } = await acquire(c, scope);
|
|
448
|
+
const { record, driver, note } = await acquire(c, scope, signal);
|
|
331
449
|
await api.memo(memo("ran"), record.tag, context);
|
|
332
450
|
return attached(c, scope, record, driver, note);
|
|
333
451
|
}),
|
|
334
452
|
relaunch: (overrides) => c.serial.run(key, () => relaunchOn(c, scope, api, memo("relaunch"), overrides)),
|
|
453
|
+
// A held session is still the attached one (a person's): the live view's gate checks a release against it.
|
|
454
|
+
current: async () => { const record = currentRecord(await stateOf(c, scope), scope.plane); return record && (open(record) || record.state === "held") ? record.tag : null; },
|
|
335
455
|
release: () => c.serial.run(key, async () => {
|
|
336
456
|
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
337
|
-
if (!record || !
|
|
457
|
+
if (!record || !releasable(record, "tool")) {
|
|
338
458
|
// Only a release under way or done says so: a lost record is custody giving up, and its browser may still run.
|
|
339
459
|
const ended = (record?.state === "releasing" || record?.state === "released") && record.releaseReason ? { ended: { reason: record.releaseReason, at: record.endedAt } } : {};
|
|
340
460
|
return { released: record?.state === "releasing", sessionId: record?.resourceId ?? null, ...ended };
|
|
@@ -349,12 +469,19 @@ function portFor(c, api, context) {
|
|
|
349
469
|
if (previous?.finished && (await answerOf(scope, previous)) !== null)
|
|
350
470
|
cross(c, "browser.between-actions");
|
|
351
471
|
}
|
|
472
|
+
// A cut whose warning is still owed, which this action's entry replaces, rides in it as `prior`, told first.
|
|
473
|
+
const prior = await owed(c, scope, journalOf(await stateOf(c, scope), scope.plane));
|
|
352
474
|
await scope.commit(async (tx) => {
|
|
353
|
-
const
|
|
475
|
+
const state = await tx.doc(c.Sessions, scope.cid);
|
|
476
|
+
const record = currentRecord(state, scope.plane);
|
|
354
477
|
if (!record)
|
|
355
478
|
return;
|
|
479
|
+
// The chain moves onto this record whole: the record that held it (an earlier session's) keeps no copy.
|
|
480
|
+
const holder = [...state.sessions].reverse().find((r) => r.plane === scope.plane && r.pendingEffect !== null);
|
|
481
|
+
if (holder && holder !== record)
|
|
482
|
+
holder.pendingEffect = null;
|
|
356
483
|
const newest = (await tx.scanEntries({ conversationId: scope.cid, order: "descending" }, 1)).items[0]?.id;
|
|
357
|
-
record.pendingEffect = { ...effect, url: effect.url === null ? null : scrubPageUrl(effect.url, c.redact), at: now(), sent: [], incarnation: c.incarnation, ...(newest === undefined ? {} : { after: newest }) };
|
|
484
|
+
record.pendingEffect = { ...effect, url: effect.url === null ? null : scrubPageUrl(effect.url, c.redact), at: now(), sent: [], incarnation: c.incarnation, ...(newest === undefined ? {} : { after: newest }), ...(prior ? { prior } : {}) };
|
|
358
485
|
});
|
|
359
486
|
},
|
|
360
487
|
journal: (row) => editState(c, scope, (state) => {
|
|
@@ -369,14 +496,16 @@ function portFor(c, api, context) {
|
|
|
369
496
|
else
|
|
370
497
|
sent[at] = scrubbed;
|
|
371
498
|
}),
|
|
372
|
-
mark: async (step, callId) => {
|
|
499
|
+
mark: async (step, callId, by) => {
|
|
373
500
|
const found = { pending: false };
|
|
374
501
|
await editState(c, scope, (state) => {
|
|
375
|
-
const pending = state.sessions.
|
|
376
|
-
if (pending)
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
502
|
+
const pending = state.sessions.filter((r) => r.plane === scope.plane).map((r) => inChain(r.pendingEffect, callId)).find(Boolean);
|
|
503
|
+
if (!pending)
|
|
504
|
+
return;
|
|
505
|
+
pending[step] = true;
|
|
506
|
+
found.pending = true;
|
|
507
|
+
if (step === "told" && by)
|
|
508
|
+
pending.toldBy = by;
|
|
380
509
|
});
|
|
381
510
|
// The host's double-run crossing: the action's driver call is over and its entry says so; pi has not committed
|
|
382
511
|
// the answer.
|
|
@@ -401,18 +530,111 @@ function portFor(c, api, context) {
|
|
|
401
530
|
if (record)
|
|
402
531
|
await emit(c, scope.cid, (await configOf(c, scope.read, scope.cid, scope.context)).label, record, "updated", await providerOf(c, scope.read, scope.cid, scope.plane, scope.context));
|
|
403
532
|
},
|
|
533
|
+
unreachable: () => c.serial.run(key, async () => {
|
|
534
|
+
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
535
|
+
// A session held for a person is theirs: custody never releases it on its own.
|
|
536
|
+
if (record?.state === "held")
|
|
537
|
+
return { released: false, lastUrl: record.lastUrl, kept: "held" };
|
|
538
|
+
if (!record || !open(record))
|
|
539
|
+
return { released: false, lastUrl: record?.lastUrl ?? null };
|
|
540
|
+
// A session a person drives or watches through the live view is theirs: custody never releases it on its own.
|
|
541
|
+
const person = personOn(c.options.gates ?? drivingGates, record.tag);
|
|
542
|
+
const kept = person && keptFor(person);
|
|
543
|
+
if (kept)
|
|
544
|
+
return { released: false, lastUrl: record.lastUrl, kept };
|
|
545
|
+
await scope.commit(async (tx) => {
|
|
546
|
+
await c.store.requestRelease(tx, rowOf(scope.cid, record), "lost", now());
|
|
547
|
+
c.store.addNotice(await tx.doc(c.Sessions, scope.cid), notices.unreachable(record.lastUrl));
|
|
548
|
+
});
|
|
549
|
+
await c.held.detach(record.tag);
|
|
550
|
+
c.idle.cancel(scope.cid);
|
|
551
|
+
return { released: true, lastUrl: record.lastUrl };
|
|
552
|
+
}),
|
|
404
553
|
dropped: () => c.serial.run(key, async () => {
|
|
405
554
|
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
406
555
|
if (record)
|
|
407
556
|
await c.held.detachDriver(record.tag);
|
|
408
557
|
}),
|
|
558
|
+
hold: (requestId) => c.serial.run(key, async () => {
|
|
559
|
+
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
560
|
+
if (record?.state === "held" && record.handoff !== requestId)
|
|
561
|
+
throw waiting(record);
|
|
562
|
+
if (record?.state !== "live" && record?.state !== "held")
|
|
563
|
+
throw new BrowserFailureError(NOTHING_TO_HOLD);
|
|
564
|
+
if (record.state === "live") {
|
|
565
|
+
await scope.commit((tx) => c.store.move(tx, rowOf(scope.cid, record), { state: "held", handoff: requestId, at: now() }));
|
|
566
|
+
c.fences.set(record.tag, { fence: (record.fence ?? 0) + 1, failure: waitingForHuman(requestId) });
|
|
567
|
+
await c.held.detach(record.tag);
|
|
568
|
+
}
|
|
569
|
+
return { tag: record.tag, sessionId: record.resourceId };
|
|
570
|
+
}),
|
|
571
|
+
resume: (notice) => c.serial.run(key, async () => {
|
|
572
|
+
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
573
|
+
if (record?.state !== "held")
|
|
574
|
+
return;
|
|
575
|
+
await scope.commit(async (tx) => {
|
|
576
|
+
await c.store.move(tx, rowOf(scope.cid, record), { state: "live", at: now() });
|
|
577
|
+
if (notice)
|
|
578
|
+
c.store.addNotice(await tx.doc(c.Sessions, scope.cid), notice);
|
|
579
|
+
});
|
|
580
|
+
c.fences.set(record.tag, { fence: (record.fence ?? 0) + 1, failure: HANDED_BACK });
|
|
581
|
+
}),
|
|
409
582
|
ended: async () => {
|
|
410
583
|
const record = currentRecord(await stateOf(c, scope), scope.plane);
|
|
411
|
-
if (record?.state !== "live")
|
|
584
|
+
if (record?.state !== "live" && record?.state !== "held")
|
|
412
585
|
return false;
|
|
413
586
|
return markEnded(c, scope, record, await providerOf(c, scope.read, scope.cid, scope.plane, scope.context));
|
|
414
587
|
},
|
|
588
|
+
handoff: async (ask) => {
|
|
589
|
+
const person = c.options.handoff;
|
|
590
|
+
if (!person)
|
|
591
|
+
throw new BrowserFailureError(NO_HANDOFF);
|
|
592
|
+
const find = () => scope.commit((tx) => c.store.findHandoff(tx, scope.cid, ask.requestId));
|
|
593
|
+
let task = await find();
|
|
594
|
+
if (task === undefined) {
|
|
595
|
+
const slot = memo(`handoff:${ask.requestId}`);
|
|
596
|
+
let interactionId = await api.memo(slot, context);
|
|
597
|
+
if (interactionId === undefined) {
|
|
598
|
+
const { tag, sessionId } = await port.hold(ask.requestId);
|
|
599
|
+
const asked = await (async () => {
|
|
600
|
+
const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
|
|
601
|
+
const liveView = provider.liveView ? await provider.liveView({ id: sessionId, tag }).catch(() => null) : null;
|
|
602
|
+
return person.request({ requestId: ask.requestId, sessionTag: tag, sessionId, liveView, instruction: ask.instruction, completionCondition: ask.completionCondition }, scope.signal);
|
|
603
|
+
})().catch(async (error) => { await port.resume(null); throw failure(error, scope, c.redact); });
|
|
604
|
+
if ("refused" in asked) {
|
|
605
|
+
await port.resume(null);
|
|
606
|
+
return asked;
|
|
607
|
+
}
|
|
608
|
+
interactionId = await api.memo(slot, asked.interactionId, context);
|
|
609
|
+
}
|
|
610
|
+
const input = { requestId: ask.requestId, interactionId, completionCondition: ask.completionCondition };
|
|
611
|
+
task = await c.serial.run(key, () => scope.commit(async (tx) => {
|
|
612
|
+
const record = currentRecord(await tx.doc(c.Sessions, scope.cid), scope.plane);
|
|
613
|
+
if (record?.state !== "held" || record.handoff !== ask.requestId)
|
|
614
|
+
return undefined;
|
|
615
|
+
return (await c.store.findHandoff(tx, scope.cid, ask.requestId)) ?? c.store.waitForHandoff(tx, { ...input, row: rowOf(scope.cid, record) });
|
|
616
|
+
}));
|
|
617
|
+
if (task === undefined)
|
|
618
|
+
throw HANDOFF_ENDED;
|
|
619
|
+
}
|
|
620
|
+
for (;;) {
|
|
621
|
+
const { state } = await api.waitForTask(task, context);
|
|
622
|
+
if (state.outcome.status === "completed" && state.outcome.result) {
|
|
623
|
+
const { outcome } = state.outcome.result;
|
|
624
|
+
const told = notices.handedBack(outcome, ask.completionCondition);
|
|
625
|
+
if ((await stateOf(c, scope)).notice?.includes(told)) {
|
|
626
|
+
await editState(c, scope, (sessions) => { sessions.notice = sessions.notice?.replace(told, "").replace(/\s+/g, " ").trim() || null; });
|
|
627
|
+
}
|
|
628
|
+
return { outcome };
|
|
629
|
+
}
|
|
630
|
+
const next = await find();
|
|
631
|
+
if (next === undefined || next === task)
|
|
632
|
+
throw HANDOFF_ENDED;
|
|
633
|
+
task = next;
|
|
634
|
+
}
|
|
635
|
+
},
|
|
415
636
|
};
|
|
637
|
+
return port;
|
|
416
638
|
}
|
|
417
639
|
/** A plane nobody calls for its idle window is released, never mid-call. A dead process's timers die with it, and the
|
|
418
640
|
* provider's own idle bound takes over. */
|
|
@@ -424,31 +646,90 @@ async function releaseIdle(c, cid, fired, idleMs) {
|
|
|
424
646
|
// lookup above waited, replaced it.
|
|
425
647
|
await releasePlane(c, conversation, "idle", c.opened.context, () => c.idle.isCurrent(cid, fired), Math.round(idleMs / 1000));
|
|
426
648
|
}
|
|
649
|
+
/** Released at the provider without the store, each bounded; a failure is a process warning (`PI_BROWSER_RELEASE`), never
|
|
650
|
+
* thrown. One that fails stays owned, for close to try once more. */
|
|
651
|
+
async function releaseDirectly(c, tags) {
|
|
652
|
+
await Promise.all(tags.map(async (tag) => {
|
|
653
|
+
const lease = c.owned.get(tag);
|
|
654
|
+
if (!lease)
|
|
655
|
+
return;
|
|
656
|
+
try {
|
|
657
|
+
await withinDeadline(lease.provider.release(lease.ref, AbortSignal.timeout(DIRECT_RELEASE_MS)), DIRECT_RELEASE_MS, "provider.release");
|
|
658
|
+
if (c.owned.get(tag) === lease)
|
|
659
|
+
c.owned.delete(tag);
|
|
660
|
+
}
|
|
661
|
+
catch (error) {
|
|
662
|
+
process.emitWarning(`pi-browser: ${tag}: the store could not record its release, and the provider's release failed: ${c.redact(error instanceof Error ? error.message : String(error))}`, { code: "PI_BROWSER_RELEASE" });
|
|
663
|
+
}
|
|
664
|
+
}));
|
|
665
|
+
}
|
|
666
|
+
const leasesOf = (c, cid) => [...c.owned].filter(([, lease]) => lease.cid === cid).map(([tag]) => tag);
|
|
667
|
+
/** `promise`'s value, or `fallback` once `ms` pass; the timer is cleared either way. */
|
|
668
|
+
async function settleWithin(promise, ms, fallback) {
|
|
669
|
+
let timer;
|
|
670
|
+
try {
|
|
671
|
+
return await Promise.race([promise, new Promise((resolve) => { timer = setTimeout(resolve, ms, fallback); })]);
|
|
672
|
+
}
|
|
673
|
+
finally {
|
|
674
|
+
clearTimeout(timer);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
427
677
|
/** A release the model did not ask for (idle, close) commits its notice with it, so whichever call next attaches a
|
|
428
|
-
* session tells it, even when the call that opened the replacement failed or died.
|
|
678
|
+
* session tells it, even when the call that opened the replacement failed or died. A release the store cannot record
|
|
679
|
+
* still closes the driver and releases the session at the provider, and leaves the record as it is: a
|
|
680
|
+
* reopened run's reconcile finds the session gone (the lost path). */
|
|
429
681
|
async function releasePlane(c, conversation, reason, context, still = () => true, idleS = 0) {
|
|
430
682
|
const key = `${conversation.id}:${PLANE}`;
|
|
683
|
+
const kept = { gate: null, tag: "" };
|
|
431
684
|
const released = await c.serial.run(key, async () => {
|
|
685
|
+
const mine = () => c.held.tags().filter((tag) => c.owned.get(tag)?.cid === conversation.id);
|
|
686
|
+
// Closing a driver needs nothing from the store, so a release other than idle's starts closing the conversation's
|
|
687
|
+
// drivers first and never waits for the commit to do it; the commit runs alongside, so the release task starts as
|
|
688
|
+
// early as before. An idle release leaves it to the commit, which can find a call since or a person on the live view.
|
|
689
|
+
const closing = reason === "idle" ? Promise.resolve() : Promise.all(mine().map((tag) => c.held.detach(tag)));
|
|
432
690
|
const tags = await conversation.commit(async (tx) => {
|
|
433
691
|
const state = await tx.doc(c.Sessions, conversation.id);
|
|
434
692
|
const record = still() ? currentRecord(state, PLANE) : null;
|
|
435
|
-
if (!record || !
|
|
693
|
+
if (!record || !releasable(record, reason))
|
|
694
|
+
return [];
|
|
695
|
+
// A person driving or watching the session through the live view keeps it from an idle release (#1098); it is
|
|
696
|
+
// released one idle window after they leave.
|
|
697
|
+
kept.gate = reason === "idle" ? personOn(c.options.gates ?? drivingGates, record.tag) : null;
|
|
698
|
+
kept.tag = record.tag;
|
|
699
|
+
if (kept.gate)
|
|
436
700
|
return [];
|
|
437
701
|
await c.store.requestRelease(tx, rowOf(conversation.id, record), reason, now());
|
|
438
702
|
if (reason === "idle" || reason === "close")
|
|
439
703
|
c.store.addNotice(state, notices.released(reason, record.lastUrl, idleS));
|
|
440
704
|
return [record.tag];
|
|
441
|
-
}, context)
|
|
705
|
+
}, context).catch(async (error) => {
|
|
706
|
+
c.failed = true;
|
|
707
|
+
await closing;
|
|
708
|
+
for (const tag of mine())
|
|
709
|
+
await c.held.detach(tag);
|
|
710
|
+
await releaseDirectly(c, leasesOf(c, conversation.id));
|
|
711
|
+
throw error;
|
|
712
|
+
});
|
|
713
|
+
await closing;
|
|
442
714
|
for (const tag of tags)
|
|
443
715
|
await c.held.detach(tag);
|
|
444
716
|
return tags.length > 0;
|
|
717
|
+
}).finally(() => {
|
|
718
|
+
// A conversation that closes leaves nothing in memory, also when its release could not be recorded.
|
|
719
|
+
if (reason === "close") {
|
|
720
|
+
c.idle.forget(conversation.id);
|
|
721
|
+
c.guards.delete(conversation.id);
|
|
722
|
+
}
|
|
445
723
|
});
|
|
446
|
-
if (reason === "close")
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
}
|
|
450
|
-
else if (released)
|
|
724
|
+
if (reason === "close")
|
|
725
|
+
return;
|
|
726
|
+
if (released)
|
|
451
727
|
c.idle.cancel(conversation.id);
|
|
728
|
+
else if (kept.gate) {
|
|
729
|
+
const tag = kept.tag;
|
|
730
|
+
c.leaving.get(tag)?.();
|
|
731
|
+
c.leaving.set(tag, rearmWhenLeft(kept.gate, () => c.idle.keys().includes(conversation.id), () => { c.leaving.delete(tag); c.idle.activity(conversation.id, 0); }, idleS * 1000));
|
|
732
|
+
}
|
|
452
733
|
}
|
|
453
734
|
async function chargeCall(c, api, context) {
|
|
454
735
|
if (currentRecord(await api.snapshot(c.Sessions, api.conversationId, context), PLANE)?.state !== "live")
|
|
@@ -470,7 +751,7 @@ const withSessionTime = (own, charged) => {
|
|
|
470
751
|
};
|
|
471
752
|
function toolsFor(c, impls) {
|
|
472
753
|
return BROWSER_TOOLS
|
|
473
|
-
.filter((contract) => impls[contract.name] && (contract.listedWhen !== "downloads" || c.options.workspace))
|
|
754
|
+
.filter((contract) => impls[contract.name] && (contract.listedWhen !== "downloads" || c.options.workspace) && (contract.listedWhen !== "upload" || c.options.files || c.options.workspace) && (contract.listedWhen !== "handoff" || c.options.handoff))
|
|
474
755
|
.map((contract) => defineTool({
|
|
475
756
|
name: contract.name,
|
|
476
757
|
description: contract.description,
|
|
@@ -481,11 +762,13 @@ function toolsFor(c, impls) {
|
|
|
481
762
|
const config = await api.snapshot(c.Config, api.conversationId, context);
|
|
482
763
|
c.idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
|
|
483
764
|
try {
|
|
484
|
-
const
|
|
765
|
+
const workspace = c.options.workspace?.(api.conversationId);
|
|
766
|
+
const files = c.options.files ?? (workspace === undefined ? undefined : workspaceFiles(workspace));
|
|
767
|
+
const call = { callId: api.callId, conversationId: api.conversationId, signal: context.abortSignal, label: config?.label ?? "", redact: c.redact, evidence: c.options.evidence, classifyPage: c.options.decisions?.classifyPage, workspace, files };
|
|
485
768
|
// Inside an async function, so a host tool that throws before it returns a promise is caught too.
|
|
486
769
|
const out = await (async () => impls[contract.name](args, portFor(c, api, context), call))().catch((error) => {
|
|
487
770
|
// A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
|
|
488
|
-
const typed = error instanceof BrowserFailureError ? error.failure : classifyBrowserError(error, contract.effect === "effect", { aborted: context.abortSignal?.aborted === true });
|
|
771
|
+
const typed = error instanceof BrowserFailureError ? error.failure : classifyBrowserError(error, contract.effect === "effect", { aborted: context.abortSignal?.aborted === true, redact: c.redact });
|
|
489
772
|
return { content: [{ type: "text", text: JSON.stringify(typed) }], isError: true };
|
|
490
773
|
});
|
|
491
774
|
// A charge that cannot be committed now is carried by the next one.
|
|
@@ -510,7 +793,8 @@ function sectionFor(c, names) {
|
|
|
510
793
|
if (!input.agent.tools.some((tool) => names.has(tool.name)))
|
|
511
794
|
return undefined;
|
|
512
795
|
const config = await input.read.snapshot(c.Config, input.conversationId, context);
|
|
513
|
-
|
|
796
|
+
const offered = (tool) => input.agent.tools.some((t) => t.name === tool && names.has(tool));
|
|
797
|
+
return [browserSection({ idleReleaseS: config?.policy.idleReleaseS ?? UNCONFIGURED.policy.idleReleaseS }, { downloads: offered("browser_downloads"), upload: offered("browser_upload") }), c.options.section?.addendum].filter(Boolean).join("\n\n");
|
|
514
798
|
},
|
|
515
799
|
};
|
|
516
800
|
}
|
|
@@ -535,27 +819,34 @@ function childConversation(c, api, context) {
|
|
|
535
819
|
const child = await api.conversation(id, context);
|
|
536
820
|
if (!child)
|
|
537
821
|
throw new Error("the child conversation is gone");
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
822
|
+
// Children on a provider whose sessions share one browser would drive the same pages, so there they take turns. One
|
|
823
|
+
// whose provider cannot be looked up waits its turn too: its own browser calls ask the factory again.
|
|
824
|
+
const shared = await providerOf(c, api, id, PLANE, context).then((provider) => provider.caps.sharedBrowser === true, () => true);
|
|
825
|
+
// The turn covers the report and the release too: on a shared browser the next child attaches only once this one has let go.
|
|
826
|
+
const run = async () => {
|
|
827
|
+
try {
|
|
828
|
+
const settled = await (await child.submit({ type: "input", content: task.prompt, requestId: task.requestId }, context)).wait(context);
|
|
829
|
+
const report = await api.commit(async (tx) => {
|
|
830
|
+
for (const entry of (await tx.scanEntries({ conversationId: id, order: "descending" }, 50)).items) {
|
|
831
|
+
for (const message of [...(entry.model ?? [])].reverse()) {
|
|
832
|
+
if (message.role !== "assistant")
|
|
833
|
+
continue;
|
|
834
|
+
const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
|
|
835
|
+
if (text)
|
|
836
|
+
return text;
|
|
837
|
+
}
|
|
548
838
|
}
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
}
|
|
839
|
+
return "";
|
|
840
|
+
}, context);
|
|
841
|
+
if (settled.status !== "done" || !report)
|
|
842
|
+
throw new Error("the child finished without a report");
|
|
843
|
+
return report;
|
|
844
|
+
}
|
|
845
|
+
finally {
|
|
846
|
+
await releasePlane(c, { id, commit: (change, ctx) => api.commit(change, ctx) }, "close", context).catch(() => undefined);
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
return await (shared ? c.childTurns(run) : run());
|
|
559
850
|
};
|
|
560
851
|
}
|
|
561
852
|
function siteTool(c, sites) {
|
|
@@ -572,6 +863,21 @@ function siteTool(c, sites) {
|
|
|
572
863
|
},
|
|
573
864
|
});
|
|
574
865
|
}
|
|
866
|
+
/** pi-durable 1.2 on: a Session that a storage error failed ends with reason "failed" (`closed`), and close begins at
|
|
867
|
+
* once (`subscribeClose`). Before 1.2 a Session has no such end, and a failed commit poisons it with no sign. */
|
|
868
|
+
function endingOf(harness) {
|
|
869
|
+
const closed = harness.closed;
|
|
870
|
+
if (typeof closed?.then !== "function")
|
|
871
|
+
return null;
|
|
872
|
+
const ending = { closing: false, failed: closed.then((end) => end.reason === "failed", () => false) };
|
|
873
|
+
try {
|
|
874
|
+
harness.subscribeClose(() => { ending.closing = true; });
|
|
875
|
+
}
|
|
876
|
+
catch {
|
|
877
|
+
ending.closing = true;
|
|
878
|
+
}
|
|
879
|
+
return ending;
|
|
880
|
+
}
|
|
575
881
|
export function createBrowserExtension(options) {
|
|
576
882
|
const name = options.name ?? "browser";
|
|
577
883
|
const redact = createRedactor(() => providerKeyValues(process.env, options.redact?.values));
|
|
@@ -584,38 +890,65 @@ export function createBrowserExtension(options) {
|
|
|
584
890
|
const scrubbed = (error) => Object.assign(new Error(redact(error instanceof Error ? error.message : String(error))), { name: error instanceof Error ? error.name : "Error" });
|
|
585
891
|
const prices = resolvePrices(options.prices);
|
|
586
892
|
const priceState = prices.sessionUsdPerHour === null ? "unpriced" : "priced";
|
|
893
|
+
// A host that names no session price is metered at the package's list price: those dollars are an estimate, and the record counts them as the charges are made, so a
|
|
894
|
+
// run that resumes under another price source keeps each charge's own label. A price the host names (even one equal to the list's) is its own, and a deliberate `null` stays a gap.
|
|
895
|
+
const listPriced = options.prices?.sessionUsdPerHour === undefined && prices.sessionUsdPerHour !== null;
|
|
587
896
|
const meter = (spent, at, final = false) => {
|
|
588
897
|
const charged = sessionCharge(spent, at, prices, priceState, final);
|
|
589
|
-
return { spent: { ...charged.spent, state: charged.usage.state }, usage: charged.usage };
|
|
898
|
+
return { spent: { ...withEstimate(spent, charged.spent, listPriced), state: charged.usage.state }, usage: charged.usage };
|
|
590
899
|
};
|
|
900
|
+
const leaving = new Map();
|
|
901
|
+
const owned = new Map();
|
|
591
902
|
const store = custodyStore({
|
|
592
903
|
name, Config, Sessions, meter, scrubbed, createDeadlineMs: options.createDeadlineMs ?? CREATE_DEADLINE_MS,
|
|
593
904
|
providerOf: (read, cid, plane, context) => providerOf(readers, read, cid, plane, context),
|
|
594
|
-
emit: (cid, label, record, change) =>
|
|
905
|
+
emit: (cid, label, record, change) => {
|
|
906
|
+
// A released session's poll ends with it, whatever released it, and nothing is left to release directly.
|
|
907
|
+
if (change === "released") {
|
|
908
|
+
leaving.get(record.tag)?.();
|
|
909
|
+
leaving.delete(record.tag);
|
|
910
|
+
owned.delete(record.tag);
|
|
911
|
+
}
|
|
912
|
+
return emit(readers, cid, label, record, change);
|
|
913
|
+
},
|
|
914
|
+
handoff: options.handoff,
|
|
915
|
+
handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
|
|
595
916
|
});
|
|
596
917
|
const c = {
|
|
597
|
-
...readers, name, Sessions, Children, store, meter, held: new Attachments(), serial: keyedSerializer(), guards: new Map(), opened: null, incarnation: randomUUID(),
|
|
918
|
+
...readers, name, Sessions, Children, store, meter, held: new Attachments(), fences: new Map(), leaving, serial: keyedSerializer(), childTurns: oneAtATime(), guards: new Map(), owned, failed: false, ending: null, opened: null, incarnation: randomUUID(),
|
|
598
919
|
idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
|
|
599
920
|
};
|
|
600
|
-
|
|
921
|
+
// 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
|
|
922
|
+
// implementations (`options.tools`) are merged in first, so they are guarded too: one that calls `port.session()` could otherwise act while a person drives.
|
|
923
|
+
const own = drivingGuarded({ ...custodyTools, ...pageTools({ guards: c.guards }), ...options.tools }, options.gates);
|
|
601
924
|
// pi checks a call's arguments against the tool's schema before execute, so each implementation receives its own shape.
|
|
602
925
|
const tools = toolsFor(c, own);
|
|
603
926
|
const names = new Set(tools.map((tool) => tool.name));
|
|
604
927
|
const siteTools = options.sites ? [siteTool(c, options.sites)] : [];
|
|
605
928
|
return {
|
|
606
|
-
extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [sectionFor(c, names)], tasks: [store.ReleaseTask] }),
|
|
929
|
+
extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [sectionFor(c, names)], tasks: [store.ReleaseTask, store.HandoffTask] }),
|
|
607
930
|
docs: { Config, Sessions, Inventory: store.Inventory, Children },
|
|
608
931
|
tools: [...tools, ...siteTools],
|
|
609
932
|
release: (conversation, reason, context) => releasePlane(c, conversation, reason, context),
|
|
610
933
|
async reconcile(harness, isActive, context) {
|
|
611
934
|
c.opened = { harness, context };
|
|
935
|
+
c.ending = endingOf(harness);
|
|
612
936
|
return store.reconcileAll(harness, isActive, context);
|
|
613
937
|
},
|
|
614
938
|
drain: (harness, context, signal) => drainReleases(name, harness, context, signal),
|
|
615
939
|
async close() {
|
|
616
940
|
c.idle.clear();
|
|
941
|
+
c.fences.clear();
|
|
942
|
+
for (const stop of c.leaving.values())
|
|
943
|
+
stop();
|
|
944
|
+
c.leaving.clear();
|
|
617
945
|
// A session whose driver was let go and not yet replaced still has its observer attached: close both kinds.
|
|
618
946
|
await Promise.all(c.held.tags().map((tag) => c.held.detach(tag)));
|
|
947
|
+
// A store that failed runs no release task again, so what this process still holds is released at the provider
|
|
948
|
+
//. Over a healthy store it is kept, for the next run to resume or reconcile.
|
|
949
|
+
if (c.failed || (c.ending?.closing && await settleWithin(c.ending.failed, FAILED_END_MS, false)))
|
|
950
|
+
await releaseDirectly(c, [...c.owned.keys()]);
|
|
951
|
+
c.owned.clear();
|
|
619
952
|
},
|
|
620
953
|
retained: () => new Set([...c.guards.keys(), ...c.idle.keys(), ...c.serial.keys().map((key) => Number(key.slice(0, key.indexOf(":"))))]).size,
|
|
621
954
|
};
|