@parcha/pi-browser 0.1.0-beta.30 → 0.1.0-beta.32
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 +52 -0
- package/NOTICE +4 -4
- package/README.md +41 -12
- package/dist/coding-agent.d.ts +1 -0
- package/dist/coding-agent.js +5 -4
- package/dist/core/contract.d.ts +9 -0
- package/dist/core/contract.js +15 -3
- package/dist/core/custody.d.ts +7 -2
- package/dist/core/custody.js +7 -3
- package/dist/core/downloads.d.ts +7 -0
- package/dist/core/downloads.js +13 -1
- package/dist/core/driving-guard.d.ts +20 -0
- package/dist/core/driving-guard.js +175 -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/failures.d.ts +15 -1
- package/dist/core/failures.js +7 -0
- package/dist/core/host.d.ts +11 -2
- package/dist/core/tools.d.ts +14 -0
- package/dist/core/tools.js +42 -8
- package/dist/driver/page-driver.js +77 -4
- package/dist/driver/sealed.d.ts +4 -12
- package/dist/driver/sealed.js +23 -37
- package/dist/driver/stagehand.d.ts +10 -15
- package/dist/driver/stagehand.js +19 -17
- package/dist/durable/result.d.ts +1 -2
- package/dist/durable/result.js +2 -2
- package/dist/durable/store.d.ts +4 -1
- package/dist/durable/store.js +16 -11
- package/dist/durable.d.ts +17 -1
- package/dist/durable.js +41 -14
- package/dist/live-view/index.d.ts +2 -1
- package/dist/live-view/index.js +1 -0
- package/dist/live-view/protocol.d.ts +38 -6
- package/dist/live-view/protocol.js +2 -0
- package/dist/live-view/server.d.ts +24 -1
- package/dist/live-view/server.js +131 -11
- 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 +33 -11
- package/dist/providers/worker-extension.d.ts +6 -0
- package/dist/providers/worker-extension.js +17 -4
- package/package.json +10 -10
- package/dist/driver/extension-worker.d.ts +0 -9
- package/dist/driver/extension-worker.js +0 -185
|
@@ -1,41 +1,188 @@
|
|
|
1
|
-
import { BrowserFailureError } from "./custody.js";
|
|
2
|
-
import { drivingGates, personDrivingFailure, PERSON_DRIVING } from "./driving.js";
|
|
1
|
+
import { BrowserFailureError, FenceRefusal } from "./custody.js";
|
|
2
|
+
import { drivingGates, epochOf, isHeld, isSettling, personDrivingFailure, PERSON_DRIVING } from "./driving.js";
|
|
3
|
+
import { asPartial, browserFailure, classifyBrowserError, PARTIAL } from "./failures.js";
|
|
3
4
|
/** Told to the model's next call once a person has driven the session through the live view: the page can change without its URL changing. */
|
|
4
5
|
export const PERSON_DROVE = "A person used this browser through the live view since your last call, so the page may have changed even where its address did not: take a snapshot before you act on an element by its id.";
|
|
6
|
+
/** Told, before PERSON_DROVE, to a call that waited while the person held the browser. */
|
|
7
|
+
export const PERSON_HAD = "This call waited while the person had the browser: they took it over through the live view and have handed it back.";
|
|
8
|
+
/** Told, instead, to a call that waited through a take the person did not use: no input of theirs reached the page, so the
|
|
9
|
+
* snapshot stands and nothing says the page changed. */
|
|
10
|
+
export const PERSON_HAD_UNUSED = "This call waited while the person had the browser: they took it over through the live view and handed it back without using it, so the page is as you left it.";
|
|
11
|
+
/** The mark (in a call's result details) of an act the person's take made stale: the person drove the session through the
|
|
12
|
+
* live view while the call waited, so the snapshot its element ids came from no longer stands. Its timeline row reads
|
|
13
|
+
* neutral, in plain words (pi-durable-agent's timeline), never as a failure. */
|
|
14
|
+
export const PAGE_CHANGED_WHILE_HELD = "page_changed_while_held";
|
|
15
|
+
/** Told to the model by such an act: nothing was done, and its next step is a snapshot. */
|
|
16
|
+
export const PAGE_CHANGED_FOR_MODEL = "The person changed the page while they had the browser, so this action was not done. Take a snapshot first, then act on the page as it is now.";
|
|
17
|
+
/** The body of a failed result whose failure is a stale snapshot, or undefined: what an act the person's take made stale
|
|
18
|
+
* answers before it is said otherwise. */
|
|
19
|
+
function staleFailureOf(out) {
|
|
20
|
+
const first = out.isError ? out.content[0] : undefined;
|
|
21
|
+
if (first?.type !== "text")
|
|
22
|
+
return undefined;
|
|
23
|
+
try {
|
|
24
|
+
const body = JSON.parse(first.text);
|
|
25
|
+
return body !== null && typeof body === "object" && body.code === "stale_snapshot" ? body : undefined;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** An act that failed on the snapshot the person's take made stale, said as what it is: no error (the call did nothing,
|
|
32
|
+
* and the agent takes a new look), the model told to snapshot first, the notice it was given kept, and the result marked
|
|
33
|
+
* PAGE_CHANGED_WHILE_HELD for its timeline row. Its details as the tool gave them, beside the mark. */
|
|
34
|
+
const pageChanged = (out, failure) => ({
|
|
35
|
+
content: [{ type: "text", text: JSON.stringify({ ...(typeof failure.notice === "string" ? { notice: failure.notice } : {}), done: false, page_changed: true, next: "snapshot", message: PAGE_CHANGED_FOR_MODEL }) }],
|
|
36
|
+
details: { ...out.details, [PAGE_CHANGED_WHILE_HELD]: true },
|
|
37
|
+
...(out.usage ? { usage: out.usage } : {}),
|
|
38
|
+
});
|
|
39
|
+
/** What a model call that was under way when the person took the browser is told at its next act on it: nothing more of it reached the page. */
|
|
40
|
+
export const personTookFailure = (acted, batch) => {
|
|
41
|
+
const failure = browserFailure("refused", `The person took over this browser through the live view while this call ran, so the rest of it was not done${batch ? ` (${batch.completed} of the ${batch.of} actions ran)` : ""}. Your next browser call waits until they hand the browser back; the page may have changed by then, so take a snapshot before you act.`, { retryable: true, effect: batch && batch.completed > 0 ? "partial" : acted ? "possibly_effected" : "none" });
|
|
42
|
+
return batch && batch.completed > 0 ? { ...failure, completed: batch.completed } : failure;
|
|
43
|
+
};
|
|
44
|
+
/** A run of several actions that failed at one after others ran: the failure it would have been, said to be partial, with
|
|
45
|
+
* how many ran (the facade's batch, once sent, never said which). */
|
|
46
|
+
function partway(error, completed, of) {
|
|
47
|
+
// A dropped connection stays the error it is, marked: the call's own handling lets its driver go (port.dropped), so the next
|
|
48
|
+
// call reconnects, and says the run was partial.
|
|
49
|
+
if (!(error instanceof BrowserFailureError) && error !== null && typeof error === "object" && classifyBrowserError(error, true, {}).code === "browser_unavailable") {
|
|
50
|
+
return Object.assign(error, { [PARTIAL]: { completed, of } });
|
|
51
|
+
}
|
|
52
|
+
const failure = error instanceof BrowserFailureError ? error.failure : classifyBrowserError(error, true, {});
|
|
53
|
+
return new BrowserFailureError(asPartial(failure, { completed, of }));
|
|
54
|
+
}
|
|
55
|
+
/** The driver as a model call holds it: each of its acts is refused once the gate's epoch has moved past the one the call entered at (the
|
|
56
|
+
* person took the browser, or a hold ended, since). A refusal is a FenceRefusal, so an action none of whose acts got through is known not sent. */
|
|
57
|
+
function epochFenced(driver, gate, epoch) {
|
|
58
|
+
let acted = false;
|
|
59
|
+
const moved = () => epochOf(gate) !== epoch;
|
|
60
|
+
return new Proxy(driver, {
|
|
61
|
+
get(target, key) {
|
|
62
|
+
const value = Reflect.get(target, key);
|
|
63
|
+
if (typeof value !== "function")
|
|
64
|
+
return value;
|
|
65
|
+
// A run of several actions is one batch inside the browser, out of reach once it is sent: it is sent one action at
|
|
66
|
+
// a time, each checked here first, so none after the person took over reaches the page. Their answers are summed
|
|
67
|
+
// as the batch's would be: how many completed, and the page's address after the last.
|
|
68
|
+
const actions = key === "run" ? (arguments_) => arguments_[0]?.actions : () => undefined;
|
|
69
|
+
return (...args) => {
|
|
70
|
+
if (moved())
|
|
71
|
+
return Promise.reject(new FenceRefusal(personTookFailure(acted)));
|
|
72
|
+
const list = actions(args);
|
|
73
|
+
if (!Array.isArray(list) || list.length < 2) {
|
|
74
|
+
acted = true;
|
|
75
|
+
return value.apply(target, args);
|
|
76
|
+
}
|
|
77
|
+
return (async () => {
|
|
78
|
+
// Every action checked first, as the batch checked them before it sent any: a stale id anywhere sends none.
|
|
79
|
+
const check = target.checkActions;
|
|
80
|
+
if (typeof check === "function")
|
|
81
|
+
await check.call(target, list);
|
|
82
|
+
let completed = 0;
|
|
83
|
+
let url;
|
|
84
|
+
for (const [index, action] of list.entries()) {
|
|
85
|
+
if (moved())
|
|
86
|
+
throw new FenceRefusal(personTookFailure(acted, { completed, of: list.length }));
|
|
87
|
+
acted = true;
|
|
88
|
+
let answer;
|
|
89
|
+
try {
|
|
90
|
+
// The batch was checked as one before any was sent, as the browser's own batch checks it once: an action after
|
|
91
|
+
// the first is not refused because the page's address moved under the batch's own earlier actions (a
|
|
92
|
+
// same-page link). The person's take-over is still fenced before each one, above.
|
|
93
|
+
answer = (await value.call(target, index === 0 ? { actions: [action] } : { actions: [action], checked: true }));
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
if (completed > 0)
|
|
97
|
+
throw partway(error, completed, list.length);
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
completed += typeof answer?.completed === "number" ? answer.completed : 1;
|
|
101
|
+
url = answer?.url;
|
|
102
|
+
}
|
|
103
|
+
return { completed, url };
|
|
104
|
+
})();
|
|
105
|
+
};
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/** The abort of a call that waited for the person and was stopped meanwhile: nothing was done. */
|
|
110
|
+
const STOPPED_WAITING = () => new BrowserFailureError(browserFailure("aborted", "The call was stopped while it waited for the person to hand the browser back; nothing was done."));
|
|
111
|
+
/** How long a call waited for the person to hand the browser back, in its result's details: a host's timeline says the
|
|
112
|
+
* call waited, and for how long, so a call row that spans a take-over does not read as the agent acting meanwhile. */
|
|
113
|
+
export const WAITED_FOR_PERSON = "waited_for_person_ms";
|
|
5
114
|
/** One browser tool as a model call on its session's driving gate: it is refused, typed and before it has done anything, while a person drives that session
|
|
6
115
|
* through the live view, and it holds the gate for as long as it runs, so the viewer's input is held meanwhile. The session is known when the tool first
|
|
7
116
|
* asks its port for it (`session()` or `relaunch()`), which is every tool's first act on the browser. */
|
|
8
117
|
export function drivingGuard(impl, gates = drivingGates, options = {}) {
|
|
118
|
+
const now = options.now ?? Date.now;
|
|
9
119
|
return async (args, port, call) => {
|
|
10
120
|
let held = null;
|
|
11
|
-
/**
|
|
12
|
-
|
|
121
|
+
/** How long this call waited for the person, all told (ms), and whether it was stopped while it waited: then nothing
|
|
122
|
+
* was done, and its result claims no wait that ended in an act. */
|
|
123
|
+
let waitedMs = 0;
|
|
124
|
+
let stopped = false;
|
|
125
|
+
/** Whether the person's own hand drove this call's session through the live view since the model's last call (their
|
|
126
|
+
* input reached it, not only a take): its snapshot's ids were dropped for it (told), so an act on them is one their hand
|
|
127
|
+
* made stale. */
|
|
128
|
+
let personDrove = false;
|
|
129
|
+
/** Takes the tag's gate for the model, first waiting (inside the call, never failing it) while the person holds the browser; `drove` when a person
|
|
130
|
+
* has driven that session since the model's last call, `waited` when this call waited for the person to hand it back. */
|
|
131
|
+
const enter = async (tag) => {
|
|
13
132
|
if (held?.tag === tag)
|
|
14
|
-
return false;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
133
|
+
return { drove: false, waited: false, handled: false };
|
|
134
|
+
let waited = false;
|
|
135
|
+
for (;;) {
|
|
136
|
+
const gate = gates(tag);
|
|
137
|
+
// Held, or handed back with the person's last command still settling: the call waits for both.
|
|
138
|
+
if (isHeld(gate) || isSettling(gate)) {
|
|
139
|
+
waited = true;
|
|
140
|
+
const from = now();
|
|
141
|
+
try {
|
|
142
|
+
await gate.untilFree?.(call?.signal);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
stopped = true;
|
|
146
|
+
throw STOPPED_WAITING();
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
waitedMs += Math.max(0, now() - from);
|
|
150
|
+
}
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const entered = gate.model();
|
|
154
|
+
// A BrowserFailureError is what a tool already turns into a typed failure result, as it does for its own refusals.
|
|
155
|
+
if (entered === PERSON_DRIVING)
|
|
156
|
+
throw new BrowserFailureError(personDrivingFailure());
|
|
157
|
+
held?.release();
|
|
158
|
+
held = { tag, release: entered.release, gate, epoch: epochOf(gate) };
|
|
159
|
+
return { drove: entered.drove === true, waited, handled: entered.handled };
|
|
160
|
+
}
|
|
22
161
|
};
|
|
23
162
|
/** A person drove: the session's snapshot ids are dropped (an old id then fails as a stale snapshot, whatever the URL), the call is told why,
|
|
24
|
-
* and only then is the gate told. A
|
|
25
|
-
|
|
26
|
-
|
|
163
|
+
* and only then is the gate told. A take the person did not use (no input of theirs reached the page) keeps the ids: the page
|
|
164
|
+
* is as the agent left it, so its next act just works, and the call is told only that it waited, if it did. A call that took
|
|
165
|
+
* the gate without its session (release, relaunch) tells nothing and uses nothing up. */
|
|
166
|
+
const told = (attached, entered) => {
|
|
167
|
+
if (!entered.drove && !entered.waited)
|
|
27
168
|
return attached;
|
|
28
|
-
|
|
29
|
-
|
|
169
|
+
if (entered.handled) {
|
|
170
|
+
try {
|
|
171
|
+
void Promise.resolve(attached.driver.forgetSnapshots?.()).catch(() => undefined);
|
|
172
|
+
}
|
|
173
|
+
catch { /* a driver without snapshot ids has none to drop */ }
|
|
30
174
|
}
|
|
31
|
-
catch { /* a driver without snapshot ids has none to drop */ }
|
|
32
175
|
gates(attached.tag).told();
|
|
33
|
-
|
|
176
|
+
const said = entered.handled ? [entered.waited ? PERSON_HAD : null, PERSON_DROVE] : [entered.waited ? PERSON_HAD_UNUSED : null];
|
|
177
|
+
const notice = [attached.notice, ...said].filter(Boolean).join(" ");
|
|
178
|
+
return notice === (attached.notice ?? "") ? attached : { ...attached, notice };
|
|
34
179
|
};
|
|
180
|
+
/** The session's driver as this call holds it: refused once the browser changes hands. */
|
|
181
|
+
const fenced = (attached) => (held?.tag === attached.tag && typeof attached.driver === "object" && attached.driver !== null ? { ...attached, driver: epochFenced(attached.driver, held.gate, held.epoch) } : attached);
|
|
35
182
|
// Every other member runs on the real port (`this` is the port, so a class-based port's own state is written to it, not to a copy).
|
|
36
183
|
const overrides = {
|
|
37
|
-
session: async (signal) => { const attached = await port.session(signal);
|
|
38
|
-
relaunch: async (o) => { const attached = await port.relaunch(o); enter(attached.tag); return attached; },
|
|
184
|
+
session: async (signal) => { const attached = await port.session(signal); const entered = await enter(attached.tag); personDrove ||= entered.handled; return fenced(told(attached, entered)); },
|
|
185
|
+
relaunch: async (o) => { const attached = await port.relaunch(o); await enter(attached.tag); return fenced(attached); },
|
|
39
186
|
};
|
|
40
187
|
const guarded = new Proxy(port, { get(target, key) { if (key in overrides)
|
|
41
188
|
return overrides[key]; const value = Reflect.get(target, key, target); return typeof value === "function" ? value.bind(target) : value; } });
|
|
@@ -44,9 +191,14 @@ export function drivingGuard(impl, gates = drivingGates, options = {}) {
|
|
|
44
191
|
if (options.early) {
|
|
45
192
|
const tag = await port.current?.();
|
|
46
193
|
if (tag)
|
|
47
|
-
enter(tag);
|
|
194
|
+
await enter(tag);
|
|
48
195
|
}
|
|
49
|
-
|
|
196
|
+
const given = await impl(args, guarded, call);
|
|
197
|
+
// An act on the snapshot the person's hand made stale (they drove the session while this call waited, or since the
|
|
198
|
+
// last one) failed only because the page moved under it: it did nothing, and the next step is a new look.
|
|
199
|
+
const stale = personDrove ? staleFailureOf(given) : undefined;
|
|
200
|
+
const out = stale ? pageChanged(given, stale) : given;
|
|
201
|
+
return waitedMs > 0 && !stopped ? { ...out, details: { ...out.details, [WAITED_FOR_PERSON]: Math.round(waitedMs) } } : out;
|
|
50
202
|
}
|
|
51
203
|
finally {
|
|
52
204
|
held?.release();
|
package/dist/core/driving.d.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { type BrowserFailure } from "./failures.js";
|
|
2
|
-
/** Who is acting on the browser. `person`: input arrived from the viewer within the idle window
|
|
3
|
-
* and viewer input is discarded (never queued, so a keystroke is not replayed into a page the model
|
|
2
|
+
/** Who is acting on the browser. `person`: input arrived from the viewer within the idle window, or the person holds the browser (`take`).
|
|
3
|
+
* `agent`: a model browser call is in flight, and viewer input is discarded (never queued, so a keystroke is not replayed into a page the model
|
|
4
|
+
* has since moved). */
|
|
4
5
|
export type DriveState = "idle" | "person" | "agent";
|
|
6
|
+
/** Why a person's hold ended: they handed the browser back (`given`), the agent's ask was answered (`answered`), the host's spend cap had no room
|
|
7
|
+
* for more of their time (`cap`), no input came for the hold's idle window (`idle`), the viewer was gone for its away window (`away`), or the
|
|
8
|
+
* session was released (`released`). */
|
|
9
|
+
export type HoldEnd = "given" | "answered" | "cap" | "idle" | "away" | "released";
|
|
5
10
|
/** The person/model mutex for one browser (core/driving.ts, keyed by the session's lease tag). Person input and a model's browser call never
|
|
6
11
|
* interleave: while a call is in flight the viewer's input is discarded with a notice, and while a person drives a model call is refused. */
|
|
7
12
|
export type DrivingGate = {
|
|
@@ -13,6 +18,7 @@ export type DrivingGate = {
|
|
|
13
18
|
model(): {
|
|
14
19
|
release(): void;
|
|
15
20
|
drove: boolean;
|
|
21
|
+
handled: boolean;
|
|
16
22
|
} | "person_driving";
|
|
17
23
|
/** The model's call has been told a person drove (its snapshot ids dropped, the notice given): `drove` is false until a person drives again. */
|
|
18
24
|
told(): void;
|
|
@@ -23,6 +29,40 @@ export type DrivingGate = {
|
|
|
23
29
|
viewing(): boolean;
|
|
24
30
|
/** The live view's server sets it when a viewer's hello is accepted and clears it when that viewer's socket closes or the session is released. */
|
|
25
31
|
setViewing(on: boolean): void;
|
|
32
|
+
/** The person's hold, below (take, give, held, epoch, setPresent, untilFree): optional, so a registry of the host's own that
|
|
33
|
+
* predates them still works. A gate without them is never held (no call waits) and its epoch never moves; the live view's
|
|
34
|
+
* takeOver needs them.
|
|
35
|
+
*
|
|
36
|
+
* The person takes the browser (the live view's Take over): a sticky hold that lasts until `give`, `idleMs` of the hold with no input, or
|
|
37
|
+
* `awayMs` with no viewer present (`setPresent`), or the session's end. While held the person's input is the only input, every model call
|
|
38
|
+
* waits (`untilFree`), and the epoch moves, so a driver a model call took before the take acts no more. `onEnd` is called once, when the hold
|
|
39
|
+
* ends, with why (and the host's words, when it gave them). False when the browser is already held (nothing changes). */
|
|
40
|
+
take?(onEnd?: (why: HoldEnd, message?: string) => void, onStart?: () => void): boolean;
|
|
41
|
+
/** Ends the hold (`given`: the person handed back; `answered`: the agent's ask was answered; `cap`: the host's spend cap has no room for more of
|
|
42
|
+
* the person's time, `message` its words). False when nothing was held. */
|
|
43
|
+
give?(why?: "given" | "answered" | "cap", message?: string): boolean;
|
|
44
|
+
/** True from a take until the hold ends: no model call starts meanwhile. A take while a model call runs is held at once
|
|
45
|
+
* (the epoch moves, so that call acts no more after its current act) but goes live, the person's input taken and
|
|
46
|
+
* `onStart` called, only once the call returns: the person never drives while the agent's act is still under way. */
|
|
47
|
+
held?(): boolean;
|
|
48
|
+
/** True while the person's hold is live: their input is taken. */
|
|
49
|
+
holding?(): boolean;
|
|
50
|
+
/** Moves at each change of hands (a take, a hold's end): a model call checks it before each act on the browser. */
|
|
51
|
+
epoch?(): number;
|
|
52
|
+
/** The take-over viewer is connected (true) or gone (false): while held with no viewer, the hold ends after the away window. */
|
|
53
|
+
setPresent?(on: boolean): void;
|
|
54
|
+
/** Resolves once nobody holds the browser and the person's last command has settled (at once when neither); rejects with `signal`'s reason when
|
|
55
|
+
* it aborts first. */
|
|
56
|
+
untilFree?(signal?: AbortSignal): Promise<void>;
|
|
57
|
+
/** One command of the person's (an input, a nav, a dialog answer) starts on the browser: `done` when it returns, whatever it did. A hold that ends
|
|
58
|
+
* while one runs (handed back, the ask answered, the cap, idle, away) wakes no model call until it returns, or until `settleMs` passes: past
|
|
59
|
+
* that the command is let go, `live()` false from then on, and a command of several steps (Back reads the history, then moves) checks it before each. */
|
|
60
|
+
command?(): {
|
|
61
|
+
live(): boolean;
|
|
62
|
+
done(): void;
|
|
63
|
+
};
|
|
64
|
+
/** True from a hold's end until the person's last command has settled (or was let go): no model call starts meanwhile. */
|
|
65
|
+
settling?(): boolean;
|
|
26
66
|
/** The session was released: listeners dropped, the gate forgotten, no viewer. */
|
|
27
67
|
end(): void;
|
|
28
68
|
};
|
|
@@ -38,6 +78,12 @@ export type Timers = {
|
|
|
38
78
|
export type DrivingOptions = {
|
|
39
79
|
/** A person keeps driving this long after their last input, then the model may act again. Default 3 s. */
|
|
40
80
|
idleMs?: number;
|
|
81
|
+
/** A person's hold (`take`) ends after this long with no input from them. Default 15 minutes. */
|
|
82
|
+
holdIdleMs?: number;
|
|
83
|
+
/** A person's hold ends after its viewer has been gone this long. Default 2 minutes. */
|
|
84
|
+
holdAwayMs?: number;
|
|
85
|
+
/** After a hold ends, model calls wait at most this long for the person's command still running to return; past it the command is let go. Default 10 s. */
|
|
86
|
+
settleMs?: number;
|
|
41
87
|
/** For tests: the timer functions. */
|
|
42
88
|
timers?: Timers;
|
|
43
89
|
};
|
|
@@ -65,3 +111,11 @@ export declare function keptReason(record: {
|
|
|
65
111
|
* announce nothing), and the moment nobody is on it `rearm` starts the idle window again. Stops once `alive` says the session
|
|
66
112
|
* is gone; the returned function stops it at once (a release, a close). */
|
|
67
113
|
export declare function rearmWhenLeft(gate: DrivingGate, alive: () => boolean, rearm: () => void, idleMs: number): () => void;
|
|
114
|
+
/** Whether `gate`'s person hold is live (their input taken): false for a gate without holds. */
|
|
115
|
+
export declare const isHolding: (gate: DrivingGate) => boolean;
|
|
116
|
+
/** Whether `gate`'s hold has ended with the person's last command still settling: false for a gate without holds. */
|
|
117
|
+
export declare const isSettling: (gate: DrivingGate) => boolean;
|
|
118
|
+
/** Whether `gate` is held for a person now: false for a gate without holds (a registry that predates them). */
|
|
119
|
+
export declare const isHeld: (gate: DrivingGate) => boolean;
|
|
120
|
+
/** `gate`'s epoch: 0, unmoving, for a gate without holds. */
|
|
121
|
+
export declare const epochOf: (gate: DrivingGate) => number;
|
package/dist/core/driving.js
CHANGED
|
@@ -11,26 +11,60 @@ class Gate {
|
|
|
11
11
|
timers;
|
|
12
12
|
idleMs;
|
|
13
13
|
forget;
|
|
14
|
+
holdIdleMs;
|
|
15
|
+
holdAwayMs;
|
|
16
|
+
settleMs;
|
|
14
17
|
model_ = 0;
|
|
15
18
|
person = false;
|
|
16
19
|
idle;
|
|
17
20
|
viewing_ = false;
|
|
18
21
|
/** A person has driven and the model has not been told yet; kept (and the gate with it) until a call has been told. */
|
|
19
22
|
drove_ = false;
|
|
23
|
+
/** The person's own input reached the session since the model was last told (a take alone sets `drove_`, this only their
|
|
24
|
+
* hand): what can have changed the page under the model's snapshot. */
|
|
25
|
+
handled_ = false;
|
|
26
|
+
/** The person's hold, while there is one: its end's listener, its idle timer and, while no viewer is present, its away timer. */
|
|
27
|
+
hold = null;
|
|
28
|
+
epoch_ = 0;
|
|
29
|
+
present_ = false;
|
|
30
|
+
/** The person's commands running on the browser now. */
|
|
31
|
+
commands = new Set();
|
|
32
|
+
/** Set from a hold's end while a command of the person's still runs: the bound's timer. Model calls wait until it clears. */
|
|
33
|
+
settling_ = null;
|
|
34
|
+
/** Model calls waiting for the hold to end. */
|
|
35
|
+
waiters = new Set();
|
|
20
36
|
listeners = new Set();
|
|
21
|
-
constructor(timers, idleMs, forget) {
|
|
37
|
+
constructor(timers, idleMs, forget, holdIdleMs = 15 * 60_000, holdAwayMs = 2 * 60_000, settleMs = 10_000) {
|
|
22
38
|
this.timers = timers;
|
|
23
39
|
this.idleMs = idleMs;
|
|
24
40
|
this.forget = forget;
|
|
41
|
+
this.holdIdleMs = holdIdleMs;
|
|
42
|
+
this.holdAwayMs = holdAwayMs;
|
|
43
|
+
this.settleMs = settleMs;
|
|
25
44
|
}
|
|
26
|
-
state() { return this.model_ > 0 ? "agent" : this.person ? "person" : "idle"; }
|
|
27
|
-
/** Viewer input: discarded (never queued) while the model acts, so a keystroke is not replayed into a page the model has since moved.
|
|
45
|
+
state() { return this.hold && !this.hold.pending ? "person" : this.model_ > 0 ? "agent" : this.person || this.hold || this.settling_ ? "person" : "idle"; }
|
|
46
|
+
/** Viewer input: discarded (never queued) while the model acts, so a keystroke is not replayed into a page the model has since moved. While the
|
|
47
|
+
* person holds the browser it is always theirs: a model call that was in flight at the take acts no more (the epoch moved). */
|
|
28
48
|
input() {
|
|
49
|
+
if (this.hold) {
|
|
50
|
+
// Taken while the agent's call ran: the person drives once it returns.
|
|
51
|
+
if (this.hold.pending)
|
|
52
|
+
return "agent_acting";
|
|
53
|
+
this.timers.clear(this.hold.idle);
|
|
54
|
+
this.hold.idle = this.timers.set(() => this.endHold("idle"), this.holdIdleMs);
|
|
55
|
+
this.drove_ = true;
|
|
56
|
+
this.handled_ = true;
|
|
57
|
+
return "driving";
|
|
58
|
+
}
|
|
59
|
+
// Handed back, the person's last command still settling: it is theirs, and it starts no new driving window.
|
|
60
|
+
if (this.settling_)
|
|
61
|
+
return "driving";
|
|
29
62
|
if (this.model_ > 0)
|
|
30
63
|
return "agent_acting";
|
|
31
64
|
const before = this.state();
|
|
32
65
|
this.person = true;
|
|
33
66
|
this.drove_ = true;
|
|
67
|
+
this.handled_ = true;
|
|
34
68
|
if (this.idle !== undefined)
|
|
35
69
|
this.timers.clear(this.idle);
|
|
36
70
|
this.idle = this.timers.set(() => this.stopDriving(), this.idleMs);
|
|
@@ -39,36 +73,170 @@ class Gate {
|
|
|
39
73
|
return "driving";
|
|
40
74
|
}
|
|
41
75
|
model() {
|
|
42
|
-
if (this.person)
|
|
76
|
+
if (this.person || this.hold || this.settling_)
|
|
43
77
|
return PERSON_DRIVING;
|
|
44
78
|
const drove = this.drove_;
|
|
79
|
+
const handled = this.handled_;
|
|
45
80
|
const before = this.state();
|
|
46
81
|
this.model_ += 1;
|
|
47
82
|
if (before !== "agent")
|
|
48
83
|
this.announce("agent");
|
|
49
84
|
let released = false;
|
|
50
|
-
return { drove, release: () => {
|
|
51
|
-
|
|
85
|
+
return { drove, handled, release: () => {
|
|
86
|
+
if (released)
|
|
87
|
+
return;
|
|
88
|
+
released = true;
|
|
89
|
+
this.model_ -= 1;
|
|
90
|
+
if (this.model_ > 0)
|
|
91
|
+
return;
|
|
92
|
+
// A take that waited for this call goes live now.
|
|
93
|
+
if (this.hold?.pending)
|
|
94
|
+
return this.startHold();
|
|
52
95
|
this.announce(this.state());
|
|
53
96
|
this.settle();
|
|
54
|
-
} }
|
|
97
|
+
} };
|
|
55
98
|
}
|
|
56
|
-
told() { this.drove_ = false; this.settle(); }
|
|
99
|
+
told() { this.drove_ = false; this.handled_ = false; this.settle(); }
|
|
57
100
|
viewing() { return this.viewing_; }
|
|
58
101
|
setViewing(on) { this.viewing_ = on; if (!on)
|
|
59
102
|
this.settle(); }
|
|
60
103
|
onChange(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); this.settle(); }; }
|
|
104
|
+
take(onEnd, onStart) {
|
|
105
|
+
if (this.hold)
|
|
106
|
+
return false;
|
|
107
|
+
this.epoch_ += 1;
|
|
108
|
+
this.drove_ = true;
|
|
109
|
+
this.hold = { onEnd, onStart, pending: this.model_ > 0, idle: this.timers.set(() => this.endHold("idle"), this.holdIdleMs), away: undefined };
|
|
110
|
+
if (!this.present_)
|
|
111
|
+
this.hold.away = this.timers.set(() => this.endHold("away"), this.holdAwayMs);
|
|
112
|
+
if (!this.hold.pending)
|
|
113
|
+
this.startHold();
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
/** The hold goes live: the person's input is taken from here, and its idle window starts now. */
|
|
117
|
+
startHold() {
|
|
118
|
+
const hold = this.hold;
|
|
119
|
+
if (!hold)
|
|
120
|
+
return;
|
|
121
|
+
hold.pending = false;
|
|
122
|
+
this.timers.clear(hold.idle);
|
|
123
|
+
hold.idle = this.timers.set(() => this.endHold("idle"), this.holdIdleMs);
|
|
124
|
+
this.announce("person");
|
|
125
|
+
try {
|
|
126
|
+
hold.onStart?.();
|
|
127
|
+
}
|
|
128
|
+
catch { /* a host's listener that throws cannot keep the person from the browser */ }
|
|
129
|
+
}
|
|
130
|
+
holding() { return this.hold !== null && !this.hold.pending; }
|
|
131
|
+
give(why = "given", message) {
|
|
132
|
+
if (!this.hold)
|
|
133
|
+
return false;
|
|
134
|
+
this.endHold(why, message);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
held() { return this.hold !== null; }
|
|
138
|
+
epoch() { return this.epoch_; }
|
|
139
|
+
setPresent(on) {
|
|
140
|
+
this.present_ = on;
|
|
141
|
+
if (this.hold) {
|
|
142
|
+
if (this.hold.away !== undefined)
|
|
143
|
+
this.timers.clear(this.hold.away);
|
|
144
|
+
this.hold.away = on ? undefined : this.timers.set(() => this.endHold("away"), this.holdAwayMs);
|
|
145
|
+
}
|
|
146
|
+
if (!on)
|
|
147
|
+
this.settle();
|
|
148
|
+
}
|
|
149
|
+
command() {
|
|
150
|
+
const mark = {};
|
|
151
|
+
this.commands.add(mark);
|
|
152
|
+
return {
|
|
153
|
+
live: () => this.commands.has(mark),
|
|
154
|
+
done: () => {
|
|
155
|
+
if (!this.commands.delete(mark))
|
|
156
|
+
return;
|
|
157
|
+
if (this.settling_ && this.commands.size === 0)
|
|
158
|
+
this.settled();
|
|
159
|
+
else
|
|
160
|
+
this.settle();
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
settling() { return this.settling_ !== null; }
|
|
165
|
+
untilFree(signal) {
|
|
166
|
+
if (!this.hold && !this.settling_)
|
|
167
|
+
return Promise.resolve();
|
|
168
|
+
return new Promise((resolve, reject) => {
|
|
169
|
+
const abort = () => { this.waiters.delete(done); reject(signal?.reason ?? new Error("aborted")); this.settle(); };
|
|
170
|
+
const done = () => { signal?.removeEventListener("abort", abort); resolve(); };
|
|
171
|
+
if (signal?.aborted) {
|
|
172
|
+
abort();
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
this.waiters.add(done);
|
|
176
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
177
|
+
});
|
|
178
|
+
}
|
|
61
179
|
end() {
|
|
180
|
+
this.endHold("released");
|
|
181
|
+
this.commands.clear();
|
|
182
|
+
this.settled();
|
|
62
183
|
if (this.idle !== undefined)
|
|
63
184
|
this.timers.clear(this.idle);
|
|
64
185
|
this.idle = undefined;
|
|
65
186
|
this.person = false;
|
|
66
187
|
this.viewing_ = false;
|
|
67
188
|
this.drove_ = false;
|
|
189
|
+
this.handled_ = false;
|
|
68
190
|
this.model_ = 0;
|
|
69
191
|
this.listeners.clear();
|
|
70
192
|
this.forget(this);
|
|
71
193
|
}
|
|
194
|
+
/** The hold ends: the epoch moves, the person's driving window with it (they let go), the waiting model calls go on, and its listener is told why. */
|
|
195
|
+
endHold(why, message) {
|
|
196
|
+
const hold = this.hold;
|
|
197
|
+
if (!hold)
|
|
198
|
+
return;
|
|
199
|
+
this.hold = null;
|
|
200
|
+
this.timers.clear(hold.idle);
|
|
201
|
+
if (hold.away !== undefined)
|
|
202
|
+
this.timers.clear(hold.away);
|
|
203
|
+
this.epoch_ += 1;
|
|
204
|
+
this.person = false;
|
|
205
|
+
if (this.idle !== undefined)
|
|
206
|
+
this.timers.clear(this.idle);
|
|
207
|
+
this.idle = undefined;
|
|
208
|
+
// A command of the person's still running (a Back between reading the history and moving, a navigation under way) would move the page under
|
|
209
|
+
// the agent's next call: the waiting calls go on once it returns, or once the bound passes and it is let go.
|
|
210
|
+
if (this.commands.size > 0 && why !== "released") {
|
|
211
|
+
if (this.settling_)
|
|
212
|
+
this.timers.clear(this.settling_.timer);
|
|
213
|
+
this.settling_ = { timer: this.timers.set(() => { this.commands.clear(); this.settled(); }, this.settleMs) };
|
|
214
|
+
}
|
|
215
|
+
else
|
|
216
|
+
this.wake();
|
|
217
|
+
this.announce(this.state());
|
|
218
|
+
try {
|
|
219
|
+
hold.onEnd?.(why, message);
|
|
220
|
+
}
|
|
221
|
+
catch { /* a host's listener that throws cannot keep the hold */ }
|
|
222
|
+
this.settle();
|
|
223
|
+
}
|
|
224
|
+
/** The person's last command has returned, or was let go: the waiting model calls go on. */
|
|
225
|
+
settled() {
|
|
226
|
+
if (this.settling_) {
|
|
227
|
+
this.timers.clear(this.settling_.timer);
|
|
228
|
+
this.settling_ = null;
|
|
229
|
+
this.announce(this.state());
|
|
230
|
+
}
|
|
231
|
+
this.wake();
|
|
232
|
+
this.settle();
|
|
233
|
+
}
|
|
234
|
+
wake() {
|
|
235
|
+
const waiting = [...this.waiters];
|
|
236
|
+
this.waiters.clear();
|
|
237
|
+
for (const wake of waiting)
|
|
238
|
+
wake();
|
|
239
|
+
}
|
|
72
240
|
stopDriving() {
|
|
73
241
|
this.idle = undefined;
|
|
74
242
|
if (!this.person)
|
|
@@ -80,7 +248,7 @@ class Gate {
|
|
|
80
248
|
/** A gate that no call, person, viewer or listener holds is dropped from the registry, so a long-running host does not keep one per session it ever ran: whoever asks again gets an
|
|
81
249
|
* identical one. A gate in use stays the same object. */
|
|
82
250
|
settle() {
|
|
83
|
-
if (this.model_ === 0 && !this.person && !this.drove_ && !this.viewing_ && this.listeners.size === 0)
|
|
251
|
+
if (this.model_ === 0 && !this.person && !this.drove_ && !this.viewing_ && !this.hold && !this.present_ && !this.settling_ && this.commands.size === 0 && this.waiters.size === 0 && this.listeners.size === 0)
|
|
84
252
|
this.forget(this);
|
|
85
253
|
}
|
|
86
254
|
announce(state) {
|
|
@@ -96,12 +264,15 @@ class Gate {
|
|
|
96
264
|
export function createDrivingGates(options = {}) {
|
|
97
265
|
const idleMs = options.idleMs ?? 3000;
|
|
98
266
|
const timers = options.timers ?? NODE_TIMERS;
|
|
267
|
+
const holdIdleMs = options.holdIdleMs ?? 15 * 60_000;
|
|
268
|
+
const holdAwayMs = options.holdAwayMs ?? 2 * 60_000;
|
|
269
|
+
const settleMs = options.settleMs ?? 10_000;
|
|
99
270
|
const byTag = new Map();
|
|
100
271
|
return (tag) => {
|
|
101
272
|
let gate = byTag.get(tag);
|
|
102
273
|
if (!gate) {
|
|
103
274
|
const made = new Gate(timers, idleMs, (ended) => { if (byTag.get(tag) === ended)
|
|
104
|
-
byTag.delete(tag); });
|
|
275
|
+
byTag.delete(tag); }, holdIdleMs, holdAwayMs, settleMs);
|
|
105
276
|
byTag.set(tag, made);
|
|
106
277
|
gate = made;
|
|
107
278
|
}
|
|
@@ -162,3 +333,11 @@ export function rearmWhenLeft(gate, alive, rearm, idleMs) {
|
|
|
162
333
|
poll.unref?.();
|
|
163
334
|
return () => clearInterval(poll);
|
|
164
335
|
}
|
|
336
|
+
/** Whether `gate`'s person hold is live (their input taken): false for a gate without holds. */
|
|
337
|
+
export const isHolding = (gate) => typeof gate.holding === "function" ? gate.holding() : isHeld(gate);
|
|
338
|
+
/** Whether `gate`'s hold has ended with the person's last command still settling: false for a gate without holds. */
|
|
339
|
+
export const isSettling = (gate) => typeof gate.settling === "function" && gate.settling();
|
|
340
|
+
/** Whether `gate` is held for a person now: false for a gate without holds (a registry that predates them). */
|
|
341
|
+
export const isHeld = (gate) => typeof gate.held === "function" && gate.held();
|
|
342
|
+
/** `gate`'s epoch: 0, unmoving, for a gate without holds. */
|
|
343
|
+
export const epochOf = (gate) => (typeof gate.epoch === "function" ? gate.epoch() : 0);
|