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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +330 -13
  2. package/client/chat.d.ts +14 -2
  3. package/client/chat.js +302 -34
  4. package/client/composer-hints.d.ts +18 -10
  5. package/client/composer-hints.js +23 -6
  6. package/client/host-transport.d.ts +7 -2
  7. package/client/host-transport.js +9 -3
  8. package/client/index.d.ts +4 -4
  9. package/client/index.js +3 -3
  10. package/client/page-dispatch.js +5 -0
  11. package/client/run-session.d.ts +27 -2
  12. package/client/run-session.js +34 -4
  13. package/client/schema-fields.d.ts +28 -1
  14. package/client/schema-fields.js +172 -13
  15. package/client/tool-result.d.ts +9 -5
  16. package/client/tool-result.js +23 -42
  17. package/client/transcript-schema.d.ts +4 -0
  18. package/client/transcript-schema.js +25 -6
  19. package/client/transport.d.ts +90 -9
  20. package/client/transport.js +56 -11
  21. package/client/turn-client.d.ts +8 -2
  22. package/client/turn-client.js +9 -0
  23. package/package.json +2 -2
  24. package/server/conversation-core.d.ts +273 -0
  25. package/server/conversation-core.js +797 -0
  26. package/server/conversation-inbox.d.ts +45 -0
  27. package/server/conversation-inbox.js +240 -0
  28. package/server/conversation-store.d.ts +43 -2
  29. package/server/conversation-store.js +15 -2
  30. package/server/conversation.d.ts +82 -2
  31. package/server/conversation.js +357 -60
  32. package/server/create-conversation-core.d.ts +28 -0
  33. package/server/create-conversation-core.js +46 -0
  34. package/server/embedding-handler.js +2 -0
  35. package/server/handler.d.ts +84 -20
  36. package/server/handler.js +279 -659
  37. package/server/mcp-handler.js +25 -11
  38. package/server/mod.d.ts +11 -4
  39. package/server/mod.js +6 -2
  40. package/server/notifier.d.ts +3 -2
  41. package/server/notifier.js +3 -2
  42. package/server/session-authority.d.ts +3 -1
  43. package/server/session-authority.js +26 -1
  44. package/server/session-boundary.d.ts +5 -3
  45. package/server/session-boundary.js +2 -2
  46. package/server/session-calls.d.ts +122 -0
  47. package/server/session-calls.js +512 -0
  48. package/server/session-store.d.ts +33 -0
  49. package/server/session-store.js +37 -2
  50. package/server/steer-inbox.d.ts +3 -4
  51. package/server/steer-inbox.js +6 -5
  52. package/server/tell-every-result.d.ts +11 -0
  53. package/server/tell-every-result.js +17 -0
  54. package/server/tool-operations.d.ts +8 -0
  55. package/server/tool-operations.js +71 -0
  56. package/server/turn-input.d.ts +4 -2
  57. package/server/turn-input.js +5 -2
  58. package/server/turn-wiring.d.ts +31 -6
  59. package/server/turn-wiring.js +59 -5
@@ -6,6 +6,7 @@
6
6
  *
7
7
  * @module
8
8
  */
9
+ import { MEDIA_INPUT_KIND_VALUES, } from '@theoremjs/agents';
9
10
  import { columnStore, fieldLabel, humanize, ISO_DATE, isPlain, isRow, printableUnit, shownEntries, storeRows, titleKey, unitsOf, unpacked, } from "./shaped-data.js";
10
11
  const MAX_FIGURES = 4;
11
12
  const MAX_CHARTS = 3;
@@ -13,25 +14,12 @@ const MAX_CHARTS = 3;
13
14
  const MAX_SERIES = 3;
14
15
  /** Bars a category chart ranks. */
15
16
  const MAX_BARS = 8;
16
- const MAX_IMAGES = 6;
17
17
  /** Rows a list needs before it reads as a chart. */
18
18
  const MIN_POINTS = 3;
19
- /** Levels searched for charts and images. */
19
+ /** Levels searched for charts. */
20
20
  const MAX_SEARCH_DEPTH = 3;
21
21
  /** Numbers that locate or name a thing rather than measure it. */
22
22
  const NOT_A_MEASURE = /(^|_)(id|ids|lat|lon|lng|latitude|longitude|offset|interval|index|rank|order)$|Id$|^(generationtime_ms|utc_offset_seconds)$/i;
23
- const IMAGE_PATH = /\.(png|jpe?g|gif|webp|avif|svg)$/i;
24
- function isImageUrl(text) {
25
- if (/\s/.test(text))
26
- return false;
27
- try {
28
- const url = new URL(text);
29
- return (url.protocol === 'http:' || url.protocol === 'https:') && IMAGE_PATH.test(url.pathname);
30
- }
31
- catch {
32
- return false;
33
- }
34
- }
35
23
  function isMeasure(key) {
36
24
  return !NOT_A_MEASURE.test(key);
37
25
  }
@@ -215,55 +203,48 @@ function chartsIn(value, path, title, units, depth) {
215
203
  }
216
204
  return entries.flatMap(([key, entry]) => chartsIn(unpacked(entry), path ? `${path}.${key}` : key, depth === 0 ? humanize(key) : `${title} › ${humanize(key)}`, unitsOf(value, key), depth + 1));
217
205
  }
218
- /** Image URLs anywhere in the value, first found first, each once. */
219
- function imagesIn(value, key, depth, found) {
220
- if (found.size >= MAX_IMAGES || depth > MAX_SEARCH_DEPTH + 1)
221
- return;
222
- const inner = unpacked(value);
223
- if (typeof inner === 'string') {
224
- if (isImageUrl(inner) && !found.has(inner))
225
- found.set(inner, { src: inner, alt: humanize(key || 'image') });
226
- return;
227
- }
228
- if (Array.isArray(inner)) {
229
- for (const item of inner)
230
- imagesIn(item, key, depth + 1, found);
231
- return;
232
- }
233
- if (isRow(inner))
234
- for (const [child, entry] of Object.entries(inner))
235
- imagesIn(entry, child, depth + 1, found);
236
- }
237
206
  /** What a tool's output leads with. Empty when nothing stands out: the data alone reads best. */
238
207
  export function layoutResult(output) {
239
208
  const value = unpacked(output);
240
- const images = new Map();
241
- imagesIn(value, '', 0, images);
242
209
  return {
243
210
  figures: leadFigures(value),
244
211
  charts: chartsIn(value, '', '', undefined, 0).slice(0, MAX_CHARTS),
245
- images: [...images.values()],
246
212
  };
247
213
  }
248
214
  function mediaSrc(part) {
249
215
  return part.mimeType && part.data ? `data:${part.mimeType};base64,${part.data}` : undefined;
250
216
  }
251
- /** The images and audio a call returned, each with its bytes; parts without them are left out. */
252
- export function returnedMedia(layout, parts, imageAlt) {
217
+ /** The images and audio a call returned, each with its bytes; parts without them (references) are left out. */
218
+ export function returnedMedia(parts, imageAlt) {
253
219
  const sourced = parts.flatMap((part) => {
254
220
  const src = mediaSrc(part);
255
221
  return src ? [{ type: part.type, src, mimeType: part.mimeType }] : [];
256
222
  });
257
223
  return {
258
- images: [
259
- ...sourced.filter((part) => part.type === 'image').map(({ src }) => ({ src, alt: imageAlt })),
260
- ...layout.images,
261
- ],
224
+ images: sourced
225
+ .filter((part) => part.type === 'image')
226
+ .map(({ src }) => ({ src, alt: imageAlt })),
262
227
  audio: sourced
263
228
  .filter((part) => part.type === 'audio')
264
229
  .map(({ src, mimeType }) => ({ src, ...(mimeType ? { mimeType } : {}) })),
265
230
  };
266
231
  }
232
+ /** The references a call returned, which only the app's resolver turns into something to show. */
233
+ export function referencesIn(parts) {
234
+ return parts.flatMap((part) => part.uri !== undefined && part.mimeType !== undefined && isMediaKind(part.type)
235
+ ? [
236
+ {
237
+ type: part.type,
238
+ mimeType: part.mimeType,
239
+ uri: part.uri,
240
+ ...(part.metadata ? { metadata: part.metadata } : {}),
241
+ },
242
+ ]
243
+ : []);
244
+ }
245
+ function isMediaKind(type) {
246
+ return MEDIA_INPUT_KIND_VALUES.includes(type);
247
+ }
267
248
  /** Whether the result has anything to lead with above its data. */
268
249
  export function hasLead(layout, media) {
269
250
  return (layout.figures.length + layout.charts.length + media.images.length + media.audio.length > 0);
@@ -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>>;
@@ -4,8 +4,9 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import { reasoningPartSchema, TURN_STOP_KINDS, turnEventSchema, z, } from '@theoremjs/agents';
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);
@@ -42,7 +43,6 @@ const toolCall = z.object({
42
43
  state: toolCallState.optional(),
43
44
  startedAt: z.number().optional(),
44
45
  endedAt: z.number().optional(),
45
- artifacts: z.array(z.unknown()),
46
46
  get steps() {
47
47
  return z.array(toolCall).optional();
48
48
  },
@@ -50,7 +50,7 @@ const toolCall = z.object({
50
50
  true;
51
51
  const turnStop = z.object({ kind: z.enum(TURN_STOP_KINDS), native: z.string().optional() });
52
52
  true;
53
- const blockId = { id: z.string() };
53
+ const blockId = { id: z.string(), host: jsonObjectSchema.optional() };
54
54
  const transcriptBlock = z.discriminatedUnion('kind', [
55
55
  z.object({ ...blockId, kind: z.literal('user-text'), text: z.string() }),
56
56
  z.object({
@@ -60,6 +60,9 @@ const transcriptBlock = z.discriminatedUnion('kind', [
60
60
  mimeType: z.string(),
61
61
  sizeBytes: z.number(),
62
62
  data: z.string().optional(),
63
+ uri: z.string().optional(),
64
+ type: z.enum(MEDIA_INPUT_KIND_VALUES).optional(),
65
+ metadata: z.record(z.string(), z.unknown()).optional(),
63
66
  }),
64
67
  z.object({ ...blockId, kind: z.literal('thought'), text: z.string() }),
65
68
  z.object({ ...blockId, kind: z.literal('text'), text: z.string() }),
@@ -75,8 +78,11 @@ const transcriptBlock = z.discriminatedUnion('kind', [
75
78
  kind: z.literal('media'),
76
79
  mimeType: z.string(),
77
80
  data: z.string().optional(),
78
- url: z.string().optional(),
79
- previewUrl: z.string().optional(),
81
+ uri: z.string().optional(),
82
+ type: z.enum(MEDIA_INPUT_KIND_VALUES).optional(),
83
+ fromTool: z.literal(true).optional(),
84
+ sent: z.literal(true).optional(),
85
+ metadata: z.record(z.string(), z.unknown()).optional(),
80
86
  }),
81
87
  z.object({
82
88
  ...blockId,
@@ -104,7 +110,13 @@ const transcriptBlock = z.discriminatedUnion('kind', [
104
110
  })),
105
111
  }),
106
112
  z.object({ ...blockId, kind: z.literal('guardrail'), guardrail: guardrailEventSchema }),
107
- z.object({ ...blockId, kind: z.literal('late-results'), text: z.string() }),
113
+ z.object({
114
+ ...blockId,
115
+ kind: z.literal('late-results'),
116
+ text: z.string(),
117
+ operationIds: z.array(z.string()),
118
+ inReply: z.boolean(),
119
+ }),
108
120
  z.object({ ...blockId, kind: z.literal('error'), message: z.string() }),
109
121
  z.object({
110
122
  ...blockId,
@@ -123,3 +135,10 @@ const transcriptBlock = z.discriminatedUnion('kind', [
123
135
  true;
124
136
  /** One transcript block, as a host stores it and the browser reads it back. */
125
137
  export const transcriptBlockSchema = transcriptBlock;
138
+ /** The block without the app's own values: a page cannot state them. */
139
+ export function withoutHost(block) {
140
+ const { host: _host, ...rest } = block;
141
+ return rest;
142
+ }
143
+ /** A block as a page's request states it: `host` is the app's to set, so it is dropped. */
144
+ 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,18 +125,51 @@ 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
+ /**
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
+ */
124
133
  export type TheoremSteerRequest = {
125
134
  turnId: string;
126
135
  /** The client's id for this steer; the turn's `stage` event names it in `injected` once it lands. */
127
136
  id: string;
128
- inject: TurnHistoryMessage[];
137
+ /** The message, as a `/turn` posts one. The host makes the user message the model reads. */
138
+ input: Pick<TheoremTurnInput, 'text' | 'attachments' | 'voice'>;
139
+ /** The ref of the conversation the turn replies in, when the page has one. */
140
+ conversation?: string;
141
+ } | {
142
+ id: string;
143
+ input: Pick<TheoremTurnInput, 'text' | 'attachments' | 'voice'>;
144
+ conversation: string;
129
145
  };
130
146
  /** A `/steer` body as `createTheoremHandler` reads it. */
131
147
  export declare const theoremSteerRequestSchema: z.ZodType<TheoremSteerRequest>;
132
- /** Stop an in-flight turn where it stands; its stream ends with what the reply left. */
148
+ /**
149
+ * A message the host saved itself (`intake`), with no reply to it on this request. `landsAs` is
150
+ * each id a reply names the message by when it reads it: an inject's id on a `stage` line, an id
151
+ * in a `conversation` line's `opened`, or a block's id in the conversation.
152
+ */
153
+ export type TheoremSavedMessage = {
154
+ conversation: string;
155
+ landsAs: string[];
156
+ };
157
+ /**
158
+ * What the host did with a steer. With `saved`, the host keeps the message; without it, the steer
159
+ * waits in the running turn, and the page sends it again when the turn ends without it.
160
+ */
161
+ export type TheoremSteerReply = {
162
+ saved?: TheoremSavedMessage;
163
+ };
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
+ */
133
169
  export type TheoremStopRequest = {
134
170
  turnId: string;
171
+ } | {
172
+ conversation: string;
135
173
  };
136
174
  /** A `/stop` body as `createTheoremHandler` reads it. */
137
175
  export declare const theoremStopRequestSchema: z.ZodType<TheoremStopRequest>;
@@ -139,16 +177,35 @@ export declare const theoremStopRequestSchema: z.ZodType<TheoremStopRequest>;
139
177
  * The ref the store issued for the conversation a run wrote: the client sends
140
178
  * it with its next request. It comes before the run's error, which ends the stream.
141
179
  * `posted` marks the write that holds the person's new message: a run that
142
- * fails before it leaves the message unsent.
180
+ * fails before it leaves the message unsent. `landsAs` says the host saved the message itself
181
+ * (`intake`), and is each id a reply names it by (see `TheoremSavedMessage`). `opened` is the id
182
+ * of each item that waited for the model and that the reply starting here reads first.
143
183
  */
144
184
  export type ConversationLine = {
145
185
  type: 'conversation';
146
186
  ref: string;
147
187
  posted?: true;
188
+ landsAs?: string[];
189
+ opened?: string[];
148
190
  };
149
191
  /** The lines a chat's reply streams: turn events, and the conversation's ref. */
150
192
  export declare const CHAT_LINES: WireLines<TurnEvent | ConversationLine>;
151
- /** 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. */
152
209
  export type ConversationView = {
153
210
  transcript: TranscriptBlock[];
154
211
  /** The reply that waits on gates: its events, and its blocks as the transcript will keep them. */
@@ -156,10 +213,14 @@ export type ConversationView = {
156
213
  events: TurnEvent[];
157
214
  blocks: TranscriptBlock[];
158
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;
159
218
  /** The host pushes the end of a call that still runs. `retryMs` is its wait to reopen the push. */
160
219
  notify?: {
161
220
  retryMs?: number;
162
221
  };
222
+ /** Results wait that no reply has read: the page wakes the conversation (`transport.wake`). */
223
+ wake?: true;
163
224
  };
164
225
  /** Read a conversation: a `/conversation` body. */
165
226
  export type TheoremConversationRequest = {
@@ -167,7 +228,23 @@ export type TheoremConversationRequest = {
167
228
  };
168
229
  /** A `/conversation` body as `createTheoremHandler` reads it. */
169
230
  export declare const theoremConversationRequestSchema: z.ZodType<TheoremConversationRequest>;
170
- /** Listen for the ends of this session's background calls: a `/notify` body. */
231
+ /**
232
+ * Wake the conversation: the model takes up the results of its background calls that ended and it
233
+ * has not read, in a reply to no message. A `/wake` body. The host does nothing when no result
234
+ * waits, a reply waits on gates or answers a message, or another wake took them already.
235
+ */
236
+ export type TheoremWakeRequest = {
237
+ conversation: string;
238
+ /** What the page sends with every message: its option picks and context. */
239
+ input?: Pick<TheoremTurnInput, 'options' | 'context'>;
240
+ model?: string;
241
+ effort?: string;
242
+ /** Client-generated id so the page can stop this reply, as it stops a message's. */
243
+ turnId?: string;
244
+ };
245
+ /** A `/wake` body as `createTheoremHandler` reads it. */
246
+ export declare const theoremWakeRequestSchema: z.ZodType<TheoremWakeRequest>;
247
+ /** Listen for changes to this session: a background call ended, or the app saved a reply. A `/notify` body. */
171
248
  export type TheoremNotifyRequest = Record<string, never>;
172
249
  /** A `/notify` body as `createTheoremHandler` reads it. */
173
250
  export declare const theoremNotifyRequestSchema: z.ZodType<TheoremNotifyRequest>;
@@ -207,13 +284,15 @@ export interface TheoremTransport {
207
284
  describe(signal?: AbortSignal): Promise<ProfileInterface>;
208
285
  turn(request: TheoremTurnRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
209
286
  invoke(request: TheoremInvokeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
210
- steer(request: TheoremSteerRequest): Promise<void>;
211
- /** Stops the turn; refused (`session.turn_ended`) when this host is not running it. */
287
+ steer(request: TheoremSteerRequest): Promise<TheoremSteerReply>;
288
+ /** Stops the reply; refused (`session.turn_ended`) when this host is not running it. */
212
289
  stop(request: TheoremStopRequest): Promise<void>;
213
290
  /** The conversation under `ref`, as the host shows it. */
214
291
  conversation(request: TheoremConversationRequest, signal?: AbortSignal): Promise<ConversationView>;
215
292
  /** Calls `changed` for each line of the host's push, and settles when the push ends. */
216
293
  notify?(changed: () => void, signal: AbortSignal): Promise<void>;
294
+ /** Streams the reply a wake runs; no line at all when the host had nothing to wake for. */
295
+ wake?(request: TheoremWakeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
217
296
  /** The conversation cut after a transcript block, under the ref the host issued for it. */
218
297
  rewind(request: TheoremRewindRequest, signal?: AbortSignal): Promise<TheoremRewound>;
219
298
  pageResult?(result: PageDispatchResult, signal?: AbortSignal): Promise<void>;
@@ -248,6 +327,8 @@ export declare const hostErrorBodySchema: z.ZodType<HostErrorBody>;
248
327
  export declare function hostError(body: HostErrorBody, fallbackKind: ErrorKind): TheoremStreamError;
249
328
  /** The host could not open the message's conversation (`session.conversation_unknown`). */
250
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;
251
332
  /**
252
333
  * Read an NDJSON reply, checking each line against `lines`: a kind it doesn't
253
334
  * list reaches `onLine` as `unsupported`, and a line that fails its check as
@@ -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(),
@@ -83,15 +84,30 @@ const theoremInvokeRequest = z.object({
83
84
  true;
84
85
  /** An `/invoke` body as `createTheoremHandler` reads it. */
85
86
  export const theoremInvokeRequestSchema = theoremInvokeRequest;
86
- const theoremSteerRequest = z.object({
87
- turnId: clientId,
88
- id: clientId,
89
- inject: z.array(turnHistoryMessageSchema).min(1),
90
- });
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
+ ]);
91
97
  true;
92
98
  /** A `/steer` body as `createTheoremHandler` reads it. */
93
99
  export const theoremSteerRequestSchema = theoremSteerRequest;
94
- const theoremStopRequest = z.object({ turnId: clientId });
100
+ const theoremSavedMessage = z.object({
101
+ conversation: z.string().min(1),
102
+ landsAs: z.array(z.string().min(1)).min(1),
103
+ });
104
+ true;
105
+ const theoremSteerReply = z.object({ saved: theoremSavedMessage.optional() });
106
+ true;
107
+ const theoremStopRequest = z.union([
108
+ z.object({ turnId: clientId }),
109
+ z.object({ conversation: z.string().min(1) }),
110
+ ]);
95
111
  true;
96
112
  /** A `/stop` body as `createTheoremHandler` reads it. */
97
113
  export const theoremStopRequestSchema = theoremStopRequest;
@@ -99,6 +115,8 @@ const conversationLine = z.object({
99
115
  type: z.literal('conversation'),
100
116
  ref: z.string().min(1),
101
117
  posted: z.literal(true).optional(),
118
+ landsAs: z.array(z.string().min(1)).min(1).optional(),
119
+ opened: z.array(z.string().min(1)).min(1).optional(),
102
120
  });
103
121
  true;
104
122
  /** The lines a chat's reply streams: turn events, and the conversation's ref. */
@@ -106,18 +124,36 @@ export const CHAT_LINES = {
106
124
  ...TURN_EVENT_SCHEMAS,
107
125
  conversation: conversationLine,
108
126
  };
127
+ const runningReply = z.object({
128
+ since: z.number(),
129
+ prompt: z.array(transcriptBlockSchema),
130
+ heldUntil: z.number(),
131
+ });
132
+ true;
109
133
  const conversationView = z.object({
110
134
  transcript: z.array(transcriptBlockSchema),
111
135
  paused: z
112
136
  .object({ events: z.array(turnEventSchema), blocks: z.array(transcriptBlockSchema) })
113
137
  .optional(),
138
+ running: runningReply.optional(),
114
139
  notify: z.object({ retryMs: z.number().optional() }).optional(),
140
+ wake: z.literal(true).optional(),
115
141
  });
116
142
  true;
117
143
  const theoremConversationRequest = z.object({ conversation: z.string().min(1) });
118
144
  true;
119
145
  /** A `/conversation` body as `createTheoremHandler` reads it. */
120
146
  export const theoremConversationRequestSchema = theoremConversationRequest;
147
+ const theoremWakeRequest = z.object({
148
+ conversation: z.string().min(1),
149
+ input: theoremTurnInput.pick({ options: true, context: true }).optional(),
150
+ model: z.string().optional(),
151
+ effort: z.string().optional(),
152
+ turnId: clientId.optional(),
153
+ });
154
+ true;
155
+ /** A `/wake` body as `createTheoremHandler` reads it. */
156
+ export const theoremWakeRequestSchema = theoremWakeRequest;
121
157
  const theoremNotifyRequest = z.strictObject({});
122
158
  /** A `/notify` body as `createTheoremHandler` reads it. */
123
159
  export const theoremNotifyRequestSchema = theoremNotifyRequest;
@@ -129,7 +165,8 @@ const theoremRewindRequest = z.object({
129
165
  true;
130
166
  /** A `/rewind` body as `createTheoremHandler` reads it. */
131
167
  export const theoremRewindRequestSchema = theoremRewindRequest;
132
- const theoremStartRequest = z.object({ blocks: z.array(transcriptBlockSchema) });
168
+ // invariant: These blocks are a page's; only the app's own save sets a block's `host`.
169
+ const theoremStartRequest = z.object({ blocks: z.array(pageBlockSchema) });
133
170
  true;
134
171
  /** A `/conversation/start` body as a host reads it. */
135
172
  export const theoremStartRequestSchema = theoremStartRequest;
@@ -182,10 +219,17 @@ export function hostError(body, fallbackKind) {
182
219
  }
183
220
  /** The host could not open the message's conversation (`session.conversation_unknown`). */
184
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) {
185
229
  if (!isTheoremStreamError(err) || err.copy === undefined)
186
230
  return false;
187
231
  const copies = Array.isArray(err.copy) ? err.copy : [err.copy];
188
- return copies.some((copy) => copy.key === 'session.conversation_unknown');
232
+ return copies.some((copy) => copy.key === key);
189
233
  }
190
234
  /** One NDJSON line checked against `lines`; an `error` line ends the stream as a {@link TheoremStreamError}. */
191
235
  function parseStreamLine(lines, text) {
@@ -353,13 +397,14 @@ export function createHttpTransport(options = {}) {
353
397
  turn: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/turn`, body, CHAT_LINES, onEvent, { ...options, signal }),
354
398
  invoke: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/invoke`, body, CHAT_LINES, onEvent, { ...options, signal }),
355
399
  conversation: (body, signal) => fetchConversation(`${base}/conversation`, body, { ...options, signal }),
400
+ wake: (body, onLine, signal) => postNdjson(`${base}/wake`, body, CHAT_LINES, onLine, { ...options, signal }),
356
401
  notify: (changed, signal) => postNdjson(`${base}/notify`, {}, NOTIFY_LINES, (line) => {
357
402
  if (line.type === 'changed')
358
403
  changed();
359
404
  }, { ...options, signal }),
360
405
  rewind: (body, signal) => fetchRewound(`${base}/rewind`, body, { ...options, signal }),
361
406
  pageResult: (body, signal) => postJson(`${base}/page-result`, body, { ...options, signal }),
362
- steer: (body) => postJson(`${base}/steer`, body, options),
407
+ steer: async (body) => theoremSteerReply.parse(await fetchJson(`${base}/steer`, { body }, options)),
363
408
  stop: (body) => postJson(`${base}/stop`, body, options),
364
409
  };
365
410
  }
@@ -1,7 +1,7 @@
1
1
  import { type TurnEvent } from '@theoremjs/agents';
2
2
  import { type AttachmentValidationIssue, type ComposerProfileInterface, type GatedToolContext, type InterfaceTurnSession, type TranscriptBlock, type UserTurnDraft } from '@theoremjs/agents/interface';
3
3
  import type { PagePart } from './tool-resume.ts';
4
- import type { TheoremInvokeRequest, TheoremReplay, TheoremTurnInput, TheoremTurnRequest } from './transport.ts';
4
+ import type { TheoremInvokeRequest, TheoremReplay, TheoremTurnInput, TheoremTurnRequest, TheoremWakeRequest } from './transport.ts';
5
5
  export declare function issuedOperationId(call: {
6
6
  operationId?: string;
7
7
  }): string;
@@ -17,14 +17,20 @@ 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;
27
31
  }): TheoremTurnRequest;
32
+ /** A wake of `conversation` with the model and effort picked now, as a message would carry them. */
33
+ export declare function buildWakeRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, conversation: string, scope?: RunScope): TheoremWakeRequest;
28
34
  export declare function buildInvokeRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, args: HeldCall & {
29
35
  gateId: string;
30
36
  operationId: string;
@@ -54,12 +54,21 @@ 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 } : {}),
60
61
  replay: { sessionPermissions: session.sessionPermissions },
61
62
  };
62
63
  }
64
+ /** A wake of `conversation` with the model and effort picked now, as a message would carry them. */
65
+ export function buildWakeRequest(iface, session, conversation, scope = {}) {
66
+ return {
67
+ conversation,
68
+ ...(scope.turnId ? { turnId: scope.turnId } : {}),
69
+ ...generationFields(iface, session),
70
+ };
71
+ }
63
72
  export function buildInvokeRequest(iface, session, args, scope = {}) {
64
73
  return {
65
74
  ...scopeFields(scope),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/web",
3
- "version": "0.3.4",
3
+ "version": "0.3.5-next.1001.g68d8dcf",
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.4"
28
+ "@theoremjs/agents": "^0.3.5-next.1001.g68d8dcf"
29
29
  }
30
30
  }