@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
@@ -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. */
@@ -67,12 +68,15 @@ async function openedAt(host, ref, restore) {
67
68
  return { ref: null, revision: null, conversation: emptyConversation() };
68
69
  }
69
70
  const snapshot = await host.store.read(host.sessionId, ref);
70
- if (snapshot)
71
- return { ref, revision: snapshot.revision, conversation: snapshot.conversation };
71
+ if (snapshot) {
72
+ const { revision, conversation, running } = snapshot;
73
+ return { ref, revision, conversation, ...(running ? { running } : {}) };
74
+ }
72
75
  if (!restore)
73
76
  throw unknownConversation();
74
77
  // 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);
78
+ // invariant: A page cannot state a block's host values; only the app's own save sets them.
79
+ const { conversation, events } = conversationFromBlocks(restore.profile, restore.blocks.map(withoutHost));
76
80
  return { ref: null, revision: null, conversation, events };
77
81
  }
78
82
  /**
@@ -131,20 +135,120 @@ export function conversationView(host, conversation) {
131
135
  : {}),
132
136
  };
133
137
  }
138
+ const CONFLICT = { code: 'conversation_conflict' };
134
139
  /** Writes `next` over what the request read; a write another request beat is refused. */
135
140
  async function save(host, opened, next) {
136
141
  const result = await host.store.write(host.sessionId, opened.ref, opened.revision, next);
137
142
  if (!result.written) {
138
143
  // labels-exempt: internal diagnostic; the user reads error.unavailable
139
144
  throw new TheoremError('unavailable', 'the conversation changed while this reply ran', {
140
- cause: { code: 'conversation_conflict' },
145
+ cause: CONFLICT,
141
146
  });
142
147
  }
143
148
  return { ref: result.ref, revision: result.revision, conversation: next };
144
149
  }
150
+ /** A refused reply's blocks: the app's values go on the block of its line, the last text. */
151
+ function refusalBlocks(blocks, refusal) {
152
+ const { host } = refusal;
153
+ const line = blocks.findLastIndex((block) => block.kind === 'text');
154
+ if (host === undefined || line < 0)
155
+ return blocks;
156
+ return blocks.map((block, index) => (index === line ? { ...block, host } : block));
157
+ }
158
+ /** The ids of the named injects that landed in `events`, in order. */
159
+ function landedIn(events) {
160
+ return events.flatMap((event) => event.type === 'stage' ? (event.injected ?? []).map((inject) => inject.id) : []);
161
+ }
162
+ /** `saving.next` as the app's `before` step shapes it, with what the store is told beside it. */
163
+ async function shaped(opened, runner, saving) {
164
+ const stored = opened.stored ?? opened.conversation.transcript.length;
165
+ const appended = saving.next.transcript.slice(stored);
166
+ const before = runner.saving?.before;
167
+ const reply = before
168
+ ? await before({
169
+ ended: saving.ended,
170
+ blocks: appended,
171
+ ...(saving.failure ? { failure: saving.failure } : {}),
172
+ landed: landedIn(saving.events),
173
+ })
174
+ : { blocks: appended, told: [] };
175
+ return {
176
+ next: before
177
+ ? {
178
+ ...saving.next,
179
+ transcript: [...saving.next.transcript.slice(0, stored), ...reply.blocks],
180
+ }
181
+ : saving.next,
182
+ context: {
183
+ ...(runner.hold ? { hold: runner.hold } : {}),
184
+ ...(runner.reply ? { reply: runner.reply } : {}),
185
+ ...(reply.host === undefined ? {} : { host: reply.host }),
186
+ ended: saving.ended,
187
+ // invariant: A reply whose hold lost the conversation tells nothing.
188
+ told: saving.ended === 'lost' ? [] : reply.told,
189
+ appended: reply.blocks,
190
+ },
191
+ };
192
+ }
193
+ /**
194
+ * Saves a reply: the app shapes it, the store writes it with its context, then the app's `after`
195
+ * step runs. Undefined when the app's `before` step threw on a reply that failed or was stopped:
196
+ * nothing is saved, the throw is reported, and the reply ends with its own failure.
197
+ */
198
+ async function saveReply(host, opened, runner, saving) {
199
+ let reply;
200
+ try {
201
+ reply = await shaped(opened, runner, saving);
202
+ }
203
+ catch (err) {
204
+ if (saving.ended !== 'failed' && saving.ended !== 'stopped')
205
+ throw err;
206
+ runner.saving?.report(err);
207
+ return undefined;
208
+ }
209
+ const result = await host.store.write(host.sessionId, opened.ref, opened.revision, reply.next, reply.context);
210
+ if (!result.written) {
211
+ // labels-exempt: internal diagnostic; the user reads error.unavailable
212
+ throw new TheoremError('unavailable', 'the conversation changed while this reply ran', {
213
+ cause: CONFLICT,
214
+ });
215
+ }
216
+ try {
217
+ await runner.saving?.after?.({ ended: saving.ended, told: reply.context.told });
218
+ }
219
+ catch (err) {
220
+ // invariant: The save is written; a step after it cannot fail the reply.
221
+ runner.saving?.report(err);
222
+ }
223
+ return { ref: result.ref, revision: result.revision, conversation: reply.next };
224
+ }
225
+ /**
226
+ * A reply to a message whose hold lost the conversation: the app's store hears what the person
227
+ * saw of it, and marks nothing told. Only with the app's `before` step, since a store that keeps
228
+ * no holds takes no write from a lost hold. It throws nothing: the reply is over.
229
+ */
230
+ async function saveLost(host, opened, runner, saving) {
231
+ if (!runner.saving?.before)
232
+ return;
233
+ try {
234
+ const reply = await shaped(opened, runner, { ...saving, ended: 'lost' });
235
+ await host.store.write(host.sessionId, opened.ref, opened.revision, reply.next, reply.context);
236
+ }
237
+ catch (err) {
238
+ runner.saving.report(err);
239
+ }
240
+ }
241
+ /** The runner's hold and steps for the save of the paused reply it walks away from. */
242
+ function walkedAway(runner, paused) {
243
+ return {
244
+ ...(runner.hold ? { hold: runner.hold } : {}),
245
+ ...(paused.reply ? { reply: paused.reply } : {}),
246
+ ...(runner.saving ? { saving: runner.saving } : {}),
247
+ };
248
+ }
145
249
  /** The line that tells the browser the ref of what was just written. */
146
250
  function refLine(opened, posted) {
147
- if (opened.ref === null)
251
+ if (!opened || opened.ref === null)
148
252
  return [];
149
253
  return [{ type: 'conversation', ref: opened.ref, ...(posted ? { posted: true } : {}) }];
150
254
  }
@@ -188,17 +292,35 @@ function pausedOn(conversation, reply, runner) {
188
292
  events: reply.events,
189
293
  base: reply.base,
190
294
  baseEvents: reply.baseEvents,
295
+ ...(reply.uncompacted ? { uncompacted: reply.uncompacted } : {}),
191
296
  workedMs: reply.workedMs,
192
297
  endedAt: Date.now(),
193
298
  ...(runner.model ? { model: runner.model } : {}),
194
299
  ...(runner.effort ? { effort: runner.effort } : {}),
195
300
  ...(runner.stated ? { stated: runner.stated } : {}),
301
+ ...(runner.reply ? { reply: runner.reply } : {}),
196
302
  };
197
303
  return { ...conversation, ...metered(conversation, reply.events), paused };
198
304
  }
199
- /** The reply failed: it commits as far as it got, closed by its error. */
200
- function failed(host, conversation, reply, failure) {
201
- const next = committed(host, conversation, reply);
305
+ /**
306
+ * The reply failed: it commits as far as it got, closed by its error. The late results it read
307
+ * leave with it, so a later reply tells them. A compaction that folded them in is undone too: the
308
+ * history goes back to its base before that compaction, and the next reply compacts again.
309
+ */
310
+ function failed(host, conversation, reply, failure, worded) {
311
+ const from = reply.uncompacted ?? reply;
312
+ const unread = (events) => events.filter((event, index) => event.type !== 'late_results' &&
313
+ !(reply.uncompacted && event.type === 'compaction' && index >= from.baseEvents));
314
+ const events = unread(reply.events);
315
+ const next = committed(host, conversation, {
316
+ base: from.base,
317
+ events,
318
+ baseEvents: unread(reply.events.slice(0, from.baseEvents)).length,
319
+ workedMs: reply.workedMs,
320
+ });
321
+ // why: An app that shapes the save words the failure itself, from `failure`.
322
+ if (worded === 'app')
323
+ return next;
202
324
  if (next.transcript.slice(conversation.transcript.length).some((b) => b.kind === 'error')) {
203
325
  return next;
204
326
  }
@@ -222,12 +344,23 @@ function stopped(host, conversation, reply) {
222
344
  * reply's base to the compacted history; `withMessage` puts the person's
223
345
  * message back on it when the reply answers one.
224
346
  */
225
- async function* runReply(host, opened, reply, runner, input, withMessage) {
347
+ async function* runReply(host, opened, reply, runner, input, withMessage, answers) {
226
348
  const { conversation } = opened;
349
+ const worded = runner.saving?.before ? 'app' : 'core';
350
+ /** What the person saw of a reply whose hold lost the conversation, for a reply to a message. */
351
+ const lost = async (from) => {
352
+ if (answers !== 'message')
353
+ return;
354
+ const next = runner.signal.aborted
355
+ ? stopped(host, conversation, from)
356
+ : committed(host, conversation, from);
357
+ await saveLost(host, opened, runner, { next, events: from.events });
358
+ };
227
359
  const startedAt = Date.now();
228
360
  const worked = () => ({ ...reply, workedMs: reply.workedMs + (Date.now() - startedAt) });
361
+ // invariant: A reply whose hold lost its chat saves nothing; the hold that has it tells what this one read.
362
+ const held = async () => !runner.held || (await runner.held());
229
363
  let errorEvent;
230
- let current = opened;
231
364
  try {
232
365
  const events = runner.run({
233
366
  input,
@@ -246,6 +379,10 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
246
379
  continue;
247
380
  }
248
381
  if (event.type === 'compaction') {
382
+ // invariant: A failure must not leave in the history a late result it gives back.
383
+ if (!reply.uncompacted && reply.events.some((seen) => seen.type === 'late_results')) {
384
+ reply.uncompacted = { base: reply.base, baseEvents: reply.baseEvents };
385
+ }
249
386
  reply.base = withMessage(event.history);
250
387
  reply.baseEvents = reply.events.length;
251
388
  }
@@ -253,37 +390,63 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
253
390
  }
254
391
  }
255
392
  catch (err) {
256
- current = await save(host, current, runner.signal.aborted
257
- ? stopped(host, conversation, worked())
258
- : failed(host, conversation, worked(), toErrorEvent(err)));
259
- yield* refLine(current);
393
+ const thrown = worked();
394
+ if (await held()) {
395
+ const failure = toErrorEvent(err);
396
+ yield* refLine(await saveReply(host, opened, runner, runner.signal.aborted
397
+ ? { ended: 'stopped', next: stopped(host, conversation, thrown), events: thrown.events }
398
+ : {
399
+ ended: 'failed',
400
+ next: failed(host, conversation, thrown, failure, worded),
401
+ events: thrown.events,
402
+ failure,
403
+ }));
404
+ }
405
+ else {
406
+ await lost(thrown);
407
+ }
260
408
  // why: A stopped reply is no failure; the browser draws what it left from the ref.
261
409
  if (!runner.signal.aborted)
262
410
  throw err;
263
411
  return;
264
412
  }
265
413
  const settled = worked();
414
+ const { events } = settled;
415
+ const refusal = runner.refused?.();
416
+ if (!(await held())) {
417
+ await lost(settled);
418
+ return;
419
+ }
266
420
  if (runner.signal.aborted) {
267
- current = await save(host, current, stopped(host, conversation, settled));
421
+ const next = stopped(host, conversation, settled);
422
+ yield* refLine(await saveReply(host, opened, runner, { ended: 'stopped', next, events }));
268
423
  }
269
424
  else if (errorEvent) {
270
- current = await save(host, current, failed(host, conversation, settled, errorEvent));
425
+ const next = failed(host, conversation, settled, errorEvent, worded);
426
+ yield* refLine(await saveReply(host, opened, runner, { ended: 'failed', next, events, failure: errorEvent }));
427
+ yield errorEvent;
428
+ }
429
+ else if (refusal) {
430
+ const next = committed(host, conversation, settled, (blocks) => refusalBlocks(blocks, refusal));
431
+ yield* refLine(await saveReply(host, opened, runner, { ended: 'refused', next, events }));
271
432
  }
272
- else if (gatedToolsFromEvents(settled.events).length) {
273
- current = await save(host, current, pausedOn(conversation, settled, runner));
433
+ else if (gatedToolsFromEvents(events).length) {
434
+ const next = pausedOn(conversation, settled, runner);
435
+ yield* refLine(await saveReply(host, opened, runner, { ended: 'paused', next, events }));
274
436
  }
275
437
  else {
276
- current = await save(host, current, committed(host, conversation, settled));
438
+ const next = committed(host, conversation, settled);
439
+ const current = await saveReply(host, opened, runner, { ended: 'committed', next, events });
440
+ if (!current)
441
+ return;
277
442
  yield* refLine(current);
278
443
  // why: The reply is the browser's before compaction runs, so a failed compaction loses none of it.
444
+ if (!(await held()))
445
+ return;
279
446
  const compacted = await compactedAfter(host, current, settled, runner, withMessage);
280
447
  if (compacted)
281
448
  yield* refLine(compacted);
282
- return;
283
449
  }
284
- yield* refLine(current);
285
- if (errorEvent)
286
- yield errorEvent;
287
450
  }
288
451
  /**
289
452
  * The profile compacts after a reply (`done.compaction.needed`): the history
@@ -294,6 +457,16 @@ async function compactedAfter(host, opened, reply, runner, withMessage) {
294
457
  const signal = done?.type === 'done' ? done.compaction : undefined;
295
458
  if (!signal?.needed)
296
459
  return undefined;
460
+ if (runner.saving?.compact) {
461
+ // invariant: The app's compaction is its own write; this reply writes nothing more.
462
+ try {
463
+ await runner.saving.compact({ history: signal.history, tokens: signal.tokens });
464
+ }
465
+ catch (err) {
466
+ runner.saving.report(err);
467
+ }
468
+ return undefined;
469
+ }
297
470
  const compacted = await runner.compact(signal.history, signal.tokens, runner.model);
298
471
  if (!compacted)
299
472
  return undefined;
@@ -394,6 +567,7 @@ function pausedReply(paused) {
394
567
  base: paused.base,
395
568
  events: [...paused.events],
396
569
  baseEvents: paused.baseEvents,
570
+ ...(paused.uncompacted ? { uncompacted: paused.uncompacted } : {}),
397
571
  workedMs: paused.workedMs,
398
572
  };
399
573
  }
@@ -401,6 +575,38 @@ function pausedReply(paused) {
401
575
  function failureOf(error) {
402
576
  return new TheoremError(error.errorKind, error.error ?? labelText(`error.${error.errorKind}`));
403
577
  }
578
+ /**
579
+ * Walks away from the reply `opened` waits on: each call settles cancelled, and the paused reply
580
+ * commits. Returns the conversation to go on from. Undefined when a call did not settle: the reply
581
+ * is saved as it waits, and the error is sent.
582
+ */
583
+ async function* walkAwayFrom(host, opened, runner, calls) {
584
+ const { paused } = opened.conversation;
585
+ requireWalkAway(opened.conversation, calls);
586
+ if (!paused)
587
+ return opened;
588
+ const walked = pausedReply(paused);
589
+ const error = yield* settleWalkedAway(walked, calls ?? []);
590
+ if (error) {
591
+ const next = {
592
+ ...opened.conversation,
593
+ paused: { ...paused, events: walked.events, endedAt: Date.now() },
594
+ };
595
+ yield* refLine(await saveReply(host, opened, walkedAway(runner, paused), {
596
+ ended: 'paused',
597
+ next,
598
+ events: walked.events,
599
+ failure: error,
600
+ }));
601
+ yield error;
602
+ return undefined;
603
+ }
604
+ return {
605
+ ...opened,
606
+ stored: opened.conversation.transcript.length,
607
+ conversation: committed(host, opened.conversation, walked),
608
+ };
609
+ }
404
610
  /**
405
611
  * The person sends a message. A reply that waits on gates is walked away
406
612
  * from first: each call settles cancelled and the paused reply commits; then
@@ -412,29 +618,42 @@ export async function* messageReply(args) {
412
618
  let opened = stored;
413
619
  yield* restored;
414
620
  const { paused } = opened.conversation;
415
- requireWalkAway(opened.conversation, args.walkAway);
416
- if (paused) {
417
- const walked = pausedReply(paused);
418
- const error = yield* settleWalkedAway(walked, args.walkAway ?? []);
419
- if (error) {
420
- opened = await save(host, opened, {
421
- ...opened.conversation,
422
- paused: { ...paused, events: walked.events, endedAt: Date.now() },
621
+ const walked = yield* walkAwayFrom(host, opened, runner, args.walkAway);
622
+ if (!walked)
623
+ return;
624
+ opened = walked;
625
+ const withMessage = (history) => appendUserDraftToHistory(history, message.draft, message.media);
626
+ let base = opened;
627
+ while (!args.saved) {
628
+ try {
629
+ // why: The message posts before the model runs, so a reply the browser stops still leaves it, in the transcript and the history.
630
+ opened = await save(host, base, {
631
+ ...base.conversation,
632
+ transcript: [...base.conversation.transcript, ...message.blocks],
633
+ history: withMessage(base.conversation.history),
423
634
  });
424
- yield* refLine(opened);
425
- yield error;
426
- return;
635
+ break;
636
+ }
637
+ catch (err) {
638
+ const moved = paused ? undefined : await savedSince(host, base, runner, err);
639
+ if (!moved)
640
+ throw err;
641
+ requireWalkAway(moved.conversation, undefined);
642
+ base = moved;
427
643
  }
428
- opened = { ...opened, conversation: committed(host, opened.conversation, walked) };
429
644
  }
430
- const { conversation } = opened;
431
- const withMessage = (history) => appendUserDraftToHistory(history, message.draft, message.media);
432
- // why: The message posts before the model runs, so a reply the browser stops still leaves it, in the transcript and the history.
433
- opened = await save(host, opened, {
434
- ...conversation,
435
- transcript: [...conversation.transcript, ...message.blocks],
436
- history: withMessage(conversation.history),
437
- });
645
+ const { conversation } = base;
646
+ if (args.saved) {
647
+ opened = {
648
+ ...base,
649
+ stored: base.stored ?? conversation.transcript.length,
650
+ conversation: {
651
+ ...conversation,
652
+ transcript: [...conversation.transcript, ...args.saved],
653
+ history: withMessage(conversation.history),
654
+ },
655
+ };
656
+ }
438
657
  yield* refLine(opened, 'posted');
439
658
  const reply = {
440
659
  base: withMessage(conversation.history),
@@ -442,14 +661,62 @@ export async function* messageReply(args) {
442
661
  baseEvents: 0,
443
662
  workedMs: 0,
444
663
  };
445
- yield* runReply(host, opened, reply, runner, {
446
- ...message.input,
664
+ yield* runReply(host, opened, reply, runner, { ...message.input, ...historyInput(conversation) }, withMessage, 'message');
665
+ }
666
+ /**
667
+ * The conversation as a save that `err` lost to left it, while this reply's hold still has the chat.
668
+ * Undefined when no hold runs the reply or it lost the chat: with no hold, the save it lost to is
669
+ * another message's.
670
+ *
671
+ * why: The hold a message took the chat from may land the one save it began first; no save of it follows.
672
+ */
673
+ async function savedSince(host, opened, runner, err) {
674
+ if (!runner.held || !(await runner.held()))
675
+ return undefined;
676
+ return newerSave(host, opened, err);
677
+ }
678
+ /**
679
+ * The conversation as the save that `err` lost to left it. Undefined when `err` is no such loss or
680
+ * no newer save is there to read.
681
+ */
682
+ async function newerSave(host, opened, err) {
683
+ if (!(err instanceof TheoremError && err.cause === CONFLICT) || opened.ref === null)
684
+ return undefined;
685
+ const snapshot = await host.store.read(host.sessionId, opened.ref);
686
+ if (!snapshot || snapshot.revision === opened.revision)
687
+ return undefined;
688
+ return { ref: opened.ref, revision: snapshot.revision, conversation: snapshot.conversation };
689
+ }
690
+ /** The conversation's history as a run reads it, with its meters. */
691
+ function historyInput(conversation) {
692
+ return {
447
693
  history: conversation.history,
448
694
  ...(conversation.inputTokens === undefined ? {} : { inputTokens: conversation.inputTokens }),
449
695
  ...(conversation.historyTokens === undefined
450
696
  ? {}
451
697
  : { historyTokens: conversation.historyTokens }),
452
- }, withMessage);
698
+ };
699
+ }
700
+ /**
701
+ * The model takes up the results of calls that ended while nothing ran: a reply to no message.
702
+ * It writes nothing until it ends, so a message posted meanwhile keeps the conversation, and this
703
+ * reply ends with no write: that message's reply read the same results. A reply that waits on
704
+ * gates is walked away from first, as a message does.
705
+ */
706
+ export async function* wakeReply(args) {
707
+ const { host, runner } = args;
708
+ const opened = yield* walkAwayFrom(host, args.opened, runner, args.walkAway);
709
+ if (!opened)
710
+ return;
711
+ const { conversation } = opened;
712
+ const reply = { base: conversation.history, events: [], baseEvents: 0, workedMs: 0 };
713
+ try {
714
+ yield* runReply(host, opened, reply, runner, { ...args.input, ...historyInput(conversation) }, (history) => history);
715
+ }
716
+ catch (err) {
717
+ if (!(err instanceof TheoremError && err.cause === CONFLICT))
718
+ throw err;
719
+ }
453
720
  }
454
721
  /**
455
722
  * The person answers one call the reply waits on. `settling` streams the
@@ -457,7 +724,7 @@ export async function* messageReply(args) {
457
724
  */
458
725
  export async function* answerReply(args) {
459
726
  const { host, runner } = args;
460
- let opened = args.opened;
727
+ const opened = args.opened;
461
728
  requireWaitingOn(opened.conversation, args.call);
462
729
  const { paused, ...waiting } = opened.conversation;
463
730
  if (!paused)
@@ -478,11 +745,18 @@ export async function* answerReply(args) {
478
745
  // why: An answer that failed before its call settled leaves the reply as it was, to answer again.
479
746
  const settledCall = reply.events.some((event) => settlesToolCall(event, args.call.callId));
480
747
  const events = error && !settledCall ? paused.events : reply.events;
481
- opened = await save(host, opened, {
748
+ if (runner.held && !(await runner.held()))
749
+ return;
750
+ const next = {
482
751
  ...opened.conversation,
483
752
  paused: { ...paused, events, workedMs: reply.workedMs, endedAt: Date.now() },
484
- });
485
- yield* refLine(opened);
753
+ };
754
+ yield* refLine(await saveReply(host, opened, runner, {
755
+ ended: 'paused',
756
+ next,
757
+ events,
758
+ ...(error ? { failure: error } : {}),
759
+ }));
486
760
  if (error)
487
761
  yield error;
488
762
  return;
@@ -512,12 +786,14 @@ function requireRewindPoint(conversation, at) {
512
786
  * start over. A paused reply is walked away from first, and commits before the cut.
513
787
  */
514
788
  export async function rewindConversation(args) {
515
- const { host, opened, at } = args;
789
+ const { host, at } = args;
790
+ let { opened } = args;
516
791
  let { conversation } = opened;
517
792
  requireRewindPoint(conversation, at);
518
793
  requireWalkAway(conversation, args.walkAway);
519
- if (conversation.paused) {
520
- const walked = pausedReply(conversation.paused);
794
+ const { paused } = conversation;
795
+ if (paused) {
796
+ const walked = pausedReply(paused);
521
797
  const settling = settleWalkedAway(walked, args.walkAway ?? []);
522
798
  let step = await settling.next();
523
799
  while (!step.done)
@@ -526,13 +802,34 @@ export async function rewindConversation(args) {
526
802
  throw failureOf(step.value);
527
803
  conversation = committed(host, conversation, walked);
528
804
  }
529
- const transcript = conversation.transcript.slice(0, at + 1);
530
- return save(host, opened, {
531
- version: 2,
532
- id: conversation.id,
533
- transcript,
534
- history: historyFromTranscriptBlocks(transcript),
535
- });
805
+ for (;;) {
806
+ const transcript = conversation.transcript.slice(0, at + 1);
807
+ try {
808
+ return await save(host, opened, {
809
+ version: 2,
810
+ id: conversation.id,
811
+ transcript,
812
+ history: historyFromTranscriptBlocks(transcript),
813
+ });
814
+ }
815
+ catch (err) {
816
+ const moved = paused ? undefined : await newerSave(host, opened, err);
817
+ if (!moved || !keepsThrough(moved.conversation, transcript))
818
+ throw err;
819
+ requireWalkAway(moved.conversation, undefined);
820
+ opened = moved;
821
+ conversation = moved.conversation;
822
+ }
823
+ }
824
+ }
825
+ /**
826
+ * Whether `conversation` still holds `kept` as its first blocks: a save that only added after the
827
+ * cut leaves the rewind the same cut.
828
+ *
829
+ * why: A reply that held the chat may land the save it began as the person rewinds.
830
+ */
831
+ function keepsThrough(conversation, kept) {
832
+ return kept.every((block, index) => conversation.transcript[index]?.id === block.id);
536
833
  }
537
834
  /** A paused call's operation: every call a session issued carries one. */
538
835
  export function requiredOperationId(call) {
@@ -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
+ }
@@ -1,4 +1,5 @@
1
1
  import { defineProfile, registerProfile, runEmbedding, z, } from '@theoremjs/agents';
2
+ import { refuseInterfacePick } from '@theoremjs/agents/interface';
2
3
  import { embeddingInterface } from "../client/embedding-transport.js";
3
4
  import { readBody } from "./handler.js";
4
5
  import { singleActionHandler } from "./single-action.js";
@@ -30,6 +31,7 @@ export function createTheoremEmbeddingHandler(options) {
30
31
  onError: options.onError,
31
32
  }, async (request) => {
32
33
  const body = await readBody(request, embedBodySchema);
34
+ refuseInterfacePick(profile, { model: body.model });
33
35
  const provider = typeof options.provider === 'function'
34
36
  ? await options.provider({ request, model: body.model })
35
37
  : options.provider;