@theoremjs/web 0.3.5-next.1020.g3a48861 → 0.3.5-next.1025.g5523d8f

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
@@ -230,6 +230,30 @@ The methods for the composer depend on the phase:
230
230
  | `branch(index)` | Cuts the conversation after transcript block `index`. |
231
231
  | `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. |
232
232
 
233
+ ### Name your app's objects in a message
234
+
235
+ Use refs when a message points at something your app holds, such as a saved document, and your server must know which one without reading the words. A message's `parts` are its words and refs in order: `{ type: 'text', text }` and `{ type: 'ref', kind, id }`. `kind` and `id` are your own strings.
236
+
237
+ ```ts
238
+ const chat = createChatController({ transport, iface, refText: (ref) => `[${ref.id}]` });
239
+
240
+ chat.setDraftText('Compare [doc-7] with the last one');
241
+ chat.setDraftParts([
242
+ { type: 'text', text: 'Compare ' },
243
+ { type: 'ref', kind: 'document', id: 'doc-7' },
244
+ { type: 'text', text: ' with the last one' },
245
+ ]);
246
+ await chat.submit();
247
+ ```
248
+
249
+ - Call `setDraftParts` after `setDraftText`: `setDraftText` clears the parts. The React composer does both.
250
+ - `refText` writes a ref into the message's text. Without it, a ref is written as its id. Give `createTheoremHandler` or `createTheoremConversationCore` the same `refText`.
251
+ - The server writes the text from the parts. It does not read the text the page sent.
252
+ - Your `prepare` reads `turn.input.parts`. The page can send any `kind` and `id`, so check that this person may use what they name.
253
+ - The model reads the text, not the parts. Earlier messages reach the model as text.
254
+ - A queued, stashed, steered, or restored message keeps its parts, and so does the saved transcript.
255
+ - With your own `intake`, call `personMessageOf(steer, refText)` to build the message.
256
+
233
257
  ### Messages the host saved
234
258
 
235
259
  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.
@@ -283,6 +307,7 @@ const transport = withPageToolDispatch(
283
307
  | `provider` | Host options, including the credential vault. A function can return these options per request, for example for tenant-specific credentials. |
284
308
  | `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. |
285
309
  | `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. |
310
+ | `refText` | Writes each ref of a message into its text. Default: the ref's id. See [Name your app's objects in a message](#name-your-apps-objects-in-a-message). |
286
311
  | `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. |
287
312
  | `core` | A `ConversationCore` your app built (`createTheoremConversationCore`). The handler runs each chat call on it, `/notify` and `/follow` too, and takes no `prepare`, `inbox`, `onStage`, `beforeSave`, `afterSave`, `compact`, `lateResultsDecider`, `background`, `notifier`, `replyFeed`, `notifyRetryMs`, `authorizeToolReplay` or `authorizationUrl` beside it: the core has them. It does take `intake` and `onContinue`. |
288
313
  | `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 needs `intake`: it saves the message into your inbox. Without `intake`, the handler refuses the steer with a `config` error. Do not set `inbox` with `lateResultsDecider`. |
package/client/chat.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ProfileOptions } from '@theoremjs/agents';
2
- import { type AttachmentValidationIssue, type ComposerMenuAction, type ComposerPendingMessage, type ComposerProfileInterface, type ComposerRunPhase, type GatedToolContext, type InterfaceTurnSession, type TranscriptBlock } from '@theoremjs/agents/interface';
2
+ import { type AttachmentValidationIssue, type ComposerMenuAction, type ComposerPendingMessage, type ComposerProfileInterface, type ComposerRunPhase, type GatedToolContext, type InterfaceTurnSession, type RefText, type TranscriptBlock, type UserPart } from '@theoremjs/agents/interface';
3
3
  import { type ClientFailure } from './failure.ts';
4
4
  import { type PageTools } from './live/live-page-tool.ts';
5
5
  import type { AnsweringGate, ToolDecisionAction } from './tool-resume.ts';
@@ -20,6 +20,11 @@ export type ChatOptions = {
20
20
  * once, and does not read it from the host again.
21
21
  */
22
22
  conversationView?: ConversationView;
23
+ /**
24
+ * Writes a message's refs into its text where the page draws it; the ref's id when absent. Give
25
+ * the composer's chips and the server the same one.
26
+ */
27
+ refText?: RefText;
23
28
  /** The text the composer starts with. Read once, when the chat is created. */
24
29
  initialText?: string;
25
30
  /** The files the composer starts with, staged to send. Read once, when the chat is created. */
@@ -76,6 +81,8 @@ export type ChatState = {
76
81
  streamBlocks: TranscriptBlock[];
77
82
  chatStarted: boolean;
78
83
  draftText: string;
84
+ /** The composer's words and refs, while it holds a ref; `draftText` is their plain copy. */
85
+ draftParts?: UserPart[];
79
86
  pendingFiles: File[];
80
87
  pendingVoice: File[];
81
88
  /** Steered, queued, and stashed messages. */
@@ -134,6 +141,8 @@ export type ChatController = {
134
141
  /** The latest options. `conversation`, `conversationView` and `initialText` are read only at creation. */
135
142
  update(options: ChatOptions): void;
136
143
  setDraftText(value: ChatUpdate<string>): void;
144
+ /** The refs of the composer's draft, as the composer reads them after `setDraftText`. */
145
+ setDraftParts(parts: UserPart[] | undefined): void;
137
146
  setPendingFiles(value: ChatUpdate<File[]>): void;
138
147
  setPendingVoice(value: ChatUpdate<File[]>): void;
139
148
  setPendingMessages(value: ChatUpdate<ComposerPendingMessage[]>): void;
package/client/chat.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { attachmentsRefused, TheoremError, } from '@theoremjs/agents';
2
- import { branchInterfaceTurnSession, consumeNextComposerQueue, convertSteersToFrontQueued, createComposerPendingMessage, defaultInterfaceEffort, emptyInterfaceTurnSession, moveComposerPendingWithinKind, orderComposerPendingMessages, prepareUserTurn, promoteComposerPendingKind, removeComposerPendingMessage, removeLandedSteers, saveComposerPendingMessage, takeSavedComposerPending, userDraftHasPayload, userDraftToSteerInject, } from '@theoremjs/agents/interface';
2
+ import { branchInterfaceTurnSession, consumeNextComposerQueue, convertSteersToFrontQueued, createComposerPendingMessage, defaultInterfaceEffort, emptyInterfaceTurnSession, hasRef, moveComposerPendingWithinKind, orderComposerPendingMessages, prepareUserTurn, 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";
@@ -96,6 +96,7 @@ function steerInput(draft) {
96
96
  const voice = extractInlineEncodedAttachments(draft.voice);
97
97
  return {
98
98
  ...(draft.text?.trim() ? { text: draft.text } : {}),
99
+ ...(draft.parts ? { parts: draft.parts } : {}),
99
100
  ...(attachments ? { attachments } : {}),
100
101
  ...(voice ? { voice } : {}),
101
102
  };
@@ -403,22 +404,36 @@ class Chat {
403
404
  // why: Editing the text answers a refusal for its length; a refusal for the files stays until they change.
404
405
  this.#set({
405
406
  draftText: next,
407
+ // why: Text set without parts holds no refs; the composer reports its refs right after.
408
+ draftParts: undefined,
406
409
  issues,
407
410
  ...(failure?.errorKind === 'input' && issues.length === 0 ? { failure: null } : {}),
408
411
  });
409
412
  };
413
+ /** The refs of the composer's draft, as the composer reads them after `setDraftText`. */
414
+ setDraftParts = (parts) => {
415
+ const next = hasRef(parts) ? parts : undefined;
416
+ if (JSON.stringify(next) === JSON.stringify(this.#state.draftParts))
417
+ return;
418
+ this.#set({ draftParts: next });
419
+ };
410
420
  setPendingFiles = (value) => this.#apply('pendingFiles', value);
411
421
  setPendingVoice = (value) => this.#apply('pendingVoice', value);
412
422
  setPendingMessages = (value) => this.#apply('pendingMessages', value);
413
423
  setIssues = (value) => this.#apply('issues', value);
414
424
  submit = async () => {
415
- const { phase, draftText, pendingFiles, pendingVoice } = this.#state;
425
+ const { phase, draftText, draftParts, pendingFiles, pendingVoice } = this.#state;
416
426
  if (phase !== 'idle') {
417
427
  await this.enqueue('queue');
418
428
  return;
419
429
  }
420
430
  this.#set({ issues: [] });
421
- await this.#sendFields({ text: draftText, files: [...pendingFiles], voice: [...pendingVoice] });
431
+ await this.#sendFields({
432
+ text: draftText,
433
+ parts: draftParts,
434
+ files: [...pendingFiles],
435
+ voice: [...pendingVoice],
436
+ });
422
437
  };
423
438
  stop = () => {
424
439
  void this.#stop();
@@ -470,16 +485,23 @@ class Chat {
470
485
  return stopped;
471
486
  }
472
487
  enqueue = async (kind) => {
473
- const { draftText, pendingFiles, pendingVoice } = this.#state;
488
+ const { draftText, draftParts, pendingFiles, pendingVoice } = this.#state;
474
489
  if (!composerHasPayload(draftText, pendingFiles, pendingVoice))
475
490
  return;
476
491
  this.#set({ issues: [] });
477
492
  let message;
478
493
  try {
479
- const draft = await encodeComposerDraft({ text: draftText, pendingFiles, pendingVoice });
494
+ const draft = await encodeComposerDraft({
495
+ text: draftText,
496
+ parts: draftParts,
497
+ pendingFiles,
498
+ pendingVoice,
499
+ });
480
500
  message = createComposerPendingMessage({ kind, draft });
481
501
  const { iface } = this.#options;
482
- const checked = kind !== 'stash' && iface ? prepareUserTurn(iface.inputs, draft, iface.guardrails) : null;
502
+ const checked = kind !== 'stash' && iface
503
+ ? prepareUserTurn(iface.inputs, draft, iface.guardrails, this.#options.refText)
504
+ : null;
483
505
  if (checked && !checked.ok) {
484
506
  // why: A message the profile refuses is never queued or steered; it stays in the composer as typed.
485
507
  this.#set({
@@ -731,7 +753,7 @@ class Chat {
731
753
  }), { turn: true, wake: true });
732
754
  }
733
755
  #clearedComposer() {
734
- return { draftText: '', pendingFiles: [], pendingVoice: [] };
756
+ return { draftText: '', draftParts: undefined, pendingFiles: [], pendingVoice: [] };
735
757
  }
736
758
  #setDelivery(next) {
737
759
  this.#delivery = next;
@@ -892,15 +914,25 @@ class Chat {
892
914
  }
893
915
  /** The composer's draft, when it holds something to send. */
894
916
  async #composerDraft() {
895
- const { draftText, pendingFiles, pendingVoice } = this.#state;
896
- const draft = await encodeComposerDraft({ text: draftText, pendingFiles, pendingVoice });
917
+ const { draftText, draftParts, pendingFiles, pendingVoice } = this.#state;
918
+ const draft = await encodeComposerDraft({
919
+ text: draftText,
920
+ parts: draftParts,
921
+ pendingFiles,
922
+ pendingVoice,
923
+ });
897
924
  return userDraftHasPayload(draft) ? draft : undefined;
898
925
  }
899
926
  /** Puts a message back in the composer. What the composer holds now is stashed first, so nothing typed is lost. */
900
927
  async #restore(fields) {
901
- const { draftText, pendingFiles, pendingVoice } = this.#state;
928
+ const { draftText, draftParts, pendingFiles, pendingVoice } = this.#state;
902
929
  if (composerHasPayload(draftText, pendingFiles, pendingVoice)) {
903
- const draft = await encodeComposerDraft({ text: draftText, pendingFiles, pendingVoice });
930
+ const draft = await encodeComposerDraft({
931
+ text: draftText,
932
+ parts: draftParts,
933
+ pendingFiles,
934
+ pendingVoice,
935
+ });
904
936
  const stash = createComposerPendingMessage({ kind: 'stash', draft });
905
937
  this.#set({
906
938
  pendingMessages: orderComposerPendingMessages([...this.#state.pendingMessages, stash]),
@@ -908,6 +940,7 @@ class Chat {
908
940
  }
909
941
  this.#set({
910
942
  draftText: fields.text,
943
+ draftParts: fields.parts,
911
944
  pendingFiles: fields.files,
912
945
  pendingVoice: fields.voice,
913
946
  issues: [],
@@ -942,6 +975,8 @@ class Chat {
942
975
  transport,
943
976
  session: this.#state.session,
944
977
  text: fields.text,
978
+ parts: fields.parts,
979
+ refText: this.#options.refText,
945
980
  pendingFiles: fields.files,
946
981
  pendingVoice: fields.voice,
947
982
  signal,
@@ -955,6 +990,7 @@ class Chat {
955
990
  id: newId(),
956
991
  draft: () => encodeComposerDraft({
957
992
  text: fields.text,
993
+ parts: fields.parts,
958
994
  pendingFiles: fields.files,
959
995
  pendingVoice: fields.voice,
960
996
  }),
@@ -968,6 +1004,7 @@ class Chat {
968
1004
  transport,
969
1005
  session: this.#state.session,
970
1006
  draft,
1007
+ refText: this.#options.refText,
971
1008
  signal,
972
1009
  scope,
973
1010
  view,
@@ -1128,7 +1165,11 @@ class Chat {
1128
1165
  const read = {
1129
1166
  type: 'stage',
1130
1167
  stage: 'pre_turn',
1131
- injected: landed.map((m) => ({ id: m.id, messages: userDraftToSteerInject(m.draft) })),
1168
+ injected: landed.map((m) => ({
1169
+ id: m.id,
1170
+ messages: userDraftToSteerInject(m.draft),
1171
+ ...(m.draft.parts ? { userParts: m.draft.parts } : {}),
1172
+ })),
1132
1173
  };
1133
1174
  if (this.#streamed || this.#ownPosted === 0) {
1134
1175
  onLine(read);
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * Restore composer fields from a serializable pending `UserTurnDraft`.
3
3
  */
4
- import type { UserTurnDraft } from '@theoremjs/agents/interface';
4
+ import type { UserPart, UserTurnDraft } from '@theoremjs/agents/interface';
5
5
  export type ComposerDraftFields = {
6
6
  text: string;
7
+ parts?: UserPart[];
7
8
  files: File[];
8
9
  voice: File[];
9
10
  };
@@ -6,6 +6,7 @@ import { pendingAttachmentsToFiles } from "./encode-files.js";
6
6
  export function composerFieldsFromDraft(draft) {
7
7
  return {
8
8
  text: draft.text ?? '',
9
+ ...(draft.parts ? { parts: draft.parts } : {}),
9
10
  files: pendingAttachmentsToFiles(draft.attachments ?? []),
10
11
  voice: pendingAttachmentsToFiles(draft.voice ?? []),
11
12
  };
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Encode composer fields into a serializable `UserTurnDraft` for pending intents.
3
3
  */
4
- import type { UserTurnDraft } from '@theoremjs/agents/interface';
4
+ import { type UserPart, type UserTurnDraft } from '@theoremjs/agents/interface';
5
5
  export declare function encodeComposerDraft(args: {
6
6
  text: string;
7
+ /** The words and refs `text` is the plain copy of. */
8
+ parts?: readonly UserPart[];
7
9
  pendingFiles?: readonly File[];
8
10
  pendingVoice?: readonly File[];
9
11
  }): Promise<UserTurnDraft>;
@@ -1,15 +1,18 @@
1
1
  /**
2
2
  * Encode composer fields into a serializable `UserTurnDraft` for pending intents.
3
3
  */
4
+ import { messageParts } from '@theoremjs/agents/interface';
4
5
  import { encodeFiles } from "./encode-files.js";
5
6
  export async function encodeComposerDraft(args) {
6
7
  const text = args.text.trim();
8
+ const parts = messageParts(args.parts);
7
9
  const files = args.pendingFiles ?? [];
8
10
  const voice = args.pendingVoice ?? [];
9
11
  const encodedFiles = files.length ? await encodeFiles(files) : [];
10
12
  const encodedVoice = voice.length ? await encodeFiles(voice) : [];
11
13
  return {
12
14
  ...(text ? { text } : {}),
15
+ ...(parts ? { parts } : {}),
13
16
  ...(encodedFiles.length
14
17
  ? {
15
18
  attachments: encodedFiles.map((blob, index) => ({
@@ -1,4 +1,5 @@
1
1
  import { type TurnEvent } from '@theoremjs/agents';
2
+ import type { RefText, UserPart } from '@theoremjs/agents/interface';
2
3
  import { type ComposerProfileInterface, type InterfaceTurnSession, type TranscriptBlock, type UserTurnDraft } from '@theoremjs/agents/interface';
3
4
  import { type TurnFailure } from './failure.ts';
4
5
  import { type StreamView } from './run-commit.ts';
@@ -27,6 +28,8 @@ export type RunOutcome = {
27
28
  failure?: TurnFailure;
28
29
  };
29
30
  export type StreamInterfaceTurnBaseArgs = {
31
+ /** Writes the message's refs into its text; the ref's id when absent. */
32
+ refText?: RefText;
30
33
  iface: ComposerProfileInterface;
31
34
  transport: TheoremTransport;
32
35
  session: InterfaceTurnSession;
@@ -54,6 +57,7 @@ export type StreamInterfaceTurnBaseArgs = {
54
57
  transcript?: readonly TranscriptBlock[];
55
58
  };
56
59
  export type StreamInterfaceTurnArgs = StreamInterfaceTurnBaseArgs & {
60
+ parts?: UserPart[];
57
61
  text: string;
58
62
  pendingFiles: readonly File[];
59
63
  pendingVoice: readonly File[];
@@ -31,6 +31,7 @@ async function streamPreparedTurn(args) {
31
31
  const walking = args.session.gatedTool !== null;
32
32
  const request = buildTurnRequest(args.iface, args.session, {
33
33
  ...(args.prepared.draft.text ? { text: args.prepared.draft.text } : {}),
34
+ ...(args.prepared.draft.parts ? { parts: args.prepared.draft.parts } : {}),
34
35
  ...(args.encodedAttachments?.length ? { attachments: args.encodedAttachments } : {}),
35
36
  ...(args.encodedVoice?.length ? { voice: args.encodedVoice } : {}),
36
37
  }, {
@@ -120,7 +121,7 @@ export async function streamInterfaceTurn(args) {
120
121
  return await runPreparedTurnStream({
121
122
  ...args,
122
123
  prepare: async () => {
123
- const prepared = prepareComposerTurn(args.iface, args.text, args.pendingFiles, args.pendingVoice);
124
+ const prepared = prepareComposerTurn(args.iface, args.text, args.pendingFiles, args.pendingVoice, { parts: args.parts, refText: args.refText });
124
125
  if (!prepared.ok)
125
126
  return prepared;
126
127
  return {
@@ -139,7 +140,7 @@ export async function streamInterfaceDraftTurn(args) {
139
140
  return await runPreparedTurnStream({
140
141
  ...args,
141
142
  prepare: () => {
142
- const prepared = projectUserTurn(args.iface, args.draft);
143
+ const prepared = projectUserTurn(args.iface, args.draft, args.refText);
143
144
  if (!prepared.ok)
144
145
  return prepared;
145
146
  return {
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import { MEDIA_INPUT_KIND_VALUES, reasoningPartSchema, TURN_STOP_KINDS, turnEventSchema, z, } from '@theoremjs/agents';
7
+ import { MEDIA_INPUT_KIND_VALUES, reasoningPartSchema, TURN_STOP_KINDS, turnEventSchema, userPartSchema, z, } from '@theoremjs/agents';
8
8
  import { guardrailEventSchema } from '@theoremjs/agents/guardrails';
9
9
  import { jsonObjectSchema } from '@theoremjs/agents/kernel';
10
10
  // why: The block shapes' event parts have one schema, the turn event's; a probe event reuses it.
@@ -53,7 +53,12 @@ const turnStop = z.object({ kind: z.enum(TURN_STOP_KINDS), native: z.string().op
53
53
  true;
54
54
  const blockId = { id: z.string(), host: jsonObjectSchema.optional() };
55
55
  const transcriptBlock = z.discriminatedUnion('kind', [
56
- z.object({ ...blockId, kind: z.literal('user-text'), text: z.string() }),
56
+ z.object({
57
+ ...blockId,
58
+ kind: z.literal('user-text'),
59
+ text: z.string(),
60
+ parts: z.array(userPartSchema).optional(),
61
+ }),
57
62
  z.object({
58
63
  ...blockId,
59
64
  kind: z.enum(['user-attachment', 'user-voice']),
@@ -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 TurnToolSnapshot, z } from '@theoremjs/agents';
13
+ import { type ErrorKind, type TurnEvent, type TurnToolSnapshot, type UserPart, 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';
@@ -25,6 +25,11 @@ export type EncodedBlob = {
25
25
  /** Turn input as sent over the wire (media is base64-encoded). */
26
26
  export type TheoremTurnInput = {
27
27
  text?: string;
28
+ /**
29
+ * The message's words and refs in order, when it names the host's objects. The server writes
30
+ * `text` from them, so a `text` sent beside them is not read.
31
+ */
32
+ parts?: UserPart[];
28
33
  attachments?: EncodedBlob[];
29
34
  voice?: EncodedBlob[];
30
35
  /** The value chosen for each of the profile's `inputs.options`. */
@@ -135,12 +140,12 @@ export type TheoremSteerRequest = {
135
140
  /** The client's id for this steer; the turn's `stage` event names it in `injected` once it lands. */
136
141
  id: string;
137
142
  /** The message, as a `/turn` posts one. The host makes the user message the model reads. */
138
- input: Pick<TheoremTurnInput, 'text' | 'attachments' | 'voice'>;
143
+ input: Pick<TheoremTurnInput, 'text' | 'parts' | 'attachments' | 'voice'>;
139
144
  /** The ref of the conversation the turn replies in, when the page has one. */
140
145
  conversation?: string;
141
146
  } | {
142
147
  id: string;
143
- input: Pick<TheoremTurnInput, 'text' | 'attachments' | 'voice'>;
148
+ input: Pick<TheoremTurnInput, 'text' | 'parts' | 'attachments' | 'voice'>;
144
149
  conversation: string;
145
150
  };
146
151
  /** A `/steer` body as `createTheoremHandler` reads it. */
@@ -9,7 +9,7 @@ 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, turnToolSnapshotSchema, z, } from '@theoremjs/agents';
12
+ import { describeError, errorKindSchema, isAbortError, TheoremError, TURN_EVENT_SCHEMAS, throwIfAborted, turnEventSchema, turnToolSnapshotSchema, userPartSchema, z, } from '@theoremjs/agents';
13
13
  import { errorCopiesSchema, kindOfHttpStatus, } from '@theoremjs/agents/guardrails';
14
14
  import { profileInterfaceSchema, } from '@theoremjs/agents/interface';
15
15
  import { pageBlockSchema, transcriptBlockSchema } from "./transcript-schema.js";
@@ -20,6 +20,7 @@ const theoremTurnInput = z.object({
20
20
  options: z.record(z.string(), z.string()).optional(),
21
21
  context: z.unknown().optional(),
22
22
  text: z.string().optional(),
23
+ parts: z.array(userPartSchema).optional(),
23
24
  attachments: z.array(encodedBlob).optional(),
24
25
  voice: z.array(encodedBlob).optional(),
25
26
  });
@@ -84,7 +85,12 @@ const theoremInvokeRequest = z.object({
84
85
  true;
85
86
  /** An `/invoke` body as `createTheoremHandler` reads it. */
86
87
  export const theoremInvokeRequestSchema = theoremInvokeRequest;
87
- const steerInput = theoremTurnInput.pick({ text: true, attachments: true, voice: true });
88
+ const steerInput = theoremTurnInput.pick({
89
+ text: true,
90
+ parts: true,
91
+ attachments: true,
92
+ voice: true,
93
+ });
88
94
  const theoremSteerRequest = z.union([
89
95
  z.object({
90
96
  turnId: clientId,
@@ -1,4 +1,5 @@
1
1
  import { type TurnEvent } from '@theoremjs/agents';
2
+ import type { RefText, UserPart } from '@theoremjs/agents/interface';
2
3
  import { type AttachmentValidationIssue, type ComposerProfileInterface, type GatedToolContext, type InterfaceTurnSession, type TranscriptBlock, type UserTurnDraft } from '@theoremjs/agents/interface';
3
4
  import type { PagePart } from './tool-resume.ts';
4
5
  import type { TheoremInvokeRequest, TheoremReplay, TheoremTurnInput, TheoremTurnRequest, TheoremWakeRequest } from './transport.ts';
@@ -38,7 +39,7 @@ export declare function buildInvokeRequest(iface: ComposerProfileInterface, sess
38
39
  secret?: string;
39
40
  page?: PagePart;
40
41
  }, scope?: RunScope): TheoremInvokeRequest;
41
- export declare function projectUserTurn(iface: ComposerProfileInterface, draft: UserTurnDraft): {
42
+ export declare function projectUserTurn(iface: ComposerProfileInterface, draft: UserTurnDraft, refText?: RefText): {
42
43
  ok: true;
43
44
  blocks: TranscriptBlock[];
44
45
  draft: UserTurnDraft;
@@ -46,5 +47,8 @@ export declare function projectUserTurn(iface: ComposerProfileInterface, draft:
46
47
  ok: false;
47
48
  issues: AttachmentValidationIssue[];
48
49
  };
49
- export declare function prepareComposerTurn(iface: ComposerProfileInterface, text: string, pendingFiles: readonly File[], pendingVoice?: readonly File[]): ReturnType<typeof projectUserTurn>;
50
+ export declare function prepareComposerTurn(iface: ComposerProfileInterface, text: string, pendingFiles: readonly File[], pendingVoice?: readonly File[], message?: {
51
+ parts?: UserPart[];
52
+ refText?: RefText;
53
+ }): ReturnType<typeof projectUserTurn>;
50
54
  export declare function foldAssistantTurn(iface: ComposerProfileInterface, events: readonly TurnEvent[]): TranscriptBlock[];
@@ -84,15 +84,17 @@ export function buildInvokeRequest(iface, session, args, scope = {}) {
84
84
  }),
85
85
  };
86
86
  }
87
- export function projectUserTurn(iface, draft) {
88
- return prepareUserTurn(iface.inputs, draft, iface.guardrails);
87
+ export function projectUserTurn(iface, draft, refText) {
88
+ return prepareUserTurn(iface.inputs, draft, iface.guardrails, refText);
89
89
  }
90
- export function prepareComposerTurn(iface, text, pendingFiles, pendingVoice = []) {
91
- return projectUserTurn(iface, {
90
+ export function prepareComposerTurn(iface, text, pendingFiles, pendingVoice = [], message = {}) {
91
+ const draft = {
92
92
  ...(text.trim() ? { text } : {}),
93
+ ...(message.parts ? { parts: message.parts } : {}),
93
94
  ...(pendingFiles.length ? { attachments: filesToPending(pendingFiles) } : {}),
94
95
  ...(pendingVoice.length ? { voice: filesToPending(pendingVoice) } : {}),
95
- });
96
+ };
97
+ return projectUserTurn(iface, draft, message.refText);
96
98
  }
97
99
  export function foldAssistantTurn(iface, events) {
98
100
  // why: Its `turn-done` blocks stay: hidden in the view, they carry the reply's worked time.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/web",
3
- "version": "0.3.5-next.1020.g3a48861",
3
+ "version": "0.3.5-next.1025.g5523d8f",
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.1020.g3a48861"
28
+ "@theoremjs/agents": "^0.3.5-next.1025.g5523d8f"
29
29
  }
30
30
  }
@@ -5,6 +5,7 @@
5
5
  *
6
6
  * @module
7
7
  */
8
+ import type { RefText } from '@theoremjs/agents';
8
9
  import { type GateReference, type NormalizedTurnRequest, type Profile, type ProfileDefinition, type ProviderHostOptions, type StageHandler, type TurnHistoryMessage, type TurnInput, type TurnRequest } from '@theoremjs/agents';
9
10
  import { type ConversationInbox, type InboxItem, type InboxPolicy, type ReplyRun } from '@theoremjs/agents/conversation';
10
11
  import type { ClientTurnOptions } from '@theoremjs/agents/host';
@@ -24,6 +25,8 @@ export type ChatContext = {
24
25
  profile: ChatProfile;
25
26
  /** Undefined when the profile keeps no conversation (`'stateless'`). */
26
27
  conversations?: TheoremConversationStore;
28
+ /** Writes a message's refs into its text; the ref's id when absent. */
29
+ refText?: RefText;
27
30
  };
28
31
  /**
29
32
  * Where the chat saves a detached call's end: its conversation store, as `clientEvents` reads it,
@@ -38,7 +41,7 @@ export declare function endingsOf(chat: ChatContext | undefined, options: {
38
41
  * The chat `definition` serves, with the store that keeps its conversation. `name` is the function
39
42
  * the app called, for the error a wrong profile throws.
40
43
  */
41
- export declare function chatOf(name: string, definition: Profile | ProfileDefinition, conversations: TheoremConversationStore | undefined): ChatContext;
44
+ export declare function chatOf(name: string, definition: Profile | ProfileDefinition, conversations: TheoremConversationStore | undefined, refText?: RefText): ChatContext;
42
45
  /**
43
46
  * The app's own inbox for a conversation, and its rule for what a reply may be told. A reply runs
44
47
  * under a hold of `conversation` in it, and the app reads the reply's items itself.
@@ -32,7 +32,7 @@ export function endingsOf(chat, options) {
32
32
  * The chat `definition` serves, with the store that keeps its conversation. `name` is the function
33
33
  * the app called, for the error a wrong profile throws.
34
34
  */
35
- export function chatOf(name, definition, conversations) {
35
+ export function chatOf(name, definition, conversations, refText) {
36
36
  const profile = defineProfile(definition);
37
37
  if (profile.type === 'decision') {
38
38
  // labels-exempt: builder config error at setup; no user sees it
@@ -55,7 +55,7 @@ export function chatOf(name, definition, conversations) {
55
55
  },
56
56
  });
57
57
  }
58
- return { profile, ...(conversations ? { conversations } : {}) };
58
+ return { profile, ...(conversations ? { conversations } : {}), ...(refText ? { refText } : {}) };
59
59
  }
60
60
  /** The profile as the server reads a message against it, its tools as registered now. */
61
61
  function chatInterface(chat) {
@@ -741,7 +741,7 @@ async function* answered(held, paused, reply) {
741
741
  * walk-away that does not name the calls the paused reply waits on. Changes nothing.
742
742
  */
743
743
  async function messageOpened(ctx, at, args) {
744
- const posted = postedMessage(chatInterface(ctx.chat), args.input, args.context);
744
+ const posted = postedMessage(chatInterface(ctx.chat), args.input, args.context, ctx.chat.refText);
745
745
  const host = conversationHost(ctx, at);
746
746
  if (!host) {
747
747
  if (args.ref !== undefined)
@@ -1016,8 +1016,8 @@ export function createConversationCore(state) {
1016
1016
  // labels-exempt: builder config error; the user reads error.config
1017
1017
  throw new TheoremError('config', "a steer goes through `intake`: the app's inbox holds the message");
1018
1018
  }
1019
- postedMessage(chatInterface(state.chat), args.input);
1020
- const message = personMessageOf(args);
1019
+ postedMessage(chatInterface(state.chat), args.input, undefined, state.chat.refText);
1020
+ const message = personMessageOf(args, state.chat.refText);
1021
1021
  const arrive = async (conversation) => {
1022
1022
  if (!state.own.stop.running(ownKey(at.sessionId, conversation)))
1023
1023
  return false;
@@ -14,6 +14,7 @@
14
14
  *
15
15
  * @module
16
16
  */
17
+ import type { RefText } from '@theoremjs/agents';
17
18
  import { type GateReference, type LabelOverrides, type Profile, type ProviderCheckpoint, TheoremError, type TurnEvent, type TurnHistoryMessage, type TurnInput } from '@theoremjs/agents';
18
19
  import { type ClientTurnOptions } from '@theoremjs/agents/host';
19
20
  import { type ComposerProfileInterface, type ReplyCarried, streamThoughtsEnabled, type TranscriptBlock, type UserTurnDraft, type UserTurnHistoryMedia } from '@theoremjs/agents/interface';
@@ -218,8 +219,9 @@ export type PostedMessage = {
218
219
  /**
219
220
  * The person's message as the profile accepts it: refused when its files break the profile's
220
221
  * limits. `server` is the host's own context for the run (the handler's `context` option).
222
+ * `refText` writes the refs of `input.parts` into the message's text.
221
223
  */
222
- export declare function postedMessage(iface: ComposerProfileInterface, input: TheoremTurnInput, server?: unknown): PostedMessage;
224
+ export declare function postedMessage(iface: ComposerProfileInterface, input: TheoremTurnInput, server?: unknown, refText?: RefText): PostedMessage;
223
225
  /**
224
226
  * The person sends a message. A reply that waits on gates is walked away
225
227
  * from first: each call settles cancelled and the paused reply commits; then
@@ -518,17 +518,19 @@ function pendingOf(blob) {
518
518
  /**
519
519
  * The person's message as the profile accepts it: refused when its files break the profile's
520
520
  * limits. `server` is the host's own context for the run (the handler's `context` option).
521
+ * `refText` writes the refs of `input.parts` into the message's text.
521
522
  */
522
- export function postedMessage(iface, input, server) {
523
+ export function postedMessage(iface, input, server, refText) {
523
524
  const prepared = prepareUserTurn(iface.inputs, {
524
525
  ...(input.text !== undefined ? { text: input.text } : {}),
526
+ ...(input.parts ? { parts: input.parts } : {}),
525
527
  ...(input.attachments ? { attachments: input.attachments.map(pendingOf) } : {}),
526
528
  ...(input.voice ? { voice: input.voice.map(pendingOf) } : {}),
527
- }, iface.guardrails);
529
+ }, iface.guardrails, refText);
528
530
  if (!prepared.ok)
529
531
  throw attachmentsRefused(prepared.issues);
530
- const { text: _sent, ...rest } = input;
531
- const { text } = prepared.draft;
532
+ const { text: _sent, parts: _parts, ...rest } = input;
533
+ const { text, parts } = prepared.draft;
532
534
  return {
533
535
  draft: prepared.draft,
534
536
  blocks: prepared.blocks,
@@ -536,7 +538,7 @@ export function postedMessage(iface, input, server) {
536
538
  ...(input.attachments ? { attachments: input.attachments } : {}),
537
539
  ...(input.voice ? { voice: input.voice } : {}),
538
540
  },
539
- input: kernelTurnInput(text === undefined ? rest : { ...rest, text }, server),
541
+ input: kernelTurnInput({ ...rest, ...(text === undefined ? {} : { text }), ...(parts ? { parts } : {}) }, server),
540
542
  };
541
543
  }
542
544
  /**
@@ -15,7 +15,7 @@ import { type CallHooks, type CoreContext } from './session-calls.ts';
15
15
  * `TheoremHandlerOptions` means what it means there. The others take the run's `CoreContext`
16
16
  * where the handler's take the `Request`.
17
17
  */
18
- export type TheoremConversationCoreOptions<Item extends InboxItem = InboxItem> = Pick<TheoremHandlerOptions, 'profile' | 'onStage' | 'sessionStore' | 'conversationStore' | 'credentialStore' | 'gateTtlMs' | 'operationRetentionMs' | 'pageToolBroker' | 'pageToolTimeoutMs' | 'notifier' | 'replyFeed' | 'notifyRetryMs' | 'lateResultsDecider' | 'conversationLeaseMs' | 'clientEvents'> & ReplyWiring<Item> & {
18
+ export type TheoremConversationCoreOptions<Item extends InboxItem = InboxItem> = Pick<TheoremHandlerOptions, 'profile' | 'onStage' | 'sessionStore' | 'conversationStore' | 'refText' | 'credentialStore' | 'gateTtlMs' | 'operationRetentionMs' | 'pageToolBroker' | 'pageToolTimeoutMs' | 'notifier' | 'replyFeed' | 'notifyRetryMs' | 'lateResultsDecider' | 'conversationLeaseMs' | 'clientEvents'> & ReplyWiring<Item> & {
19
19
  /** Host options for registered providers, or a factory for apps that pick keys per run. */
20
20
  provider: ProviderHostOptions | ((at: CoreContext, model?: string) => ProviderHostOptions | Promise<ProviderHostOptions>);
21
21
  /**
@@ -12,7 +12,7 @@ import { sessionParts } from "./session-calls.js";
12
12
  /** Creates the conversation core for `options.profile`. */
13
13
  export function createTheoremConversationCore(options) {
14
14
  const name = 'createTheoremConversationCore';
15
- const chat = chatOf(name, options.profile, options.conversationStore);
15
+ const chat = chatOf(name, options.profile, options.conversationStore, options.refText);
16
16
  const { provider, wake } = options;
17
17
  if (options.lateResultsDecider && !wake) {
18
18
  // labels-exempt: builder config error at setup; no user sees it
@@ -54,6 +54,7 @@ import type { TheoremNotifier } from './notifier.ts';
54
54
  import type { TheoremReplyFeed } from './reply-feed.ts';
55
55
  import { type CoreContext } from './session-calls.ts';
56
56
  export { theoremSession, theoremSessionId } from './session-identity.ts';
57
+ import type { RefText } from '@theoremjs/agents';
57
58
  import type { SessionToolOperation, TheoremSessionStore } from './session-store.ts';
58
59
  export type TheoremRequestContext = {
59
60
  request: Request;
@@ -112,6 +113,11 @@ export type TheoremHandlerOptions<Item extends InboxItem = InboxItem> = ReplyWir
112
113
  * own database.
113
114
  */
114
115
  conversationStore?: TheoremConversationStore;
116
+ /**
117
+ * Writes each ref of a message (`input.parts`) into the message's text, which the model reads and
118
+ * the transcript keeps. The ref's id when absent.
119
+ */
120
+ refText?: RefText;
115
121
  /**
116
122
  * How long a gate (permission, confirmation, sign-in) waits for its answer, in
117
123
  * milliseconds. An answer after that is refused with `session.gate_expired`,
package/server/handler.js CHANGED
@@ -594,7 +594,7 @@ async function route(ctx, request, session) {
594
594
  return steer(ctx, chat, request, session);
595
595
  }
596
596
  export function createTheoremHandler(options) {
597
- const chat = chatOf('createTheoremHandler', options.profile, options.conversationStore);
597
+ const chat = chatOf('createTheoremHandler', options.profile, options.conversationStore, options.refText);
598
598
  oneInbox(options);
599
599
  oneCore(options);
600
600
  if (options.intake && !options.inbox && !options.core) {
@@ -10,13 +10,15 @@
10
10
  *
11
11
  * @module
12
12
  */
13
- import { type LateResultItem, type LateResultsDecider, type LateResultsSource, type StageHandler, type TurnHistoryMessage } from '@theoremjs/agents';
13
+ import { type LateResultItem, type LateResultsDecider, type LateResultsSource, type RefText, type StageHandler, type TurnHistoryMessage, type UserPart } from '@theoremjs/agents';
14
14
  import { type InboxItem, type InboxPolicy, type MemoryInbox, type ReplyRun } from '@theoremjs/agents/conversation';
15
15
  import type { TheoremSteerRequest } from '../client/transport.ts';
16
16
  import type { HoldStop } from './conversation-core.ts';
17
17
  /** A message the person sent into a running reply, as the one user message the model reads. */
18
18
  export interface PersonMessage extends InboxItem<'person_message'> {
19
19
  messages: TurnHistoryMessage[];
20
+ /** The message's words and refs, when it names the host's objects (`StageInject.userParts`). */
21
+ userParts?: UserPart[];
20
22
  }
21
23
  /** What Theorem's own inbox holds: ended background calls and the person's messages. */
22
24
  export type OwnItem = LateResultItem | PersonMessage;
@@ -25,7 +27,7 @@ export type OwnItem = LateResultItem | PersonMessage;
25
27
  * client's, and a reply names it in `stage.injected` once it lands. A message with no text and no
26
28
  * file is refused.
27
29
  */
28
- export declare function personMessageOf(steer: Pick<TheoremSteerRequest, 'id' | 'input'>): PersonMessage;
30
+ export declare function personMessageOf(steer: Pick<TheoremSteerRequest, 'id' | 'input'>, refText?: RefText): PersonMessage;
29
31
  /** The person's messages the session inbox keeps in memory, by session and conversation. */
30
32
  export type MessageShelf = Map<string, Map<string, PersonMessage>>;
31
33
  /** The stop of replies run by this process, which Theorem's own inbox uses when the app gives none. */
@@ -10,7 +10,7 @@
10
10
  *
11
11
  * @module
12
12
  */
13
- import { isTurnInjectStage, TheoremError, } from '@theoremjs/agents';
13
+ import { isTurnInjectStage, messageParts, TheoremError, textOfParts, } from '@theoremjs/agents';
14
14
  import { createMemoryInbox, } from '@theoremjs/agents/conversation';
15
15
  import { appendUserDraftToHistory } from '@theoremjs/agents/interface';
16
16
  /** Whether `item` is a person's message. */
@@ -22,13 +22,23 @@ function isPersonMessage(item) {
22
22
  * client's, and a reply names it in `stage.injected` once it lands. A message with no text and no
23
23
  * file is refused.
24
24
  */
25
- export function personMessageOf(steer) {
26
- const { text, attachments, voice } = steer.input;
25
+ export function personMessageOf(steer, refText) {
26
+ const { attachments, voice } = steer.input;
27
+ const userParts = messageParts(steer.input.parts);
28
+ const text = steer.input.parts
29
+ ? textOfParts(userParts ?? steer.input.parts, refText)
30
+ : steer.input.text;
27
31
  const messages = appendUserDraftToHistory([], { ...(text === undefined ? {} : { text }) }, { ...(attachments ? { attachments } : {}), ...(voice ? { voice } : {}) });
28
32
  // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
29
33
  if (!messages.length)
30
34
  throw new TheoremError('request', 'a steer needs text or a file');
31
- return { id: steer.id, kind: 'person_message', handovers: [], messages };
35
+ return {
36
+ id: steer.id,
37
+ kind: 'person_message',
38
+ handovers: [],
39
+ messages,
40
+ ...(userParts ? { userParts } : {}),
41
+ };
32
42
  }
33
43
  /** Creates the memory stop. A stop asked reaches every model run of the conversation under way. */
34
44
  function createMemoryHoldStop() {
@@ -168,7 +178,10 @@ export function ownReads(run) {
168
178
  if (!message)
169
179
  return undefined;
170
180
  handed.add(message.id);
171
- return { inject: message.messages, injectId: message.id };
181
+ const { id, messages, userParts } = message;
182
+ return userParts
183
+ ? { injects: [{ id, messages, userParts }] }
184
+ : { inject: messages, injectId: id };
172
185
  },
173
186
  mine: (ids) => ids.filter((id) => handed.has(id)),
174
187
  };
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @module
10
10
  */
11
- import { jsonObjectSchema, jsonValueSchema, labelText, savedToolInvocationSchema, TheoremError, TOOL_AUTH_TYPES, TOOL_GATE_KINDS, TOOL_PERMISSION, TURN_INJECT_STAGES, toolOperationOutcomeSchema, toolOperationReplySchema, turnHistoryMessageSchema, turnToolSnapshotSchema, z, } from '@theoremjs/agents';
11
+ import { jsonObjectSchema, jsonValueSchema, labelText, savedToolInvocationSchema, TheoremError, TOOL_AUTH_TYPES, TOOL_GATE_KINDS, TOOL_PERMISSION, TURN_INJECT_STAGES, toolOperationOutcomeSchema, toolOperationReplySchema, turnHistoryMessageSchema, turnToolSnapshotSchema, userPartSchema, z, } from '@theoremjs/agents';
12
12
  import { gateExpired } from '@theoremjs/agents/kernel';
13
13
  import { checkedCapacity } from "./session-limits.js";
14
14
  /** The reply the model read for a call that detached, whatever has happened to the call since. */
@@ -26,6 +26,7 @@ const blobSchema = z.strictObject({
26
26
  });
27
27
  const inputSchema = z.strictObject({
28
28
  text: z.string().optional(),
29
+ parts: z.array(userPartSchema).optional(),
29
30
  role: z.string().optional(),
30
31
  options: z.record(z.string(), z.string()).optional(),
31
32
  context: z