@theoremjs/web 0.3.5-next.996.g1635914 → 0.3.5-next.997.g6d32810

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
@@ -386,6 +386,7 @@ interface ConversationDatabase {
386
386
  - Check what you read back with `storedConversationSchema`.
387
387
  - A store that keeps each block in its own place (a row, a column) checks one block with `transcriptBlockSchema`.
388
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).
389
390
 
390
391
  ### Share session authority
391
392
 
@@ -553,7 +554,7 @@ async function received(sessionId: string, text: string, ref: string | undefined
553
554
  | `read(at, { ref })` | Returns the conversation as a page draws it. |
554
555
  | `rewind(at, { ref, at })` | Cuts the conversation after transcript block `at`. |
555
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`. |
556
- | `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. |
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`. |
557
558
 
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`:
559
560
 
@@ -659,6 +660,33 @@ const stop: HoldStop = {
659
660
 
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.
661
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
+
662
690
  ### Shape the save that ends a reply
663
691
 
664
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`.
package/client/chat.d.ts CHANGED
@@ -3,7 +3,7 @@ import { type AttachmentValidationIssue, type ComposerMenuAction, type ComposerP
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. */
@@ -95,6 +95,13 @@ export type ChatState = {
95
95
  /** The latest message's delivery; `null` before the first and once its turn failed. */
96
96
  delivery: MessageDelivery | null;
97
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;
98
105
  /** `undefined` when the profile declares no options. */
99
106
  options: ChatOptionPicks | undefined;
100
107
  };
package/client/chat.js CHANGED
@@ -9,7 +9,7 @@ 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
11
  import { extractInlineEncodedAttachments, keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
12
- import { isUnknownConversation, } from "./transport.js";
12
+ import { isTurnEnded, isUnknownConversation, } from "./transport.js";
13
13
  import { foldAssistantTurn, issuedOperationId } from "./turn-client.js";
14
14
  const DELIVERY_ORDER = ['sending', 'sent', 'delivered', 'read'];
15
15
  /** The server's own reports (bookkeeping, a failure, the end), which say nothing of the model having the message. */
@@ -143,6 +143,10 @@ class Chat {
143
143
  #streamed = false;
144
144
  #reading = null;
145
145
  #readAgain = false;
146
+ /** Reads the conversation again once the hold of the reply that runs elsewhere lapses. */
147
+ #holdTimer = null;
148
+ /** The `heldUntil` of the last read made when a hold lapsed. */
149
+ #heldUntilRead = null;
146
150
  constructor(options) {
147
151
  this.#options = options;
148
152
  this.#conversation = options.conversation;
@@ -163,6 +167,7 @@ class Chat {
163
167
  session: emptyInterfaceTurnSession(),
164
168
  delivery: null,
165
169
  streaming: false,
170
+ runningElsewhere: null,
166
171
  options: picksOf(options.iface, options.options, {}).options,
167
172
  };
168
173
  this.#notified = this.#state;
@@ -177,9 +182,11 @@ class Chat {
177
182
  this.#settle();
178
183
  }
179
184
  this.#followPush();
185
+ this.#followHold();
180
186
  return () => {
181
187
  this.#listeners.delete(listener);
182
188
  this.#followPush();
189
+ this.#followHold();
183
190
  };
184
191
  };
185
192
  refresh = () => {
@@ -242,6 +249,28 @@ class Chat {
242
249
  this.#listening = listening;
243
250
  void this.#listen(listening);
244
251
  }
252
+ /**
253
+ * Reads the conversation again when the hold of the reply that runs elsewhere lapses, while
254
+ * someone is here to see it. The app says when that reply ends; this covers a server that died
255
+ * holding it, which says nothing.
256
+ */
257
+ #followHold() {
258
+ if (this.#holdTimer)
259
+ clearTimeout(this.#holdTimer);
260
+ this.#holdTimer = null;
261
+ const running = this.#state.runningElsewhere;
262
+ if (!running || this.#listeners.size === 0)
263
+ return;
264
+ // why: A read that still shows a hold already followed lapsed waits for the app's publish; the
265
+ // server's clock and this one differ, so one read per hold, not one per draw.
266
+ if (running.heldUntil === this.#heldUntilRead)
267
+ return;
268
+ this.#holdTimer = setTimeout(() => {
269
+ this.#holdTimer = null;
270
+ this.#heldUntilRead = running.heldUntil;
271
+ void this.refresh();
272
+ }, Math.max(0, running.heldUntil - Date.now()));
273
+ }
245
274
  async #listen(listening) {
246
275
  const { signal } = listening;
247
276
  while (!signal.aborted) {
@@ -306,12 +335,18 @@ class Chat {
306
335
  stop = () => {
307
336
  void this.#stop();
308
337
  };
309
- /** Asks the host to stop the turn, so the reply it leaves comes back; a host that can't drops the stream. */
338
+ /**
339
+ * Asks the host to stop the reply, so what it leaves comes back; a host that can't drops the
340
+ * stream. A reply that runs elsewhere is stopped by the conversation, and the read after it
341
+ * draws what it left.
342
+ */
310
343
  async #stop() {
311
344
  const abort = this.#abort;
312
345
  const turnId = this.#turnId;
313
- if (!abort)
346
+ if (!abort) {
347
+ await this.#stopElsewhere();
314
348
  return;
349
+ }
315
350
  this.#stopped = true;
316
351
  if (!turnId) {
317
352
  abort.abort();
@@ -325,6 +360,27 @@ class Chat {
325
360
  abort.abort();
326
361
  }
327
362
  }
363
+ /** Stops the reply that runs elsewhere. False when it may still run: the stop was refused or failed. */
364
+ async #stopElsewhere() {
365
+ const conversation = this.#conversation;
366
+ if (!this.#state.runningElsewhere || conversation === undefined)
367
+ return true;
368
+ this.#stopped = true;
369
+ let stopped = true;
370
+ try {
371
+ await this.#options.transport.stop({ conversation });
372
+ }
373
+ catch (err) {
374
+ // why: A reply that ended first is not running; the read below shows what it left.
375
+ if (!isTurnEnded(err)) {
376
+ stopped = false;
377
+ this.#stopped = false;
378
+ this.#set({ failure: clientFailure(err, this.#options.iface?.labels) });
379
+ }
380
+ }
381
+ await this.refresh();
382
+ return stopped;
383
+ }
328
384
  enqueue = async (kind) => {
329
385
  const { draftText, pendingFiles, pendingVoice } = this.#state;
330
386
  if (!composerHasPayload(draftText, pendingFiles, pendingVoice))
@@ -360,22 +416,16 @@ class Chat {
360
416
  this.#drainArmed = true;
361
417
  if (message.kind !== 'steer')
362
418
  return;
363
- const turnId = this.#turnId;
364
- if (!turnId) {
419
+ const target = this.#steerTarget();
420
+ if (!target) {
365
421
  this.#steerAfterTurnEnded();
366
422
  return;
367
423
  }
368
424
  const input = steerInput(message.draft);
369
425
  if (Object.keys(input).length === 0)
370
426
  return;
371
- const conversation = this.#conversation;
372
427
  try {
373
- const { saved } = await this.#options.transport.steer({
374
- turnId,
375
- id: message.id,
376
- input,
377
- ...(conversation === undefined ? {} : { conversation }),
378
- });
428
+ const { saved } = await this.#options.transport.steer({ ...target, id: message.id, input });
379
429
  if (!saved)
380
430
  return;
381
431
  this.#set({
@@ -390,6 +440,16 @@ class Chat {
390
440
  this.#set({ failure: clientFailure(err, this.#options.iface?.labels) });
391
441
  }
392
442
  };
443
+ /** Where a steer goes: the turn this page runs, or the reply that runs elsewhere. */
444
+ #steerTarget() {
445
+ const conversation = this.#conversation;
446
+ const turnId = this.#turnId;
447
+ if (turnId)
448
+ return { turnId, ...(conversation === undefined ? {} : { conversation }) };
449
+ if (this.#state.runningElsewhere && conversation !== undefined)
450
+ return { conversation };
451
+ return null;
452
+ }
393
453
  sendNow = async (source) => {
394
454
  if (!this.#options.iface || source?.saved)
395
455
  return;
@@ -400,6 +460,10 @@ class Chat {
400
460
  await this.#stop();
401
461
  await this.#run;
402
462
  }
463
+ else if (!(await this.#stopElsewhere())) {
464
+ // why: A reply that may still run is not sent into; the message stays where it was.
465
+ return;
466
+ }
403
467
  this.#set({ pendingMessages: convertSteersToFrontQueued(this.#state.pendingMessages) });
404
468
  this.#drainArmed = false;
405
469
  // why: Sent while the reply waits on gates, the message walks away from them in its own request.
@@ -455,7 +519,7 @@ class Chat {
455
519
  authenticate = (secret) => this.#answerGate({ action: 'auth', ...(secret === undefined ? {} : { secret }) });
456
520
  branch = async (index) => {
457
521
  const { iface } = this.#options;
458
- if (!iface || this.#busy)
522
+ if (!iface || this.#busy || this.#state.runningElsewhere)
459
523
  return;
460
524
  const ref = this.#conversation;
461
525
  if (!keepsConversation(iface) || ref === undefined) {
@@ -516,7 +580,8 @@ class Chat {
516
580
  };
517
581
  #set(patch) {
518
582
  const next = { ...this.#state, ...patch };
519
- next.phase = this.#busy ? 'streaming' : next.session.gatedTool ? 'gated' : 'idle';
583
+ const running = this.#busy || next.runningElsewhere !== null;
584
+ next.phase = running ? 'streaming' : next.session.gatedTool ? 'gated' : 'idle';
520
585
  const gate = next.session.gatedTool;
521
586
  next.waitingGate = next.phase === 'gated' && gate && gate.gateKind !== 'page' ? gate : null;
522
587
  this.#state = next;
@@ -611,18 +676,27 @@ class Chat {
611
676
  #draw(view, session, events) {
612
677
  const shown = [...this.#state.blocks, ...this.#state.streamBlocks];
613
678
  const blocks = keepIds(shown, view.transcript);
614
- const drawn = [...view.transcript, ...(view.paused?.blocks ?? [])].map((block) => block.id);
679
+ const after = view.paused?.blocks ?? view.running?.prompt ?? [];
680
+ const drawn = [...view.transcript, ...after].map((block) => block.id);
681
+ const ended = this.#state.runningElsewhere !== null && view.running === undefined;
615
682
  this.#set({
616
683
  // why: A saved message the conversation now shows is no longer waiting.
617
684
  pendingMessages: takeSavedComposerPending(this.#state.pendingMessages, drawn).remaining,
618
685
  blocks,
619
- streamBlocks: keepIds(shown.slice(blocks.length), view.paused?.blocks ?? []),
686
+ streamBlocks: keepIds(shown.slice(blocks.length), after),
620
687
  // why: A reply at rest leaves the run's own events (tokens, an ask); a paused one, the host's.
621
688
  session: this.#sessionAfter(session, view.paused?.events ?? events),
622
- chatStarted: view.transcript.length > 0 || view.paused !== undefined,
689
+ chatStarted: view.transcript.length > 0 || after.length > 0 || view.running !== undefined,
690
+ runningElsewhere: view.running ?? null,
623
691
  });
624
692
  this.#wakeDue = view.wake === true;
625
693
  this.#setPush(view.notify);
694
+ this.#followHold();
695
+ // why: The reply that ran elsewhere ended as a reply here ends: the queue sends on, unless it was stopped.
696
+ if (ended && !this.#busy) {
697
+ this.#runEnded(!this.#stopped);
698
+ this.#stopped = false;
699
+ }
626
700
  }
627
701
  /**
628
702
  * Keeps the model and effort valid as the interface changes: a pick still on the old defaults
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 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';
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, type RunningReply, 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';
@@ -125,7 +125,11 @@ export type TheoremInvokeRequest = {
125
125
  };
126
126
  /** An `/invoke` body as `createTheoremHandler` reads it. */
127
127
  export declare const theoremInvokeRequestSchema: z.ZodType<TheoremInvokeRequest>;
128
- /** The person's message for an in-flight turn. */
128
+ /**
129
+ * The person's message for an in-flight reply. With `turnId`, it goes to the turn this page
130
+ * started. Without it, it goes to the reply that holds `conversation` now, one the view says runs
131
+ * elsewhere (`ConversationView.running`).
132
+ */
129
133
  export type TheoremSteerRequest = {
130
134
  turnId: string;
131
135
  /** The client's id for this steer; the turn's `stage` event names it in `injected` once it lands. */
@@ -134,6 +138,10 @@ export type TheoremSteerRequest = {
134
138
  input: Pick<TheoremTurnInput, 'text' | 'attachments' | 'voice'>;
135
139
  /** The ref of the conversation the turn replies in, when the page has one. */
136
140
  conversation?: string;
141
+ } | {
142
+ id: string;
143
+ input: Pick<TheoremTurnInput, 'text' | 'attachments' | 'voice'>;
144
+ conversation: string;
137
145
  };
138
146
  /** A `/steer` body as `createTheoremHandler` reads it. */
139
147
  export declare const theoremSteerRequestSchema: z.ZodType<TheoremSteerRequest>;
@@ -153,9 +161,15 @@ export type TheoremSavedMessage = {
153
161
  export type TheoremSteerReply = {
154
162
  saved?: TheoremSavedMessage;
155
163
  };
156
- /** Stop an in-flight turn where it stands; its stream ends with what the reply left. */
164
+ /**
165
+ * Stop an in-flight reply where it stands; its stream ends with what the reply left. With
166
+ * `turnId`, the turn this page started; with `conversation`, the reply that holds it now, one the
167
+ * view says runs elsewhere (`ConversationView.running`).
168
+ */
157
169
  export type TheoremStopRequest = {
158
170
  turnId: string;
171
+ } | {
172
+ conversation: string;
159
173
  };
160
174
  /** A `/stop` body as `createTheoremHandler` reads it. */
161
175
  export declare const theoremStopRequestSchema: z.ZodType<TheoremStopRequest>;
@@ -176,7 +190,22 @@ export type ConversationLine = {
176
190
  };
177
191
  /** The lines a chat's reply streams: turn events, and the conversation's ref. */
178
192
  export declare const CHAT_LINES: WireLines<TurnEvent | ConversationLine>;
179
- /** What the browser draws: the transcript, and the reply that waits on gates. */
193
+ /**
194
+ * A reply that runs now, away from the page that reads it: another tab, another channel, a page
195
+ * reloaded while it ran. The app's store says so (`ConversationSnapshot.running`).
196
+ */
197
+ export type RunningReply = {
198
+ /** When the reply started, in epoch milliseconds. */
199
+ since: number;
200
+ /** What the person said that the transcript does not hold yet, the messages the reply answers first. */
201
+ prompt: TranscriptBlock[];
202
+ /**
203
+ * When the hold the reply runs under lapses unless it is renewed, in epoch milliseconds. A page
204
+ * that has heard nothing by then reads the conversation again.
205
+ */
206
+ heldUntil: number;
207
+ };
208
+ /** What the browser draws: the transcript, the reply that waits on gates, and one that runs elsewhere. */
180
209
  export type ConversationView = {
181
210
  transcript: TranscriptBlock[];
182
211
  /** The reply that waits on gates: its events, and its blocks as the transcript will keep them. */
@@ -184,6 +213,8 @@ export type ConversationView = {
184
213
  events: TurnEvent[];
185
214
  blocks: TranscriptBlock[];
186
215
  };
216
+ /** A reply that runs now, away from this page. The page shows it working, and can stop and steer it. */
217
+ running?: RunningReply;
187
218
  /** The host pushes the end of a call that still runs. `retryMs` is its wait to reopen the push. */
188
219
  notify?: {
189
220
  retryMs?: number;
@@ -254,7 +285,7 @@ export interface TheoremTransport {
254
285
  turn(request: TheoremTurnRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
255
286
  invoke(request: TheoremInvokeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
256
287
  steer(request: TheoremSteerRequest): Promise<TheoremSteerReply>;
257
- /** Stops the turn; refused (`session.turn_ended`) when this host is not running it. */
288
+ /** Stops the reply; refused (`session.turn_ended`) when this host is not running it. */
258
289
  stop(request: TheoremStopRequest): Promise<void>;
259
290
  /** The conversation under `ref`, as the host shows it. */
260
291
  conversation(request: TheoremConversationRequest, signal?: AbortSignal): Promise<ConversationView>;
@@ -296,6 +327,8 @@ export declare const hostErrorBodySchema: z.ZodType<HostErrorBody>;
296
327
  export declare function hostError(body: HostErrorBody, fallbackKind: ErrorKind): TheoremStreamError;
297
328
  /** The host could not open the message's conversation (`session.conversation_unknown`). */
298
329
  export declare function isUnknownConversation(err: unknown): boolean;
330
+ /** Whether the host refused a steer or stop because the reply it names is not running (`session.turn_ended`). */
331
+ export declare function isTurnEnded(err: unknown): boolean;
299
332
  /**
300
333
  * Read an NDJSON reply, checking each line against `lines`: a kind it doesn't
301
334
  * list reaches `onLine` as `unsupported`, and a line that fails its check as
@@ -84,12 +84,16 @@ const theoremInvokeRequest = z.object({
84
84
  true;
85
85
  /** An `/invoke` body as `createTheoremHandler` reads it. */
86
86
  export const theoremInvokeRequestSchema = theoremInvokeRequest;
87
- const theoremSteerRequest = z.object({
88
- turnId: clientId,
89
- id: clientId,
90
- input: theoremTurnInput.pick({ text: true, attachments: true, voice: true }),
91
- conversation: z.string().min(1).optional(),
92
- });
87
+ const steerInput = theoremTurnInput.pick({ text: true, attachments: true, voice: true });
88
+ const theoremSteerRequest = z.union([
89
+ z.object({
90
+ turnId: clientId,
91
+ id: clientId,
92
+ input: steerInput,
93
+ conversation: z.string().min(1).optional(),
94
+ }),
95
+ z.object({ id: clientId, input: steerInput, conversation: z.string().min(1) }),
96
+ ]);
93
97
  true;
94
98
  /** A `/steer` body as `createTheoremHandler` reads it. */
95
99
  export const theoremSteerRequestSchema = theoremSteerRequest;
@@ -100,7 +104,10 @@ const theoremSavedMessage = z.object({
100
104
  true;
101
105
  const theoremSteerReply = z.object({ saved: theoremSavedMessage.optional() });
102
106
  true;
103
- const theoremStopRequest = z.object({ turnId: clientId });
107
+ const theoremStopRequest = z.union([
108
+ z.object({ turnId: clientId }),
109
+ z.object({ conversation: z.string().min(1) }),
110
+ ]);
104
111
  true;
105
112
  /** A `/stop` body as `createTheoremHandler` reads it. */
106
113
  export const theoremStopRequestSchema = theoremStopRequest;
@@ -117,11 +124,18 @@ export const CHAT_LINES = {
117
124
  ...TURN_EVENT_SCHEMAS,
118
125
  conversation: conversationLine,
119
126
  };
127
+ const runningReply = z.object({
128
+ since: z.number(),
129
+ prompt: z.array(transcriptBlockSchema),
130
+ heldUntil: z.number(),
131
+ });
132
+ true;
120
133
  const conversationView = z.object({
121
134
  transcript: z.array(transcriptBlockSchema),
122
135
  paused: z
123
136
  .object({ events: z.array(turnEventSchema), blocks: z.array(transcriptBlockSchema) })
124
137
  .optional(),
138
+ running: runningReply.optional(),
125
139
  notify: z.object({ retryMs: z.number().optional() }).optional(),
126
140
  wake: z.literal(true).optional(),
127
141
  });
@@ -205,10 +219,17 @@ export function hostError(body, fallbackKind) {
205
219
  }
206
220
  /** The host could not open the message's conversation (`session.conversation_unknown`). */
207
221
  export function isUnknownConversation(err) {
222
+ return hostSaid(err, 'session.conversation_unknown');
223
+ }
224
+ /** Whether the host refused a steer or stop because the reply it names is not running (`session.turn_ended`). */
225
+ export function isTurnEnded(err) {
226
+ return hostSaid(err, 'session.turn_ended');
227
+ }
228
+ function hostSaid(err, key) {
208
229
  if (!isTheoremStreamError(err) || err.copy === undefined)
209
230
  return false;
210
231
  const copies = Array.isArray(err.copy) ? err.copy : [err.copy];
211
- return copies.some((copy) => copy.key === 'session.conversation_unknown');
232
+ return copies.some((copy) => copy.key === key);
212
233
  }
213
234
  /** One NDJSON line checked against `lines`; an `error` line ends the stream as a {@link TheoremStreamError}. */
214
235
  function parseStreamLine(lines, text) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/web",
3
- "version": "0.3.5-next.996.g1635914",
3
+ "version": "0.3.5-next.997.g6d32810",
4
4
  "description": "Theorem on the web platform, with no UI framework: Web-standard server handlers that serve a profile, and the browser client that talks to them.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,6 +25,6 @@
25
25
  },
26
26
  "peerDependencies": {
27
27
  "zod": "^4.6.5",
28
- "@theoremjs/agents": "^0.3.5-next.996.g1635914"
28
+ "@theoremjs/agents": "^0.3.5-next.997.g6d32810"
29
29
  }
30
30
  }
@@ -5,11 +5,11 @@
5
5
  *
6
6
  * @module
7
7
  */
8
- import { type GateReference, type NormalizedTurnRequest, type Profile, type ProfileDefinition, type ProviderHostOptions, type TurnHistoryMessage, type TurnInput, type TurnRequest } from '@theoremjs/agents';
8
+ import { type GateReference, type NormalizedTurnRequest, type Profile, type ProfileDefinition, type ProviderHostOptions, TheoremError, type TurnHistoryMessage, type TurnInput, type TurnRequest } from '@theoremjs/agents';
9
9
  import { type ConversationInbox, type InboxItem, type InboxPolicy, type ReplyRun } from '@theoremjs/agents/conversation';
10
10
  import type { ClientTurnOptions } from '@theoremjs/agents/host';
11
11
  import { type TranscriptBlock } from '@theoremjs/agents/interface';
12
- import type { ConversationView, StatedTurn, TheoremInvokeRequest, TheoremRewound, TheoremSteerRequest, TheoremTurnInput } from '../client/transport.ts';
12
+ import type { ConversationView, StatedTurn, TheoremInvokeRequest, TheoremRewound, TheoremSteerRequest, TheoremStopRequest, TheoremTurnInput } from '../client/transport.ts';
13
13
  import { type ReplyLine, type ReplyToSave, type ShapedReply } from './conversation.ts';
14
14
  import { type ReplyEnd, type TheoremConversationStore } from './conversation-store.ts';
15
15
  import { type CallsContext, type CoreContext } from './session-calls.ts';
@@ -166,6 +166,12 @@ export type Generation = {
166
166
  turnId?: string;
167
167
  stated?: StatedTurn;
168
168
  };
169
+ /** Steer inboxes are scoped to the session, so a turn id alone can't reach another user's turn. */
170
+ /**
171
+ * The refusal of a stop or steer by conversation on a host that can't reach a reply it does not
172
+ * run: no app stop, or no intake for a steer. Not `turn_ended`: the reply may still be running.
173
+ */
174
+ export declare function replyUnreachable(): TheoremError;
169
175
  /**
170
176
  * What the caller of a run that ended `continue` does with its hold. `here`: runs the follow-up
171
177
  * in the same stream. `taken`: the app runs it elsewhere, by a call of its own to `followUp`.
@@ -256,12 +262,12 @@ export type ConversationCore = {
256
262
  turnId: string;
257
263
  } & Pick<TheoremSteerRequest, 'id' | 'input'>): Promise<boolean>;
258
264
  /**
259
- * Stops a running turn where it stands. False when the turn is not running. Where the app's
260
- * `inbox` has a `stop`, it stops the reply that holds the conversation, and reads no `turnId`.
265
+ * Stops a running reply where it stands: the turn `turnId` names, or the reply that holds
266
+ * `conversation`. False when it is not running. Where the app's `inbox` has a `stop`, it stops
267
+ * the reply that holds the conversation, and reads neither. Without one, only a turn this
268
+ * server runs can be stopped, by its `turnId`.
261
269
  */
262
- stop(at: CoreContext, args: {
263
- turnId: string;
264
- }): Promise<boolean>;
270
+ stop(at: CoreContext, args: TheoremStopRequest): Promise<boolean>;
265
271
  };
266
272
  /** The conversation core over `state`. */
267
273
  export declare function createConversationCore<Item extends InboxItem = InboxItem>(state: CoreState<Item>): ConversationCore;
@@ -62,6 +62,16 @@ async function* unheld(lines) {
62
62
  return { outcome: 'released' };
63
63
  }
64
64
  /** Steer inboxes are scoped to the session, so a turn id alone can't reach another user's turn. */
65
+ /**
66
+ * The refusal of a stop or steer by conversation on a host that can't reach a reply it does not
67
+ * run: no app stop, or no intake for a steer. Not `turn_ended`: the reply may still be running.
68
+ */
69
+ export function replyUnreachable() {
70
+ // labels-exempt: internal diagnostic; the user reads session.reply_unreachable
71
+ return new TheoremError('request', 'this host cannot reach a reply that runs elsewhere', {
72
+ copy: { key: 'session.reply_unreachable' },
73
+ });
74
+ }
65
75
  function inboxKey(sessionId, turnId) {
66
76
  return `${sessionId}\u0000${turnId}`;
67
77
  }
@@ -508,8 +518,9 @@ async function* wakeReplyLines(ctx, at, host, ref, generation, held, input) {
508
518
  * why: The transcript keeps a detached call as the turn left it. The session holds what became of
509
519
  * it, so a call that has ended does not read as running.
510
520
  */
511
- async function currentView(ctx, at, host, ref, conversation) {
512
- const view = conversationView(host, conversation);
521
+ async function currentView(ctx, at, host, ref, opened) {
522
+ const { conversation, running } = opened;
523
+ const view = { ...conversationView(host, conversation), ...(running ? { running } : {}) };
513
524
  const detached = view.transcript.some(isDetachedBlock);
514
525
  // why: a session's late results come from detached calls only; an app's items come from anywhere
515
526
  if (!detached && !ctx.options.inbox)
@@ -730,7 +741,7 @@ async function read(ctx, at, args) {
730
741
  if (!host)
731
742
  throw statelessRefusal('read');
732
743
  const opened = await openConversation(host, args.ref, { kind: 'read' });
733
- return currentView(ctx, at, host, args.ref, opened.conversation);
744
+ return currentView(ctx, at, host, args.ref, opened);
734
745
  }
735
746
  /** The conversation cut after one block; a reply that waits on gates is walked away from first. */
736
747
  async function rewind(ctx, at, args) {
@@ -752,7 +763,7 @@ async function rewind(ctx, at, args) {
752
763
  throw new TheoremError('internal', labelText('error.internal'));
753
764
  return {
754
765
  conversation: next.ref,
755
- view: await currentView(ctx, at, host, next.ref, next.conversation),
766
+ view: await currentView(ctx, at, host, next.ref, next),
756
767
  };
757
768
  }
758
769
  /** The conversation core over `state`. */
@@ -773,11 +784,14 @@ export function createConversationCore(state) {
773
784
  postedMessage(chatInterface(state.chat), steer.input);
774
785
  return await state.steer.enqueue(inboxKey(at.sessionId, turnId), steerUnitOf(steer));
775
786
  },
776
- stop: (at, { turnId }) => {
787
+ stop: (at, args) => {
777
788
  const app = state.options.inbox?.(at);
778
789
  if (app?.stop)
779
790
  return app.stop.ask(app.conversation);
780
- return Promise.resolve(state.steer.stop(inboxKey(at.sessionId, turnId)));
791
+ // why: without the app's stop, only this server's turns are known, each by its id
792
+ if (!('turnId' in args))
793
+ throw replyUnreachable();
794
+ return Promise.resolve(state.steer.stop(inboxKey(at.sessionId, args.turnId)));
781
795
  },
782
796
  };
783
797
  }
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { type ProviderCheckpoint, TheoremError, type TurnEvent, type TurnHistoryMessage, z } from '@theoremjs/agents';
13
13
  import type { TranscriptBlock } from '@theoremjs/agents/interface';
14
- import { type StatedTurn } from '../client/transport.ts';
14
+ import { type RunningReply, type StatedTurn } from '../client/transport.ts';
15
15
  import { type MemorySessionStoreOptions } from './session-store.ts';
16
16
  /** A reply's base and the count of its events that base holds, as they stood before a compaction. */
17
17
  export type UncompactedBase = {
@@ -64,6 +64,14 @@ export declare function emptyConversation(): StoredConversation;
64
64
  export interface ConversationSnapshot {
65
65
  revision: string;
66
66
  conversation: StoredConversation;
67
+ /**
68
+ * A reply that runs on the conversation now, as the app's own records say: one under a hold the
69
+ * app keeps (`inbox`), whichever server, channel or wake runs it. Set only while that hold is
70
+ * live. A page reads it to show the reply working, and stops and steers it by the conversation.
71
+ * The app tells the page when the reply ends (`notifier.publish` after its save). Unset, no
72
+ * reply runs, or the store does not know.
73
+ */
74
+ running?: RunningReply;
67
75
  }
68
76
  /**
69
77
  * How the reply a write saves ended. `committed`: it is over. `failed`: it ended with an error.
@@ -17,7 +17,7 @@
17
17
  import { type GateReference, type LabelOverrides, type Profile, type ProviderCheckpoint, TheoremError, type TurnEvent, type TurnHistoryMessage, type TurnInput } from '@theoremjs/agents';
18
18
  import { type ClientTurnOptions } from '@theoremjs/agents/host';
19
19
  import { type ComposerProfileInterface, type ReplyCarried, streamThoughtsEnabled, type TranscriptBlock, type UserTurnDraft, type UserTurnHistoryMedia } from '@theoremjs/agents/interface';
20
- import type { ConversationLine, ConversationView, StatedTurn, TheoremTurnInput } from '../client/transport.ts';
20
+ import type { ConversationLine, ConversationView, RunningReply, StatedTurn, TheoremTurnInput } from '../client/transport.ts';
21
21
  import { type ReplyEnd, type StoredConversation, type TheoremConversationStore } from './conversation-store.ts';
22
22
  import type { ReplyRefusal } from './turn-wiring.ts';
23
23
  /** One walked-away call: its id, and the run that settles it (`invokeTool` with the abandoned resume). */
@@ -67,6 +67,8 @@ export type OpenedConversation = {
67
67
  stored?: number;
68
68
  /** What the guardrails decided reading a restored transcript, for the reply to stream first. */
69
69
  events?: TurnEvent[];
70
+ /** The reply the store says runs on the conversation now (`ConversationSnapshot.running`). */
71
+ running?: RunningReply;
70
72
  };
71
73
  /**
72
74
  * What a request opens a conversation for, checked as it opens, before the host starts any run:
@@ -68,8 +68,10 @@ async function openedAt(host, ref, restore) {
68
68
  return { ref: null, revision: null, conversation: emptyConversation() };
69
69
  }
70
70
  const snapshot = await host.store.read(host.sessionId, ref);
71
- if (snapshot)
72
- return { ref, revision: snapshot.revision, conversation: snapshot.conversation };
71
+ if (snapshot) {
72
+ const { revision, conversation, running } = snapshot;
73
+ return { ref, revision, conversation, ...(running ? { running } : {}) };
74
+ }
73
75
  if (!restore)
74
76
  throw unknownConversation();
75
77
  // why: A null ref makes the reply's write a new conversation, whose ref the `conversation` line hands the page.
package/server/handler.js CHANGED
@@ -45,7 +45,7 @@ import { blockWithoutToolData, clientProfileInterface, eventWithoutToolData, pro
45
45
  import { hostInterface, theoremHostCallRequestSchema } from "../client/host-transport.js";
46
46
  import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
47
47
  import { statelessRefusal } from "./conversation.js";
48
- import { chatOf, createConversationCore, followedUp, oneInbox, unconversedAnswer, } from "./conversation-core.js";
48
+ import { chatOf, createConversationCore, followedUp, oneInbox, replyUnreachable, unconversedAnswer, } from "./conversation-core.js";
49
49
  import { callEvents, sessionParts } from "./session-calls.js";
50
50
  import { theoremSession } from "./session-identity.js";
51
51
  import { kernelTurnInput } from "./turn-input.js";
@@ -131,10 +131,11 @@ function shownView(ctx, view) {
131
131
  if (profileShowsToolData(ctx.profile))
132
132
  return view;
133
133
  const blocks = (list) => list.flatMap((block) => blockWithoutToolData(block) ?? []);
134
- const { paused, ...rest } = view;
134
+ const { paused, running, ...rest } = view;
135
135
  return {
136
136
  ...rest,
137
137
  transcript: blocks(view.transcript),
138
+ ...(running ? { running: { ...running, prompt: blocks(running.prompt) } } : {}),
138
139
  ...(paused
139
140
  ? {
140
141
  paused: {
@@ -442,24 +443,29 @@ async function steer(ctx, chat, request, session) {
442
443
  const saved = { conversation: taken.ref, landsAs: [...taken.landsAs] };
443
444
  return jsonResponse(200, { ok: true, saved });
444
445
  }
445
- if (!(await core.steer(at, { turnId: body.turnId, id: body.id, input: body.input }))) {
446
- // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
447
- throw new TheoremError('request', `turn ${body.turnId} is not running`, {
448
- copy: { key: 'session.turn_ended' },
449
- });
450
- }
446
+ // why: without `intake`, a steer reaches only a turn this server runs, by its id
447
+ if (!('turnId' in body))
448
+ throw replyUnreachable();
449
+ const steered = await core.steer(at, { turnId: body.turnId, id: body.id, input: body.input });
450
+ if (!steered)
451
+ throw replyNotRunning(body);
451
452
  return jsonResponse(200, { ok: true });
452
453
  }
454
+ /** The refusal of a steer or stop for a reply that is not running. */
455
+ function replyNotRunning(target) {
456
+ // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
457
+ const what = 'turnId' in target ? `turn ${target.turnId}` : 'a reply on the conversation';
458
+ // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
459
+ return new TheoremError('request', `${what} is not running`, {
460
+ copy: { key: 'session.turn_ended' },
461
+ });
462
+ }
453
463
  /** Stops a running turn where it stands; its stream goes on to save and send what the reply left. */
454
464
  async function stop(ctx, chat, request, session) {
455
465
  const body = await readBody(request, theoremStopRequestSchema, ctx.options.maxRequestBytes);
456
466
  const core = coreOf(ctx, chat, request);
457
- if (!(await core.stop(contextOf(ctx, request, session.id), { turnId: body.turnId }))) {
458
- // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
459
- throw new TheoremError('request', `turn ${body.turnId} is not running`, {
460
- copy: { key: 'session.turn_ended' },
461
- });
462
- }
467
+ if (!(await core.stop(contextOf(ctx, request, session.id), body)))
468
+ throw replyNotRunning(body);
463
469
  return jsonResponse(200, { ok: true });
464
470
  }
465
471
  /** A route this profile doesn't serve. */