@theoremjs/web 0.3.5-next.933.gfc0e83b → 0.3.5-next.936.ga984349

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/README.md CHANGED
@@ -271,7 +271,8 @@ const transport = withPageToolDispatch(
271
271
  | `pageStatesTurn` | Let the page say which prompt lines a turn gets, through `stated` on a turn or a live call. Set it only for a page you trust as yourself, such as a builder's own tool. Without it, a request with `stated` is refused. |
272
272
  | `conversationStore` | Where the conversation is kept. Required, except for a stateless profile, which must not have one. See [Keep the conversation](#keep-the-conversation). |
273
273
  | `sessionStore`, `steerInbox` | Where open gates are kept, and where steers and stops reach a running turn. Default: process memory, which reaches only turns this process runs. On more than one instance, give a shared `SteerInbox`. |
274
- | `lateResultsDecider` | Who tells the model that a background call ended: `TurnWiring.lateResultsDecider`. Set it on your `TurnWiring`, and the studio uses it too. Unset, no page wakes the chat and no reply reads a late result. `pageWakes` lets the open page wake it. See [the background section](#share-session-authority). |
274
+ | `lateResultsDecider` | Who tells the model that a background call ended: `TurnWiring.lateResultsDecider`. Set it on your `TurnWiring`, and the studio uses it too. Unset, no page wakes the chat and no reply reads a late result. `tellEveryResult` tells each result to the first reply that runs. See [the background section](#share-session-authority). |
275
+ | `conversationLeaseMs` | How long a reply keeps its chat after it last renewed, in milliseconds. A running reply renews every third of it. A wake that finds another reply running tries again once this runs out. Default: `60000`. |
275
276
  | `notifier`, `notifyRetryMs` | Tell an open page that a background call ended, and how long the page waits to reopen a cut stream. Unset, the page reads the end on its next turn or reload. See [the background section](#share-session-authority). |
276
277
  | `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
277
278
  | `authorizationUrl` | Returns the sign-in URL for an OAuth gate. Without it, an OAuth gate has no URL. |
@@ -460,15 +461,18 @@ Browser dispatch uses a host-owned `PageToolExecution` service beside the execut
460
461
  A tool with a `background` setting runs inline until you pass the `background` option to `createTheoremHandler`, or return `background` from `prepare`, with an `execution` of your own that has `detach`, when the same turns run elsewhere in your app too. The option takes `{ request, sessionId }` and returns a `ToolBackgroundService`, which receives each detached call and its late events. The session keeps the call as `background` until it settles, and a late settlement does not invalidate a checkpoint. A conversation read shows the call as it stands: running, then its result, or an error for a marked call. An open page reads it on its next turn or reload, unless you set `notifier`. When the session has dropped a settled operation, the block reads an error with the code `outcome_not_retained`. On a durable store, a worker that dies leaves the operation as `background`, so your sweep marks it `uncertain` with `worker_lost` through `compareAndSwap`. Keep the service's values valid after the request ends. A live relay passes its service to `runSession`.
461
462
  To show an open page that a background call ended, with no turn or reload, pass `notifier: createMemoryNotifier()` to `createTheoremHandler`. While a call runs, the conversation read tells the page to open `POST <base>/notify`. The handler sends one `changed` line when the stream opens, and one when each background call in the session ends. The line carries no content, so the page calls the same conversation read as before. The page closes the stream when no call runs. The model reads the result only as your decider says.
462
463
 
463
- Set `lateResultsDecider` on your `TurnWiring` and pass it to `createTheoremHandler`. Unset, nothing tells the model a background call ended: the conversation read never says `wake: true`, `<base>/wake` runs nothing, and the next message reads no late result. A result waits for the model when its call settled and no `late-results` block names the call, while the session keeps the operation. A call `authorizeToolReplay` withholds from the request does not wait.
464
+ Set `lateResultsDecider` on your `TurnWiring` and pass it to `createTheoremHandler`. Unset, nothing tells the model a background call ended: the conversation read never says `wake: true`, `<base>/wake` runs nothing, and the next message reads no late result. A result waits for the model when its call settled, no saved reply told it, and the session keeps the operation. A call `authorizeToolReplay` withholds from the request does not wait.
464
465
 
465
- - `give({ reason, host, conversation, results })` picks, by `operationId`, the results a reply reads. It is asked once for each reply, before the model runs: `reason: 'message'` for the person's message, `'wake'` for a reply to no message. The model reads each result it gives once. One it leaves out waits for a later reply. `host` is what your `host` option makes of the request.
466
- - `due({ host, conversation, results })` says whether a page open on the chat wakes it now. It is asked on every conversation read, so it must change nothing. Say yes only when `give` would give something. Unset, no page wakes the chat.
466
+ The handler runs each reply under a hold of the chat, with `runConversation` from `@theoremjs/agents/conversation`. One reply at a time reads the chat's results. A result is told only when the reply that read it is saved. A reply that fails gives its results back, and a later reply reads them.
467
+
468
+ - `policy(items, moment)` picks, by `id` (the call's `operationId`), the results the model reads now. Each item has the call's `outcome`, and `handovers`: the earlier replies it was given to that ended unsaved. The handler asks it as a reply opens (`stage: 'pre_turn'`), after each step whose calls settled (`'post_tool'`), and once the model has answered (`'before_end'`). `moment.opening` is `'message'` for the person's message, `'wake'` for a reply to no message, and `'follow_up'` as a reply ends, for results that ended while it ran. The handler also asks it at `opening: 'wake'` on each conversation read, to say whether the page wakes the chat. It must change nothing. A result it leaves out waits for a later reply. A result it puts in `giveUp` is never read, and is reported once to `onError` with the code `late_results_given_up`.
467
469
  - `ended({ host, result, wake, notify })` hears each background call end. `wake(conversation)` runs a reply to no message from the server, as a page's wake does, so a chat answers with no page open. `notify()` tells the session's open pages to read again.
468
470
 
469
- `pageWakes` is the decider for an app with no server of its own: the page open on the chat wakes it, and every reply reads every result that waits. Write your own to keep a count, such as a cap or quiet hours, or to reply from the server.
471
+ `tellEveryResult` is the decider for an app with no server of its own: every reply reads every result that waits, and the open page wakes the chat. Write your own to keep a count, such as a cap or quiet hours, or to reply from the server.
472
+
473
+ When the policy tells a result at `opening: 'wake'`, the conversation read says `wake: true`, and the page posts `<base>/wake` once it is idle. The handler runs a reply with no message, under a hold of the chat, so two pages that post at once run one reply. No wake runs while a reply waits on a gate: the reply that goes on after the answer reads what waits. A wake that fails gives its results back, so the chat wakes again. A message the person sends during a wake takes the chat: the wake writes nothing, and its stream ends with no error.
470
474
 
471
- When `due` says yes, the conversation read says `wake: true`, and the page posts `<base>/wake` once it is idle. The handler runs a turn with no message and passes what `give` gives in `input.lateResults`. A wake runs only when the transcript does not end on a person's message and no reply waits on a gate. The handler takes each result (`wokenAt` on the session's operation) before it asks `give`, so two pages that post at once run one turn. A result `give` leaves out loses that mark, and a later wake can take it. A wake that fails is not tried again; the next message's `give` is asked. A message the person sends during a wake wins: the wake writes nothing, and its stream ends with no error.
475
+ When a result ends while a reply runs, that reply reads it at its next moment. If it ends as the reply saves, the policy is asked once more before the reply lets the chat go. A reply from the server then runs a follow-up under the same hold. A page's reply lets the chat go, and the conversation read tells the page to wake. A server wake that finds another reply running tries again once that reply's lease runs out (`conversationLeaseMs`).
472
476
 
473
477
  The decider is the one way a result reaches the model. If your `background` service told the model a result some other way, such as with your own `onStage`, remove that, or the model reads it twice.
474
478
 
@@ -110,6 +110,7 @@ const transcriptBlock = z.discriminatedUnion('kind', [
110
110
  kind: z.literal('late-results'),
111
111
  text: z.string(),
112
112
  operationIds: z.array(z.string()),
113
+ inReply: z.boolean(),
113
114
  }),
114
115
  z.object({ ...blockId, kind: z.literal('error'), message: z.string() }),
115
116
  z.object({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/web",
3
- "version": "0.3.5-next.933.gfc0e83b",
3
+ "version": "0.3.5-next.936.ga984349",
4
4
  "description": "Theorem on the web platform, with no UI framework: Web-standard server handlers that serve a profile, and the browser client that talks to them.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,6 +25,6 @@
25
25
  },
26
26
  "peerDependencies": {
27
27
  "zod": "^4.6.5",
28
- "@theoremjs/agents": "^0.3.5-next.933.gfc0e83b"
28
+ "@theoremjs/agents": "^0.3.5-next.936.ga984349"
29
29
  }
30
30
  }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The handler's conversation inbox: each chat's late results, kept in the session store. An item
3
+ * is a detached call that ended; the transcript says whether a saved reply told it, and the
4
+ * session keeps who holds the chat and which replies were handed what.
5
+ *
6
+ * @module
7
+ */
8
+ import type { LateResultItem } from '@theoremjs/agents';
9
+ import type { ConversationInbox } from '@theoremjs/agents/conversation';
10
+ import type { StoredConversation } from './conversation-store.ts';
11
+ import type { MutableStore } from './session-authority.ts';
12
+ import type { SessionToolOperation, TheoremSessionState } from './session-store.ts';
13
+ /** A background call that ended, as the session keeps it. */
14
+ export type SettledOperation = Extract<SessionToolOperation, {
15
+ status: 'settled';
16
+ }>;
17
+ /** Options for {@link sessionConversationInbox}. */
18
+ export type SessionConversationInboxOptions = {
19
+ sessions: MutableStore<TheoremSessionState>;
20
+ sessionId: string;
21
+ /** How long a hold has a chat after it opens or renews, in milliseconds. */
22
+ leaseMs: number;
23
+ /** The chat as its last save left it, by its id; undefined when the store no longer has it. */
24
+ conversation: (key: string) => Promise<StoredConversation | undefined>;
25
+ /** Whether this request may read the call's result: the handler's `authorizeToolReplay`. */
26
+ readable: (operation: SettledOperation) => Promise<boolean>;
27
+ now?: () => number;
28
+ };
29
+ /** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
30
+ export declare function sessionConversationInbox(options: SessionConversationInboxOptions): ConversationInbox<LateResultItem>;
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The handler's conversation inbox: each chat's late results, kept in the session store. An item
3
+ * is a detached call that ended; the transcript says whether a saved reply told it, and the
4
+ * session keeps who holds the chat and which replies were handed what.
5
+ *
6
+ * @module
7
+ */
8
+ /** The operation ids a chat's saved replies told, and those its paused reply holds. */
9
+ function transcriptState(conversation) {
10
+ const told = new Set();
11
+ const detached = [];
12
+ for (const block of conversation?.transcript ?? []) {
13
+ if (block.kind === 'late-results')
14
+ for (const id of block.operationIds)
15
+ told.add(id);
16
+ if (block.kind === 'tool' && block.tool.state?.phase === 'background' && block.tool.operationId)
17
+ detached.push(block.tool.operationId);
18
+ }
19
+ const paused = new Set();
20
+ for (const event of conversation?.paused?.events ?? []) {
21
+ if (event.type === 'late_results')
22
+ for (const id of event.operationIds)
23
+ paused.add(id);
24
+ }
25
+ return {
26
+ told,
27
+ paused,
28
+ pausedReply: conversation?.paused?.reply,
29
+ untold: detached.filter((id) => !told.has(id)),
30
+ };
31
+ }
32
+ function settledOperation(state, id) {
33
+ const operation = Object.hasOwn(state.operations, id) ? state.operations[id] : undefined;
34
+ return operation?.status === 'settled' ? operation : undefined;
35
+ }
36
+ /** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
37
+ export function sessionConversationInbox(options) {
38
+ const { sessions, sessionId, leaseMs } = options;
39
+ const now = options.now ?? Date.now;
40
+ const inboxOf = (state, key) => {
41
+ state.inbox ??= { version: 0, conversations: {} };
42
+ const conversations = state.inbox.conversations;
43
+ if (!Object.hasOwn(conversations, key))
44
+ conversations[key] = { leasedUntil: 0, entries: {} };
45
+ return conversations[key];
46
+ };
47
+ const has = (inbox, hold, at) => inbox.hold === hold && inbox.leasedUntil > at;
48
+ /** Handed to a reply whose hold still has the chat. */
49
+ const heldLive = (inbox, entry, at) => entry.handed !== undefined && has(inbox, entry.handed.hold, at);
50
+ const entryOf = (inbox, id) => {
51
+ if (!Object.hasOwn(inbox.entries, id))
52
+ inbox.entries[id] = { handovers: [] };
53
+ return inbox.entries[id];
54
+ };
55
+ const item = (operation, entry) => ({
56
+ id: operation.operationId,
57
+ kind: 'late_result',
58
+ handovers: [...(entry?.handovers ?? [])],
59
+ outcome: operation.outcome,
60
+ });
61
+ const handTo = (entry, hold, handover, at) => {
62
+ // invariant: A reply that lost its hold never gave its item back: what it was handed counts as a handover.
63
+ if (entry.handed)
64
+ entry.handovers.push(entry.handed);
65
+ entry.handed = { ...handover, hold, at };
66
+ };
67
+ /** The untold results no live hold has and no paused reply keeps, as this request may read them. */
68
+ const readableIds = async (key) => {
69
+ const conversation = await options.conversation(key);
70
+ const chat = transcriptState(conversation);
71
+ return { chat, ids: chat.untold.filter((id) => !chat.paused.has(id)) };
72
+ };
73
+ const waiting = (inbox, state, id, at) => {
74
+ const operation = settledOperation(state, id);
75
+ if (!operation)
76
+ return undefined;
77
+ const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
78
+ if (entry?.givenUp || (entry && heldLive(inbox, entry, at)))
79
+ return undefined;
80
+ return operation;
81
+ };
82
+ const authorized = async (operations) => {
83
+ const kept = [];
84
+ for (const operation of operations)
85
+ if (await options.readable(operation))
86
+ kept.push(operation);
87
+ return kept;
88
+ };
89
+ /** Changes one chat's lock and entries in one session write. */
90
+ const change = (key, apply) => sessions.mutate(sessionId, (state) => apply(inboxOf(state, key), state, now()));
91
+ /** Acts on each of `ids` that waits, only while `hold` has the chat; returns those it acted on. */
92
+ const actOnWaiting = async (key, hold, ids, act) => {
93
+ const { ids: open } = await readableIds(key);
94
+ const wanted = ids.filter((id) => open.includes(id));
95
+ return change(key, (inbox, state, at) => {
96
+ if (!has(inbox, hold, at))
97
+ return [];
98
+ return wanted.flatMap((id) => {
99
+ const operation = waiting(inbox, state, id, at);
100
+ if (!operation)
101
+ return [];
102
+ const entry = entryOf(inbox, id);
103
+ act(entry, at);
104
+ return [item(operation, entry)];
105
+ });
106
+ });
107
+ };
108
+ const lease = (inbox, hold, at) => {
109
+ inbox.hold = hold;
110
+ inbox.leasedUntil = at + leaseMs;
111
+ };
112
+ return {
113
+ open(key, hold) {
114
+ return change(key, (inbox, _state, at) => {
115
+ if (inbox.hold !== undefined && inbox.hold !== hold && inbox.leasedUntil > at) {
116
+ return { outcome: 'held', leasedUntil: inbox.leasedUntil };
117
+ }
118
+ lease(inbox, hold, at);
119
+ return { outcome: 'opened' };
120
+ });
121
+ },
122
+ takeOver(key, hold) {
123
+ return change(key, (inbox, _state, at) => lease(inbox, hold, at));
124
+ },
125
+ renew(key, hold) {
126
+ return change(key, (inbox, _state, at) => {
127
+ if (!has(inbox, hold, at))
128
+ return false;
129
+ lease(inbox, hold, at);
130
+ return true;
131
+ });
132
+ },
133
+ async read(key) {
134
+ const { ids } = await readableIds(key);
135
+ const state = await sessions.read(sessionId);
136
+ const inbox = state.inbox?.conversations[key] ?? { leasedUntil: 0, entries: {} };
137
+ const at = now();
138
+ const found = ids.flatMap((id) => {
139
+ const operation = waiting(inbox, state, id, at);
140
+ return operation ? [operation] : [];
141
+ });
142
+ const items = (await authorized(found)).map((operation) => item(operation, inbox.entries[operation.operationId]));
143
+ return { items, version: String(state.inbox?.version ?? 0) };
144
+ },
145
+ hand(key, hold, handover, ids) {
146
+ return actOnWaiting(key, hold, ids, (entry, at) => handTo(entry, hold, handover, at));
147
+ },
148
+ async giveBack(key, hold, reply, ids) {
149
+ const { chat } = await readableIds(key);
150
+ await change(key, (inbox) => {
151
+ for (const id of ids) {
152
+ const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
153
+ if (entry?.handed?.hold !== hold || entry.handed.reply !== reply)
154
+ continue;
155
+ if (chat.told.has(id)) {
156
+ delete inbox.entries[id];
157
+ continue;
158
+ }
159
+ entry.handovers.push(entry.handed);
160
+ delete entry.handed;
161
+ }
162
+ });
163
+ },
164
+ async resume(key, hold, paused, handover) {
165
+ const { chat } = await readableIds(key);
166
+ if (chat.pausedReply !== paused)
167
+ return [];
168
+ return change(key, (inbox, state, at) => {
169
+ if (!has(inbox, hold, at))
170
+ return [];
171
+ return [...chat.paused].flatMap((id) => {
172
+ const operation = settledOperation(state, id);
173
+ const entry = entryOf(inbox, id);
174
+ if (!operation || heldLive(inbox, entry, at))
175
+ return [];
176
+ handTo(entry, hold, handover, at);
177
+ return [item(operation, entry)];
178
+ });
179
+ });
180
+ },
181
+ giveUp(key, hold, ids) {
182
+ return actOnWaiting(key, hold, ids, (entry) => {
183
+ if (entry.handed)
184
+ entry.handovers.push(entry.handed);
185
+ delete entry.handed;
186
+ entry.givenUp = true;
187
+ });
188
+ },
189
+ release(key, hold, version) {
190
+ return change(key, (inbox, state) => {
191
+ if (inbox.hold !== hold)
192
+ return 'lost';
193
+ if (String(state.inbox?.version ?? 0) !== version)
194
+ return 'moved';
195
+ delete inbox.hold;
196
+ inbox.leasedUntil = 0;
197
+ return 'released';
198
+ });
199
+ },
200
+ };
201
+ }
@@ -28,6 +28,8 @@ export type PausedReply = {
28
28
  model?: string;
29
29
  effort?: string;
30
30
  stated?: StatedTurn;
31
+ /** The reply's id under its chat's hold, so the reply that goes on after its gates resumes what it read. */
32
+ reply?: string;
31
33
  };
32
34
  /** One conversation as the host stores it. */
33
35
  export type StoredConversation = {
@@ -23,6 +23,7 @@ const pausedReply = z.object({
23
23
  model: z.string().optional(),
24
24
  effort: z.string().optional(),
25
25
  stated: statedTurnSchema.optional(),
26
+ reply: z.string().min(1).optional(),
26
27
  });
27
28
  true;
28
29
  const storedConversation = z.object({
@@ -122,19 +122,7 @@ export type ReplyTurn = {
122
122
  stated?: StatedTurn;
123
123
  /** The tools and steps the reply had when it paused, for a reply that goes on. */
124
124
  carried?: ReplyCarried;
125
- /** The conversation's detached calls whose results its model has not read yet. */
126
- unread?: DetachedCall[];
127
125
  };
128
- /** A call that detached in a conversation: the operation the session keeps its end under. */
129
- export type DetachedCall = {
130
- callId: string;
131
- operationId: string;
132
- };
133
- /**
134
- * The calls a wake would read: none while a reply waits on gates or answers a message just posted.
135
- * invariant: A wake never runs beside a reply, so it never takes a person's message from one.
136
- */
137
- export declare function wakeableCalls(conversation: StoredConversation): DetachedCall[];
138
126
  /** What a reply's model run takes from the host. */
139
127
  export type ReplyRunner = {
140
128
  /** The reply's events for one run (`runTurn` with the host's own options). */
@@ -149,6 +137,13 @@ export type ReplyRunner = {
149
137
  stated?: StatedTurn;
150
138
  carried?: ReplyCarried;
151
139
  signal: AbortSignal;
140
+ /** The reply's id under its chat's hold: a paused reply keeps it, so the reply that goes on resumes what it read. */
141
+ reply?: string;
142
+ /**
143
+ * Whether the reply's hold still has its chat, asked before each save. A reply that lost it saves
144
+ * nothing: the hold that took the chat tells what it read.
145
+ */
146
+ held?: () => Promise<boolean>;
152
147
  };
153
148
  /** A line of a reply's stream: an event, or the ref of what the store wrote. */
154
149
  export type ReplyLine = TurnEvent | ConversationLine;
@@ -149,31 +149,6 @@ function refLine(opened, posted) {
149
149
  return [];
150
150
  return [{ type: 'conversation', ref: opened.ref, ...(posted ? { posted: true } : {}) }];
151
151
  }
152
- /**
153
- * The conversation's detached calls that no late-results block names.
154
- * invariant: The transcript is the record of what the model read, so a result is fed once.
155
- */
156
- function unreadDetachedCalls(transcript) {
157
- const read = new Set(transcript.flatMap((block) => (block.kind === 'late-results' ? block.operationIds : [])));
158
- return transcript.flatMap((block) => block.kind === 'tool' &&
159
- block.tool.state?.phase === 'background' &&
160
- block.tool.operationId &&
161
- !read.has(block.tool.operationId)
162
- ? [{ callId: block.tool.callId, operationId: block.tool.operationId }]
163
- : []);
164
- }
165
- /**
166
- * The calls a wake would read: none while a reply waits on gates or answers a message just posted.
167
- * invariant: A wake never runs beside a reply, so it never takes a person's message from one.
168
- */
169
- export function wakeableCalls(conversation) {
170
- if (conversation.paused)
171
- return [];
172
- const last = conversation.transcript.at(-1);
173
- if (!last || last.kind.startsWith('user-'))
174
- return [];
175
- return unreadDetachedCalls(conversation.transcript);
176
- }
177
152
  /** The model's history once the reply's events enter it. */
178
153
  function replyHistory(reply) {
179
154
  return appendAssistantEventsToHistory(reply.base, reply.events.slice(reply.baseEvents));
@@ -219,12 +194,21 @@ function pausedOn(conversation, reply, runner) {
219
194
  ...(runner.model ? { model: runner.model } : {}),
220
195
  ...(runner.effort ? { effort: runner.effort } : {}),
221
196
  ...(runner.stated ? { stated: runner.stated } : {}),
197
+ ...(runner.reply ? { reply: runner.reply } : {}),
222
198
  };
223
199
  return { ...conversation, ...metered(conversation, reply.events), paused };
224
200
  }
225
- /** The reply failed: it commits as far as it got, closed by its error. */
201
+ /**
202
+ * The reply failed: it commits as far as it got, closed by its error. The late results it read
203
+ * leave with it, so a later reply tells them.
204
+ */
226
205
  function failed(host, conversation, reply, failure) {
227
- const next = committed(host, conversation, reply);
206
+ const unread = (events) => events.filter((event) => event.type !== 'late_results');
207
+ const next = committed(host, conversation, {
208
+ ...reply,
209
+ events: unread(reply.events),
210
+ baseEvents: unread(reply.events.slice(0, reply.baseEvents)).length,
211
+ });
228
212
  if (next.transcript.slice(conversation.transcript.length).some((b) => b.kind === 'error')) {
229
213
  return next;
230
214
  }
@@ -252,8 +236,9 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
252
236
  const { conversation } = opened;
253
237
  const startedAt = Date.now();
254
238
  const worked = () => ({ ...reply, workedMs: reply.workedMs + (Date.now() - startedAt) });
239
+ // invariant: A reply whose hold lost its chat saves nothing; the hold that has it tells what this one read.
240
+ const held = async () => !runner.held || (await runner.held());
255
241
  let errorEvent;
256
- let current = opened;
257
242
  try {
258
243
  const events = runner.run({
259
244
  input,
@@ -263,8 +248,6 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
263
248
  effort: runner.effort,
264
249
  ...(runner.stated ? { stated: runner.stated } : {}),
265
250
  ...(runner.carried ? { carried: runner.carried } : {}),
266
- // why: Late results open a reply; a reply that goes on after a pause reads them on the next one.
267
- ...(runner.carried ? {} : { unread: unreadDetachedCalls(conversation.transcript) }),
268
251
  });
269
252
  for await (const event of events) {
270
253
  reply.events.push(event);
@@ -281,37 +264,40 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
281
264
  }
282
265
  }
283
266
  catch (err) {
284
- current = await save(host, current, runner.signal.aborted
285
- ? stopped(host, conversation, worked())
286
- : failed(host, conversation, worked(), toErrorEvent(err)));
287
- yield* refLine(current);
267
+ if (await held()) {
268
+ const written = await save(host, opened, runner.signal.aborted
269
+ ? stopped(host, conversation, worked())
270
+ : failed(host, conversation, worked(), toErrorEvent(err)));
271
+ yield* refLine(written);
272
+ }
288
273
  // why: A stopped reply is no failure; the browser draws what it left from the ref.
289
274
  if (!runner.signal.aborted)
290
275
  throw err;
291
276
  return;
292
277
  }
293
278
  const settled = worked();
279
+ if (!(await held()))
280
+ return;
294
281
  if (runner.signal.aborted) {
295
- current = await save(host, current, stopped(host, conversation, settled));
282
+ yield* refLine(await save(host, opened, stopped(host, conversation, settled)));
296
283
  }
297
284
  else if (errorEvent) {
298
- current = await save(host, current, failed(host, conversation, settled, errorEvent));
285
+ yield* refLine(await save(host, opened, failed(host, conversation, settled, errorEvent)));
286
+ yield errorEvent;
299
287
  }
300
288
  else if (gatedToolsFromEvents(settled.events).length) {
301
- current = await save(host, current, pausedOn(conversation, settled, runner));
289
+ yield* refLine(await save(host, opened, pausedOn(conversation, settled, runner)));
302
290
  }
303
291
  else {
304
- current = await save(host, current, committed(host, conversation, settled));
292
+ const current = await save(host, opened, committed(host, conversation, settled));
305
293
  yield* refLine(current);
306
294
  // why: The reply is the browser's before compaction runs, so a failed compaction loses none of it.
295
+ if (!(await held()))
296
+ return;
307
297
  const compacted = await compactedAfter(host, current, settled, runner, withMessage);
308
298
  if (compacted)
309
299
  yield* refLine(compacted);
310
- return;
311
300
  }
312
- yield* refLine(current);
313
- if (errorEvent)
314
- yield errorEvent;
315
301
  }
316
302
  /**
317
303
  * The profile compacts after a reply (`done.compaction.needed`): the history
@@ -526,6 +512,8 @@ export async function* answerReply(args) {
526
512
  // why: An answer that failed before its call settled leaves the reply as it was, to answer again.
527
513
  const settledCall = reply.events.some((event) => settlesToolCall(event, args.call.callId));
528
514
  const events = error && !settledCall ? paused.events : reply.events;
515
+ if (runner.held && !(await runner.held()))
516
+ return;
529
517
  opened = await save(host, opened, {
530
518
  ...opened.conversation,
531
519
  paused: { ...paused, events, workedMs: reply.workedMs, endedAt: Date.now() },
@@ -155,9 +155,16 @@ export type TheoremHandlerOptions = {
155
155
  }) => boolean | Promise<boolean>;
156
156
  /**
157
157
  * Who tells the model that a background call ended: `TurnWiring.lateResultsDecider`. Unset, no
158
- * page wakes the chat and no reply reads a late result. `pageWakes` lets the open page wake it.
158
+ * page wakes the chat and no reply reads a late result. `tellEveryResult` tells each result to
159
+ * the first reply that runs, and lets the open page wake the chat.
159
160
  */
160
161
  lateResultsDecider?: TurnWiring['lateResultsDecider'];
162
+ /**
163
+ * How long a reply keeps its chat after it last renewed, in milliseconds: it renews every third
164
+ * of it while it runs. A wake the chat turned away tries again once this runs out, and a reply
165
+ * that stopped without letting go keeps the chat no longer. Default 60000.
166
+ */
167
+ conversationLeaseMs?: number;
161
168
  /**
162
169
  * Tool credentials by session. Your OAuth callback route saves the token here
163
170
  * under the same session id; every turn reads from here. Default: in-process
@@ -191,7 +198,7 @@ export type TheoremHandlerOptions = {
191
198
  }) => void;
192
199
  };
193
200
  /** A host profile runs no model, and takes no turns to steer. */
194
- export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'steerInbox' | 'conversationStore' | 'prepare' | 'notifier' | 'notifyRetryMs'> & {
201
+ export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'steerInbox' | 'conversationStore' | 'prepare' | 'notifier' | 'notifyRetryMs' | 'conversationLeaseMs'> & {
195
202
  /** Host profile to serve. Registered with the kernel when the handler is created. */
196
203
  profile: Extract<Profile, {
197
204
  type: 'host';