@theoremjs/web 0.3.5-next.979.g76aac35 → 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/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) {
@@ -143,6 +159,7 @@ class Chat {
143
159
  failure: null,
144
160
  answering: null,
145
161
  phase: 'idle',
162
+ waitingGate: null,
146
163
  session: emptyInterfaceTurnSession(),
147
164
  delivery: null,
148
165
  streaming: false,
@@ -326,18 +343,33 @@ class Chat {
326
343
  this.#steerAfterTurnEnded();
327
344
  return;
328
345
  }
329
- const inject = userDraftToSteerInject(message.draft);
330
- if (inject.length === 0)
346
+ const input = steerInput(message.draft);
347
+ if (Object.keys(input).length === 0)
331
348
  return;
349
+ const conversation = this.#conversation;
332
350
  try {
333
- 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();
334
366
  }
335
367
  catch (err) {
336
368
  this.#set({ failure: clientFailure(err, this.#options.iface?.labels) });
337
369
  }
338
370
  };
339
371
  sendNow = async (source) => {
340
- if (!this.#options.iface)
372
+ if (!this.#options.iface || source?.saved)
341
373
  return;
342
374
  const draft = source ? source.draft : await this.#composerDraft();
343
375
  if (!draft)
@@ -350,6 +382,7 @@ class Chat {
350
382
  this.#drainArmed = false;
351
383
  // why: Sent while the reply waits on gates, the message walks away from them in its own request.
352
384
  await this.#sendDraft(draft, {
385
+ id: source?.id ?? newId(),
353
386
  walkAway: this.#state.session.gatedTool !== null,
354
387
  // why: The sent message leaves the queue, or the composer it came from.
355
388
  onPosted: () => this.#set(source
@@ -369,7 +402,7 @@ class Chat {
369
402
  };
370
403
  restorePending = async (id) => {
371
404
  const message = this.#state.pendingMessages.find((m) => m.id === id);
372
- if (!message)
405
+ if (!message || message.saved)
373
406
  return;
374
407
  try {
375
408
  await this.#restore(composerFieldsFromDraft(message.draft));
@@ -462,6 +495,8 @@ class Chat {
462
495
  #set(patch) {
463
496
  const next = { ...this.#state, ...patch };
464
497
  next.phase = this.#busy ? 'streaming' : next.session.gatedTool ? 'gated' : 'idle';
498
+ const gate = next.session.gatedTool;
499
+ next.waitingGate = next.phase === 'gated' && gate && gate.gateKind !== 'page' ? gate : null;
465
500
  this.#state = next;
466
501
  if (this.#flushQueued)
467
502
  return;
@@ -554,7 +589,10 @@ class Chat {
554
589
  #draw(view, session, events) {
555
590
  const shown = [...this.#state.blocks, ...this.#state.streamBlocks];
556
591
  const blocks = keepIds(shown, view.transcript);
592
+ const drawn = [...view.transcript, ...(view.paused?.blocks ?? [])].map((block) => block.id);
557
593
  this.#set({
594
+ // why: A saved message the conversation now shows is no longer waiting.
595
+ pendingMessages: takeSavedComposerPending(this.#state.pendingMessages, drawn).remaining,
558
596
  blocks,
559
597
  streamBlocks: keepIds(shown.slice(blocks.length), view.paused?.blocks ?? []),
560
598
  // why: A reply at rest leaves the run's own events (tokens, an ask); a paused one, the host's.
@@ -639,6 +677,7 @@ class Chat {
639
677
  this.#draining = true;
640
678
  // why: The message leaves the queue once it posts; one that never starts stays queued.
641
679
  void this.#sendDraft(message.draft, {
680
+ id: message.id,
642
681
  onPosted: () => this.#set({
643
682
  pendingMessages: removeComposerPendingMessage(this.#state.pendingMessages, message.id),
644
683
  }),
@@ -695,7 +734,8 @@ class Chat {
695
734
  });
696
735
  }
697
736
  /** The message posted: it joins the transcript, and the reply starts streaming. */
698
- #posted(blocks, patch) {
737
+ #posted(blocks, own, patch) {
738
+ this.#ownPosted = own;
699
739
  this.#setDelivery({ status: 'sending' });
700
740
  this.#set({
701
741
  blocks: [...this.#state.blocks, ...blocks],
@@ -716,8 +756,19 @@ class Chat {
716
756
  scope,
717
757
  view,
718
758
  transcript: this.#state.blocks,
719
- onUserBlocks: (blocks) => this.#posted(blocks, this.#clearedComposer()),
720
- }), { 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
+ });
721
772
  }
722
773
  #sendDraft(draft, options) {
723
774
  return this.#runTurn(({ iface, view, transport, scope, signal }) => streamInterfaceDraftTurn({
@@ -730,11 +781,18 @@ class Chat {
730
781
  view,
731
782
  transcript: this.#state.blocks,
732
783
  walkAway: options.walkAway === true,
733
- onUserBlocks: (blocks) => {
734
- this.#posted(blocks, { streamBlocks: [] });
784
+ onUserBlocks: (blocks, own) => {
785
+ this.#posted(blocks, own, { streamBlocks: [] });
735
786
  options.onPosted();
736
787
  },
737
- }), { 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
+ });
738
796
  }
739
797
  /** The gate on the reply still running that no answer is on its way to. */
740
798
  #drawnGate() {
@@ -799,6 +857,8 @@ class Chat {
799
857
  const base = withPageToolDispatch(transport, pageTools);
800
858
  const tap = (onLine) => (line) => {
801
859
  this.#took(line);
860
+ if (line.type === 'conversation' && line.opened)
861
+ this.#opened(line.opened, onLine);
802
862
  onLine(line);
803
863
  };
804
864
  return {
@@ -853,10 +913,43 @@ class Chat {
853
913
  DELIVERY_ORDER.indexOf(reached) > DELIVERY_ORDER.indexOf(delivery.status)) {
854
914
  this.#setDelivery({ status: reached });
855
915
  }
856
- if (line.type === 'conversation')
916
+ if (line.type === 'conversation') {
857
917
  this.#adopt(line.ref);
858
- else
859
- 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
+ });
860
953
  }
861
954
  #streamFrame(partial) {
862
955
  this.#frameBlocks = partial;
@@ -883,12 +976,15 @@ class Chat {
883
976
  const { message } = options;
884
977
  const priorDelivery = this.#delivery;
885
978
  const abort = options.turn ? new AbortController() : null;
886
- const turnId = options.turn ? newTurnId() : undefined;
979
+ const turnId = options.turn ? newId() : undefined;
887
980
  this.#busy = true;
888
981
  this.#abort = abort;
889
982
  this.#turnId = turnId ?? null;
890
983
  this.#stopped = false;
891
984
  this.#drainArmed = false;
985
+ this.#savedAs = null;
986
+ this.#ownPosted = 0;
987
+ this.#streamed = false;
892
988
  // why: A message streams once it posts, so the previous reply never shows as streaming before it.
893
989
  // A wake shows only once the host's reply begins; one with nothing to wake for shows nothing.
894
990
  if (!options.wake)
@@ -903,7 +999,7 @@ class Chat {
903
999
  const outcome = await run({
904
1000
  iface,
905
1001
  transport: this.#runTransport(),
906
- scope: { conversation: this.#conversation, turnId },
1002
+ scope: { conversation: this.#conversation, turnId, id: message?.id },
907
1003
  signal: abort?.signal,
908
1004
  view: {
909
1005
  blocks: (partial) => this.#streamFrame(partial),
@@ -920,7 +1016,7 @@ class Chat {
920
1016
  await this.#takeBack(start, message);
921
1017
  let waits;
922
1018
  if (keepsConversation(iface)) {
923
- waits = await this.#settleHosted(outcome, start);
1019
+ waits = await this.#settleHosted(outcome, start, options);
924
1020
  }
925
1021
  else if (unposted) {
926
1022
  this.#showFailure(outcome.failure);
@@ -976,7 +1072,7 @@ class Chat {
976
1072
  * in the composer unless the host's transcript closed on it. Returns whether the reply waits
977
1073
  * on gates.
978
1074
  */
979
- async #settleHosted(outcome, start) {
1075
+ async #settleHosted(outcome, start, { message, wake }) {
980
1076
  const { failure } = outcome;
981
1077
  if (failure)
982
1078
  this.#setDelivery(null);
@@ -987,12 +1083,34 @@ class Chat {
987
1083
  return this.#state.session.gatedTool !== null;
988
1084
  }
989
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
+ }
990
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;
991
1094
  if (!view.transcript.slice(start.blocks.length).some((b) => b.kind === 'error')) {
992
1095
  this.#showFailure(failure);
993
1096
  }
994
1097
  return view.paused !== undefined;
995
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
+ }
996
1114
  /**
997
1115
  * A stateless chat keeps the reply as the run streamed it: in the transcript once it ends
998
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';
@@ -35,9 +35,10 @@ export type StreamInterfaceTurnBaseArgs = {
35
35
  /**
36
36
  * Fires once the message posts, with the blocks the transcript gains: a
37
37
  * walked-away reply's settled blocks, then the message's own (with media
38
- * preview data). Walking away, it posts once the host has it.
38
+ * preview data). Walking away, it posts once the host has it. `own` is how many of the blocks,
39
+ * at the end, are the message's.
39
40
  */
40
- onUserBlocks: (blocks: TranscriptBlock[]) => void;
41
+ onUserBlocks: (blocks: TranscriptBlock[], own: number) => void;
41
42
  signal?: AbortSignal;
42
43
  /**
43
44
  * Send while the reply waits on gates: the message walks away from every
@@ -60,6 +61,15 @@ export type StreamInterfaceTurnArgs = StreamInterfaceTurnBaseArgs & {
60
61
  export type StreamInterfaceDraftTurnArgs = StreamInterfaceTurnBaseArgs & {
61
62
  draft: UserTurnDraft;
62
63
  };
64
+ export declare function extractInlineEncodedAttachments(attachments?: readonly {
65
+ name: string;
66
+ mimeType: string;
67
+ data?: unknown;
68
+ }[]): Array<{
69
+ name: string;
70
+ mimeType: string;
71
+ data: string;
72
+ }> | undefined;
63
73
  export declare function streamInterfaceTurn(args: StreamInterfaceTurnArgs): Promise<RunOutcome>;
64
74
  /** Send a turn from an already-encoded pending draft (queue drain / send now). */
65
75
  export declare function streamInterfaceDraftTurn(args: StreamInterfaceDraftTurnArgs): Promise<RunOutcome>;
@@ -41,13 +41,13 @@ async function streamPreparedTurn(args) {
41
41
  const events = walking ? [...paused] : [];
42
42
  let posted = !keeps;
43
43
  if (!walking)
44
- args.onUserBlocks(userBlocks);
44
+ args.onUserBlocks(userBlocks, userBlocks.length);
45
45
  const onConversation = (line) => {
46
46
  if (!line.posted)
47
47
  return;
48
48
  posted = true;
49
49
  if (walking) {
50
- args.onUserBlocks([...foldAssistantTurn(args.iface, events), ...userBlocks]);
50
+ args.onUserBlocks([...foldAssistantTurn(args.iface, events), ...userBlocks], userBlocks.length);
51
51
  events.length = 0;
52
52
  }
53
53
  };
@@ -87,7 +87,7 @@ async function streamPreparedTurn(args) {
87
87
  }
88
88
  return { session: args.session, events, posted };
89
89
  }
90
- function extractInlineEncodedAttachments(attachments) {
90
+ export function extractInlineEncodedAttachments(attachments) {
91
91
  const filtered = attachments
92
92
  ?.filter((a) => typeof a.data === 'string')
93
93
  .map((a) => ({ name: a.name, mimeType: a.mimeType, data: a.data }));
@@ -8,3 +8,7 @@ import { z } from '@theoremjs/agents';
8
8
  import type { TranscriptBlock } from '@theoremjs/agents/interface';
9
9
  /** One transcript block, as a host stores it and the browser reads it back. */
10
10
  export declare const transcriptBlockSchema: z.ZodType<TranscriptBlock>;
11
+ /** The block without the app's own values: a page cannot state them. */
12
+ export declare function withoutHost(block: TranscriptBlock): TranscriptBlock;
13
+ /** A block as a page's request states it: `host` is the app's to set, so it is dropped. */
14
+ export declare const pageBlockSchema: z.ZodPipe<z.ZodType<TranscriptBlock, unknown, z.core.$ZodTypeInternals<TranscriptBlock, unknown>>, z.ZodTransform<import("../../../src/interface/types").UserTextBlock | import("../../../src/interface/types").UserAttachmentBlock | import("../../../src/interface/types").ThoughtBlock | import("../../../src/interface/types").TextBlock | import("../../../src/interface/types").ToolBlock | import("../../../src/interface/types").StructuredBlock | import("../../../src/interface/types").MediaBlock | import("../../../src/interface/types").GroundingBlock | import("../../../src/interface/types").CitationBlock | import("../../../src/interface/types").EvidenceBlock | import("../../../src/interface/types").GuardrailBlock | import("../../../src/interface/types").LateResultsBlock | import("../../../src/interface/types").ErrorBlock | import("../../../src/interface/types").TurnDoneBlock, TranscriptBlock>>;
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { MEDIA_INPUT_KIND_VALUES, reasoningPartSchema, TURN_STOP_KINDS, turnEventSchema, z, } from '@theoremjs/agents';
8
8
  import { guardrailEventSchema } from '@theoremjs/agents/guardrails';
9
+ import { jsonObjectSchema } from '@theoremjs/agents/kernel';
9
10
  // why: The block shapes' event parts have one schema, the turn event's; a probe event reuses it.
10
11
  function eventPart(probe) {
11
12
  return z.custom((value) => turnEventSchema.safeParse(probe(value)).success);
@@ -49,7 +50,7 @@ const toolCall = z.object({
49
50
  true;
50
51
  const turnStop = z.object({ kind: z.enum(TURN_STOP_KINDS), native: z.string().optional() });
51
52
  true;
52
- const blockId = { id: z.string() };
53
+ const blockId = { id: z.string(), host: jsonObjectSchema.optional() };
53
54
  const transcriptBlock = z.discriminatedUnion('kind', [
54
55
  z.object({ ...blockId, kind: z.literal('user-text'), text: z.string() }),
55
56
  z.object({
@@ -131,3 +132,10 @@ const transcriptBlock = z.discriminatedUnion('kind', [
131
132
  true;
132
133
  /** One transcript block, as a host stores it and the browser reads it back. */
133
134
  export const transcriptBlockSchema = transcriptBlock;
135
+ /** The block without the app's own values: a page cannot state them. */
136
+ export function withoutHost(block) {
137
+ const { host: _host, ...rest } = block;
138
+ return rest;
139
+ }
140
+ /** A block as a page's request states it: `host` is the app's to set, so it is dropped. */
141
+ export const pageBlockSchema = transcriptBlockSchema.transform(withoutHost);
@@ -10,7 +10,7 @@ import type { PageDispatchResult } from './page-dispatch.ts';
10
10
  *
11
11
  * @module
12
12
  */
13
- import { type ErrorKind, type TurnEvent, type TurnHistoryMessage, type TurnToolSnapshot, z } from '@theoremjs/agents';
13
+ import { type ErrorKind, type TurnEvent, type TurnToolSnapshot, z } from '@theoremjs/agents';
14
14
  import { type ErrorCopies } from '@theoremjs/agents/guardrails';
15
15
  import { type ProfileInterface, type TranscriptBlock } from '@theoremjs/agents/interface';
16
16
  import type { PagePart } from './tool-resume.ts';
@@ -74,6 +74,11 @@ export type TheoremTurnRequest = {
74
74
  stated?: StatedTurn;
75
75
  /** Client-generated id so mid-turn steers can find this turn's inbox. */
76
76
  turnId?: string;
77
+ /**
78
+ * The client's id for this message. A message keeps its id when the page sends it again, so a
79
+ * host that saves messages itself (`intake`) saves it one time.
80
+ */
81
+ id?: string;
77
82
  /** invariant: Both issued IDs identify each paused action that this message abandons. */
78
83
  abandon?: GateReference[];
79
84
  /** The tools the person allowed for the page, for a host without a session (the studio). */
@@ -120,15 +125,34 @@ export type TheoremInvokeRequest = {
120
125
  };
121
126
  /** An `/invoke` body as `createTheoremHandler` reads it. */
122
127
  export declare const theoremInvokeRequestSchema: z.ZodType<TheoremInvokeRequest>;
123
- /** Inject user messages into an in-flight turn. */
128
+ /** The person's message for an in-flight turn. */
124
129
  export type TheoremSteerRequest = {
125
130
  turnId: string;
126
131
  /** The client's id for this steer; the turn's `stage` event names it in `injected` once it lands. */
127
132
  id: string;
128
- inject: TurnHistoryMessage[];
133
+ /** The message, as a `/turn` posts one. The host makes the user message the model reads. */
134
+ input: Pick<TheoremTurnInput, 'text' | 'attachments' | 'voice'>;
135
+ /** The ref of the conversation the turn replies in, when the page has one. */
136
+ conversation?: string;
129
137
  };
130
138
  /** A `/steer` body as `createTheoremHandler` reads it. */
131
139
  export declare const theoremSteerRequestSchema: z.ZodType<TheoremSteerRequest>;
140
+ /**
141
+ * A message the host saved itself (`intake`), with no reply to it on this request. `landsAs` is
142
+ * each id a reply names the message by when it reads it: an inject's id on a `stage` line, an id
143
+ * in a `conversation` line's `opened`, or a block's id in the conversation.
144
+ */
145
+ export type TheoremSavedMessage = {
146
+ conversation: string;
147
+ landsAs: string[];
148
+ };
149
+ /**
150
+ * What the host did with a steer. With `saved`, the host keeps the message; without it, the steer
151
+ * waits in the running turn, and the page sends it again when the turn ends without it.
152
+ */
153
+ export type TheoremSteerReply = {
154
+ saved?: TheoremSavedMessage;
155
+ };
132
156
  /** Stop an in-flight turn where it stands; its stream ends with what the reply left. */
133
157
  export type TheoremStopRequest = {
134
158
  turnId: string;
@@ -139,12 +163,16 @@ export declare const theoremStopRequestSchema: z.ZodType<TheoremStopRequest>;
139
163
  * The ref the store issued for the conversation a run wrote: the client sends
140
164
  * it with its next request. It comes before the run's error, which ends the stream.
141
165
  * `posted` marks the write that holds the person's new message: a run that
142
- * fails before it leaves the message unsent.
166
+ * fails before it leaves the message unsent. `landsAs` says the host saved the message itself
167
+ * (`intake`), and is each id a reply names it by (see `TheoremSavedMessage`). `opened` is the id
168
+ * of each item that waited for the model and that the reply starting here reads first.
143
169
  */
144
170
  export type ConversationLine = {
145
171
  type: 'conversation';
146
172
  ref: string;
147
173
  posted?: true;
174
+ landsAs?: string[];
175
+ opened?: string[];
148
176
  };
149
177
  /** The lines a chat's reply streams: turn events, and the conversation's ref. */
150
178
  export declare const CHAT_LINES: WireLines<TurnEvent | ConversationLine>;
@@ -225,7 +253,7 @@ export interface TheoremTransport {
225
253
  describe(signal?: AbortSignal): Promise<ProfileInterface>;
226
254
  turn(request: TheoremTurnRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
227
255
  invoke(request: TheoremInvokeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
228
- steer(request: TheoremSteerRequest): Promise<void>;
256
+ steer(request: TheoremSteerRequest): Promise<TheoremSteerReply>;
229
257
  /** Stops the turn; refused (`session.turn_ended`) when this host is not running it. */
230
258
  stop(request: TheoremStopRequest): Promise<void>;
231
259
  /** The conversation under `ref`, as the host shows it. */
@@ -9,10 +9,10 @@ import { gateReferenceSchema, TOOL_GATE_KINDS, } from '@theoremjs/agents';
9
9
  *
10
10
  * @module
11
11
  */
12
- import { describeError, errorKindSchema, isAbortError, TheoremError, TURN_EVENT_SCHEMAS, throwIfAborted, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, z, } from '@theoremjs/agents';
12
+ import { describeError, errorKindSchema, isAbortError, TheoremError, TURN_EVENT_SCHEMAS, throwIfAborted, turnEventSchema, turnToolSnapshotSchema, z, } from '@theoremjs/agents';
13
13
  import { errorCopiesSchema, kindOfHttpStatus, } from '@theoremjs/agents/guardrails';
14
14
  import { profileInterfaceSchema, } from '@theoremjs/agents/interface';
15
- import { transcriptBlockSchema } from "./transcript-schema.js";
15
+ import { pageBlockSchema, transcriptBlockSchema } from "./transcript-schema.js";
16
16
  import { checkWire, parseWireJson, readWireLine, } from "./wire-line.js";
17
17
  const encodedBlob = z.object({ name: z.string(), mimeType: z.string(), data: z.string() });
18
18
  true;
@@ -53,6 +53,7 @@ const theoremTurnRequest = z.object({
53
53
  effort: z.string().optional(),
54
54
  stated: statedTurn.optional(),
55
55
  turnId: clientId.optional(),
56
+ id: clientId.optional(),
56
57
  abandon: z.array(gateReferenceSchema).min(1).optional(),
57
58
  replay: theoremReplay.pick({ sessionPermissions: true }).optional(),
58
59
  transcript: z.array(transcriptBlockSchema).optional(),
@@ -86,11 +87,19 @@ export const theoremInvokeRequestSchema = theoremInvokeRequest;
86
87
  const theoremSteerRequest = z.object({
87
88
  turnId: clientId,
88
89
  id: clientId,
89
- inject: z.array(turnHistoryMessageSchema).min(1),
90
+ input: theoremTurnInput.pick({ text: true, attachments: true, voice: true }),
91
+ conversation: z.string().min(1).optional(),
90
92
  });
91
93
  true;
92
94
  /** A `/steer` body as `createTheoremHandler` reads it. */
93
95
  export const theoremSteerRequestSchema = theoremSteerRequest;
96
+ const theoremSavedMessage = z.object({
97
+ conversation: z.string().min(1),
98
+ landsAs: z.array(z.string().min(1)).min(1),
99
+ });
100
+ true;
101
+ const theoremSteerReply = z.object({ saved: theoremSavedMessage.optional() });
102
+ true;
94
103
  const theoremStopRequest = z.object({ turnId: clientId });
95
104
  true;
96
105
  /** A `/stop` body as `createTheoremHandler` reads it. */
@@ -99,6 +108,8 @@ const conversationLine = z.object({
99
108
  type: z.literal('conversation'),
100
109
  ref: z.string().min(1),
101
110
  posted: z.literal(true).optional(),
111
+ landsAs: z.array(z.string().min(1)).min(1).optional(),
112
+ opened: z.array(z.string().min(1)).min(1).optional(),
102
113
  });
103
114
  true;
104
115
  /** The lines a chat's reply streams: turn events, and the conversation's ref. */
@@ -140,7 +151,8 @@ const theoremRewindRequest = z.object({
140
151
  true;
141
152
  /** A `/rewind` body as `createTheoremHandler` reads it. */
142
153
  export const theoremRewindRequestSchema = theoremRewindRequest;
143
- const theoremStartRequest = z.object({ blocks: z.array(transcriptBlockSchema) });
154
+ // invariant: These blocks are a page's; only the app's own save sets a block's `host`.
155
+ const theoremStartRequest = z.object({ blocks: z.array(pageBlockSchema) });
144
156
  true;
145
157
  /** A `/conversation/start` body as a host reads it. */
146
158
  export const theoremStartRequestSchema = theoremStartRequest;
@@ -371,7 +383,7 @@ export function createHttpTransport(options = {}) {
371
383
  }, { ...options, signal }),
372
384
  rewind: (body, signal) => fetchRewound(`${base}/rewind`, body, { ...options, signal }),
373
385
  pageResult: (body, signal) => postJson(`${base}/page-result`, body, { ...options, signal }),
374
- steer: (body) => postJson(`${base}/steer`, body, options),
386
+ steer: async (body) => theoremSteerReply.parse(await fetchJson(`${base}/steer`, { body }, options)),
375
387
  stop: (body) => postJson(`${base}/stop`, body, options),
376
388
  };
377
389
  }
@@ -17,10 +17,14 @@ export type HeldCall = {
17
17
  export type WalkAway = {
18
18
  calls: readonly GatedToolContext[];
19
19
  };
20
- /** Where a request goes on from: the ref of the conversation the host keeps, and the run's id for steers. */
20
+ /**
21
+ * Where a request goes on from: the ref of the conversation the host keeps, the run's id for
22
+ * steers, and the id of the message a turn sends.
23
+ */
21
24
  export type RunScope = {
22
25
  conversation?: string;
23
26
  turnId?: string;
27
+ id?: string;
24
28
  };
25
29
  export declare function buildTurnRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, input: TheoremTurnInput, options?: RunScope & {
26
30
  walkAway?: WalkAway;
@@ -54,6 +54,7 @@ export function buildTurnRequest(iface, session, input, options = {}) {
54
54
  }));
55
55
  return {
56
56
  ...scopeFields(options),
57
+ ...(options.id ? { id: options.id } : {}),
57
58
  ...generationFields(iface, session),
58
59
  input,
59
60
  ...(abandon.length ? { abandon } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/web",
3
- "version": "0.3.5-next.979.g76aac35",
3
+ "version": "0.3.5-next.981.gf4729de",
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.979.g76aac35"
28
+ "@theoremjs/agents": "^0.3.5-next.981.gf4729de"
29
29
  }
30
30
  }