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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -65,6 +65,30 @@ export interface ConversationSnapshot {
65
65
  revision: string;
66
66
  conversation: StoredConversation;
67
67
  }
68
+ /**
69
+ * How the reply a write saves ended. `committed`: it is over. `failed`: it ended with an error.
70
+ * `stopped`: the person stopped it. `paused`: it waits on gates. `lost`: its hold no longer has
71
+ * the conversation, so it tells nothing.
72
+ */
73
+ export type ReplyEnd = 'committed' | 'failed' | 'stopped' | 'paused' | 'lost' | 'refused';
74
+ /**
75
+ * What a write that saves a reply says beside the conversation. A store that keeps the app's own
76
+ * records honours it in the same statement as the write. A write with no context saves no reply:
77
+ * a new conversation, a posted message, a compaction, or a rewind.
78
+ */
79
+ export type WriteContext = {
80
+ /** The hold the reply runs under. A store that keeps the holds refuses one that lost the conversation. */
81
+ hold?: string;
82
+ /** The reply's id under its hold. */
83
+ reply?: string;
84
+ /** What the app's `beforeSave` returned as `host`. Theorem never reads it. */
85
+ host?: unknown;
86
+ ended: ReplyEnd;
87
+ /** The ids of the inbox items this reply told, to mark in the same write. Empty when `ended` is `lost`. */
88
+ told: readonly string[];
89
+ /** The blocks this write adds to the transcript the store holds, so a store need not compare. */
90
+ appended: readonly TranscriptBlock[];
91
+ };
68
92
  export type ConversationWriteResult = {
69
93
  written: true;
70
94
  ref: string;
@@ -85,7 +109,7 @@ export interface TheoremConversationStore {
85
109
  * write lands only on a conversation this session can read, while its
86
110
  * stored revision is still `expectedRevision`.
87
111
  */
88
- write(sessionId: string, ref: string | null, expectedRevision: string | null, next: StoredConversation): Promise<ConversationWriteResult>;
112
+ write(sessionId: string, ref: string | null, expectedRevision: string | null, next: StoredConversation, context?: WriteContext): Promise<ConversationWriteResult>;
89
113
  }
90
114
  /** Refuses a ref the store does not know or cannot open: the browser reads `session.conversation_unknown`. */
91
115
  export declare function unknownConversation(cause?: unknown): TheoremError;
@@ -70,7 +70,10 @@ export function createMemoryConversationStore(options = {}) {
70
70
  }
71
71
  return entry.snapshot;
72
72
  };
73
- const written = (...[sessionId, ref, expectedRevision, next]) => {
73
+ const written = (...[sessionId, ref, expectedRevision, next, context]) => {
74
+ // invariant: This store keeps no holds, so a reply whose hold lost the conversation writes nothing here.
75
+ if (context?.ended === 'lost')
76
+ return { written: false };
74
77
  const snapshot = ref === null ? undefined : current(sessionId, ref);
75
78
  // invariant: A ref this session cannot read takes no write, so no session overwrites another's conversation.
76
79
  if (ref !== null && snapshot === undefined)
@@ -125,7 +128,10 @@ export function createSealedConversationStore(options) {
125
128
  const conversation = storedConversation.parse(JSON.parse(plaintext));
126
129
  return { revision: ref, conversation };
127
130
  },
128
- async write(sessionId, ref, expectedRevision, next) {
131
+ async write(sessionId, ref, expectedRevision, next, context) {
132
+ // invariant: This store keeps no holds, so a reply whose hold lost the conversation writes nothing here.
133
+ if (context?.ended === 'lost')
134
+ return { written: false };
129
135
  if (ref !== expectedRevision)
130
136
  return { written: false };
131
137
  const conversation = storedConversation.parse(next);
@@ -18,7 +18,8 @@ import { type GateReference, type LabelOverrides, type Profile, type ProviderChe
18
18
  import { type ClientTurnOptions } from '@theoremjs/agents/host';
19
19
  import { type ComposerProfileInterface, type ReplyCarried, streamThoughtsEnabled, type TranscriptBlock, type UserTurnDraft, type UserTurnHistoryMedia } from '@theoremjs/agents/interface';
20
20
  import type { ConversationLine, ConversationView, StatedTurn, TheoremTurnInput } from '../client/transport.ts';
21
- import { type StoredConversation, type TheoremConversationStore } from './conversation-store.ts';
21
+ import { type ReplyEnd, type StoredConversation, type TheoremConversationStore } from './conversation-store.ts';
22
+ import type { ReplyRefusal } from './turn-wiring.ts';
22
23
  /** One walked-away call: its id, and the run that settles it (`invokeTool` with the abandoned resume). */
23
24
  export type WalkedAwayCall = {
24
25
  callId: string;
@@ -59,6 +60,11 @@ export type OpenedConversation = {
59
60
  ref: string | null;
60
61
  revision: string | null;
61
62
  conversation: StoredConversation;
63
+ /**
64
+ * How many of the transcript's blocks the store holds, when `conversation` has blocks the store
65
+ * has not heard of yet: a message the app saved itself, a walked-away reply not yet written.
66
+ */
67
+ stored?: number;
62
68
  /** What the guardrails decided reading a restored transcript, for the reply to stream first. */
63
69
  events?: TurnEvent[];
64
70
  };
@@ -144,6 +150,51 @@ export type ReplyRunner = {
144
150
  * nothing: the hold that took the chat tells what it read.
145
151
  */
146
152
  held?: () => Promise<boolean>;
153
+ /** The hold the reply runs under, for the store's write. */
154
+ hold?: string;
155
+ /** The app's own steps around the save. */
156
+ saving?: ReplySaving;
157
+ /**
158
+ * The app's refusal of the reply, once `run` ended on it: `run` then gave the line as its text
159
+ * and ran no model. The reply saves as `refused`.
160
+ */
161
+ refused?: () => ReplyRefusal['refuse'] | undefined;
162
+ };
163
+ /** A reply as the app's `before` step reads it. */
164
+ export type ReplyToSave = {
165
+ ended: ReplyEnd;
166
+ /** The blocks the save adds to the transcript the store holds. */
167
+ blocks: readonly TranscriptBlock[];
168
+ /** Why the reply ended `failed`, or why a `paused` reply's answer did not settle its call. */
169
+ failure?: ErrorEvent;
170
+ /** The ids of the named injects that landed in this reply, in order. */
171
+ landed: readonly string[];
172
+ };
173
+ /** A reply as the app shaped it for the save. */
174
+ export type ShapedReply = {
175
+ /** The blocks to save in place of the reply's `blocks`. */
176
+ blocks: readonly TranscriptBlock[];
177
+ /** The ids of the inbox items the reply told. */
178
+ told: readonly string[];
179
+ /** The app's own values for its store's write. */
180
+ host?: unknown;
181
+ };
182
+ /** The app's own steps around a reply's save, bound to the run they belong to. */
183
+ export type ReplySaving = {
184
+ /** Shapes the reply before each save. */
185
+ before?: (reply: ReplyToSave) => Promise<ShapedReply>;
186
+ /** Runs once a save is written. What it throws is reported, and the save stands. */
187
+ after?: (saved: {
188
+ ended: ReplyEnd;
189
+ told: readonly string[];
190
+ }) => Promise<void>;
191
+ /** The app's compaction, in place of the runner's. What it throws is reported. */
192
+ compact?: (signal: {
193
+ history: TurnHistoryMessage[];
194
+ tokens: number;
195
+ }) => Promise<void>;
196
+ /** Reports an error the save does not throw. */
197
+ report: (err: unknown) => void;
147
198
  };
148
199
  /** A line of a reply's stream: an event, or the ref of what the store wrote. */
149
200
  export type ReplyLine = TurnEvent | ConversationLine;
@@ -172,12 +223,18 @@ export declare function messageReply(args: {
172
223
  message: PostedMessage;
173
224
  /** The paused reply's calls, each with the run that settles it: exactly the calls it waits on. */
174
225
  walkAway?: readonly IssuedWalkAway[];
226
+ /**
227
+ * The message's blocks as the app saved them itself. The reply then posts nothing: the store
228
+ * hears of the message first in the save that ends the reply.
229
+ */
230
+ saved?: readonly TranscriptBlock[];
175
231
  runner: ReplyRunner;
176
232
  }): AsyncGenerator<ReplyLine>;
177
233
  /**
178
234
  * The model takes up the results of calls that ended while nothing ran: a reply to no message.
179
235
  * It writes nothing until it ends, so a message posted meanwhile keeps the conversation, and this
180
- * reply ends with no write: that message's reply read the same results.
236
+ * reply ends with no write: that message's reply read the same results. A reply that waits on
237
+ * gates is walked away from first, as a message does.
181
238
  */
182
239
  export declare function wakeReply(args: {
183
240
  host: ConversationHost;
@@ -185,6 +242,8 @@ export declare function wakeReply(args: {
185
242
  runner: ReplyRunner;
186
243
  /** What the page sends with every message: its option picks and context. */
187
244
  input?: Pick<TurnInput, 'options' | 'context'>;
245
+ /** The paused reply's calls, each with the run that settles it: exactly the calls it waits on. */
246
+ walkAway?: readonly IssuedWalkAway[];
188
247
  }): AsyncGenerator<ReplyLine>;
189
248
  /**
190
249
  * The person answers one call the reply waits on. `settling` streams the
@@ -20,6 +20,7 @@ import { forClient } from '@theoremjs/agents/host';
20
20
  import { appendAssistantEventsToHistory, appendUserDraftToHistory, applyTurnEventsToSession, emptyInterfaceTurnSession, foldTurnEvents, gatedToolsFromEvents, historyFromTranscriptBlocks, prepareUserTurn, replyCarriedFromEvents, settlesToolCall, streamThoughtsEnabled, } from '@theoremjs/agents/interface';
21
21
  import { base64ToBytes } from '@theoremjs/agents/kernel';
22
22
  import { stampWorked, stoppedReply } from "../client/run-commit.js";
23
+ import { withoutHost } from "../client/transcript-schema.js";
23
24
  import { emptyConversation, unknownConversation, } from "./conversation-store.js";
24
25
  import { kernelTurnInput } from "./turn-input.js";
25
26
  /** The paused call a reference names, when its call id and its operation both match. */
@@ -72,7 +73,8 @@ async function openedAt(host, ref, restore) {
72
73
  if (!restore)
73
74
  throw unknownConversation();
74
75
  // why: A null ref makes the reply's write a new conversation, whose ref the `conversation` line hands the page.
75
- const { conversation, events } = conversationFromBlocks(restore.profile, restore.blocks);
76
+ // invariant: A page cannot state a block's host values; only the app's own save sets them.
77
+ const { conversation, events } = conversationFromBlocks(restore.profile, restore.blocks.map(withoutHost));
76
78
  return { ref: null, revision: null, conversation, events };
77
79
  }
78
80
  /**
@@ -143,9 +145,108 @@ async function save(host, opened, next) {
143
145
  }
144
146
  return { ref: result.ref, revision: result.revision, conversation: next };
145
147
  }
148
+ /** A refused reply's blocks: the app's values go on the block of its line, the last text. */
149
+ function refusalBlocks(blocks, refusal) {
150
+ const { host } = refusal;
151
+ const line = blocks.findLastIndex((block) => block.kind === 'text');
152
+ if (host === undefined || line < 0)
153
+ return blocks;
154
+ return blocks.map((block, index) => (index === line ? { ...block, host } : block));
155
+ }
156
+ /** The ids of the named injects that landed in `events`, in order. */
157
+ function landedIn(events) {
158
+ return events.flatMap((event) => event.type === 'stage' ? (event.injected ?? []).map((inject) => inject.id) : []);
159
+ }
160
+ /** `saving.next` as the app's `before` step shapes it, with what the store is told beside it. */
161
+ async function shaped(opened, runner, saving) {
162
+ const stored = opened.stored ?? opened.conversation.transcript.length;
163
+ const appended = saving.next.transcript.slice(stored);
164
+ const before = runner.saving?.before;
165
+ const reply = before
166
+ ? await before({
167
+ ended: saving.ended,
168
+ blocks: appended,
169
+ ...(saving.failure ? { failure: saving.failure } : {}),
170
+ landed: landedIn(saving.events),
171
+ })
172
+ : { blocks: appended, told: [] };
173
+ return {
174
+ next: before
175
+ ? {
176
+ ...saving.next,
177
+ transcript: [...saving.next.transcript.slice(0, stored), ...reply.blocks],
178
+ }
179
+ : saving.next,
180
+ context: {
181
+ ...(runner.hold ? { hold: runner.hold } : {}),
182
+ ...(runner.reply ? { reply: runner.reply } : {}),
183
+ ...(reply.host === undefined ? {} : { host: reply.host }),
184
+ ended: saving.ended,
185
+ // invariant: A reply whose hold lost the conversation tells nothing.
186
+ told: saving.ended === 'lost' ? [] : reply.told,
187
+ appended: reply.blocks,
188
+ },
189
+ };
190
+ }
191
+ /**
192
+ * Saves a reply: the app shapes it, the store writes it with its context, then the app's `after`
193
+ * step runs. Undefined when the app's `before` step threw on a reply that failed or was stopped:
194
+ * nothing is saved, the throw is reported, and the reply ends with its own failure.
195
+ */
196
+ async function saveReply(host, opened, runner, saving) {
197
+ let reply;
198
+ try {
199
+ reply = await shaped(opened, runner, saving);
200
+ }
201
+ catch (err) {
202
+ if (saving.ended !== 'failed' && saving.ended !== 'stopped')
203
+ throw err;
204
+ runner.saving?.report(err);
205
+ return undefined;
206
+ }
207
+ const result = await host.store.write(host.sessionId, opened.ref, opened.revision, reply.next, reply.context);
208
+ if (!result.written) {
209
+ // labels-exempt: internal diagnostic; the user reads error.unavailable
210
+ throw new TheoremError('unavailable', 'the conversation changed while this reply ran', {
211
+ cause: CONFLICT,
212
+ });
213
+ }
214
+ try {
215
+ await runner.saving?.after?.({ ended: saving.ended, told: reply.context.told });
216
+ }
217
+ catch (err) {
218
+ // invariant: The save is written; a step after it cannot fail the reply.
219
+ runner.saving?.report(err);
220
+ }
221
+ return { ref: result.ref, revision: result.revision, conversation: reply.next };
222
+ }
223
+ /**
224
+ * A reply to a message whose hold lost the conversation: the app's store hears what the person
225
+ * saw of it, and marks nothing told. Only with the app's `before` step, since a store that keeps
226
+ * no holds takes no write from a lost hold. It throws nothing: the reply is over.
227
+ */
228
+ async function saveLost(host, opened, runner, saving) {
229
+ if (!runner.saving?.before)
230
+ return;
231
+ try {
232
+ const reply = await shaped(opened, runner, { ...saving, ended: 'lost' });
233
+ await host.store.write(host.sessionId, opened.ref, opened.revision, reply.next, reply.context);
234
+ }
235
+ catch (err) {
236
+ runner.saving.report(err);
237
+ }
238
+ }
239
+ /** The runner's hold and steps for the save of the paused reply it walks away from. */
240
+ function walkedAway(runner, paused) {
241
+ return {
242
+ ...(runner.hold ? { hold: runner.hold } : {}),
243
+ ...(paused.reply ? { reply: paused.reply } : {}),
244
+ ...(runner.saving ? { saving: runner.saving } : {}),
245
+ };
246
+ }
146
247
  /** The line that tells the browser the ref of what was just written. */
147
248
  function refLine(opened, posted) {
148
- if (opened.ref === null)
249
+ if (!opened || opened.ref === null)
149
250
  return [];
150
251
  return [{ type: 'conversation', ref: opened.ref, ...(posted ? { posted: true } : {}) }];
151
252
  }
@@ -204,7 +305,7 @@ function pausedOn(conversation, reply, runner) {
204
305
  * leave with it, so a later reply tells them. A compaction that folded them in is undone too: the
205
306
  * history goes back to its base before that compaction, and the next reply compacts again.
206
307
  */
207
- function failed(host, conversation, reply, failure) {
308
+ function failed(host, conversation, reply, failure, worded) {
208
309
  const from = reply.uncompacted ?? reply;
209
310
  const unread = (events) => events.filter((event, index) => event.type !== 'late_results' &&
210
311
  !(reply.uncompacted && event.type === 'compaction' && index >= from.baseEvents));
@@ -215,6 +316,9 @@ function failed(host, conversation, reply, failure) {
215
316
  baseEvents: unread(reply.events.slice(0, from.baseEvents)).length,
216
317
  workedMs: reply.workedMs,
217
318
  });
319
+ // why: An app that shapes the save words the failure itself, from `failure`.
320
+ if (worded === 'app')
321
+ return next;
218
322
  if (next.transcript.slice(conversation.transcript.length).some((b) => b.kind === 'error')) {
219
323
  return next;
220
324
  }
@@ -238,8 +342,18 @@ function stopped(host, conversation, reply) {
238
342
  * reply's base to the compacted history; `withMessage` puts the person's
239
343
  * message back on it when the reply answers one.
240
344
  */
241
- async function* runReply(host, opened, reply, runner, input, withMessage) {
345
+ async function* runReply(host, opened, reply, runner, input, withMessage, answers) {
242
346
  const { conversation } = opened;
347
+ const worded = runner.saving?.before ? 'app' : 'core';
348
+ /** What the person saw of a reply whose hold lost the conversation, for a reply to a message. */
349
+ const lost = async (from) => {
350
+ if (answers !== 'message')
351
+ return;
352
+ const next = runner.signal.aborted
353
+ ? stopped(host, conversation, from)
354
+ : committed(host, conversation, from);
355
+ await saveLost(host, opened, runner, { next, events: from.events });
356
+ };
243
357
  const startedAt = Date.now();
244
358
  const worked = () => ({ ...reply, workedMs: reply.workedMs + (Date.now() - startedAt) });
245
359
  // invariant: A reply whose hold lost its chat saves nothing; the hold that has it tells what this one read.
@@ -274,11 +388,20 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
274
388
  }
275
389
  }
276
390
  catch (err) {
391
+ const thrown = worked();
277
392
  if (await held()) {
278
- const written = await save(host, opened, runner.signal.aborted
279
- ? stopped(host, conversation, worked())
280
- : failed(host, conversation, worked(), toErrorEvent(err)));
281
- yield* refLine(written);
393
+ const failure = toErrorEvent(err);
394
+ yield* refLine(await saveReply(host, opened, runner, runner.signal.aborted
395
+ ? { ended: 'stopped', next: stopped(host, conversation, thrown), events: thrown.events }
396
+ : {
397
+ ended: 'failed',
398
+ next: failed(host, conversation, thrown, failure, worded),
399
+ events: thrown.events,
400
+ failure,
401
+ }));
402
+ }
403
+ else {
404
+ await lost(thrown);
282
405
  }
283
406
  // why: A stopped reply is no failure; the browser draws what it left from the ref.
284
407
  if (!runner.signal.aborted)
@@ -286,20 +409,34 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
286
409
  return;
287
410
  }
288
411
  const settled = worked();
289
- if (!(await held()))
412
+ const { events } = settled;
413
+ const refusal = runner.refused?.();
414
+ if (!(await held())) {
415
+ await lost(settled);
290
416
  return;
417
+ }
291
418
  if (runner.signal.aborted) {
292
- yield* refLine(await save(host, opened, stopped(host, conversation, settled)));
419
+ const next = stopped(host, conversation, settled);
420
+ yield* refLine(await saveReply(host, opened, runner, { ended: 'stopped', next, events }));
293
421
  }
294
422
  else if (errorEvent) {
295
- yield* refLine(await save(host, opened, failed(host, conversation, settled, errorEvent)));
423
+ const next = failed(host, conversation, settled, errorEvent, worded);
424
+ yield* refLine(await saveReply(host, opened, runner, { ended: 'failed', next, events, failure: errorEvent }));
296
425
  yield errorEvent;
297
426
  }
298
- else if (gatedToolsFromEvents(settled.events).length) {
299
- yield* refLine(await save(host, opened, pausedOn(conversation, settled, runner)));
427
+ else if (refusal) {
428
+ const next = committed(host, conversation, settled, (blocks) => refusalBlocks(blocks, refusal));
429
+ yield* refLine(await saveReply(host, opened, runner, { ended: 'refused', next, events }));
430
+ }
431
+ else if (gatedToolsFromEvents(events).length) {
432
+ const next = pausedOn(conversation, settled, runner);
433
+ yield* refLine(await saveReply(host, opened, runner, { ended: 'paused', next, events }));
300
434
  }
301
435
  else {
302
- const current = await save(host, opened, committed(host, conversation, settled));
436
+ const next = committed(host, conversation, settled);
437
+ const current = await saveReply(host, opened, runner, { ended: 'committed', next, events });
438
+ if (!current)
439
+ return;
303
440
  yield* refLine(current);
304
441
  // why: The reply is the browser's before compaction runs, so a failed compaction loses none of it.
305
442
  if (!(await held()))
@@ -318,6 +455,16 @@ async function compactedAfter(host, opened, reply, runner, withMessage) {
318
455
  const signal = done?.type === 'done' ? done.compaction : undefined;
319
456
  if (!signal?.needed)
320
457
  return undefined;
458
+ if (runner.saving?.compact) {
459
+ // invariant: The app's compaction is its own write; this reply writes nothing more.
460
+ try {
461
+ await runner.saving.compact({ history: signal.history, tokens: signal.tokens });
462
+ }
463
+ catch (err) {
464
+ runner.saving.report(err);
465
+ }
466
+ return undefined;
467
+ }
321
468
  const compacted = await runner.compact(signal.history, signal.tokens, runner.model);
322
469
  if (!compacted)
323
470
  return undefined;
@@ -426,6 +573,38 @@ function pausedReply(paused) {
426
573
  function failureOf(error) {
427
574
  return new TheoremError(error.errorKind, error.error ?? labelText(`error.${error.errorKind}`));
428
575
  }
576
+ /**
577
+ * Walks away from the reply `opened` waits on: each call settles cancelled, and the paused reply
578
+ * commits. Returns the conversation to go on from. Undefined when a call did not settle: the reply
579
+ * is saved as it waits, and the error is sent.
580
+ */
581
+ async function* walkAwayFrom(host, opened, runner, calls) {
582
+ const { paused } = opened.conversation;
583
+ requireWalkAway(opened.conversation, calls);
584
+ if (!paused)
585
+ return opened;
586
+ const walked = pausedReply(paused);
587
+ const error = yield* settleWalkedAway(walked, calls ?? []);
588
+ if (error) {
589
+ const next = {
590
+ ...opened.conversation,
591
+ paused: { ...paused, events: walked.events, endedAt: Date.now() },
592
+ };
593
+ yield* refLine(await saveReply(host, opened, walkedAway(runner, paused), {
594
+ ended: 'paused',
595
+ next,
596
+ events: walked.events,
597
+ failure: error,
598
+ }));
599
+ yield error;
600
+ return undefined;
601
+ }
602
+ return {
603
+ ...opened,
604
+ stored: opened.conversation.transcript.length,
605
+ conversation: committed(host, opened.conversation, walked),
606
+ };
607
+ }
429
608
  /**
430
609
  * The person sends a message. A reply that waits on gates is walked away
431
610
  * from first: each call settles cancelled and the paused reply commits; then
@@ -437,24 +616,13 @@ export async function* messageReply(args) {
437
616
  let opened = stored;
438
617
  yield* restored;
439
618
  const { paused } = opened.conversation;
440
- requireWalkAway(opened.conversation, args.walkAway);
441
- if (paused) {
442
- const walked = pausedReply(paused);
443
- const error = yield* settleWalkedAway(walked, args.walkAway ?? []);
444
- if (error) {
445
- opened = await save(host, opened, {
446
- ...opened.conversation,
447
- paused: { ...paused, events: walked.events, endedAt: Date.now() },
448
- });
449
- yield* refLine(opened);
450
- yield error;
451
- return;
452
- }
453
- opened = { ...opened, conversation: committed(host, opened.conversation, walked) };
454
- }
619
+ const walked = yield* walkAwayFrom(host, opened, runner, args.walkAway);
620
+ if (!walked)
621
+ return;
622
+ opened = walked;
455
623
  const withMessage = (history) => appendUserDraftToHistory(history, message.draft, message.media);
456
624
  let base = opened;
457
- for (;;) {
625
+ while (!args.saved) {
458
626
  try {
459
627
  // why: The message posts before the model runs, so a reply the browser stops still leaves it, in the transcript and the history.
460
628
  opened = await save(host, base, {
@@ -473,6 +641,17 @@ export async function* messageReply(args) {
473
641
  }
474
642
  }
475
643
  const { conversation } = base;
644
+ if (args.saved) {
645
+ opened = {
646
+ ...base,
647
+ stored: base.stored ?? conversation.transcript.length,
648
+ conversation: {
649
+ ...conversation,
650
+ transcript: [...conversation.transcript, ...args.saved],
651
+ history: withMessage(conversation.history),
652
+ },
653
+ };
654
+ }
476
655
  yield* refLine(opened, 'posted');
477
656
  const reply = {
478
657
  base: withMessage(conversation.history),
@@ -480,7 +659,7 @@ export async function* messageReply(args) {
480
659
  baseEvents: 0,
481
660
  workedMs: 0,
482
661
  };
483
- yield* runReply(host, opened, reply, runner, { ...message.input, ...historyInput(conversation) }, withMessage);
662
+ yield* runReply(host, opened, reply, runner, { ...message.input, ...historyInput(conversation) }, withMessage, 'message');
484
663
  }
485
664
  /**
486
665
  * The conversation as a save that `err` lost to left it, while this reply's hold still has the chat.
@@ -519,10 +698,14 @@ function historyInput(conversation) {
519
698
  /**
520
699
  * The model takes up the results of calls that ended while nothing ran: a reply to no message.
521
700
  * It writes nothing until it ends, so a message posted meanwhile keeps the conversation, and this
522
- * reply ends with no write: that message's reply read the same results.
701
+ * reply ends with no write: that message's reply read the same results. A reply that waits on
702
+ * gates is walked away from first, as a message does.
523
703
  */
524
704
  export async function* wakeReply(args) {
525
- const { host, opened, runner } = args;
705
+ const { host, runner } = args;
706
+ const opened = yield* walkAwayFrom(host, args.opened, runner, args.walkAway);
707
+ if (!opened)
708
+ return;
526
709
  const { conversation } = opened;
527
710
  const reply = { base: conversation.history, events: [], baseEvents: 0, workedMs: 0 };
528
711
  try {
@@ -539,7 +722,7 @@ export async function* wakeReply(args) {
539
722
  */
540
723
  export async function* answerReply(args) {
541
724
  const { host, runner } = args;
542
- let opened = args.opened;
725
+ const opened = args.opened;
543
726
  requireWaitingOn(opened.conversation, args.call);
544
727
  const { paused, ...waiting } = opened.conversation;
545
728
  if (!paused)
@@ -562,11 +745,16 @@ export async function* answerReply(args) {
562
745
  const events = error && !settledCall ? paused.events : reply.events;
563
746
  if (runner.held && !(await runner.held()))
564
747
  return;
565
- opened = await save(host, opened, {
748
+ const next = {
566
749
  ...opened.conversation,
567
750
  paused: { ...paused, events, workedMs: reply.workedMs, endedAt: Date.now() },
568
- });
569
- yield* refLine(opened);
751
+ };
752
+ yield* refLine(await saveReply(host, opened, runner, {
753
+ ended: 'paused',
754
+ next,
755
+ events,
756
+ ...(error ? { failure: error } : {}),
757
+ }));
570
758
  if (error)
571
759
  yield error;
572
760
  return;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The conversation core for a server that takes messages with no HTTP request of the page's: a
3
+ * messaging channel, a voice channel, a timer. It runs the replies `createTheoremHandler` runs,
4
+ * on the same stores, and reads a `CoreContext` where the handler reads the `Request`.
5
+ *
6
+ * @module
7
+ */
8
+ import { type ProviderHostOptions } from '@theoremjs/agents';
9
+ import type { InboxItem } from '@theoremjs/agents/conversation';
10
+ import { type ConversationCore, type ReplyWiring } from './conversation-core.ts';
11
+ import type { TheoremHandlerOptions } from './handler.ts';
12
+ import { type CallHooks, type CoreContext } from './session-calls.ts';
13
+ /**
14
+ * Options for {@link createTheoremConversationCore}. Each option picked from
15
+ * `TheoremHandlerOptions` means what it means there. The others take the run's `CoreContext`
16
+ * where the handler's take the `Request`.
17
+ */
18
+ export type TheoremConversationCoreOptions<Item extends InboxItem = InboxItem> = Pick<TheoremHandlerOptions, 'profile' | 'onStage' | 'sessionStore' | 'conversationStore' | 'credentialStore' | 'gateTtlMs' | 'operationRetentionMs' | 'pageToolBroker' | 'pageToolTimeoutMs' | 'notifier' | 'notifyRetryMs' | 'lateResultsDecider' | 'conversationLeaseMs' | 'steerInbox' | 'clientEvents'> & ReplyWiring<Item> & {
19
+ /** Host options for registered providers, or a factory for apps that pick keys per run. */
20
+ provider: ProviderHostOptions | ((at: CoreContext, model?: string) => ProviderHostOptions | Promise<ProviderHostOptions>);
21
+ /**
22
+ * The `lateResultsDecider`'s wake: start a reply to no message for the conversation under
23
+ * `ref`, such as by a queued call to `wake`. Required with `lateResultsDecider`.
24
+ */
25
+ wake?: (at: CoreContext, ref: string) => Promise<void>;
26
+ } & CallHooks;
27
+ /** Creates the conversation core for `options.profile`. */
28
+ export declare function createTheoremConversationCore<Item extends InboxItem = InboxItem>(options: TheoremConversationCoreOptions<Item>): ConversationCore;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The conversation core for a server that takes messages with no HTTP request of the page's: a
3
+ * messaging channel, a voice channel, a timer. It runs the replies `createTheoremHandler` runs,
4
+ * on the same stores, and reads a `CoreContext` where the handler reads the `Request`.
5
+ *
6
+ * @module
7
+ */
8
+ import { TheoremError } from '@theoremjs/agents';
9
+ import { chatOf, createConversationCore, } from "./conversation-core.js";
10
+ import { sessionParts } from "./session-calls.js";
11
+ import { createMemorySteerInbox } from "./steer-inbox.js";
12
+ /** Creates the conversation core for `options.profile`. */
13
+ export function createTheoremConversationCore(options) {
14
+ const name = 'createTheoremConversationCore';
15
+ const chat = chatOf(name, options.profile, options.conversationStore);
16
+ const { provider, wake } = options;
17
+ if (options.lateResultsDecider && !wake) {
18
+ // labels-exempt: builder config error at setup; no user sees it
19
+ throw new TheoremError('config', `${name} needs \`wake\` with \`lateResultsDecider\``);
20
+ }
21
+ return createConversationCore({
22
+ ...sessionParts(name, chat.profile, options),
23
+ chat,
24
+ steer: options.steerInbox ?? createMemorySteerInbox(),
25
+ options: {
26
+ prepare: options.prepare,
27
+ onStage: options.onStage,
28
+ pageToolTimeoutMs: options.pageToolTimeoutMs,
29
+ notifier: options.notifier,
30
+ notifyRetryMs: options.notifyRetryMs,
31
+ lateResultsDecider: options.lateResultsDecider,
32
+ conversationLeaseMs: options.conversationLeaseMs,
33
+ clientEvents: options.clientEvents,
34
+ background: options.background,
35
+ authorizeToolReplay: options.authorizeToolReplay,
36
+ authorizationUrl: options.authorizationUrl,
37
+ onError: options.onError,
38
+ inbox: options.inbox,
39
+ beforeSave: options.beforeSave,
40
+ afterSave: options.afterSave,
41
+ compact: options.compact,
42
+ provider: (at, model) => (typeof provider === 'function' ? provider(at, model) : provider),
43
+ wake: (at, ref) => (wake ? wake(at, ref) : Promise.resolve()),
44
+ },
45
+ });
46
+ }