@theoremjs/web 0.3.5-next.935.ga3dc485 → 0.3.5-next.938.g3cbd0dd

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.
@@ -155,9 +155,16 @@ export type TheoremHandlerOptions = {
155
155
  }) => boolean | Promise<boolean>;
156
156
  /**
157
157
  * Who tells the model that a background call ended: `TurnWiring.lateResultsDecider`. Unset, no
158
- * page wakes the chat and no reply reads a late result. `pageWakes` lets the open page wake it.
158
+ * page wakes the chat and no reply reads a late result. `tellEveryResult` tells each result to
159
+ * the first reply that runs, and lets the open page wake the chat.
159
160
  */
160
161
  lateResultsDecider?: TurnWiring['lateResultsDecider'];
162
+ /**
163
+ * How long a reply keeps its chat after it last renewed, in milliseconds: it renews every third
164
+ * of it while it runs. A wake the chat turned away tries again once this runs out, and a reply
165
+ * that stopped without letting go keeps the chat no longer. Default 60000.
166
+ */
167
+ conversationLeaseMs?: number;
161
168
  /**
162
169
  * Tool credentials by session. Your OAuth callback route saves the token here
163
170
  * under the same session id; every turn reads from here. Default: in-process
@@ -191,7 +198,7 @@ export type TheoremHandlerOptions = {
191
198
  }) => void;
192
199
  };
193
200
  /** A host profile runs no model, and takes no turns to steer. */
194
- export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'steerInbox' | 'conversationStore' | 'prepare' | 'notifier' | 'notifyRetryMs'> & {
201
+ export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'steerInbox' | 'conversationStore' | 'prepare' | 'notifier' | 'notifyRetryMs' | 'conversationLeaseMs'> & {
195
202
  /** Host profile to serve. Registered with the kernel when the handler is created. */
196
203
  profile: Extract<Profile, {
197
204
  type: 'host';
package/server/handler.js CHANGED
@@ -40,12 +40,14 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
40
40
  * @module
41
41
  */
42
42
  import { authorizeToolReplay, compactHistory, defaultKernelScope, defineProfile, invokeTool, jsonObjectSchema, labelText, registerProfile, runTurn, TheoremError, toolInvocationHash, } from '@theoremjs/agents';
43
+ import { runConversation } from '@theoremjs/agents/conversation';
43
44
  import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremjs/agents/host';
44
45
  import { clientProfileInterface, gatedToolsFromEvents, interfaceFromProfile, promotedToolIdsFromEvents, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
45
46
  import { answerGatedCall, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
46
47
  import { hostInterface, theoremHostCallRequestSchema, } from "../client/host-transport.js";
47
48
  import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
48
- import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, wakeableCalls, wakeReply, } from "./conversation.js";
49
+ import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
50
+ import { detachedEnd, sessionConversationInbox } from "./conversation-inbox.js";
49
51
  import { unknownConversation, } from "./conversation-store.js";
50
52
  import { createMemoryCredentialStore, } from "./credential-store.js";
51
53
  import { sessionStateStore, } from "./session-authority.js";
@@ -440,14 +442,16 @@ function announced(ctx, request, sessionId, service) {
440
442
  if (!ended)
441
443
  return;
442
444
  const { operations } = await ctx.sessions.read(sessionId);
443
- const operation = Object.hasOwn(operations, call.operationId)
444
- ? operations[call.operationId]
445
+ const { operationId, callId, toolId } = call;
446
+ const operation = Object.hasOwn(operations, operationId)
447
+ ? operations[operationId]
445
448
  : undefined;
446
- if (operation?.status !== 'settled')
449
+ const outcome = detachedEnd({ operationId, callId, name: toolId, at: Date.now() }, operation, ctx.profile.labels);
450
+ if (!outcome)
447
451
  return;
448
452
  await ended({
449
453
  host: await ctx.options.host?.(request),
450
- result: { operationId: call.operationId, outcome: operation.outcome },
454
+ result: { operationId, outcome },
451
455
  wake: (conversation) => serverWake(ctx, request, sessionId, conversation),
452
456
  notify,
453
457
  });
@@ -459,13 +463,21 @@ function announced(ctx, request, sessionId, service) {
459
463
  }
460
464
  /**
461
465
  * The decider's wake, with no page: the reply runs on a request of its own, with the headers of
462
- * the one that started the call and no signal, because that request has ended.
466
+ * the one that started the call and no signal, because that request has ended. When another reply
467
+ * holds the chat, it tries again as that hold's lease runs out.
463
468
  */
464
- async function serverWake(ctx, started, sessionId, conversation) {
469
+ async function serverWake(ctx, started, sessionId, ref) {
465
470
  const request = new Request(started.url, { headers: started.headers });
466
- const lines = await wakeLines(ctx, request, { id: sessionId }, conversation, {});
467
- if (!lines)
468
- return;
471
+ const session = { id: sessionId };
472
+ const host = conversationHost(ctx, session);
473
+ if (!host)
474
+ throw statelessRefusal('wake');
475
+ const retry = (leasedUntil) => {
476
+ setTimeout(() => {
477
+ serverWake(ctx, started, sessionId, ref).catch((err) => ctx.options.onError?.(err, { request }));
478
+ }, Math.max(0, leasedUntil - Date.now()));
479
+ };
480
+ const lines = await wakeLines(ctx, request, session, host, ref, {}, { retry });
469
481
  for await (const line of lines) {
470
482
  if (line.type === 'error') {
471
483
  // labels-exempt: internal diagnostic for the decider's wake; no page reads it
@@ -477,57 +489,153 @@ async function serverWake(ctx, started, sessionId, conversation) {
477
489
  async function* once(event, labels) {
478
490
  yield withPublicLabels(event, labels);
479
491
  }
492
+ /** Whether this request may read a settled call's result: the host's `authorizeToolReplay`. */
493
+ async function replayAllowed(ctx, request, operation) {
494
+ const { authorizeToolReplay } = ctx.options;
495
+ return !authorizeToolReplay || (await authorizeToolReplay({ request, operation }));
496
+ }
497
+ const DEFAULT_CONVERSATION_LEASE_MS = 60_000;
498
+ /**
499
+ * The chat's inbox as this request reads it: the chat as this request last wrote it, and the
500
+ * results this request may read. `seen` follows each line's ref, because a store's ref can change
501
+ * with each write.
502
+ */
503
+ function chatInbox(ctx, request, session, host, opened) {
504
+ let ref = opened.ref;
505
+ const leaseMs = ctx.options.conversationLeaseMs ?? DEFAULT_CONVERSATION_LEASE_MS;
506
+ const inbox = sessionConversationInbox({
507
+ sessions: ctx.sessions,
508
+ sessionId: session.id,
509
+ leaseMs,
510
+ conversation: async (key) => {
511
+ const conversation = ref === null ? opened.conversation : (await host.store.read(session.id, ref))?.conversation;
512
+ return conversation?.id === key ? conversation : undefined;
513
+ },
514
+ readable: (operation) => replayAllowed(ctx, request, operation),
515
+ labels: ctx.profile.labels,
516
+ });
517
+ return {
518
+ inbox,
519
+ key: opened.conversation.id,
520
+ leaseMs,
521
+ seen(line) {
522
+ if (line.type === 'conversation')
523
+ ref = line.ref;
524
+ },
525
+ get ref() {
526
+ return ref;
527
+ },
528
+ };
529
+ }
530
+ /** The values `produce` sends, as it sends them, then its end or what it threw. */
531
+ async function* sent(produce) {
532
+ const queue = [];
533
+ let ended;
534
+ let wake = () => { };
535
+ produce((value) => {
536
+ queue.push(value);
537
+ wake();
538
+ }).then(() => {
539
+ ended = { failed: false };
540
+ wake();
541
+ }, (failure) => {
542
+ ended = { failed: true, failure };
543
+ wake();
544
+ });
545
+ for (;;) {
546
+ if (queue.length > 0) {
547
+ yield queue.splice(0, 1)[0];
548
+ continue;
549
+ }
550
+ if (ended?.failed)
551
+ throw ended.failure;
552
+ if (ended)
553
+ return;
554
+ await new Promise((resolve) => {
555
+ wake = resolve;
556
+ });
557
+ }
558
+ }
480
559
  /**
481
- * The late results this reply gives the model as it opens: those the wake took, or those the
482
- * decider gives a message. A reply that goes on after a pause has none, so it is asked once.
560
+ * Runs a reply under a hold of the chat, and streams its lines. The reply reads the late results
561
+ * the decider's policy tells it. Without a decider no reply reads one, and no hold is taken.
562
+ * invariant: One hold has a chat at a time, and lets it go only once nothing waits that may be told.
563
+ * A page's reply that leaves results waiting lets the chat go, so the page wakes for them; a
564
+ * server's wake runs the next reply under its hold.
483
565
  */
484
- async function openingLateResults(ctx, request, host, turn, operations, late) {
485
- if (!turn.unread)
486
- return {};
487
- const given = late.given ??
488
- (await givenResults(ctx, host, late.conversation, await readableResults(ctx, request, turn.unread, operations), 'message'));
489
- if (given.length === 0)
490
- return {};
491
- const outcomes = given.map((operation) => operation.outcome);
492
- return { lateResults: ({ stage }) => (stage === 'pre_turn' ? outcomes : []) };
493
- }
494
- /** Those of `results` the decider gives the reply; none without a decider. */
495
- async function givenResults(ctx, host, conversation, results, reason) {
566
+ function heldLines(ctx, request, session, host, opened, start, reply, follow = {}) {
496
567
  const decider = ctx.options.lateResultsDecider;
497
- if (!decider || conversation === undefined || results.length === 0)
498
- return [];
499
- const ids = new Set(await decider.give({
500
- reason,
501
- host,
502
- conversation,
503
- results: results.map(lateResult),
504
- }));
505
- return results.filter((operation) => ids.has(operation.operationId));
568
+ if (!decider)
569
+ return reply(undefined, () => opened.ref);
570
+ const chat = chatInbox(ctx, request, session, host, opened);
571
+ const ref = () => chat.ref;
572
+ return sent(async (send) => {
573
+ const runOnce = (begin, lines) => runConversation({
574
+ conversation: chat.key,
575
+ inbox: chat.inbox,
576
+ policy: decider.policy,
577
+ start: begin,
578
+ newId: () => crypto.randomUUID(),
579
+ renewEveryMs: chat.leaseMs / 3,
580
+ reply: async (run) => {
581
+ const renew = () => chat.inbox.renew(chat.key, run.hold);
582
+ for await (const line of lines({ run, renew })) {
583
+ chat.seen(line);
584
+ send(line);
585
+ }
586
+ },
587
+ gaveUp: (items) => {
588
+ ctx.options.onError?.(
589
+ // labels-exempt: internal diagnostic; no reader sees a given-up result
590
+ new TheoremError('unavailable', 'The late-results policy gave up results', {
591
+ cause: { code: 'late_results_given_up', operationIds: items.map((item) => item.id) },
592
+ }), { request });
593
+ },
594
+ });
595
+ let run = await runOnce(start, (held) => reply(held, ref));
596
+ let failure = run.outcome === 'held' ? undefined : run.failure;
597
+ while (run.outcome === 'continue') {
598
+ const paused = await isPaused(host, session, chat.ref, opened.conversation);
599
+ if (follow.retry === undefined || paused) {
600
+ await letGo(chat.inbox, chat.key, run.hold);
601
+ break;
602
+ }
603
+ run = await runOnce({ opening: 'follow_up', hold: run.hold }, (held) => wakeReplyLines(ctx, request, session, host, chat.ref, {}, held));
604
+ if (run.outcome !== 'held' && run.failure !== undefined)
605
+ failure ??= run.failure;
606
+ }
607
+ if (run.outcome === 'held')
608
+ follow.retry?.(run.leasedUntil);
609
+ if (failure !== undefined)
610
+ throw failure;
611
+ });
506
612
  }
507
- function lateResult(operation) {
508
- return { operationId: operation.operationId, outcome: operation.outcome };
613
+ /** Whether the chat waits on gates: a wake leaves it to the answer that goes on. */
614
+ async function isPaused(host, session, ref, fallback) {
615
+ const conversation = ref === null ? fallback : (await host.store.read(session.id, ref))?.conversation;
616
+ return conversation?.paused !== undefined;
509
617
  }
510
- /** The calls among `unread` that ended, as this request may read them. */
511
- async function readableResults(ctx, request, unread, operations) {
512
- const readable = [];
513
- for (const { operationId } of unread) {
514
- const operation = Object.hasOwn(operations, operationId) ? operations[operationId] : undefined;
515
- if (operation?.status !== 'settled')
516
- continue;
517
- const { authorizeToolReplay } = ctx.options;
518
- if (authorizeToolReplay && !(await authorizeToolReplay({ request, operation })))
519
- continue;
520
- readable.push(operation);
618
+ /** Lets the chat go under `hold`, reading again each time a result arrives first. */
619
+ async function letGo(inbox, key, hold) {
620
+ for (;;) {
621
+ const { version } = await inbox.read(key);
622
+ if ((await inbox.release(key, hold, version)) !== 'moved')
623
+ return;
521
624
  }
522
- return readable;
523
625
  }
524
- /** The results a wake would take up: readable, and no wake has taken them. */
525
- async function wakeResults(ctx, request, conversation, operations) {
526
- const readable = await readableResults(ctx, request, wakeableCalls(conversation), operations);
527
- return readable.filter((operation) => operation.wokenAt === undefined);
626
+ /** The late results a reply's model reads: what it opened with, then what each later moment hands it. */
627
+ function lateSource(run) {
628
+ let opening = true;
629
+ return async ({ stage, step }) => {
630
+ if (opening && stage === 'pre_turn') {
631
+ opening = false;
632
+ return run.opened.map((item) => item.outcome);
633
+ }
634
+ return (await run.take({ stage, step })).map((item) => item.outcome);
635
+ };
528
636
  }
529
637
  /** One model run of a chat's reply, its gates recorded in the session as they pause. */
530
- async function* chatTurn(ctx, request, session, turn, key, stop, late) {
638
+ async function* chatTurn(ctx, request, session, turn, key, signal, stop, late) {
531
639
  const state = await ctx.sessions.read(session.id);
532
640
  const provider = await providerFor(ctx, request, turn.model);
533
641
  const host = await ctx.options.host?.(request);
@@ -543,11 +651,11 @@ async function* chatTurn(ctx, request, session, turn, key, stop, late) {
543
651
  ...backgroundWiring(ctx, request, session.id),
544
652
  pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
545
653
  input: turn.input,
546
- ...(await openingLateResults(ctx, request, host, turn, state.operations, late)),
654
+ ...(late ? { lateResults: lateSource(late) } : {}),
547
655
  ...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
548
656
  ...(turn.providerState ? { providerState: turn.providerState } : {}),
549
657
  sessionPermissions: state.permissions,
550
- signal: AbortSignal.any([request.signal, stop.signal]),
658
+ signal,
551
659
  host,
552
660
  ...(turn.model ? { model: turn.model } : {}),
553
661
  ...(turn.effort ? { effort: turn.effort } : {}),
@@ -570,16 +678,16 @@ async function* chatTurn(ctx, request, session, turn, key, stop, late) {
570
678
  await ctx.inbox.close(key);
571
679
  }
572
680
  }
573
- /** How this request runs the model for a reply: its generation, and its abort (the request's, or a stop). */
574
- function chatRunner(ctx, request, session, generation, given) {
681
+ /**
682
+ * How this request runs the model for a reply: its generation, its abort (the request's, a stop,
683
+ * or its hold losing the chat), and the chat's hold it saves under.
684
+ */
685
+ function chatRunner(ctx, request, session, generation, held) {
575
686
  const key = generation.turnId ? inboxKey(session.id, generation.turnId) : undefined;
576
687
  const stop = new AbortController();
577
- const signal = AbortSignal.any([request.signal, stop.signal]);
688
+ const signal = AbortSignal.any([request.signal, stop.signal, ...(held ? [held.run.signal] : [])]);
578
689
  return {
579
- run: (turn) => chatTurn(ctx, request, session, turn, key, stop, {
580
- ...(generation.conversation === undefined ? {} : { conversation: generation.conversation }),
581
- ...(given ? { given } : {}),
582
- }),
690
+ run: (turn) => chatTurn(ctx, request, session, turn, key, signal, stop, held?.run),
583
691
  async compact(history, tokens, model) {
584
692
  const provider = await providerFor(ctx, request, model);
585
693
  const compacted = await compactHistory({
@@ -595,6 +703,7 @@ function chatRunner(ctx, request, session, generation, given) {
595
703
  ...(generation.effort ? { effort: generation.effort } : {}),
596
704
  ...(generation.stated ? { stated: generation.stated } : {}),
597
705
  signal,
706
+ ...(held ? { reply: held.run.reply, held: held.renew } : {}),
598
707
  };
599
708
  }
600
709
  /** The chat's conversation as this session's runs read and write it; undefined when the profile keeps none. */
@@ -616,7 +725,6 @@ async function turn(ctx, chat, request, session) {
616
725
  throw new TheoremError('request', labelText('error.request'));
617
726
  }
618
727
  const message = postedMessage(chatInterface(chat), body.input, await ctx.options.context?.(request));
619
- const runner = chatRunner(ctx, request, session, body);
620
728
  const host = conversationHost(ctx, session);
621
729
  if (!host) {
622
730
  if (body.conversation !== undefined)
@@ -624,6 +732,7 @@ async function turn(ctx, chat, request, session) {
624
732
  // labels-exempt: internal diagnostic; the user reads error.request
625
733
  if (body.abandon)
626
734
  throw statelessRefusal('walk away from');
735
+ const runner = chatRunner(ctx, request, session, body);
627
736
  return eventStream(ctx, request, () => runner.run({
628
737
  input: message.input,
629
738
  model: body.model,
@@ -639,7 +748,13 @@ async function turn(ctx, chat, request, session) {
639
748
  const walkAway = body.abandon
640
749
  ? await takeWalkedAway(ctx, request, session, body.abandon, opened.conversation)
641
750
  : undefined;
642
- return eventStream(ctx, request, () => messageReply({ host, opened, message, ...(walkAway ? { walkAway } : {}), runner }));
751
+ return eventStream(ctx, request, () => heldLines(ctx, request, session, host, opened, { opening: 'message', takeOver: true }, (held) => messageReply({
752
+ host,
753
+ opened,
754
+ message,
755
+ ...(walkAway ? { walkAway } : {}),
756
+ runner: chatRunner(ctx, request, session, body, held),
757
+ })));
643
758
  }
644
759
  /** The conversation as the browser draws it. */
645
760
  async function conversation(ctx, request, session) {
@@ -651,68 +766,41 @@ async function conversation(ctx, request, session) {
651
766
  return jsonResponse(200, await currentView(ctx, request, session, host, body.conversation, opened.conversation));
652
767
  }
653
768
  /**
654
- * A reply to no message, for results that ended since the model last ran. Each result is taken by
655
- * one wake before the decider is asked, so two pages that wake at once run it once. The decider's
656
- * `give` picks what the reply reads; what it leaves is let go, for a later reply.
769
+ * A reply to no message, for results that ended since the model last ran. It runs under a hold of
770
+ * the chat, so two pages that wake at once run it once, and reads what the decider's policy tells.
657
771
  */
658
772
  async function wake(ctx, request, session) {
659
773
  const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
660
774
  const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
661
- const lines = await wakeLines(ctx, request, session, body.conversation, body, input);
662
- return eventStream(ctx, request, lines ? () => lines : async function* () { });
663
- }
664
- /** The wake's reply, or undefined when the decider gives it nothing to read. */
665
- async function wakeLines(ctx, request, session, conversation, generation, input) {
666
775
  const host = conversationHost(ctx, session);
667
776
  if (!host)
668
777
  throw statelessRefusal('wake');
669
- if (!ctx.options.lateResultsDecider)
670
- return undefined;
671
- const opened = await openConversation(host, conversation, { kind: 'read' });
672
- const { operations } = await ctx.sessions.read(session.id);
673
- const due = await wakeResults(ctx, request, opened.conversation, operations);
674
- if (due.length === 0)
675
- return undefined;
676
- const now = Date.now();
677
- const taken = await ctx.sessions.mutate(session.id, (state) => due.filter(({ operationId }) => {
678
- const operation = state.operations[operationId];
679
- if (operation?.status !== 'settled' || operation.wokenAt !== undefined)
680
- return false;
681
- state.operations[operationId] = { ...operation, wokenAt: now };
682
- return true;
683
- }));
684
- let given = [];
685
- try {
686
- given = await givenResults(ctx, await ctx.options.host?.(request), conversation, taken, 'wake');
687
- }
688
- finally {
689
- const kept = new Set(given.map((operation) => operation.operationId));
690
- const left = taken.filter((operation) => !kept.has(operation.operationId));
691
- // why: A result the decider did not give leaves no mark, so a later wake can still give it.
692
- if (left.length)
693
- await letGo(ctx, session, left, now);
694
- }
695
- if (given.length === 0)
696
- return undefined;
697
- const runner = chatRunner(ctx, request, session, { ...generation, conversation }, given);
698
- const { notifier } = ctx.options;
699
- return (async function* () {
700
- yield* wakeReply({ host, opened, runner, ...(input ? { input } : {}) });
701
- // why: The page that woke draws its reply; any other page open on the session reads it now.
702
- notifier?.publish(session.id);
703
- })();
704
- }
705
- /** Takes the wake's mark off results it did not read. */
706
- async function letGo(ctx, session, left, wokenAt) {
707
- await ctx.sessions.mutate(session.id, (state) => {
708
- for (const { operationId } of left) {
709
- const operation = state.operations[operationId];
710
- if (operation?.status !== 'settled' || operation.wokenAt !== wokenAt)
711
- continue;
712
- const { wokenAt: _taken, ...rest } = operation;
713
- state.operations[operationId] = rest;
714
- }
715
- });
778
+ const lines = await wakeLines(ctx, request, session, host, body.conversation, body, {}, input);
779
+ return eventStream(ctx, request, () => lines);
780
+ }
781
+ /**
782
+ * The wake's reply under a hold of the chat; nothing when no decider tells a result, or while a
783
+ * reply waits on gates: the answer that goes on reads what waits.
784
+ */
785
+ async function wakeLines(ctx, request, session, host, ref, generation, follow, input) {
786
+ const opened = await openConversation(host, ref, { kind: 'read' });
787
+ if (!ctx.options.lateResultsDecider || opened.conversation.paused)
788
+ return noLines();
789
+ return heldLines(ctx, request, session, host, opened, { opening: 'wake' }, (held, current) => wakeReplyLines(ctx, request, session, host, current(), generation, held, input), follow);
790
+ }
791
+ /** No reply lines. */
792
+ async function* noLines() { }
793
+ /**
794
+ * A reply to no message under `held`, on the chat as it stands now. The page that woke draws it;
795
+ * any other page open on the session reads it once it ends.
796
+ */
797
+ async function* wakeReplyLines(ctx, request, session, host, ref, generation, held, input) {
798
+ if (ref === null)
799
+ return;
800
+ const opened = await openConversation(host, ref, { kind: 'read' });
801
+ const runner = chatRunner(ctx, request, session, generation, held);
802
+ yield* wakeReply({ host, opened, runner, ...(input ? { input } : {}) });
803
+ ctx.options.notifier?.publish(session.id);
716
804
  }
717
805
  const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
718
806
  /**
@@ -771,24 +859,25 @@ async function currentView(ctx, request, session, host, ref, conversation) {
771
859
  ...(notifier && transcript.some(isDetachedBlock)
772
860
  ? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
773
861
  : {}),
774
- ...((await wakeDue(ctx, request, ref, conversation, operations))
862
+ ...((await wakeDue(ctx, request, session, host, ref, conversation))
775
863
  ? { wake: true }
776
864
  : {}),
777
865
  };
778
866
  }
779
- /** Whether the page wakes the chat now: results wait that no wake took, and the decider says so. */
780
- async function wakeDue(ctx, request, ref, conversation, operations) {
781
- const due = ctx.options.lateResultsDecider?.due;
782
- if (!due)
867
+ /**
868
+ * Whether the page wakes the chat now: the decider's policy tells a waiting result to a reply to no
869
+ * message. Never while a reply waits on gates: the answer that goes on reads what waits.
870
+ */
871
+ async function wakeDue(ctx, request, session, host, ref, conversation) {
872
+ const decider = ctx.options.lateResultsDecider;
873
+ if (!decider || conversation.paused)
783
874
  return false;
784
- const results = await wakeResults(ctx, request, conversation, operations);
785
- if (results.length === 0)
875
+ const chat = chatInbox(ctx, request, session, host, { ref, conversation });
876
+ const { items } = await chat.inbox.read(chat.key);
877
+ if (items.length === 0)
786
878
  return false;
787
- return await due.call(ctx.options.lateResultsDecider, {
788
- host: await ctx.options.host?.(request),
789
- conversation: ref,
790
- results: results.map(lateResult),
791
- });
879
+ const { tell } = await decider.policy(items, { stage: 'pre_turn', step: 0, opening: 'wake' });
880
+ return tell.length > 0;
792
881
  }
793
882
  function isDetachedBlock(block) {
794
883
  return block.kind === 'tool' && block.tool.state?.phase === 'background';
@@ -826,22 +915,12 @@ async function lateBlock(ctx, request, block, operations, host) {
826
915
  return block;
827
916
  return { ...block, tool: { ...tool, state, endedAt: operation.settledAt } };
828
917
  }
829
- const message = labelText('tool.execution_uncertain', {}, labels);
830
- const failure = {
831
- code: operation?.status === 'uncertain' ? operation.reason : 'outcome_not_retained',
832
- kind: 'internal',
833
- message,
834
- };
835
918
  const { name, callId } = tool;
836
- const at = operation?.status === 'uncertain' ? operation.detectedAt : (tool.state?.at ?? Date.now());
837
- return {
838
- ...block,
839
- tool: {
840
- ...tool,
841
- state: { name, callId, at, phase: 'error', failure, readBack: message },
842
- endedAt: at,
843
- },
844
- };
919
+ const unresolved = detachedEnd({ operationId: id ?? '', callId, name, at: tool.state?.at ?? Date.now() }, operation, labels);
920
+ if (!unresolved)
921
+ return block;
922
+ const { operationId: _id, ...state } = unresolved.event.tool;
923
+ return { ...block, tool: { ...tool, state, endedAt: state.at } };
845
924
  }
846
925
  /** The conversation cut after one block; a reply that waits on gates is walked away from first. */
847
926
  async function rewind(ctx, request, session) {
@@ -989,8 +1068,20 @@ async function invoke(ctx, request, session) {
989
1068
  const call = { callId: body.gateId, operationId: body.operationId };
990
1069
  const opened = await openConversation(host, body.conversation, { kind: 'answer', call });
991
1070
  const settling = await settlingOf(ctx, request, session, body);
992
- const runner = chatRunner(ctx, request, session, body);
993
- return eventStream(ctx, request, () => answerReply({ host, opened, call, settling: settling(), runner }));
1071
+ const paused = opened.conversation.paused?.reply;
1072
+ return eventStream(ctx, request, () => heldLines(ctx, request, session, host, opened, { opening: 'message', takeOver: true }, (held) => answered(held, paused, () => answerReply({
1073
+ host,
1074
+ opened,
1075
+ call,
1076
+ settling: settling(),
1077
+ runner: chatRunner(ctx, request, session, body, held),
1078
+ }))));
1079
+ }
1080
+ /** The answer's reply, handed first what the paused reply read, so it tells them as it goes on. */
1081
+ async function* answered(held, paused, reply) {
1082
+ if (held && paused)
1083
+ await held.run.resume(paused);
1084
+ yield* reply();
994
1085
  }
995
1086
  /** The answered call's events: its saved outcome again, or the call run as answered. */
996
1087
  async function settlingOf(ctx, request, session, body) {
package/server/mod.d.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  export { theoremHostCallRequestSchema } from '../client/host-transport.ts';
9
9
  export type { LiveClientMessage, LiveOpenMessage } from '../client/live-messages.ts';
10
10
  export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from '../client/transport.ts';
11
- export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplyTurn, readerConversationHost, rewindConversation, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeableCalls, wakeReply, } from './conversation.ts';
12
- export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, unknownConversation, } from './conversation-store.ts';
11
+ export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplyTurn, readerConversationHost, rewindConversation, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeReply, } from './conversation.ts';
12
+ export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, type UncompactedBase, unknownConversation, } from './conversation-store.ts';
13
13
  export { createMemoryCredentialStore, type TheoremCredentialStore, type TheoremCredentials, } from './credential-store.ts';
14
14
  export { createTheoremDecisionHandler, type DecisionQuestionsBuilder, isQuestionsBuilder, type TheoremDecisionHandlerOptions, } from './decision-handler.ts';
15
15
  export { createTheoremEmbeddingHandler, embedBodySchema, embedRequest, type TheoremEmbeddingHandlerOptions, } from './embedding-handler.ts';
@@ -17,12 +17,12 @@ export { createTheoremHandler, createTheoremHostHandler, readBody, type TheoremH
17
17
  export { createTheoremMcpHandler, type TheoremMcpHandlerOptions } from './mcp-handler.ts';
18
18
  export { createMemoryNotifier, type TheoremNotifier } from './notifier.ts';
19
19
  export { createMemoryPageToolBroker, type PageToolBroker, type PageToolResult, pageToolResultSchema, sessionPageDispatch, } from './page-dispatch.ts';
20
- export { pageWakes } from './page-wakes.ts';
21
20
  export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from './request-check.ts';
22
21
  export { sessionStateStore } from './session-authority.ts';
23
22
  export { createTheoremSessionBoundary, type PreparedLiveOpen, type SessionBoundaryOptions, type TheoremSessionBoundary, } from './session-boundary.ts';
24
23
  export type { TheoremSessionCapacity } from './session-limits.ts';
25
24
  export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, type MemorySessionStoreOptions, type PendingToolGate, type SessionSnapshot, type SessionToolOperation, type SessionWriteResult, type TheoremSessionState, type TheoremSessionStore, theoremSessionStateSchema, } from './session-store.ts';
26
25
  export { createMemorySteerInbox, type SteerInbox, type SteerUnit, steerStage, steerUnitOf, stopOnRequest, } from './steer-inbox.ts';
26
+ export { tellEveryResult } from './tell-every-result.ts';
27
27
  export { sessionToolCoordinator } from './tool-operations.ts';
28
28
  export { kernelTurnInput, liveSessionOpen } from './turn-input.ts';
package/server/mod.js CHANGED
@@ -7,7 +7,7 @@
7
7
  */
8
8
  export { theoremHostCallRequestSchema } from "../client/host-transport.js";
9
9
  export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
10
- export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeableCalls, wakeReply, } from "./conversation.js";
10
+ export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
11
11
  export { createMemoryConversationStore, createSealedConversationStore, emptyConversation, storedConversationSchema, unknownConversation, } from "./conversation-store.js";
12
12
  export { createMemoryCredentialStore, } from "./credential-store.js";
13
13
  export { createTheoremDecisionHandler, isQuestionsBuilder, } from "./decision-handler.js";
@@ -16,11 +16,11 @@ export { createTheoremHandler, createTheoremHostHandler, readBody, theoremSessio
16
16
  export { createTheoremMcpHandler } from "./mcp-handler.js";
17
17
  export { createMemoryNotifier } from "./notifier.js";
18
18
  export { createMemoryPageToolBroker, pageToolResultSchema, sessionPageDispatch, } from "./page-dispatch.js";
19
- export { pageWakes } from "./page-wakes.js";
20
19
  export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from "./request-check.js";
21
20
  export { sessionStateStore } from "./session-authority.js";
22
21
  export { createTheoremSessionBoundary, } from "./session-boundary.js";
23
22
  export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, theoremSessionStateSchema, } from "./session-store.js";
24
23
  export { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
24
+ export { tellEveryResult } from "./tell-every-result.js";
25
25
  export { sessionToolCoordinator } from "./tool-operations.js";
26
26
  export { kernelTurnInput, liveSessionOpen } from "./turn-input.js";
@@ -1,6 +1,6 @@
1
1
  import { labelText, TheoremError, z } from '@theoremjs/agents';
2
2
  import { checkedCapacity, fitSession } from "./session-limits.js";
3
- import { emptySessionState, pruneGates, theoremSessionStateSchema, } from "./session-store.js";
3
+ import { emptySessionState, pruneGates, pruneInbox, theoremSessionStateSchema, } from "./session-store.js";
4
4
  /** Session state, with expired gates dropped as it loads so they can't be answered. */
5
5
  export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
6
6
  if (typeof store.compareAndSwap !== 'function') {
@@ -33,6 +33,7 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
33
33
  }
34
34
  state.operations = Object.fromEntries(Object.entries(state.operations).filter(([, operation]) => operation.status !== 'settled' ||
35
35
  now < (operation.retainUntil ?? operation.settledAt + operationRetentionMs)));
36
+ pruneInbox(state, now);
36
37
  return { revision: snapshot?.revision ?? null, state };
37
38
  };
38
39
  return {
@@ -54,6 +55,7 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
54
55
  }
55
56
  if (capacity)
56
57
  fitSession(state, capacity);
58
+ pruneInbox(state, now);
57
59
  const next = theoremSessionStateSchema.safeParse(state);
58
60
  if (!next.success) {
59
61
  throw new TheoremError('config', labelText('error.config'), {