@theoremjs/web 0.3.4 → 0.3.5-next.1001.g68d8dcf

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 (59) hide show
  1. package/README.md +330 -13
  2. package/client/chat.d.ts +14 -2
  3. package/client/chat.js +302 -34
  4. package/client/composer-hints.d.ts +18 -10
  5. package/client/composer-hints.js +23 -6
  6. package/client/host-transport.d.ts +7 -2
  7. package/client/host-transport.js +9 -3
  8. package/client/index.d.ts +4 -4
  9. package/client/index.js +3 -3
  10. package/client/page-dispatch.js +5 -0
  11. package/client/run-session.d.ts +27 -2
  12. package/client/run-session.js +34 -4
  13. package/client/schema-fields.d.ts +28 -1
  14. package/client/schema-fields.js +172 -13
  15. package/client/tool-result.d.ts +9 -5
  16. package/client/tool-result.js +23 -42
  17. package/client/transcript-schema.d.ts +4 -0
  18. package/client/transcript-schema.js +25 -6
  19. package/client/transport.d.ts +90 -9
  20. package/client/transport.js +56 -11
  21. package/client/turn-client.d.ts +8 -2
  22. package/client/turn-client.js +9 -0
  23. package/package.json +2 -2
  24. package/server/conversation-core.d.ts +273 -0
  25. package/server/conversation-core.js +797 -0
  26. package/server/conversation-inbox.d.ts +45 -0
  27. package/server/conversation-inbox.js +240 -0
  28. package/server/conversation-store.d.ts +43 -2
  29. package/server/conversation-store.js +15 -2
  30. package/server/conversation.d.ts +82 -2
  31. package/server/conversation.js +357 -60
  32. package/server/create-conversation-core.d.ts +28 -0
  33. package/server/create-conversation-core.js +46 -0
  34. package/server/embedding-handler.js +2 -0
  35. package/server/handler.d.ts +84 -20
  36. package/server/handler.js +279 -659
  37. package/server/mcp-handler.js +25 -11
  38. package/server/mod.d.ts +11 -4
  39. package/server/mod.js +6 -2
  40. package/server/notifier.d.ts +3 -2
  41. package/server/notifier.js +3 -2
  42. package/server/session-authority.d.ts +3 -1
  43. package/server/session-authority.js +26 -1
  44. package/server/session-boundary.d.ts +5 -3
  45. package/server/session-boundary.js +2 -2
  46. package/server/session-calls.d.ts +122 -0
  47. package/server/session-calls.js +512 -0
  48. package/server/session-store.d.ts +33 -0
  49. package/server/session-store.js +37 -2
  50. package/server/steer-inbox.d.ts +3 -4
  51. package/server/steer-inbox.js +6 -5
  52. package/server/tell-every-result.d.ts +11 -0
  53. package/server/tell-every-result.js +17 -0
  54. package/server/tool-operations.d.ts +8 -0
  55. package/server/tool-operations.js +71 -0
  56. package/server/turn-input.d.ts +4 -2
  57. package/server/turn-input.js +5 -2
  58. package/server/turn-wiring.d.ts +31 -6
  59. package/server/turn-wiring.js +59 -5
package/README.md CHANGED
@@ -103,7 +103,7 @@ export const mcp = createTheoremMcpHandler({ profile: docsTools, version: '1.0.0
103
103
 
104
104
  - `tools/list` gives each allowed tool with its input schema. A tool's `access` becomes the read-only and destructive hints of MCP.
105
105
  - Clients of the current revision may cache the tool list for 5 minutes and the discovery result for an hour. Neither holds anything about the caller, so a shared cache may keep them.
106
- - `tools/call` runs the tool through the gates, the guardrails, and the trace of the kernel. The client receives the text a model would read, not the raw output.
106
+ - `tools/call` runs the tool through the gates, the guardrails, and the trace of the kernel. The client receives the text and media a model would read, not the raw output. A reference a tool returned, which no model reads, is left out. So is all the media of a hidden tool (`exposeToModel: false`), whose model reads only that the call completed.
107
107
  - A tool that fails returns a result marked `isError`, so the model can read it and try again.
108
108
  - No one can approve a call over MCP. The handler refuses a profile when an allowed tool has a permission other than `auto`.
109
109
  - A browser page on another origin is refused unless `origins` lists it.
@@ -133,7 +133,7 @@ const open = parseLiveOpenMessage(firstFrame);
133
133
  const session = await runSession(
134
134
  {
135
135
  profile,
136
- ...await boundary.prepareLiveOpen(open, hostContext),
136
+ ...await boundary.prepareLiveOpen(open, profile, hostContext),
137
137
  execution: boundary.toolExecution,
138
138
  pageExecution: boundary.pageExecution,
139
139
  },
@@ -148,7 +148,8 @@ for await (const event of session.events()) {
148
148
  ```
149
149
 
150
150
  - `prepareLiveOpen` returns validated history, options, context, native state, and absence duration. It removes system-role history.
151
- - Its second argument supplies server context. Browser context stays under `client`.
151
+ - Its second argument is the profile the call opens on. A model or effort the page picks is refused unless that profile sets `allowModelSelect` (or the binding's `allowEffortSelect`).
152
+ - Its third argument supplies server context. Browser context stays under `client`.
152
153
  - Save checkpoint ownership before you send the event. If storage fails, close the session without advertising that checkpoint.
153
154
  - The boundary refuses native resumption while a saved operation is ready, running, or uncertain. It does not repeat the operation.
154
155
  - Without a session resolver, the boundary uses an anonymous cookie. Forward its `setCookie` value in the upgrade response.
@@ -206,13 +207,16 @@ await chat.submit();
206
207
  - `update(options)` gives the controller your latest options, such as a new `context`, `options`, or `pageTools`. Each turn reads the options as they are when it is sent. `conversation`, `conversationView`, `initialText`, `initialFiles`, `initialVoice`, and `initialPending` are read only when the controller is created.
207
208
  - A live call takes `stated` in its options, and `setStated(stated)` changes it during the call. As with `setOptions`, the call is taken up again with the prompt lines the new value chooses.
208
209
  - Each method is bound to the controller. Pass it as a callback as it is.
210
+ - `state.delivery` says how far the latest message has got: `sending` while it posts, `sent` once the server has it, `delivered` once the model works on it, and `read` once the reply starts. The server's own events (`stage`, `guardrail`, `late_results`, `session`, `hook_failed`, `error`, `done`) leave it at `sent`, because they say nothing of the model. It is `null` before the first message and after its turn fails.
209
211
 
210
- `state.phase` is `'idle'`, `'streaming'`, or `'gated'`. The methods for the composer depend on it:
212
+ `state.phase` is `'idle'`, `'streaming'`, or `'gated'`. At `'gated'`, the reply waits on a tool gate. `state.waitingGate` is that gate when the person must answer it: a confirmation, a permission or a sign-in. It is `null` at other times, and for a page gate, which the page answers.
213
+
214
+ The methods for the composer depend on the phase:
211
215
 
212
216
  | Method | What it does |
213
217
  | --- | --- |
214
218
  | `submit()` | At `idle`, sends the draft. Otherwise, queues it. |
215
- | `enqueue('steer')` | Sends the draft to the running turn with `transport.steer`. The steer leaves `pendingMessages` when the turn's `stage` event names it in `injected`, and joins the transcript there, between the reply before it and the reply after. A steer the turn never takes waits at the front of the queue. |
219
+ | `enqueue('steer')` | Sends the draft to the running turn with `transport.steer`. The steer leaves `pendingMessages` when the turn's `stage` event names it in `injected`, and joins the transcript there, between the reply before it and the reply after. A steer the turn never takes waits at the front of the queue. When the host saves the steer itself (`intake`), the steer stays in `pendingMessages` with `saved` set, and the page does not send it again. See [Messages the host saved](#messages-the-host-saved). |
216
220
  | `enqueue('queue')` | Keeps the draft to send after the reply. When the reply ends without a failure and no gate waits, the first queued message is sent. |
217
221
  | `enqueue('stash')` | Keeps the draft without sending it. `queuePending(id)` moves it to the queue. |
218
222
  | `pend(message)` | Steers, queues, or stashes a message you made with `createComposerPendingMessage`, as `enqueue` does the draft. A message queued on an idle chat sends at once. A composer shared by several chats gives each the same message, so its id names it in all of them. |
@@ -224,6 +228,19 @@ await chat.submit();
224
228
  | `branch(index)` | Cuts the conversation after transcript block `index`. |
225
229
  | `sendText(text, options?)` | Sends a message from your code. `options` can add `files`, `voice`, a `model` and its `effort`. The model becomes the chat's pick, as if chosen in the composer. An `effort` without a `model` applies to the chat's current model. A model the profile does not have is refused by the turn, not replaced by the default. It resolves with the blocks the turn added, or `null` when the chat cannot take a message now. |
226
230
 
231
+ ### Messages the host saved
232
+
233
+ A host with `intake` saves each message before a reply runs. When another reply holds the conversation, the host saves the message and runs nothing. The controller then keeps the message in `pendingMessages`, as kind `steer`, with `saved: { landsAs }`. `landsAs` is the ids a reply names the message by when it reads it.
234
+
235
+ - The page cannot edit, move, send, or remove a saved message. The host has it.
236
+ - The message leaves `pendingMessages` when a reply reads it, and joins the transcript before that reply.
237
+ - The message also leaves when a conversation read shows one of its blocks.
238
+ - `saveComposerPendingMessage` and `takeSavedComposerPending` from `@theoremjs/agents/interface` make these two changes for a controller of your own.
239
+
240
+ With `intake`, each `/turn` and each `/steer` carries an `id`: the pending message's id, or a new one. The host saves a message one time for each `id`, so a request sent twice saves one message.
241
+
242
+ After a wake that fails, that the person stops, or that runs nothing, the page does not wake again by itself. The next conversation read can ask for a wake.
243
+
227
244
  The controller uses these methods of the transport: `turn`, `invoke` (to answer a gate), `steer`, `stop`, `conversation`, and `rewind`. `conversation` and `rewind` are called only for a profile whose host keeps the conversation. `pageResult` is called when the reply hands a tool to the page.
228
245
 
229
246
  The controller writes no English text. The helpers below give the composer's controls as values, and you choose the words:
@@ -233,7 +250,7 @@ The controller writes no English text. The helpers below give the composer's con
233
250
  | `composerActionState(args)` | The primary button (`send`, `queue`, `stop`, or `none`), the send menu, and whether the button is off. |
234
251
  | `composerDrawerSummary(args)` | The count of waiting messages by kind, for a collapsed drawer. |
235
252
  | `resolveComposerHint(args)` | The stash hint, when the whole draft is selected. |
236
- | `isStashShortcut(event)` | Whether a key press is the stash shortcut, `STASH_SHORTCUT`. |
253
+ | `composerShortcut(event)` | The send-menu action a key press asks for: ⌘↵ steers, ⌘⇧↵ sends now, ⌘⇧S stashes; `null` otherwise. `COMPOSER_SHORTCUTS` has each action's key for `Kbd`. |
237
254
 
238
255
  ## A custom browser transport
239
256
 
@@ -263,17 +280,22 @@ const transport = withPageToolDispatch(
263
280
  | `profile` | The profile to serve. The kernel registers it when you create the handler. |
264
281
  | `provider` | Host options, including the credential vault. A function can return these options per request, for example for tenant-specific credentials. |
265
282
  | `session` | Returns the session id of the caller, for example `${userId}:${conversationId}`. Return `undefined` to refuse the request with a 401. Default: a random id in an HttpOnly, SameSite=Lax cookie that lasts 30 days. |
266
- | `host` | App data for the tool handlers (`ctx.host`), such as the signed-in user. |
267
- | `prepare` | Your app's own turn, from the one the handler builds (`TurnWiring.prepare` from `@theoremjs/agents`). Set what your app sets per turn, such as `system`, `credentials`, `onStage`, `onEvent` and `onAgentCall`; read your app data as `turn.host`. The handler keeps its profile, its tool execution and its abort. Your `onStage` runs before the handler's steering, and your `credentials` are read before the session's. A call held at a gate runs on, once answered, with the `host`, `onStage` and `credentials` you give for that call's turn; that turn has `answersHeldCall`, and its `onEvent` is not called, because no new turn runs. |
283
+ | `host` | App data for the tool handlers (`ctx.host`), such as the signed-in user. The handler asks it one time for each run, when the run first reads it. |
284
+ | `prepare` | Your app's own turn, from the one the handler builds (`TurnWiring.prepare` from `@theoremjs/agents`). Set what your app sets per turn, such as `system`, `credentials`, `onStage`, `onEvent` and `onAgentCall`; read your app data as `turn.host`. The handler keeps its profile and its abort. Your `onStage` runs before the handler's steering, and your `credentials` are read before the session's. An `execution` you return decides each call, and the session still records the same call; a `background` you return takes the place of the `background` option. A call held at a gate runs on, once answered, with the `host`, `onStage`, `credentials`, `execution` and `background` you give for that call's turn; that turn has `answersHeldCall`, and its `onEvent` is not called, because no new turn runs. |
285
+ | `inbox`, `beforeSave`, `afterSave`, `compact` | Your app's own inbox and your steps around each save, as [the conversation core](#run-replies-with-no-page-request) takes them. Each is given the request's context: its `host` is what `host` returned for the request, so `await at.host`. With `inbox`, every reply the page starts runs under a hold of your conversation, and a wake tells the items that wait in it. A steer still reaches the running reply itself, and does not arrive in your inbox, unless you set `intake`. Do not set `inbox` with `lateResultsDecider`. |
268
286
  | `onStage` | The server's own stage handler, on every call the handler runs, a host profile's included: after your app's (`prepare`), before steering. For a rule the server adds to whatever the app says, such as a question before each tool that writes. |
269
287
  | `pageToolBroker` | Delivers results to active page dispatches. Default: bounded process memory. |
270
288
  | `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. |
271
289
  | `conversationStore` | Where the conversation is kept. Required, except for a stateless profile, which must not have one. See [Keep the conversation](#keep-the-conversation). |
272
290
  | `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`. |
291
+ | `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, and gives up a result two replies read without telling. See [the background section](#share-session-authority). |
292
+ | `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`. |
293
+ | `onContinue` | Who runs the next reply when a reply ends with items that wait and may be told now. Return `'here'`, and the handler runs it in the same response. Return `'taken'`, and your app runs it with the conversation core's `followUp`. Unset, the handler lets the chat go, and the page wakes it. |
294
+ | `intake` | Your app's own save of each message the page sends, on `/turn` and `/steer`. Set it when a message must be in your database before any reply runs. Needs `inbox`. See [Save a page's message in your own write](#save-a-pages-message-in-your-own-write). |
273
295
  | `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). |
274
296
  | `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
275
297
  | `authorizationUrl` | Returns the sign-in URL for an OAuth gate. Without it, an OAuth gate has no URL. |
276
- | `gateTtlMs` | How long a gate waits for an answer. A later answer fails with `session.gate_expired`, and the next message cancels the call. Unset, a gate waits until it is answered. |
298
+ | `gateTtlMs` | How long a gate waits for an answer. A later answer fails with `session.gate_expired`, and the next message or the next wake cancels the call. Unset, a gate waits until it is answered. |
277
299
  | `maxRequestBytes` | The largest browser request body, in bytes. Unset, a body of any size is read. |
278
300
  | `pageToolTimeoutMs` | How long the page has to answer a tool call it runs. A call it has not answered by then settles as timed out. Unset, the call waits until the page answers or the turn stops. The browser clients answer every call they get, so only a page function that never returns holds a turn. |
279
301
  | `operationRetentionMs` | How long a settled tool result is kept. Default: 24 hours. |
@@ -362,7 +384,9 @@ interface ConversationDatabase {
362
384
  - A null `ref` creates a conversation. Return a new opaque `ref` and `revision`.
363
385
  - Otherwise, write only while the stored revision is still `expectedRevision`, as one atomic operation. Return `{ written: false }` on a conflict.
364
386
  - Check what you read back with `storedConversationSchema`.
387
+ - A store that keeps each block in its own place (a row, a column) checks one block with `transcriptBlockSchema`.
365
388
  - Keep `id` as the handler gives it. It names the conversation in each turn's trace as `gen_ai.conversation.id`, and stays the same through every save and rewind.
389
+ - Set `running` on the snapshot while a reply runs on the conversation under a hold you keep. See [Show a reply that runs elsewhere](#show-a-reply-that-runs-elsewhere).
366
390
 
367
391
  ### Share session authority
368
392
 
@@ -455,8 +479,25 @@ To retain execution claims across connections, supply a durable coordinator as `
455
479
  Browser dispatch uses a host-owned `PageToolExecution` service beside the execution coordinator.
456
480
  `createTheoremHandler` supplies both services. Live relays put the session boundary's `pageExecution` and `toolExecution` on `SessionRequest`.
457
481
 
458
- A tool with a `background` setting runs inline until you pass the `background` option to `createTheoremHandler`. 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`.
459
- 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 nothing new: a late result still reaches it through `input.lateResults`.
482
+ 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`.
483
+ 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. With `inbox`, the read always tells the page to listen, because your app saves replies the page did not start: call `notifier.publish(sessionId)` after each one. The model reads the result only as your decider says.
484
+
485
+ 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 ended and no saved reply told it. When the session holds no end for the call (it dropped the settled operation, or marked the call `uncertain`), the result waits as an error with the code `outcome_not_retained` or the uncertainty's reason, and the model reads that the action is unresolved. `ended` hears that end too. A call `authorizeToolReplay` withholds from the request does not wait.
486
+
487
+ 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.
488
+
489
+ - `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.host` is the request's `host`, as `ended` gets it, so a policy can keep one person's quiet hours. `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`.
490
+ - `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.
491
+
492
+ `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. A result that two replies read and did not tell (the model failed, or the reply lost the chat) is given up and reported once as `late_results_given_up`, so a model that keeps failing does not reply again and again. Write your own to keep a count, such as a cap or quiet hours, or to reply from the server.
493
+
494
+ 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 that the person can still answer: the reply that goes on after the answer reads what waits. With `gateTtlMs` set, a wake that finds every gate of the reply past its limit cancels those calls as expired, and then runs. The model reads `sign_in.expired` for a sign-in and `session.gate_lapsed` for any other gate. 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. When the wake was already saving its reply as the message read the chat, the message posts after that reply. When that reply stopped on an approval, the message fails with `session.gate_pending`, and the approval waits.
495
+
496
+ 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`).
497
+
498
+ 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.
499
+
500
+ To wake from the server, call `wake` with the conversation's current reference. Your `conversationStore` must keep that reference across writes: the reference of `createSealedConversationStore` is the sealed conversation itself, so each write gives a new one, which only the page holds. The reply runs with the headers of the request that started the call and no signal, because that request has ended.
460
501
 
461
502
  `createMemoryNotifier` reaches only pages connected to the process that ran the call. On more than one instance, give a shared `TheoremNotifier`. Your sweep calls `publish` with the session id after it marks a call `worker_lost`, because that write does not pass through the handler. Hosting platforms cut long responses. Set `notifyRetryMs` so that the page reopens the stream after that wait. Unset, the page does not reopen it, and reads the end on its next turn or reload.
462
503
 
@@ -468,9 +509,284 @@ Use `pageToolBroker` to supply that broker. It carries results; the atomic sessi
468
509
  Lost result delivery does not permit another dispatch. The operation retains its claim or an uncertain outcome.
469
510
  Set `pageToolTimeoutMs` to give the page a deadline for a result. Unset, a dispatch waits until the page answers or the turn stops. The browser clients answer every dispatch they get, with no answer when the page has no function for the tool, so only a page function that never returns holds a turn. An expired or interrupted result cannot reopen approval.
470
511
 
512
+ ## Run replies with no page request
513
+
514
+ Use `createTheoremConversationCore` when a message reaches your server with no `Request` from a page: a messaging channel, a voice channel, or a timer. The core runs the replies that `createTheoremHandler` runs, on the same stores. A page that uses the handler reads the same conversation.
515
+
516
+ Each call takes a **run context** where the handler takes the `Request`: `{ sessionId, signal, host? }`. `sessionId` names the session, `signal` aborts the run, and `host` is your context for tool handlers.
517
+
518
+ ```ts
519
+ import { createMemoryConversationStore, createTheoremConversationCore } from '@theoremjs/web/server';
520
+
521
+ const core = createTheoremConversationCore({
522
+ profile: support,
523
+ provider: { vault: { main: process.env.GEMINI_API_KEY } },
524
+ conversationStore: createMemoryConversationStore(),
525
+ });
526
+
527
+ async function received(sessionId: string, text: string, ref: string | undefined, signal: AbortSignal) {
528
+ const reply = await core.message({ sessionId, signal }, { ...(ref ? { ref } : {}), input: { text } });
529
+ for (;;) {
530
+ const next = await reply.next();
531
+ if (next.done) return next.value;
532
+ deliver(next.value);
533
+ }
534
+ }
535
+ ```
536
+
537
+ `deliver` is your function: it sends one line to the channel. A run yields the lines that the handler streams. The `conversation` line carries the ref: keep it, and pass it with the next message. The run then returns how it ended:
538
+
539
+ | `outcome` | Meaning |
540
+ | --- | --- |
541
+ | `released` | The run ended, and no run holds the conversation. |
542
+ | `continue` | Items wait that a reply may be told now. The run's `hold` still has the conversation under `ref`. See [Run the follow-up](#run-the-follow-up). |
543
+ | `held` | Another run holds the conversation until `leasedUntil`. This run ran nothing. |
544
+ | `lost` | Another run took the conversation from this run. |
545
+
546
+ | Method | Use |
547
+ | --- | --- |
548
+ | `message(at, { ref?, input, context?, generation?, abandon?, saved? })` | Posts the person's message and runs the reply. |
549
+ | `checkMessage(at, { ref?, input, context?, abandon? })` | Throws what `message` throws before it runs anything, and changes nothing. Call it before your app saves a message itself. |
550
+ | `answer(at, body)` | Answers a call that a paused reply waits on. |
551
+ | `wake(at, { ref })` | Runs a reply to no message, for items that arrived since the model last ran. |
552
+ | `followUp(at, { ref, hold })` | Runs the next reply to no message, under the hold of a run that ended `continue`. |
553
+ | `release(at, { ref, hold })` | Lets the conversation go under that hold, with no follow-up. |
554
+ | `read(at, { ref })` | Returns the conversation as a page draws it. |
555
+ | `rewind(at, { ref, at })` | Cuts the conversation after transcript block `at`. |
556
+ | `steer(at, { turnId, id, input })` | Puts `input` into a running turn. Returns `false` when the turn is not running. Throws what `message` throws for an `input` the profile does not take, such as text over `inputs.maxTextChars`. |
557
+ | `stop(at, { turnId } \| { conversation })` | Stops a running reply: the turn `turnId` names, or the reply that holds `conversation`. Returns `false` when it is not running. When your `inbox` has a `stop`, it stops the reply that holds the conversation, and reads neither. Without one, only `{ turnId }` reaches a turn, and `{ conversation }` throws `session.reply_unreachable`. |
558
+
559
+ The core takes these options from [Server options](#server-options), with the same meaning: `profile`, `onStage`, `sessionStore`, `conversationStore`, `credentialStore`, `gateTtlMs`, `operationRetentionMs`, `pageToolBroker`, `pageToolTimeoutMs`, `notifier`, `notifyRetryMs`, `lateResultsDecider`, `conversationLeaseMs`, `steerInbox`, and `clientEvents`. These options take the run context in place of the `Request`:
560
+
561
+ | Option | Use |
562
+ | --- | --- |
563
+ | `provider` | Required. The host options for registered providers, or `(at, model?)` that returns them. |
564
+ | `prepare(turn, run?)` | Your `TurnWiring.prepare`. With `inbox`, `run` is the reply's hold of your inbox. |
565
+ | `background(at)` | The service for tools with a `background` setting. |
566
+ | `authorizeToolReplay(at, operation)` | Checks access before the core discloses a saved tool result. |
567
+ | `authorizationUrl(challenge, at)` | The sign-in URL for an OAuth gate. |
568
+ | `onError(err, at)` | Receives each error that a run reports and does not throw. |
569
+ | `wake(at, ref)` | Required with `lateResultsDecider`. Start a reply to no message for the conversation under `ref`, for example with a queued call to `core.wake`. |
570
+ | `inbox(at)` | Your own inbox for the conversation. See below. |
571
+ | `beforeSave(at, reply)`, `afterSave(at, saved)`, `compact(at, signal)` | Your steps around the save that ends a reply. See [Shape the save that ends a reply](#shape-the-save-that-ends-a-reply). |
572
+
573
+ ### Hold the conversation in your own inbox
574
+
575
+ Use `inbox` when messages and events arrive from more than one place, and one reply at a time must run for a conversation. An **inbox** is a `ConversationInbox` from `@theoremjs/agents/conversation`: it holds the items that wait for a reply, and it gives one run at a time a hold of the conversation, on a lease.
576
+
577
+ `inbox(at)` returns `{ inbox, conversation, policy, leaseMs }`:
578
+
579
+ | Field | Use |
580
+ | --- | --- |
581
+ | `inbox` | Your `ConversationInbox`. `createMemoryInbox` is one for tests. |
582
+ | `conversation` | The name of the conversation in your inbox. |
583
+ | `policy` | Your `InboxPolicy`: which waiting items a reply is told, and which are given up. |
584
+ | `leaseMs` | How long a hold keeps the conversation after it last renewed, in milliseconds. |
585
+ | `stop` | Optional. Your `HoldStop`: a stop for the reply that holds the conversation. See [Stop a reply from any server](#stop-a-reply-from-any-server). |
586
+
587
+ Each run then holds `conversation` in your inbox while it runs. Your `prepare` receives that hold as `run`, a `ReplyRun`. `run.opened` is the items the reply reads as it opens. `run.take` returns the items that arrive while the reply runs. To tell the model an item, add it to the turn that `prepare` returns, or inject it from that turn's `onStage`.
588
+
589
+ A run that finds the conversation held returns `held` and runs nothing. A wake on a reply that waits on a gate also returns `held`, and `leasedUntil` is when the last gate lapses. When a gate has no time limit, the wake returns `released` and runs nothing. `read` answers `wake: true` when your policy tells a waiting item to a reply to no message.
590
+
591
+ ### Save the person's message in your own write
592
+
593
+ Use `saved` when your app saves each message when it arrives, before any reply runs. In that write, your app also takes the conversation in your inbox under a hold. Pass both to `message`:
594
+
595
+ ```ts
596
+ await core.message(at, { ref, input, saved: { hold, blocks } });
597
+ ```
598
+
599
+ `hold` is the hold your write took. `blocks` is the message as your app saved it, as transcript blocks. The core then posts nothing. The reply runs under `hold`, and the save that ends the reply writes `blocks` with the reply. When another run holds the conversation, the run returns `held` and writes nothing. `saved` needs `inbox`.
600
+
601
+ ### Save a page's message in your own write
602
+
603
+ Use `intake` on `createTheoremHandler` when the page's messages must be in your database before any reply runs. Then a message that arrives during a reply is not lost when the reply fails, and a message from the page waits in the same inbox as a message from any other channel.
604
+
605
+ ```ts
606
+ createTheoremHandler({
607
+ profile,
608
+ provider,
609
+ conversationStore,
610
+ inbox,
611
+ intake: async (at, sent) => {
612
+ const saved = await saveMessage(at.sessionId, sent.id, sent.ref, sent.message);
613
+ return saved.hold === undefined
614
+ ? { outcome: 'saved', ref: saved.ref, landsAs: saved.ids }
615
+ : { outcome: 'opened', ref: saved.ref, landsAs: saved.ids, hold: saved.hold, blocks: saved.blocks };
616
+ },
617
+ });
618
+ ```
619
+
620
+ The save that `intake` calls in this example is your function. In one write, it does three things:
621
+
622
+ 1. It saves the message under `sent.id`. A second call with the same `sent.id` saves nothing new.
623
+ 2. It puts the message in your inbox as an item.
624
+ 3. It takes the conversation under a hold, when no reply holds it.
625
+
626
+ `intake` returns a `MessageIntake`:
627
+
628
+ | Field | Use |
629
+ | --- | --- |
630
+ | `outcome` | `'opened'` when your write took the conversation. `'saved'` when another reply holds it, or when the message was saved before. |
631
+ | `ref` | The conversation that holds the message. Your `conversationStore` must be able to read it. |
632
+ | `landsAs` | Each id a reply names the message by: the id of its inbox item, of its inject on a `stage` line, and of each of its blocks. |
633
+ | `hold`, `blocks` | With `opened`: the hold your write took, and the message as transcript blocks. The handler passes them to `message` as `saved`. |
634
+
635
+ The handler checks the message before it calls `intake`, with the core's `checkMessage`. A message with no `id`, with content the profile does not take, or to a conversation the session cannot read is refused, and `intake` is not called.
636
+
637
+ On `/turn`, the stream opens with a `conversation` line that has `posted` and `landsAs`. With `opened`, the reply follows on the same stream. With `saved`, the stream ends there.
638
+
639
+ On `/steer`, the handler does not put the message into the running turn. The reply that holds the conversation reads the message from your inbox: in the same reply when your `prepare` takes it with `run.take`, or in a follow-up. The response is `{ ok: true, saved: { conversation, landsAs } }`. When the steer's save took the conversation, no reply was running. The handler then asks `onContinue`. For `'taken'`, your app runs the reply with `followUp`. Otherwise the handler lets the conversation go, and the page's wake runs the reply. Your `policy` must tell the message to a reply at `opening: 'wake'`.
640
+
641
+ A reply that opens with items from your inbox sends a `conversation` line with `opened`, the ids of those items. The page uses it to move a saved message from the pending list into the transcript.
642
+
643
+ Your store marks the items in `told` in its `write`. If an item in `told` that the reply was handed still waits when the run ends `continue`, the run lets the conversation go and fails with a `config` error, because each follow-up would tell that item again. `onError` receives the error.
644
+
645
+ ### Stop a reply from any server
646
+
647
+ Without `stop` in your `inbox`, a stop reaches a turn by its `turnId` in `steerInbox`. That reaches only a reply that a page turn started. Set `stop` to keep the stop in your own store. A stop then reaches the reply that holds the conversation, on any server, and from any channel or wake.
648
+
649
+ ```ts
650
+ const stop: HoldStop = {
651
+ ask: async (conversation) => false,
652
+ stopped: async (conversation, hold, over) => false,
653
+ clear: async (conversation, hold) => {},
654
+ };
655
+ ```
656
+
657
+ - `ask` records a stop for the hold that has `conversation` now. Return `false` when no hold has it. `<base>/stop` and the core's `stop` call it, and `turnId` is not read. Read the hold and write the stop in one statement, or a stop can name a hold that no longer runs.
658
+ - `stopped` settles `true` when a stop is asked for `hold`. It settles `false` when `over` aborts, which is the end of the model run. Each model run of a reply under a hold calls it.
659
+ - `clear` removes a stop asked for `hold`. The core calls it as each model run ends.
660
+
661
+ A stop is for the reply that holds the conversation when the stop arrives. The follow-up keeps the hold. Because the core clears the stop as the reply ends, a stop that came too late for the reply does not stop the follow-up.
662
+
663
+ ### Show a reply that runs elsewhere
664
+
665
+ A page that opens while a reply runs, after a reload, in another tab, or while another channel's reply runs, did not start that reply. Only your records know that it runs. Your store's `read` tells the page with `running` on the snapshot:
666
+
667
+ ```ts
668
+ const snapshot: ConversationSnapshot = {
669
+ revision,
670
+ conversation,
671
+ running: { since, prompt, heldUntil },
672
+ };
673
+ ```
674
+
675
+ - `since`: when the reply started, in epoch milliseconds. The working pill counts from it.
676
+ - `prompt`: what the person said that the transcript does not hold yet, as transcript blocks. These are the messages the reply answers, and steers that are saved but not read yet. The page shows them under the transcript.
677
+ - `heldUntil`: when the hold lapses unless it is renewed. A page that has heard nothing by then reads the conversation again, so a reply whose server died does not show as working forever.
678
+ - Set `running` only while the hold is live. Leave it unset when no reply runs.
679
+
680
+ The view the page reads has the same `running`. While it is set, the chat's phase is `streaming` and `runningElsewhere` holds it, so the page acts as it does for its own reply:
681
+
682
+ - The stop button sends `/stop` with `{ conversation }`. Your `inbox`'s `stop` stops the reply. Without one, the stop is refused with `session.reply_unreachable`, the page shows that error, and the reply still shows as working.
683
+ - A steer sends `/steer` with `{ conversation }` and no `turnId`. `intake` saves it. Without `intake`, the steer is refused with `session.reply_unreachable`.
684
+ - A message sent while it works waits in the queue. Send now stops the reply, then sends the message. When the stop is refused, the message stays in the composer.
685
+
686
+ The page reads again at `heldUntil` once for each `heldUntil`. When your server's clock and the browser's differ, a hold can look lapsed to the page while your store still returns it. The page then waits for your `notifier.publish`, or for a read that returns a new `heldUntil`.
687
+
688
+ Call `notifier.publish` after each save that ends the reply. The page reads the conversation again. When `running` is gone, the queue sends its next message, unless the person stopped the reply.
689
+
690
+ ### Shape the save that ends a reply
691
+
692
+ Use `beforeSave` when your app keeps each block as its own record, and must decide what a reply writes. The core calls it once for each save that ends a reply, before the store's `write`.
693
+
694
+ ```ts
695
+ const core = createTheoremConversationCore({
696
+ // ...
697
+ beforeSave: async (at, reply) => ({ blocks: reply.blocks, told: [], host: {} }),
698
+ afterSave: async (at, { ended, told }) => {},
699
+ });
700
+ ```
701
+
702
+ `reply` has these fields:
703
+
704
+ | Field | Meaning |
705
+ | --- | --- |
706
+ | `ended` | How the reply ended: `committed`, `failed`, `stopped`, `paused`, `lost`, or `refused`. |
707
+ | `blocks` | The blocks this save adds to what the store last wrote. They include a message that you passed in `saved`, and the blocks of a paused reply that this message walked away from. |
708
+ | `failure` | The error event, when the reply failed. With `ended: 'paused'`, an answer or a walk-away did not settle, and the reply still waits. |
709
+ | `landed` | The ids of the named injects and the steers that the model read in this reply. |
710
+ | `held` | With `inbox`, the reply's hold of your inbox, as `prepare` receives it. |
711
+
712
+ Return `{ blocks, told, host? }`:
713
+
714
+ - `blocks` replaces `reply.blocks` in the transcript. Add, remove, or reword blocks here. Set `host` on a block, a JSON object, to keep your own values with it, such as the id of its record. The core never reads a block's `host`.
715
+ - `told` is the ids of the inbox items that this save marks as told.
716
+ - `host` is a value of your own for the store.
717
+
718
+ The store's `write` then receives a fifth argument, a `WriteContext`: `{ hold?, reply?, host?, ended, told, appended }`. `appended` is the blocks that you returned. A store on your database can write the reply, mark the items in `told`, and check that `hold` still holds the conversation, in one statement. A write with no context saves no reply: a new conversation, a posted message, a rewind, or the core's own compaction.
719
+
720
+ These rules apply:
721
+
722
+ - A reply that paused keeps its own blocks with the paused reply, and they are not in `blocks`. They arrive in the save that ends the reply after the person answers.
723
+ - With `beforeSave`, the core adds no error block to a reply that failed. Word the failure from `reply.failure`.
724
+ - When `beforeSave` throws on a reply that failed or stopped, the core reports the error to `onError`, saves nothing, and the run ends with the reply's own failure. On any other reply, the throw fails the reply.
725
+ - `afterSave` runs after the store wrote the reply, while the run still holds the conversation. Use it to send the reply to a channel. When it throws, the core reports the error to `onError`, and the save stands.
726
+ - With no `beforeSave`, `told` is empty and the blocks are saved as they are.
727
+
728
+ ### Refuse a reply
729
+
730
+ To answer with a line of your own and run no model, return `{ refuse: { text, host? } }` from `prepare` in place of the turn. Use it for a limit that your app keeps, such as a daily limit or a paused plan.
731
+
732
+ ```ts
733
+ const core = createTheoremConversationCore({
734
+ // ...
735
+ prepare: async (turn) =>
736
+ (await overLimit(turn.host)) ? { refuse: { text: 'You reached the limit for today.' } } : turn,
737
+ });
738
+ ```
739
+
740
+ - The run yields the line as the reply's text. The reply saves with `ended: 'refused'`, and has no error block and no usage.
741
+ - `host` goes on the block of the line, as a `host` that `beforeSave` sets does.
742
+ - `beforeSave` and `afterSave` run as for any reply. The items in `told` are marked as told. The items that the reply read and did not tell go back to the inbox.
743
+ - A reply that goes on after an answered call, a wake, and a follow-up can be refused in the same way.
744
+ - Do not refuse a turn that has `answersHeldCall`. An answered call has no reply to refuse, so the call fails with a `config` error and does not run.
745
+ - While your app would refuse, its `policy` must tell only the items that the refusal answers, and `beforeSave` must mark each of them as told. An item that is told and not marked makes the run end `continue`, and each follow-up saves the line again.
746
+ - To make a wake say nothing, do not refuse it. While your app would refuse, return an empty `tell` from `policy` at each `opening` for the items that have no reply to a refusal, such as a reminder. A wake then runs no reply and saves nothing, the conversation read does not say `wake: true`, and the items wait.
747
+ - `createTheoremHandler` takes the same `prepare`. The page shows the line as the reply.
748
+
749
+ A reply to a message can lose its hold while it runs: a newer message took the conversation over. The core then calls `beforeSave` with `ended: 'lost'`, and calls `write` with `ended: 'lost'` and an empty `told`. Your store keeps the blocks that the person saw and marks no item as told. `afterSave` does not run. The memory store and the sealed store refuse this write, because they keep no holds. A store that refuses it keeps nothing, and the core reports nothing. With no `beforeSave`, or for a reply to no message, a lost reply writes nothing.
750
+
751
+ Set `compact` when your app compacts the history in its own run. After a reply's save, the core calls `compact(at, { history, tokens })` in place of its own compaction, and writes nothing more. When it throws, the core reports the error to `onError`.
752
+
753
+ A block's `host` goes to the page with the block: in the conversation that the page reads, and on the `stage` line of an inject. Put nothing in it that the person must not read.
754
+
755
+ A page cannot set `host` on a block. The core drops `host` from the blocks of a transcript that a page restores, and `theoremStartRequestSchema` drops it from the blocks of a start request. An app with no server keeps no `host`: its page restores the transcript on each message.
756
+
757
+ ### Run the follow-up
758
+
759
+ A run ends `continue` when items arrived that a reply may be told now. For example, a person sent a second message while the reply ran. The run still holds the conversation, so no other run can start. Your server does one of two things with `ref` and `hold`:
760
+
761
+ - Call `followUp` to run the next reply. It can end `continue` again.
762
+ - Call `release` to let the conversation go. The next run that opens the conversation reads what waits.
763
+
764
+ A run that ends `continue` can carry `failure`, which is what the run threw. Throw it after the follow-up or the release.
765
+
766
+ A follow-up answers in the chat that `ref` names, and `at` must be able to read that chat. With `inbox`, one conversation can have a chat in more than one session. Pass the `at` and the `ref` of the session that the follow-up answers in. A follow-up that cannot open its chat throws, and lets the conversation go. With `inbox`, `release` reads no chat.
767
+
768
+ `followedUp` does this for you. Pass it the run and a function that returns `'here'`, `'taken'`, or `'let_go'` for each `continue`:
769
+
770
+ ```ts
771
+ import { followedUp } from '@theoremjs/web/server';
772
+
773
+ const reply = await core.message(at, { ref, input });
774
+ const lines = followedUp(core, at, reply, () => 'here');
775
+ ```
776
+
777
+ | Choice | What `followedUp` does |
778
+ | --- | --- |
779
+ | `here` | Runs the follow-up, and yields its lines after the run's lines. |
780
+ | `taken` | Does nothing, and returns the `continue`. Your app calls `followUp` from another place, such as a queue. |
781
+ | `let_go` | Calls `release`, and returns `released`. |
782
+
783
+ Read each run to its end, because the end is where a `continue` arrives. A run goes on to its end and saves its reply even when your server stops reading its lines. A `continue` that nothing follows up or releases keeps the conversation until its lease runs out.
784
+
785
+ You cannot pass `inbox` together with `lateResultsDecider`. The core fails at setup with a `config` error.
786
+
471
787
  ## Build your own server
472
788
 
473
- `createTheoremHandler` runs each chat reply through a small loop that `@theoremjs/web/server` exports. Use the loop when your server is not a `fetch` handler, or when your routes differ from the handler's. The conversation store, the guardrails, and the wire stay the same, so `TheoremChat` and the hooks work with your server unchanged.
789
+ `createTheoremHandler` runs each chat reply through a small loop that `@theoremjs/web/server` exports. Use the loop when your server is not a `fetch` handler, or when your routes differ from the handler's. For a server that only has no page request, [the conversation core](#run-replies-with-no-page-request) is less work. The conversation store, the guardrails, and the wire stay the same, so `TheoremChat` and the hooks work with your server unchanged.
474
790
 
475
791
  | Function | Use |
476
792
  | --- | --- |
@@ -479,7 +795,7 @@ Set `pageToolTimeoutMs` to give the page a deadline for a result. Unset, a dispa
479
795
  | `postedMessage(iface, input, context?)` | Checks the person's message against the profile's inputs. `iface` is `interfaceFromProfile(profile, defaultKernelScope.tools)` from `@theoremjs/agents/interface`. |
480
796
  | `messageReply({ host, opened, message, walkAway?, runner })` | Posts the message, runs the reply and writes it back. Returns the lines to stream. |
481
797
  | `answerReply({ host, opened, call, settling, runner })` | Continues a reply after one of its calls was answered. `settling` is the call's events from the kernel's `invokeTool`. |
482
- | `rewindConversation({ host, opened, at, walkAway? })` | Cuts the conversation after transcript block `at`. `-1` empties it. |
798
+ | `rewindConversation({ host, opened, at, walkAway? })` | Cuts the conversation after transcript block `at`. `-1` empties it. A save that only added after `at` as the rewind read the chat is cut away too. When that save stopped on an approval, the rewind fails with `session.gate_pending`. |
483
799
  | `conversationView(host, conversation)` | The conversation as the chat draws it. |
484
800
  | `waitingCalls(conversation)` | The calls a paused reply waits on. A message or a rewind walks away from exactly these. |
485
801
 
@@ -527,6 +843,7 @@ What the loop leaves to you:
527
843
  - The session. Every read and write names it, and the store refuses a ref from another session.
528
844
  - Gates. A profile whose tools wait for approval needs a session store that issues each gate and checks its answer. `createTheoremHandler` keeps one. With your own server, check the answer, run the call with `invokeTool`, and pass its events to `answerReply`.
529
845
  - Walking away. A message to a reply that waits on gates must name exactly `waitingCalls(conversation)` as `abandon`, and pass each call's cancelled run as `walkAway`.
846
+ - Tool data. When `profileShowsToolData(profile)` is `false`, give the page each line through `eventWithoutToolData` and each block of a view through `blockWithoutToolData`. All three come from `@theoremjs/agents/interface`. Drop a line or a block that either one returns as `undefined`. Do not apply them to what you save: the model's history is rebuilt from the saved transcript.
530
847
 
531
848
  On the browser side, `@theoremjs/web/client` reads what your server sends:
532
849
 
package/client/chat.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { type ProfileOptions } from '@theoremjs/agents';
2
- import { type AttachmentValidationIssue, type ComposerMenuAction, type ComposerPendingMessage, type ComposerProfileInterface, type ComposerRunPhase, type InterfaceTurnSession, type TranscriptBlock } from '@theoremjs/agents/interface';
2
+ import { type AttachmentValidationIssue, type ComposerMenuAction, type ComposerPendingMessage, type ComposerProfileInterface, type ComposerRunPhase, type GatedToolContext, type InterfaceTurnSession, type TranscriptBlock } from '@theoremjs/agents/interface';
3
3
  import { type ClientFailure } from './failure.ts';
4
4
  import { type PageTools } from './live/live-page-tool.ts';
5
5
  import type { AnsweringGate, ToolDecisionAction } from './tool-resume.ts';
6
- import { type ConversationView, type StatedTurn, type TheoremTransport, type TurnEventSink } from './transport.ts';
6
+ import { type ConversationView, type RunningReply, type StatedTurn, type TheoremTransport, type TurnEventSink } from './transport.ts';
7
7
  export type ChatOptions = {
8
8
  transport: TheoremTransport;
9
9
  /** The profile's composer interface, as `transport.describe()` returns it. `null` while it loads. */
@@ -86,10 +86,22 @@ export type ChatState = {
86
86
  /** The answer on its way to a gate, shown on it until the answer settles or fails. */
87
87
  answering: AnsweringGate | null;
88
88
  phase: ComposerRunPhase;
89
+ /**
90
+ * The gate that waits for the person: a confirmation, a permission or a sign-in; `null` when
91
+ * none waits. A page gate, which the page answers, is never one.
92
+ */
93
+ waitingGate: GatedToolContext | null;
89
94
  session: InterfaceTurnSession;
90
95
  /** The latest message's delivery; `null` before the first and once its turn failed. */
91
96
  delivery: MessageDelivery | null;
92
97
  streaming: boolean;
98
+ /**
99
+ * A reply that runs away from this page (another tab, another channel, or before a reload), as
100
+ * the host's last read said; `null` when none does. While one runs the phase is `streaming`:
101
+ * the page stops and steers it by the conversation, queues behind it, and its prompt shows in
102
+ * `streamBlocks`.
103
+ */
104
+ runningElsewhere: RunningReply | null;
93
105
  /** `undefined` when the profile declares no options. */
94
106
  options: ChatOptionPicks | undefined;
95
107
  };