@theoremjs/web 0.3.5-next.980.g83e419d → 0.3.5-next.981.gf4729de

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
@@ -216,7 +216,7 @@ The methods for the composer depend on the phase:
216
216
  | Method | What it does |
217
217
  | --- | --- |
218
218
  | `submit()` | At `idle`, sends the draft. Otherwise, queues it. |
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. |
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). |
220
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. |
221
221
  | `enqueue('stash')` | Keeps the draft without sending it. `queuePending(id)` moves it to the queue. |
222
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. |
@@ -228,6 +228,19 @@ The methods for the composer depend on the phase:
228
228
  | `branch(index)` | Cuts the conversation after transcript block `index`. |
229
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. |
230
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
+
231
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.
232
245
 
233
246
  The controller writes no English text. The helpers below give the composer's controls as values, and you choose the words:
@@ -267,8 +280,9 @@ const transport = withPageToolDispatch(
267
280
  | `profile` | The profile to serve. The kernel registers it when you create the handler. |
268
281
  | `provider` | Host options, including the credential vault. A function can return these options per request, for example for tenant-specific credentials. |
269
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. |
270
- | `host` | App data for the tool handlers (`ctx.host`), such as the signed-in user. |
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. |
271
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`. |
272
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. |
273
287
  | `pageToolBroker` | Delivers results to active page dispatches. Default: bounded process memory. |
274
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. |
@@ -276,10 +290,12 @@ const transport = withPageToolDispatch(
276
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`. |
277
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). |
278
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). |
279
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). |
280
296
  | `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
281
297
  | `authorizationUrl` | Returns the sign-in URL for an OAuth gate. Without it, an OAuth gate has no URL. |
282
- | `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. |
283
299
  | `maxRequestBytes` | The largest browser request body, in bytes. Unset, a body of any size is read. |
284
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. |
285
301
  | `operationRetentionMs` | How long a settled tool result is kept. Default: 24 hours. |
@@ -473,7 +489,7 @@ The handler runs each reply under a hold of the chat, with `runConversation` fro
473
489
 
474
490
  `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.
475
491
 
476
- 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. 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.
492
+ 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.
477
493
 
478
494
  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`).
479
495
 
@@ -491,9 +507,257 @@ Use `pageToolBroker` to supply that broker. It carries results; the atomic sessi
491
507
  Lost result delivery does not permit another dispatch. The operation retains its claim or an uncertain outcome.
492
508
  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.
493
509
 
510
+ ## Run replies with no page request
511
+
512
+ 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.
513
+
514
+ 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.
515
+
516
+ ```ts
517
+ import { createMemoryConversationStore, createTheoremConversationCore } from '@theoremjs/web/server';
518
+
519
+ const core = createTheoremConversationCore({
520
+ profile: support,
521
+ provider: { vault: { main: process.env.GEMINI_API_KEY } },
522
+ conversationStore: createMemoryConversationStore(),
523
+ });
524
+
525
+ async function received(sessionId: string, text: string, ref: string | undefined, signal: AbortSignal) {
526
+ const reply = await core.message({ sessionId, signal }, { ...(ref ? { ref } : {}), input: { text } });
527
+ for (;;) {
528
+ const next = await reply.next();
529
+ if (next.done) return next.value;
530
+ deliver(next.value);
531
+ }
532
+ }
533
+ ```
534
+
535
+ `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:
536
+
537
+ | `outcome` | Meaning |
538
+ | --- | --- |
539
+ | `released` | The run ended, and no run holds the conversation. |
540
+ | `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). |
541
+ | `held` | Another run holds the conversation until `leasedUntil`. This run ran nothing. |
542
+ | `lost` | Another run took the conversation from this run. |
543
+
544
+ | Method | Use |
545
+ | --- | --- |
546
+ | `message(at, { ref?, input, context?, generation?, abandon?, saved? })` | Posts the person's message and runs the reply. |
547
+ | `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. |
548
+ | `answer(at, body)` | Answers a call that a paused reply waits on. |
549
+ | `wake(at, { ref })` | Runs a reply to no message, for items that arrived since the model last ran. |
550
+ | `followUp(at, { ref, hold })` | Runs the next reply to no message, under the hold of a run that ended `continue`. |
551
+ | `release(at, { ref, hold })` | Lets the conversation go under that hold, with no follow-up. |
552
+ | `read(at, { ref })` | Returns the conversation as a page draws it. |
553
+ | `rewind(at, { ref, at })` | Cuts the conversation after transcript block `at`. |
554
+ | `steer(at, { turnId, unit })` | Puts `unit` into a running turn. Returns `false` when the turn is not running. |
555
+ | `stop(at, { turnId })` | Stops a running turn. Returns `false` when the turn is not running. When your `inbox` has a `stop`, it stops the reply that holds the conversation, and `turnId` is not read. |
556
+
557
+ 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`:
558
+
559
+ | Option | Use |
560
+ | --- | --- |
561
+ | `provider` | Required. The host options for registered providers, or `(at, model?)` that returns them. |
562
+ | `prepare(turn, run?)` | Your `TurnWiring.prepare`. With `inbox`, `run` is the reply's hold of your inbox. |
563
+ | `background(at)` | The service for tools with a `background` setting. |
564
+ | `authorizeToolReplay(at, operation)` | Checks access before the core discloses a saved tool result. |
565
+ | `authorizationUrl(challenge, at)` | The sign-in URL for an OAuth gate. |
566
+ | `onError(err, at)` | Receives each error that a run reports and does not throw. |
567
+ | `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`. |
568
+ | `inbox(at)` | Your own inbox for the conversation. See below. |
569
+ | `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). |
570
+
571
+ ### Hold the conversation in your own inbox
572
+
573
+ 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.
574
+
575
+ `inbox(at)` returns `{ inbox, conversation, policy, leaseMs }`:
576
+
577
+ | Field | Use |
578
+ | --- | --- |
579
+ | `inbox` | Your `ConversationInbox`. `createMemoryInbox` is one for tests. |
580
+ | `conversation` | The name of the conversation in your inbox. |
581
+ | `policy` | Your `InboxPolicy`: which waiting items a reply is told, and which are given up. |
582
+ | `leaseMs` | How long a hold keeps the conversation after it last renewed, in milliseconds. |
583
+ | `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). |
584
+
585
+ 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`.
586
+
587
+ 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.
588
+
589
+ ### Save the person's message in your own write
590
+
591
+ 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`:
592
+
593
+ ```ts
594
+ await core.message(at, { ref, input, saved: { hold, blocks } });
595
+ ```
596
+
597
+ `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`.
598
+
599
+ ### Save a page's message in your own write
600
+
601
+ 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.
602
+
603
+ ```ts
604
+ createTheoremHandler({
605
+ profile,
606
+ provider,
607
+ conversationStore,
608
+ inbox,
609
+ intake: async (at, sent) => {
610
+ const saved = await saveMessage(at.sessionId, sent.id, sent.ref, sent.message);
611
+ return saved.hold === undefined
612
+ ? { outcome: 'saved', ref: saved.ref, landsAs: saved.ids }
613
+ : { outcome: 'opened', ref: saved.ref, landsAs: saved.ids, hold: saved.hold, blocks: saved.blocks };
614
+ },
615
+ });
616
+ ```
617
+
618
+ The save that `intake` calls in this example is your function. In one write, it does three things:
619
+
620
+ 1. It saves the message under `sent.id`. A second call with the same `sent.id` saves nothing new.
621
+ 2. It puts the message in your inbox as an item.
622
+ 3. It takes the conversation under a hold, when no reply holds it.
623
+
624
+ `intake` returns a `MessageIntake`:
625
+
626
+ | Field | Use |
627
+ | --- | --- |
628
+ | `outcome` | `'opened'` when your write took the conversation. `'saved'` when another reply holds it, or when the message was saved before. |
629
+ | `ref` | The conversation that holds the message. Your `conversationStore` must be able to read it. |
630
+ | `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. |
631
+ | `hold`, `blocks` | With `opened`: the hold your write took, and the message as transcript blocks. The handler passes them to `message` as `saved`. |
632
+
633
+ 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.
634
+
635
+ 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.
636
+
637
+ 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'`.
638
+
639
+ 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.
640
+
641
+ 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.
642
+
643
+ ### Stop a reply from any server
644
+
645
+ 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.
646
+
647
+ ```ts
648
+ const stop: HoldStop = {
649
+ ask: async (conversation) => false,
650
+ stopped: async (conversation, hold, over) => false,
651
+ clear: async (conversation, hold) => {},
652
+ };
653
+ ```
654
+
655
+ - `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.
656
+ - `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.
657
+ - `clear` removes a stop asked for `hold`. The core calls it as each model run ends.
658
+
659
+ 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.
660
+
661
+ ### Shape the save that ends a reply
662
+
663
+ 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`.
664
+
665
+ ```ts
666
+ const core = createTheoremConversationCore({
667
+ // ...
668
+ beforeSave: async (at, reply) => ({ blocks: reply.blocks, told: [], host: {} }),
669
+ afterSave: async (at, { ended, told }) => {},
670
+ });
671
+ ```
672
+
673
+ `reply` has these fields:
674
+
675
+ | Field | Meaning |
676
+ | --- | --- |
677
+ | `ended` | How the reply ended: `committed`, `failed`, `stopped`, `paused`, `lost`, or `refused`. |
678
+ | `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. |
679
+ | `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. |
680
+ | `landed` | The ids of the named injects and the steers that the model read in this reply. |
681
+ | `held` | With `inbox`, the reply's hold of your inbox, as `prepare` receives it. |
682
+
683
+ Return `{ blocks, told, host? }`:
684
+
685
+ - `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`.
686
+ - `told` is the ids of the inbox items that this save marks as told.
687
+ - `host` is a value of your own for the store.
688
+
689
+ 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.
690
+
691
+ These rules apply:
692
+
693
+ - 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.
694
+ - With `beforeSave`, the core adds no error block to a reply that failed. Word the failure from `reply.failure`.
695
+ - 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.
696
+ - `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.
697
+ - With no `beforeSave`, `told` is empty and the blocks are saved as they are.
698
+
699
+ ### Refuse a reply
700
+
701
+ 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.
702
+
703
+ ```ts
704
+ const core = createTheoremConversationCore({
705
+ // ...
706
+ prepare: async (turn) =>
707
+ (await overLimit(turn.host)) ? { refuse: { text: 'You reached the limit for today.' } } : turn,
708
+ });
709
+ ```
710
+
711
+ - The run yields the line as the reply's text. The reply saves with `ended: 'refused'`, and has no error block and no usage.
712
+ - `host` goes on the block of the line, as a `host` that `beforeSave` sets does.
713
+ - `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.
714
+ - A reply that goes on after an answered call, a wake, and a follow-up can be refused in the same way.
715
+ - 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.
716
+ - 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.
717
+ - 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.
718
+ - `createTheoremHandler` takes the same `prepare`. The page shows the line as the reply.
719
+
720
+ 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.
721
+
722
+ 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`.
723
+
724
+ 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.
725
+
726
+ 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.
727
+
728
+ ### Run the follow-up
729
+
730
+ 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`:
731
+
732
+ - Call `followUp` to run the next reply. It can end `continue` again.
733
+ - Call `release` to let the conversation go. The next run that opens the conversation reads what waits.
734
+
735
+ A run that ends `continue` can carry `failure`, which is what the run threw. Throw it after the follow-up or the release.
736
+
737
+ 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.
738
+
739
+ `followedUp` does this for you. Pass it the run and a function that returns `'here'`, `'taken'`, or `'let_go'` for each `continue`:
740
+
741
+ ```ts
742
+ import { followedUp } from '@theoremjs/web/server';
743
+
744
+ const reply = await core.message(at, { ref, input });
745
+ const lines = followedUp(core, at, reply, () => 'here');
746
+ ```
747
+
748
+ | Choice | What `followedUp` does |
749
+ | --- | --- |
750
+ | `here` | Runs the follow-up, and yields its lines after the run's lines. |
751
+ | `taken` | Does nothing, and returns the `continue`. Your app calls `followUp` from another place, such as a queue. |
752
+ | `let_go` | Calls `release`, and returns `released`. |
753
+
754
+ 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.
755
+
756
+ You cannot pass `inbox` together with `lateResultsDecider`. The core fails at setup with a `config` error.
757
+
494
758
  ## Build your own server
495
759
 
496
- `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.
760
+ `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.
497
761
 
498
762
  | Function | Use |
499
763
  | --- | --- |
package/client/chat.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TheoremError, } from '@theoremjs/agents';
2
- import { branchInterfaceTurnSession, consumeNextComposerQueue, convertSteersToFrontQueued, createComposerPendingMessage, defaultInterfaceEffort, emptyInterfaceTurnSession, moveComposerPendingWithinKind, orderComposerPendingMessages, promoteComposerPendingKind, removeComposerPendingMessage, removeLandedSteers, userDraftHasPayload, userDraftToSteerInject, } from '@theoremjs/agents/interface';
2
+ import { branchInterfaceTurnSession, consumeNextComposerQueue, convertSteersToFrontQueued, createComposerPendingMessage, defaultInterfaceEffort, emptyInterfaceTurnSession, moveComposerPendingWithinKind, orderComposerPendingMessages, promoteComposerPendingKind, removeComposerPendingMessage, removeLandedSteers, saveComposerPendingMessage, takeSavedComposerPending, userDraftHasPayload, userDraftToSteerInject, } from '@theoremjs/agents/interface';
3
3
  import { composerHasPayload } from "./composer-primary.js";
4
4
  import { composerFieldsFromDraft } from "./decode-composer-draft.js";
5
5
  import { encodeComposerDraft } from "./encode-composer-draft.js";
@@ -8,7 +8,7 @@ import { followGenerationDefaults } from "./generation-selection.js";
8
8
  import { warnPageToolMismatch } from "./live/live-page-tool.js";
9
9
  import { withPageToolDispatch } from "./page-dispatch.js";
10
10
  import { sessionAfter, stampWorked, stoppedReply } from "./run-commit.js";
11
- import { keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
11
+ import { extractInlineEncodedAttachments, keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
12
12
  import { isUnknownConversation, } from "./transport.js";
13
13
  import { foldAssistantTurn, issuedOperationId } from "./turn-client.js";
14
14
  const DELIVERY_ORDER = ['sending', 'sent', 'delivered', 'read'];
@@ -87,9 +87,19 @@ function nextFrame(run) {
87
87
  const id = setTimeout(run, 16);
88
88
  return () => clearTimeout(id);
89
89
  }
90
- function newTurnId() {
90
+ function newId() {
91
91
  return crypto.randomUUID();
92
92
  }
93
+ /** A pending message's draft as the input a steer sends. */
94
+ function steerInput(draft) {
95
+ const attachments = extractInlineEncodedAttachments(draft.attachments);
96
+ const voice = extractInlineEncodedAttachments(draft.voice);
97
+ return {
98
+ ...(draft.text?.trim() ? { text: draft.text } : {}),
99
+ ...(attachments ? { attachments } : {}),
100
+ ...(voice ? { voice } : {}),
101
+ };
102
+ }
93
103
  class Chat {
94
104
  #options;
95
105
  #state;
@@ -125,6 +135,12 @@ class Chat {
125
135
  #listening = null;
126
136
  /** The last view said results wait that no reply has read: the chat wakes once it is idle. */
127
137
  #wakeDue = false;
138
+ /** The ids a reply names the run's message by, once the host said it saved the message itself. */
139
+ #savedAs = null;
140
+ /** How many blocks, at the end of the transcript, are the message the run posted. */
141
+ #ownPosted = 0;
142
+ /** The run in flight has streamed an event of its reply. */
143
+ #streamed = false;
128
144
  #reading = null;
129
145
  #readAgain = false;
130
146
  constructor(options) {
@@ -327,18 +343,33 @@ class Chat {
327
343
  this.#steerAfterTurnEnded();
328
344
  return;
329
345
  }
330
- const inject = userDraftToSteerInject(message.draft);
331
- if (inject.length === 0)
346
+ const input = steerInput(message.draft);
347
+ if (Object.keys(input).length === 0)
332
348
  return;
349
+ const conversation = this.#conversation;
333
350
  try {
334
- await this.#options.transport.steer({ turnId, id: message.id, inject });
351
+ const { saved } = await this.#options.transport.steer({
352
+ turnId,
353
+ id: message.id,
354
+ input,
355
+ ...(conversation === undefined ? {} : { conversation }),
356
+ });
357
+ if (!saved)
358
+ return;
359
+ this.#set({
360
+ pendingMessages: saveComposerPendingMessage(this.#state.pendingMessages, message.id, saved.landsAs),
361
+ });
362
+ this.#adopt(saved.conversation);
363
+ // why: A run in flight reads the conversation once it ends, after this save. With none, the chat reads now, and wakes for the message.
364
+ if (!this.#busy)
365
+ await this.refresh();
335
366
  }
336
367
  catch (err) {
337
368
  this.#set({ failure: clientFailure(err, this.#options.iface?.labels) });
338
369
  }
339
370
  };
340
371
  sendNow = async (source) => {
341
- if (!this.#options.iface)
372
+ if (!this.#options.iface || source?.saved)
342
373
  return;
343
374
  const draft = source ? source.draft : await this.#composerDraft();
344
375
  if (!draft)
@@ -351,6 +382,7 @@ class Chat {
351
382
  this.#drainArmed = false;
352
383
  // why: Sent while the reply waits on gates, the message walks away from them in its own request.
353
384
  await this.#sendDraft(draft, {
385
+ id: source?.id ?? newId(),
354
386
  walkAway: this.#state.session.gatedTool !== null,
355
387
  // why: The sent message leaves the queue, or the composer it came from.
356
388
  onPosted: () => this.#set(source
@@ -370,7 +402,7 @@ class Chat {
370
402
  };
371
403
  restorePending = async (id) => {
372
404
  const message = this.#state.pendingMessages.find((m) => m.id === id);
373
- if (!message)
405
+ if (!message || message.saved)
374
406
  return;
375
407
  try {
376
408
  await this.#restore(composerFieldsFromDraft(message.draft));
@@ -557,7 +589,10 @@ class Chat {
557
589
  #draw(view, session, events) {
558
590
  const shown = [...this.#state.blocks, ...this.#state.streamBlocks];
559
591
  const blocks = keepIds(shown, view.transcript);
592
+ const drawn = [...view.transcript, ...(view.paused?.blocks ?? [])].map((block) => block.id);
560
593
  this.#set({
594
+ // why: A saved message the conversation now shows is no longer waiting.
595
+ pendingMessages: takeSavedComposerPending(this.#state.pendingMessages, drawn).remaining,
561
596
  blocks,
562
597
  streamBlocks: keepIds(shown.slice(blocks.length), view.paused?.blocks ?? []),
563
598
  // why: A reply at rest leaves the run's own events (tokens, an ask); a paused one, the host's.
@@ -642,6 +677,7 @@ class Chat {
642
677
  this.#draining = true;
643
678
  // why: The message leaves the queue once it posts; one that never starts stays queued.
644
679
  void this.#sendDraft(message.draft, {
680
+ id: message.id,
645
681
  onPosted: () => this.#set({
646
682
  pendingMessages: removeComposerPendingMessage(this.#state.pendingMessages, message.id),
647
683
  }),
@@ -698,7 +734,8 @@ class Chat {
698
734
  });
699
735
  }
700
736
  /** The message posted: it joins the transcript, and the reply starts streaming. */
701
- #posted(blocks, patch) {
737
+ #posted(blocks, own, patch) {
738
+ this.#ownPosted = own;
702
739
  this.#setDelivery({ status: 'sending' });
703
740
  this.#set({
704
741
  blocks: [...this.#state.blocks, ...blocks],
@@ -719,8 +756,19 @@ class Chat {
719
756
  scope,
720
757
  view,
721
758
  transcript: this.#state.blocks,
722
- onUserBlocks: (blocks) => this.#posted(blocks, this.#clearedComposer()),
723
- }), { turn: true, message: { restore: () => this.#restore(fields) } });
759
+ onUserBlocks: (blocks, own) => this.#posted(blocks, own, this.#clearedComposer()),
760
+ }), {
761
+ turn: true,
762
+ message: {
763
+ id: newId(),
764
+ draft: () => encodeComposerDraft({
765
+ text: fields.text,
766
+ pendingFiles: fields.files,
767
+ pendingVoice: fields.voice,
768
+ }),
769
+ restore: () => this.#restore(fields),
770
+ },
771
+ });
724
772
  }
725
773
  #sendDraft(draft, options) {
726
774
  return this.#runTurn(({ iface, view, transport, scope, signal }) => streamInterfaceDraftTurn({
@@ -733,11 +781,18 @@ class Chat {
733
781
  view,
734
782
  transcript: this.#state.blocks,
735
783
  walkAway: options.walkAway === true,
736
- onUserBlocks: (blocks) => {
737
- this.#posted(blocks, { streamBlocks: [] });
784
+ onUserBlocks: (blocks, own) => {
785
+ this.#posted(blocks, own, { streamBlocks: [] });
738
786
  options.onPosted();
739
787
  },
740
- }), { turn: true, message: { restore: () => this.#restore(composerFieldsFromDraft(draft)) } });
788
+ }), {
789
+ turn: true,
790
+ message: {
791
+ id: options.id,
792
+ draft: () => Promise.resolve(draft),
793
+ restore: () => this.#restore(composerFieldsFromDraft(draft)),
794
+ },
795
+ });
741
796
  }
742
797
  /** The gate on the reply still running that no answer is on its way to. */
743
798
  #drawnGate() {
@@ -802,6 +857,8 @@ class Chat {
802
857
  const base = withPageToolDispatch(transport, pageTools);
803
858
  const tap = (onLine) => (line) => {
804
859
  this.#took(line);
860
+ if (line.type === 'conversation' && line.opened)
861
+ this.#opened(line.opened, onLine);
805
862
  onLine(line);
806
863
  };
807
864
  return {
@@ -856,10 +913,43 @@ class Chat {
856
913
  DELIVERY_ORDER.indexOf(reached) > DELIVERY_ORDER.indexOf(delivery.status)) {
857
914
  this.#setDelivery({ status: reached });
858
915
  }
859
- if (line.type === 'conversation')
916
+ if (line.type === 'conversation') {
860
917
  this.#adopt(line.ref);
861
- else
862
- this.#options.onTurnEvent?.(line);
918
+ if (line.landsAs)
919
+ this.#savedAs = line.landsAs;
920
+ return;
921
+ }
922
+ this.#streamed = true;
923
+ this.#options.onTurnEvent?.(line);
924
+ }
925
+ /**
926
+ * A reply opened with messages the host saved before: they leave the pending list and join the
927
+ * transcript where the reply reads them. That is before the message this run posted, when the
928
+ * reply has streamed nothing.
929
+ */
930
+ #opened(ids, onLine) {
931
+ const { iface } = this.#options;
932
+ const { landed, remaining } = takeSavedComposerPending(this.#state.pendingMessages, ids);
933
+ if (!iface || landed.length === 0)
934
+ return;
935
+ this.#set({ pendingMessages: remaining });
936
+ const read = {
937
+ type: 'stage',
938
+ stage: 'pre_turn',
939
+ injected: landed.map((m) => ({ id: m.id, messages: userDraftToSteerInject(m.draft) })),
940
+ };
941
+ if (this.#streamed || this.#ownPosted === 0) {
942
+ onLine(read);
943
+ return;
944
+ }
945
+ const at = this.#state.blocks.length - this.#ownPosted;
946
+ this.#set({
947
+ blocks: [
948
+ ...this.#state.blocks.slice(0, at),
949
+ ...foldAssistantTurn(iface, [read]),
950
+ ...this.#state.blocks.slice(at),
951
+ ],
952
+ });
863
953
  }
864
954
  #streamFrame(partial) {
865
955
  this.#frameBlocks = partial;
@@ -886,12 +976,15 @@ class Chat {
886
976
  const { message } = options;
887
977
  const priorDelivery = this.#delivery;
888
978
  const abort = options.turn ? new AbortController() : null;
889
- const turnId = options.turn ? newTurnId() : undefined;
979
+ const turnId = options.turn ? newId() : undefined;
890
980
  this.#busy = true;
891
981
  this.#abort = abort;
892
982
  this.#turnId = turnId ?? null;
893
983
  this.#stopped = false;
894
984
  this.#drainArmed = false;
985
+ this.#savedAs = null;
986
+ this.#ownPosted = 0;
987
+ this.#streamed = false;
895
988
  // why: A message streams once it posts, so the previous reply never shows as streaming before it.
896
989
  // A wake shows only once the host's reply begins; one with nothing to wake for shows nothing.
897
990
  if (!options.wake)
@@ -906,7 +999,7 @@ class Chat {
906
999
  const outcome = await run({
907
1000
  iface,
908
1001
  transport: this.#runTransport(),
909
- scope: { conversation: this.#conversation, turnId },
1002
+ scope: { conversation: this.#conversation, turnId, id: message?.id },
910
1003
  signal: abort?.signal,
911
1004
  view: {
912
1005
  blocks: (partial) => this.#streamFrame(partial),
@@ -923,7 +1016,7 @@ class Chat {
923
1016
  await this.#takeBack(start, message);
924
1017
  let waits;
925
1018
  if (keepsConversation(iface)) {
926
- waits = await this.#settleHosted(outcome, start);
1019
+ waits = await this.#settleHosted(outcome, start, options);
927
1020
  }
928
1021
  else if (unposted) {
929
1022
  this.#showFailure(outcome.failure);
@@ -979,7 +1072,7 @@ class Chat {
979
1072
  * in the composer unless the host's transcript closed on it. Returns whether the reply waits
980
1073
  * on gates.
981
1074
  */
982
- async #settleHosted(outcome, start) {
1075
+ async #settleHosted(outcome, start, { message, wake }) {
983
1076
  const { failure } = outcome;
984
1077
  if (failure)
985
1078
  this.#setDelivery(null);
@@ -990,12 +1083,34 @@ class Chat {
990
1083
  return this.#state.session.gatedTool !== null;
991
1084
  }
992
1085
  const view = await this.#options.transport.conversation({ conversation: ref });
1086
+ const savedAs = this.#savedAs;
1087
+ if (message && savedAs && !view.transcript.some((block) => savedAs.includes(block.id))) {
1088
+ await this.#keepSaved(message, savedAs);
1089
+ }
993
1090
  this.#draw(view, outcome.session, outcome.events);
1091
+ // why: The page does not repeat a run that failed or was stopped, or a wake the host ran nothing for (another reply holds the conversation). The next read can wake.
1092
+ if (failure || (wake && !this.#streamed))
1093
+ this.#wakeDue = false;
994
1094
  if (!view.transcript.slice(start.blocks.length).some((b) => b.kind === 'error')) {
995
1095
  this.#showFailure(failure);
996
1096
  }
997
1097
  return view.paused !== undefined;
998
1098
  }
1099
+ /** The host saved the message and no reply has read it: it waits with the pending messages. */
1100
+ async #keepSaved(message, landsAs) {
1101
+ this.#setDelivery(null);
1102
+ const waiting = createComposerPendingMessage({
1103
+ kind: 'steer',
1104
+ draft: await message.draft(),
1105
+ id: message.id,
1106
+ });
1107
+ this.#set({
1108
+ pendingMessages: orderComposerPendingMessages([
1109
+ ...this.#state.pendingMessages,
1110
+ { ...waiting, saved: { landsAs } },
1111
+ ]),
1112
+ });
1113
+ }
999
1114
  /**
1000
1115
  * A stateless chat keeps the reply as the run streamed it: in the transcript once it ends
1001
1116
  * (closed by its failure, or by the visitor's stop), or beside it while it waits on a gate.
package/client/index.d.ts CHANGED
@@ -33,5 +33,5 @@ export { hasLead, layoutResult, type ResultChart, type ResultFigure, type Result
33
33
  export type { AnsweringGate, ToolDecisionAction, ToolGateResolution, } from './tool-resume.ts';
34
34
  export { continueGatedToolInvocation, type PersonGateResolution } from './tool-resume.ts';
35
35
  export { createTraceFeed, recordedFeed, type TraceFeed } from './trace-feed.ts';
36
- export { CHAT_LINES, type ChatLine, type ChatLineSink, type ClientTurnEvent, type ConversationLine, type ConversationView, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, type HostErrorBody, type HttpOptions, type HttpTransportOptions, hostError, isTheoremStreamError, type MalformedEvent, type NotifyLine, postJson, postNdjson, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremStartRequest, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TheoremWakeRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
36
+ export { CHAT_LINES, type ChatLine, type ChatLineSink, type ClientTurnEvent, type ConversationLine, type ConversationView, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, type HostErrorBody, type HttpOptions, type HttpTransportOptions, hostError, isTheoremStreamError, type MalformedEvent, type NotifyLine, postJson, postNdjson, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremSavedMessage, type TheoremStartRequest, type TheoremSteerReply, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TheoremWakeRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
37
37
  export { buildInvokeRequest, buildTurnRequest, foldAssistantTurn, issuedOperationId, type RunScope, type WalkAway, } from './turn-client.ts';