@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.
Files changed (48) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/NOTICE +4 -4
  3. package/README.md +41 -12
  4. package/dist/coding-agent.d.ts +1 -0
  5. package/dist/coding-agent.js +5 -4
  6. package/dist/core/contract.d.ts +9 -0
  7. package/dist/core/contract.js +15 -3
  8. package/dist/core/custody.d.ts +7 -2
  9. package/dist/core/custody.js +7 -3
  10. package/dist/core/downloads.d.ts +7 -0
  11. package/dist/core/downloads.js +13 -1
  12. package/dist/core/driving-guard.d.ts +20 -0
  13. package/dist/core/driving-guard.js +175 -23
  14. package/dist/core/driving.d.ts +56 -2
  15. package/dist/core/driving.js +189 -10
  16. package/dist/core/effects.d.ts +80 -6
  17. package/dist/core/effects.js +374 -41
  18. package/dist/core/failures.d.ts +15 -1
  19. package/dist/core/failures.js +7 -0
  20. package/dist/core/host.d.ts +11 -2
  21. package/dist/core/tools.d.ts +14 -0
  22. package/dist/core/tools.js +42 -8
  23. package/dist/driver/page-driver.js +77 -4
  24. package/dist/driver/sealed.d.ts +4 -12
  25. package/dist/driver/sealed.js +23 -37
  26. package/dist/driver/stagehand.d.ts +10 -15
  27. package/dist/driver/stagehand.js +19 -17
  28. package/dist/durable/result.d.ts +1 -2
  29. package/dist/durable/result.js +2 -2
  30. package/dist/durable/store.d.ts +4 -1
  31. package/dist/durable/store.js +16 -11
  32. package/dist/durable.d.ts +17 -1
  33. package/dist/durable.js +41 -14
  34. package/dist/live-view/index.d.ts +2 -1
  35. package/dist/live-view/index.js +1 -0
  36. package/dist/live-view/protocol.d.ts +38 -6
  37. package/dist/live-view/protocol.js +2 -0
  38. package/dist/live-view/server.d.ts +24 -1
  39. package/dist/live-view/server.js +131 -11
  40. package/dist/live-view/stream.js +16 -3
  41. package/dist/live-view/viewer.js +106 -13
  42. package/dist/providers/cdp.d.ts +0 -1
  43. package/dist/providers/cdp.js +33 -11
  44. package/dist/providers/worker-extension.d.ts +6 -0
  45. package/dist/providers/worker-extension.js +17 -4
  46. package/package.json +10 -10
  47. package/dist/driver/extension-worker.d.ts +0 -9
  48. package/dist/driver/extension-worker.js +0 -185
@@ -6,8 +6,8 @@ const cidOf = (row) => row.conversationId;
6
6
  /** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
7
7
  export const RELEASE_ATTEMPTS = 6;
8
8
  export const CONFIRM_POLLS = 5;
9
- export function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack }) {
10
- const Inventory = defineDoc({ kind: `${name}.inventory`, version: 1, scope: "session", initial: () => ({ rows: {} }) });
9
+ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook }) {
10
+ const Inventory = defineDoc({ kind: `${name}.inventory`, version: 1, scope: "session", initial: () => ({ rows: {} }), checkpointWhen: () => false });
11
11
  /** One state change: the record and the open-session inventory move in the same commit. */
12
12
  async function move(tx, row, next) {
13
13
  const inventory = await tx.doc(Inventory);
@@ -106,8 +106,9 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
106
106
  }, context);
107
107
  return;
108
108
  }
109
- await runtime.sleep(runtime.now() + backoffMs(attempt), context);
110
- await runtime.commit(() => ({ status: "running", checkpoint: { phase: "release", attempt: attempt + 1, ...(found.length ? { found } : {}) } }), context);
109
+ // pi 1.5: the wait is a durable sleep. Its deadline is computed once on the Harness clock and stored with the sleep
110
+ // (the task's `until`), so a process that dies while it sleeps resumes at that same deadline, never a new one.
111
+ await runtime.sleepUntil(runtime.now() + backoffMs(attempt), { phase: "release", attempt: attempt + 1, ...(found.length ? { found } : {}) }, context);
111
112
  }
112
113
  const ReleaseTask = defineTask({
113
114
  name: `${name}.release`,
@@ -118,8 +119,10 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
118
119
  const { row, notBefore } = task.input;
119
120
  const { attempt } = task.state.checkpoint;
120
121
  const found = union(task.input.found, task.state.checkpoint.found);
122
+ // The create deadline from the task's input (durable): sleep to it, then this phase runs again at the same
123
+ // checkpoint, past the deadline.
121
124
  if (attempt === 0 && notBefore && runtime.now() < notBefore)
122
- await runtime.sleep(notBefore, context);
125
+ return runtime.sleepUntil(notBefore, task.state.checkpoint, context);
123
126
  let seen = [];
124
127
  // Ids the lookup found that the task does not hold yet are committed before any stop is sent: an attempt cut
125
128
  // between its stop and its next commit (the task's abort) leaves them for the abort handler, whose own lookup
@@ -134,6 +137,7 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
134
137
  // What the lookup found goes on to the next attempt even when its release failed: the stop may have landed.
135
138
  if (!released)
136
139
  return retry(runtime, row, attempt, context, union(found, seen));
140
+ stoppedHook?.(row.tag);
137
141
  // Confirmed together: what this attempt released and what earlier ones did.
138
142
  const ids = union(found, released);
139
143
  await runtime.commit(() => ({ status: "running", checkpoint: { phase: "confirm", attempt, ids, polls: 0 } }), context);
@@ -143,8 +147,7 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
143
147
  const { attempt, ids, polls } = task.state.checkpoint;
144
148
  const running = await step(runtime, async () => anyRunning(await providerOf(runtime, cidOf(row), row.plane, context), row, ids, runtime.signal), true);
145
149
  if (running && polls + 1 < CONFIRM_POLLS) {
146
- await runtime.sleep(runtime.now() + backoffMs(polls), context);
147
- await runtime.commit(() => ({ status: "running", checkpoint: { phase: "confirm", attempt, ids, polls: polls + 1 } }), context);
150
+ await runtime.sleepUntil(runtime.now() + backoffMs(polls), { phase: "confirm", attempt, ids, polls: polls + 1 }, context);
148
151
  return;
149
152
  }
150
153
  if (running)
@@ -169,6 +172,8 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
169
172
  // Before the create deadline nothing found is proof of nothing: the successor keeps the delayed lookup.
170
173
  if (!(notBefore && runtime.now() < notBefore))
171
174
  stopped = await providerOf(runtime, cidOf(row), row.plane, context).then((provider) => releasedIds(provider, row, context.abortSignal, (ids) => void (found = union(found, ids)))).catch(() => null);
175
+ if (stopped)
176
+ stoppedHook?.(row.tag);
172
177
  await runtime.commit(async (tx) => {
173
178
  if (stopped)
174
179
  await move(tx, row, { state: "released", at: iso(runtime.now()), ...foundId(row, union(found, stopped)) });
@@ -211,11 +216,11 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
211
216
  runtime.report(scrubbed(error));
212
217
  }
213
218
  if (answer === "pending") {
214
- await runtime.sleep(runtime.now() + backoffMs(attempt), context);
215
- await runtime.commit(() => ({ status: "running", checkpoint: { phase: "poll", attempt: attempt + 1 } }), context);
219
+ await runtime.sleepUntil(runtime.now() + backoffMs(attempt), { phase: "poll", attempt: attempt + 1 }, context);
216
220
  return;
217
221
  }
218
- const outcome = answer;
222
+ const outcome = typeof answer === "string" ? answer : answer.outcome;
223
+ const reason = typeof answer === "string" ? undefined : answer.reason;
219
224
  await runtime.commit(async (tx) => {
220
225
  const state = await tx.doc(Sessions, cidOf(row));
221
226
  const record = state.sessions.find((r) => r.tag === row.tag);
@@ -224,7 +229,7 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
224
229
  addNotice(state, notices.handedBack(outcome, completionCondition));
225
230
  handedBack?.(row.tag, record.fence ?? 0);
226
231
  }
227
- return { status: "terminal", outcome: { status: "completed", result: { outcome } } };
232
+ return { status: "terminal", outcome: { status: "completed", result: { outcome, ...(reason ? { reason } : {}) } } };
228
233
  }, context);
229
234
  },
230
235
  },
package/dist/durable.d.ts CHANGED
@@ -10,9 +10,19 @@ import { type BrowserToolImpls, type PageDriver } from "./core/tools.js";
10
10
  import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionCharge, SessionRow, SessionsState, SiteInfo, SiteRunPort, HandoffPort, WorkspaceFiles } from "./core/host.js";
11
11
  export type { BrowserToolArgs, BrowserToolImpls, PageDriver, ToolCall, ToolImpl } from "./core/tools.js";
12
12
  export type { DriverFactory, DriverOptions } from "./core/custody.js";
13
+ /** A host's step before a session is created at its provider (`BrowserExtensionOptions.beforeCreate`): the session's
14
+ * conversation, its tag, and the session's own commit, for a record of the host's beside it in the same store. */
15
+ export type BeforeCreate = (open: {
16
+ conversationId: ConversationId;
17
+ tag: string;
18
+ commit<T>(change: (tx: Tx) => Promise<T>): Promise<T>;
19
+ }) => Promise<void>;
13
20
  export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOptions & {
14
21
  /** Default "browser"; a second plane installs a second extension under another name. */
15
22
  name?: string;
23
+ /** The plane's sessions open on its agent's saved sign-ins (a host's kept profile): `run` tells the model so, for a page
24
+ * behind a sign-in. Default: whether a `sessionVault` is given. Without either, it claims cookies across pages only. */
25
+ signIns?: boolean;
16
26
  /** Called per use: the provider for this conversation's plane. Holds the credentials in its closure; nothing it
17
27
  * returns is committed. */
18
28
  provider: (target: {
@@ -62,6 +72,11 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOp
62
72
  decisions?: Decisions;
63
73
  /** How long a create may still land at the provider after its caller stopped waiting; default 60 s. */
64
74
  createDeadlineMs?: number;
75
+ /** The host's step between the session's record (state `creating`, its tag, in the inventory) reaching the store and
76
+ * the provider's create: a barrier that makes that record durable, a record of the host's own beside it in the same
77
+ * store (`commit`). Nothing is sent to the provider before it resolves; one that throws sends nothing, and the record
78
+ * ends there, nothing made. */
79
+ beforeCreate?: BeforeCreate;
65
80
  /** How the request observer attaches (default `EffectObserver.open`); a seam for tests that have no Chrome. */
66
81
  openObserver?: typeof EffectObserver.open;
67
82
  /** Called synchronously at two moments of a page action, for a host that kills the process there to test a resume:
@@ -95,7 +110,8 @@ export type BrowserExtensionHandle = {
95
110
  reconcile(harness: Harness, isActive: (conversationId: ConversationId) => boolean, context: Context): Promise<ReconcileReport>;
96
111
  /** Shutdown is release, `waitForIdle`, `drain`, close: resolves when none of this extension's release tasks is live. */
97
112
  drain(harness: Harness, context: Context, signal?: AbortSignal): Promise<void>;
98
- /** Drop in-memory driver attachments and idle timers (process exit). Over a healthy store it releases nothing; over
113
+ /** Drop in-memory driver attachments and idle timers (process exit). It first waits (30 s at most) for this process's
114
+ * `close` releases that no `drain` since covered to reach the provider. Over a healthy store it releases nothing; over
99
115
  * one that failed (a release commit of this process threw, or the Session ended failed) it releases every session
100
116
  * this process still owns at the provider. */
101
117
  close(): Promise<void>;
package/dist/durable.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { configure, defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
3
- import { BROWSER_TOOL_NAMES, BROWSER_TOOLS, browserSection, listedFor, WEB_TOOL_NAMES } from "./core/contract.js";
3
+ import { BROWSER_TOOL_NAMES, browserSection, browserToolsFor, listedFor, WEB_TOOL_NAMES } from "./core/contract.js";
4
4
  import { BrowserFailureError, closeDriver, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
5
5
  import { forModel } from "./durable/result.js";
6
6
  import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
@@ -55,6 +55,9 @@ const CHILD_TOOLS = new Set([...BROWSER_TOOL_NAMES, ...WEB_TOOL_NAMES].filter((n
55
55
  const DIRECT_RELEASE_MS = 30_000;
56
56
  /** How long close waits to learn whether a Session that began closing failed. */
57
57
  const FAILED_END_MS = 5_000;
58
+ /** How long close, with no drain before it, waits for this process's close releases to reach the provider, as a direct
59
+ * release may take. */
60
+ const CLOSE_STOP_MS = DIRECT_RELEASE_MS;
58
61
  class Attachments {
59
62
  drivers = new Map();
60
63
  observers = new Map();
@@ -249,6 +252,17 @@ async function create(c, scope, overrides, presetTag) {
249
252
  state.current[scope.plane] = state.sessions.length - 1;
250
253
  await c.store.begin(tx, row);
251
254
  });
255
+ // The host's barrier, with the record in the store: nothing is created at the provider until it is through.
256
+ if (c.options.beforeCreate) {
257
+ try {
258
+ await c.options.beforeCreate({ conversationId: scope.cid, tag, commit: scope.commit });
259
+ }
260
+ catch (error) {
261
+ await scope.commit((tx) => c.store.move(tx, row, { state: "released", reason: "create_failed", at: now() })).catch(() => undefined);
262
+ await c.store.emitReleased(scope.cid, tag, scope.read, scope.context).catch(() => undefined);
263
+ throw failure(error, scope, c.redact);
264
+ }
265
+ }
252
266
  // An answer lost on the way back is not a session that never started: it is settled by its tag.
253
267
  const ref = await provider.create(plan.spec, scope.signal).then(async (made) => {
254
268
  // Owned before it is recorded: a store that cannot record it still lets close release it.
@@ -572,7 +586,7 @@ function portFor(c, api, context) {
572
586
  for (;;) {
573
587
  const { state } = await api.waitForTask(task, context);
574
588
  if (state.outcome.status === "completed" && state.outcome.result) {
575
- const { outcome } = state.outcome.result;
589
+ const { outcome, reason } = state.outcome.result;
576
590
  // A sign-in just happened and the person has handed back: kept now, so a crash after it does not lose it.
577
591
  const current = currentRecord(await stateOf(c, scope), scope.plane);
578
592
  if (current)
@@ -581,7 +595,7 @@ function portFor(c, api, context) {
581
595
  if ((await stateOf(c, scope)).notice?.includes(told)) {
582
596
  await editState(c, scope, (sessions) => { sessions.notice = sessions.notice?.replace(told, "").replace(/\s+/g, " ").trim() || null; });
583
597
  }
584
- return { outcome };
598
+ return { outcome, ...(reason ? { reason } : {}) };
585
599
  }
586
600
  const next = await find();
587
601
  if (next === undefined || next === task)
@@ -657,11 +671,17 @@ async function releasePlane(c, conversation, reason, context, still = () => true
657
671
  if (kept.gate)
658
672
  return [];
659
673
  await c.store.requestRelease(tx, rowOf(conversation.id, record), reason, now());
674
+ if (reason === "close" && !c.stops.has(record.tag)) {
675
+ let stop = () => { };
676
+ const stopped = new Promise((resolve) => { stop = resolve; });
677
+ c.stops.set(record.tag, { stopped, stop, drained: false });
678
+ }
660
679
  if (reason === "idle" || reason === "close")
661
680
  c.store.addNotice(state, notices.released(reason, record.lastUrl, idleS));
662
681
  return [record.tag];
663
682
  }, context).catch(async (error) => {
664
683
  c.failed = true;
684
+ c.stops.delete(kept.tag);
665
685
  await closing;
666
686
  for (const tag of mine())
667
687
  await c.held.detach(tag);
@@ -706,7 +726,7 @@ const withSessionTime = (own, charged) => {
706
726
  return { ...charged.usage, ...own, cost: { ...charged.usage.cost, ...ownCost, total: charged.usage.cost.total + (ownCost.total ?? 0) } };
707
727
  };
708
728
  function toolsFor(c, impls) {
709
- return BROWSER_TOOLS
729
+ return browserToolsFor(c.options.signIns ?? !!c.options.sessionVault)
710
730
  .filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!(c.options.files || c.options.workspace), handoff: !!c.options.handoff }))
711
731
  .map((contract) => defineTool({
712
732
  name: contract.name,
@@ -819,13 +839,11 @@ function siteTool(c, sites) {
819
839
  },
820
840
  });
821
841
  }
822
- /** pi-durable 1.2 on: a Session that a storage error failed ends with reason "failed" (`closed`), and close begins at
823
- * once (`subscribeClose`). Before 1.2 a Session has no such end, and a failed commit poisons it with no sign. */
842
+ /** A Session that a storage error failed ends `{ kind: "failed" }` (`closed`, pi-durable's SessionEnd), and close begins
843
+ * at once (`subscribeClose`). */
824
844
  function endingOf(harness) {
825
845
  const closed = harness.closed;
826
- if (typeof closed?.then !== "function")
827
- return null;
828
- const ending = { closing: false, failed: closed.then((end) => end.reason === "failed", () => false) };
846
+ const ending = { closing: false, failed: closed.then((end) => end.kind === "failed", () => false) };
829
847
  try {
830
848
  harness.subscribeClose(() => { ending.closing = true; });
831
849
  }
@@ -840,10 +858,10 @@ export function createBrowserExtension(options) {
840
858
  const tracked = new Set();
841
859
  const redact = createRedactor(() => [...providerKeyValues(process.env, options.redact?.values), ...tracked]);
842
860
  const vault = vaultRuntime(options, (secret) => { tracked.add(secret); }, (message) => process.emitWarning(`pi-browser: ${redact(message)}`, { code: "PI_BROWSER_VAULT" }));
843
- const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED) });
844
- const Children = defineDoc({ kind: `${name}.children`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ byRequest: {} }) });
861
+ const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED), checkpointWhen: () => false });
862
+ const Children = defineDoc({ kind: `${name}.children`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ byRequest: {} }), checkpointWhen: () => false });
845
863
  // A fork starts with no sessions: it never shares a live browser.
846
- const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: emptySessions });
864
+ const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: emptySessions, checkpointWhen: () => false });
847
865
  const readers = { options, redact, Config };
848
866
  /** Class name and redacted message only: a vendor SDK's error text can repeat the request's credentials. */
849
867
  const scrubbed = (error) => Object.assign(new Error(redact(error instanceof Error ? error.message : String(error))), { name: error instanceof Error ? error.name : "Error" });
@@ -883,9 +901,10 @@ export function createBrowserExtension(options) {
883
901
  },
884
902
  handoff: options.handoff,
885
903
  handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
904
+ stopped: (tag) => { c.stops.get(tag)?.stop(); c.stops.delete(tag); },
886
905
  });
887
906
  const c = {
888
- ...readers, name, Sessions, Children, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, serial: keyedSerializer(), childTurns: oneAtATime(), guards: new Map(), owned, failed: false, ending: null, opened: null, incarnation: randomUUID(),
907
+ ...readers, name, Sessions, Children, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, serial: keyedSerializer(), childTurns: oneAtATime(), guards: new Map(), owned, failed: false, stops: new Map(), ending: null, opened: null, incarnation: randomUUID(),
889
908
  idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
890
909
  };
891
910
  // 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
@@ -912,7 +931,9 @@ export function createBrowserExtension(options) {
912
931
  }
913
932
  return report;
914
933
  },
915
- drain: (harness, context, signal) => drainReleases(name, harness, context, signal),
934
+ // The releases recorded so far are the drain's, however it ends (the host's signal may cut it short); a later one is not.
935
+ drain: (harness, context, signal) => { for (const wait of c.stops.values())
936
+ wait.drained = true; return drainReleases(name, harness, context, signal); },
916
937
  async close() {
917
938
  c.idle.clear();
918
939
  c.fences.clear();
@@ -921,6 +942,12 @@ export function createBrowserExtension(options) {
921
942
  c.leaving.clear();
922
943
  // A session whose driver was let go and not yet replaced still has its observer attached: close both kinds.
923
944
  await Promise.all(c.held.tags().map((tag) => c.held.detach(tag)));
945
+ // Closing the Harness cancels a release task that has not released yet. A host that closes with no drain after its
946
+ // close releases (the crash-and-resume example) gets them at the provider all the same: close waits for their tasks,
947
+ // at most CLOSE_STOP_MS, rather than counting on a slow driver close to have given them time. One a drain covered is
948
+ // not waited for again (the host bounded that wait itself); a Harness that runs no task leaves them to the next run.
949
+ await Promise.all([...c.stops.values()].filter((wait) => !wait.drained).map((wait) => settleWithin(wait.stopped, CLOSE_STOP_MS, undefined)));
950
+ c.stops.clear();
924
951
  // A store that failed runs no release task again, so what this process still holds is released at the provider.
925
952
  // Over a healthy store it is kept, for the next run to resume or reconcile.
926
953
  if (c.failed || (c.ending?.closing && await settleWithin(c.ending.failed, FAILED_END_MS, false)))
@@ -1,4 +1,5 @@
1
- export { createLiveView, type LiveViewHost, type LiveViewOptions } from "./server.js";
1
+ export { createLiveView, type LiveViewHost, type LiveViewOptions, type TakeAnswer } from "./server.js";
2
2
  export { liveViewProvider } from "./provider.js";
3
3
  export * from "./protocol.js";
4
4
  export { createDrivingGates, drivingGates, personDrivingFailure, PERSON_DRIVING, withModelCall, type DrivingOptions } from "../core/driving.js";
5
+ export { viewerAssets } from "./viewer.js";
@@ -2,3 +2,4 @@ export { createLiveView } from "./server.js";
2
2
  export { liveViewProvider } from "./provider.js";
3
3
  export * from "./protocol.js";
4
4
  export { createDrivingGates, drivingGates, personDrivingFailure, PERSON_DRIVING, withModelCall } from "../core/driving.js";
5
+ export { viewerAssets } from "./viewer.js";
@@ -1,5 +1,5 @@
1
- import type { DriveState, DrivingGate, DrivingGates } from "../core/driving.js";
2
- export type { DriveState, DrivingGate, DrivingGates };
1
+ import type { DriveState, DrivingGate, DrivingGates, HoldEnd } from "../core/driving.js";
2
+ export type { DriveState, DrivingGate, DrivingGates, HoldEnd };
3
3
  /** The viewer's first message, and nothing else is accepted before it. The token is read from the URL fragment by the viewer's script and
4
4
  * never travels in a path, a query or a header. */
5
5
  export type Hello = {
@@ -56,12 +56,37 @@ export type DialogAnswer = {
56
56
  accept: boolean;
57
57
  promptText?: string;
58
58
  };
59
- export type ClientMessage = Hello | InputMessage | NavMessage | DialogAnswer;
59
+ /** A take-over viewer's hands (LiveViewOptions.takeOver): `take` asks to hold the browser, `give` hands it back. */
60
+ export type HandsMessage = {
61
+ type: "take";
62
+ } | {
63
+ type: "give";
64
+ };
65
+ export type ClientMessage = Hello | InputMessage | NavMessage | DialogAnswer | HandsMessage;
60
66
  export type ServerMessage =
61
- /** Sent once, after a valid hello. */
67
+ /** Sent once, after a valid hello. `readOnly`: the viewer watches and never drives (LiveViewOptions.readOnly); `takeOver`: it drives only while
68
+ * it holds the browser (LiveViewOptions.takeOver), and `held` says whether it does now; neither: it may drive. */
62
69
  {
63
70
  type: "ready";
64
71
  drive: DriveState;
72
+ readOnly?: true;
73
+ takeOver?: true;
74
+ held?: boolean;
75
+ }
76
+ /** A take-over viewer's hold began (`held: true`), or ended (`held: false`, why, and the host's words when it gave them: a spend cap's). */
77
+ | {
78
+ type: "hold";
79
+ held: true;
80
+ } | {
81
+ type: "hold";
82
+ held: false;
83
+ reason: HoldEnd;
84
+ message?: string;
85
+ }
86
+ /** A `take` the host refused, in its words (a spend cap with no room for the person's time). Nothing changed. */
87
+ | {
88
+ type: "take_refused";
89
+ message: string;
65
90
  } | {
66
91
  type: "status";
67
92
  drive: DriveState;
@@ -71,6 +96,10 @@ export type ServerMessage =
71
96
  type: "page";
72
97
  url: string;
73
98
  title: string;
99
+ }
100
+ /** The browser has no page to show (one that starts with none, or whose last page closed): until a page opens there is nothing to draw. */
101
+ | {
102
+ type: "no_page";
74
103
  } | {
75
104
  type: "dialog";
76
105
  kind: "alert" | "confirm" | "prompt" | "beforeunload";
@@ -82,7 +111,7 @@ export type ServerMessage =
82
111
  /** One input or nav message was not delivered, and why. */
83
112
  | {
84
113
  type: "held";
85
- reason: "agent_acting" | "no_page" | "bad_message" | "busy";
114
+ reason: "agent_acting" | "no_page" | "bad_message" | "busy" | "read_only" | "not_taken" | "taking";
86
115
  } | {
87
116
  type: "refused";
88
117
  reason: RefusalReason;
@@ -120,6 +149,8 @@ export type StreamHandlers = {
120
149
  url: string;
121
150
  title: string;
122
151
  }): void;
152
+ /** The browser has no page to follow: none when the stream starts, or its last one closed. A page that opens next is announced by `page`. */
153
+ noPage?(): void;
123
154
  dialog(dialog: {
124
155
  kind: "alert" | "confirm" | "prompt" | "beforeunload";
125
156
  message: string;
@@ -130,7 +161,8 @@ export type StreamHandlers = {
130
161
  };
131
162
  export type Stream = {
132
163
  input(message: InputMessage): Promise<void>;
133
- nav(message: NavMessage): Promise<void>;
164
+ /** `live` is false once the command was let go (handed back, and the agent's call went on): a nav of several steps checks it before each. */
165
+ nav(message: NavMessage, live?: () => boolean): Promise<void>;
134
166
  dialog(answer: DialogAnswer): Promise<void>;
135
167
  close(): void;
136
168
  };
@@ -75,6 +75,8 @@ export function parseClientMessage(raw) {
75
75
  if (m.action === "back" || m.action === "reload")
76
76
  return { type: "nav", action: m.action };
77
77
  return m.action === "url" && word(m.url, LIMITS.url) && viewerMayOpen(m.url) ? { type: "nav", action: "url", url: m.url } : null;
78
+ case "take":
79
+ case "give": return Object.keys(m).length === 1 ? { type: m.type } : null;
78
80
  case "dialog":
79
81
  if (typeof m.accept !== "boolean" || (m.promptText !== undefined && (typeof m.promptText !== "string" || m.promptText.length > LIMITS.promptText)))
80
82
  return null;
@@ -1,7 +1,7 @@
1
1
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import type { Duplex } from "node:stream";
3
3
  import type { LiveView } from "../core/host.js";
4
- import { type DrivingGates, type StreamFactory, type ViewerAssets } from "./protocol.js";
4
+ import { type DrivingGates, type HoldEnd, type StreamFactory, type ViewerAssets } from "./protocol.js";
5
5
  export type LiveViewOptions = {
6
6
  /** The one origin allowed to frame the viewer (`frame-ancestors`). Null: none. Required, so the choice is never a default. */
7
7
  hostOrigin: string | null;
@@ -21,10 +21,33 @@ export type LiveViewOptions = {
21
21
  gates?: DrivingGates;
22
22
  /** The viewer page (viewer.ts); the default is the package's own. */
23
23
  viewer?: ViewerAssets;
24
+ /** The viewer watches and never drives: every input, navigation and dialog answer it sends is dropped here, before the browser (`held read_only`), not
25
+ * only hidden by the page, and it is told so (`ready` carries `readOnly: true`). A watching viewer holds no turn and keeps no session from its idle
26
+ * release (it never sets `viewing`). */
27
+ readOnly?: boolean;
28
+ /** The viewer drives only while it holds the browser. Its `take` asks the host first (`take`, which may refuse in its own words, a spend cap with
29
+ * no room for the person's time, shown to the viewer as `take_refused`), then moves the session's driving gate into the person's sticky hold
30
+ * (DrivingGate.take: until the viewer's `give`, the gate's idle window with no input, its away window with no viewer, or the session's end),
31
+ * and the host's `end` is called once when the hold ends, with why. Outside a hold every input, navigation and dialog answer is dropped here,
32
+ * before the browser (`held not_taken`), whatever the page does. A watching viewer keeps no session from its idle release, as a read-only one
33
+ * does; a held one is kept by its hold. Ignored with `readOnly`. */
34
+ takeOver?: {
35
+ take(tag: string): Promise<{
36
+ refused: string;
37
+ } | TakeAnswer>;
38
+ };
24
39
  /** How long a connection may stay silent before its hello, and how many may wait for one. */
25
40
  helloTimeoutMs?: number;
26
41
  maxPending?: number;
27
42
  };
43
+ /** What the host answers a take that it allows: `end` once the hold ends (with why), `started` as it goes live (at once, or
44
+ * once the agent's call under way returns), and `cancel` when no hold started after all (the session released, the viewer
45
+ * gone, or the browser held already), instead of `end`. */
46
+ export type TakeAnswer = {
47
+ end(why: HoldEnd): void;
48
+ started?(): void;
49
+ cancel?(): void;
50
+ };
28
51
  export type LiveViewHost = {
29
52
  /** Serves the viewer page and its two static files; true when the request was this host's (mounted at `baseUrl`'s path), false when it was not. */
30
53
  handle(req: IncomingMessage, res: ServerResponse): boolean;