@theoremjs/web 0.3.5-next.932.g295cc67 → 0.3.5-next.935.ga3dc485

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -271,7 +271,7 @@ const transport = withPageToolDispatch(
271
271
  | `pageStatesTurn` | Let the page say which prompt lines a turn gets, through `stated` on a turn or a live call. Set it only for a page you trust as yourself, such as a builder's own tool. Without it, a request with `stated` is refused. |
272
272
  | `conversationStore` | Where the conversation is kept. Required, except for a stateless profile, which must not have one. See [Keep the conversation](#keep-the-conversation). |
273
273
  | `sessionStore`, `steerInbox` | Where open gates are kept, and where steers and stops reach a running turn. Default: process memory, which reaches only turns this process runs. On more than one instance, give a shared `SteerInbox`. |
274
- | `authorizeWake` | Whether a wake turn runs: `TurnWiring.authorizeWake`, called with `{ host, conversation }`, where `host` is what your `host` option makes of the request. Return `false` to skip it, for example to cap wakes. The results stay unread for the next message. Unset, every due wake runs. Set it on your `TurnWiring`, and the studio applies it too. See [the background section](#share-session-authority). |
274
+ | `lateResultsDecider` | Who tells the model that a background call ended: `TurnWiring.lateResultsDecider`. Set it on your `TurnWiring`, and the studio uses it too. Unset, no page wakes the chat and no reply reads a late result. `pageWakes` lets the open page wake it. See [the background section](#share-session-authority). |
275
275
  | `notifier`, `notifyRetryMs` | Tell an open page that a background call ended, and how long the page waits to reopen a cut stream. Unset, the page reads the end on its next turn or reload. See [the background section](#share-session-authority). |
276
276
  | `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
277
277
  | `authorizationUrl` | Returns the sign-in URL for an OAuth gate. Without it, an OAuth gate has no URL. |
@@ -458,11 +458,21 @@ Browser dispatch uses a host-owned `PageToolExecution` service beside the execut
458
458
  `createTheoremHandler` supplies both services. Live relays put the session boundary's `pageExecution` and `toolExecution` on `SessionRequest`.
459
459
 
460
460
  A tool with a `background` setting runs inline until you pass the `background` option to `createTheoremHandler`, or return `background` from `prepare`, with an `execution` of your own that has `detach`, when the same turns run elsewhere in your app too. The option takes `{ request, sessionId }` and returns a `ToolBackgroundService`, which receives each detached call and its late events. The session keeps the call as `background` until it settles, and a late settlement does not invalidate a checkpoint. A conversation read shows the call as it stands: running, then its result, or an error for a marked call. An open page reads it on its next turn or reload, unless you set `notifier`. When the session has dropped a settled operation, the block reads an error with the code `outcome_not_retained`. On a durable store, a worker that dies leaves the operation as `background`, so your sweep marks it `uncertain` with `worker_lost` through `compareAndSwap`. Keep the service's values valid after the request ends. A live relay passes its service to `runSession`.
461
- To show an open page that a background call ended, with no turn or reload, pass `notifier: createMemoryNotifier()` to `createTheoremHandler`. While a call runs, the conversation read tells the page to open `POST <base>/notify`. The handler sends one `changed` line when the stream opens, and one when each background call in the session ends. The line carries no content, so the page calls the same conversation read as before. The page closes the stream when no call runs. The model reads the result without a new message. When results are due, the conversation read says `wake: true`, and the page posts `<base>/wake` once it is idle. The handler runs a turn with no message: it passes the session's stored outcome in `input.lateResults`, and the model answers. The turn is the wake. A result is due when its call settled, the transcript does not end on a person's message, no `late-results` block names the call, and no wake took the result up before. The handler marks each result taken (`wokenAt` on the session's operation) before the model runs, so one result wakes the conversation once. Two pages that post at once run one turn, and a wake that fails is not tried again. The next message still reads any result that no `late-results` block names, while the session keeps the operation. A message the person sends during a wake wins: the wake writes nothing, and its stream ends with no error. `authorizeWake` on your `TurnWiring` decides whether a wake runs, for example to cap wakes for each person. It reads the turn's `host`, so the same function works in the studio, where `host` is the person the builder acts as. A refused wake still marks its results taken. A call `authorizeToolReplay` withholds from the request stays unread and does not wake.
461
+ To show an open page that a background call ended, with no turn or reload, pass `notifier: createMemoryNotifier()` to `createTheoremHandler`. While a call runs, the conversation read tells the page to open `POST <base>/notify`. The handler sends one `changed` line when the stream opens, and one when each background call in the session ends. The line carries no content, so the page calls the same conversation read as before. The page closes the stream when no call runs. The model reads the result only as your decider says.
462
462
 
463
- The late-results feed is the one way a result reaches the model. If your `background` service told the model a result some other way, such as with your own `onStage`, remove that, or the model reads it twice.
463
+ Set `lateResultsDecider` on your `TurnWiring` and pass it to `createTheoremHandler`. Unset, nothing tells the model a background call ended: the conversation read never says `wake: true`, `<base>/wake` runs nothing, and the next message reads no late result. A result waits for the model when its call settled and no `late-results` block names the call, while the session keeps the operation. A call `authorizeToolReplay` withholds from the request does not wait.
464
464
 
465
- To wake a conversation with no page open, post `<base>/wake` through the handler from your server, with your own `Request` and the conversation's current reference. Your `conversationStore` must give that reference: the reference of `createSealedConversationStore` is the sealed conversation itself, so each write gives a new one, which only the page holds.
465
+ - `give({ reason, host, conversation, results })` picks, by `operationId`, the results a reply reads. It is asked once for each reply, before the model runs: `reason: 'message'` for the person's message, `'wake'` for a reply to no message. The model reads each result it gives once. One it leaves out waits for a later reply. `host` is what your `host` option makes of the request.
466
+ - `due({ host, conversation, results })` says whether a page open on the chat wakes it now. It is asked on every conversation read, so it must change nothing. Say yes only when `give` would give something. Unset, no page wakes the chat.
467
+ - `ended({ host, result, wake, notify })` hears each background call end. `wake(conversation)` runs a reply to no message from the server, as a page's wake does, so a chat answers with no page open. `notify()` tells the session's open pages to read again.
468
+
469
+ `pageWakes` is the decider for an app with no server of its own: the page open on the chat wakes it, and every reply reads every result that waits. Write your own to keep a count, such as a cap or quiet hours, or to reply from the server.
470
+
471
+ When `due` says yes, the conversation read says `wake: true`, and the page posts `<base>/wake` once it is idle. The handler runs a turn with no message, and the turn reads what `give` gives as it opens (`TurnRequest.lateResults`). A wake runs only when the transcript does not end on a person's message and no reply waits on a gate. The handler takes each result (`wokenAt` on the session's operation) before it asks `give`, so two pages that post at once run one turn. A result `give` leaves out loses that mark, and a later wake can take it. A wake that fails is not tried again; the next message's `give` is asked. A message the person sends during a wake wins: the wake writes nothing, and its stream ends with no error.
472
+
473
+ The decider is the one way a result reaches the model. If your `background` service told the model a result some other way, such as with your own `onStage`, remove that, or the model reads it twice.
474
+
475
+ To wake from the server, call `wake` with the conversation's current reference. Your `conversationStore` must keep that reference across writes: the reference of `createSealedConversationStore` is the sealed conversation itself, so each write gives a new one, which only the page holds. The reply runs with the headers of the request that started the call and no signal, because that request has ended.
466
476
 
467
477
  `createMemoryNotifier` reaches only pages connected to the process that ran the call. On more than one instance, give a shared `TheoremNotifier`. Your sweep calls `publish` with the session id after it marks a call `worker_lost`, because that write does not pass through the handler. Hosting platforms cut long responses. Set `notifyRetryMs` so that the page reopens the stream after that wait. Unset, the page does not reopen it, and reads the end on its next turn or reload.
468
478
 
@@ -110,6 +110,7 @@ const transcriptBlock = z.discriminatedUnion('kind', [
110
110
  kind: z.literal('late-results'),
111
111
  text: z.string(),
112
112
  operationIds: z.array(z.string()),
113
+ inReply: z.boolean(),
113
114
  }),
114
115
  z.object({ ...blockId, kind: z.literal('error'), message: z.string() }),
115
116
  z.object({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/web",
3
- "version": "0.3.5-next.932.g295cc67",
3
+ "version": "0.3.5-next.935.ga3dc485",
4
4
  "description": "Theorem on the web platform, with no UI framework: Web-standard server handlers that serve a profile, and the browser client that talks to them.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,6 +25,6 @@
25
25
  },
26
26
  "peerDependencies": {
27
27
  "zod": "^4.6.5",
28
- "@theoremjs/agents": "^0.3.5-next.932.g295cc67"
28
+ "@theoremjs/agents": "^0.3.5-next.935.ga3dc485"
29
29
  }
30
30
  }
@@ -153,8 +153,11 @@ export type TheoremHandlerOptions = {
153
153
  status: 'settled';
154
154
  }>;
155
155
  }) => boolean | Promise<boolean>;
156
- /** Whether a wake may run: `TurnWiring.authorizeWake`, given the `host` this request makes. */
157
- authorizeWake?: TurnWiring['authorizeWake'];
156
+ /**
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.
159
+ */
160
+ lateResultsDecider?: TurnWiring['lateResultsDecider'];
158
161
  /**
159
162
  * Tool credentials by session. Your OAuth callback route saves the token here
160
163
  * under the same session id; every turn reads from here. Default: in-process
package/server/handler.js CHANGED
@@ -419,35 +419,93 @@ function backgroundWiring(ctx, request, sessionId) {
419
419
  const service = ctx.options.background?.({ request, sessionId });
420
420
  return service ? { background: announced(ctx, request, sessionId, service) } : {};
421
421
  }
422
- /** `service`, telling the session's open page through the notifier when each of its calls ends. */
422
+ /**
423
+ * `service`, telling the session's open pages when each of its calls ends, and the decider's
424
+ * `ended`, with the wake and the notify it may use.
425
+ */
423
426
  function announced(ctx, request, sessionId, service) {
424
- const { notifier } = ctx.options;
425
- if (!notifier)
427
+ const { notifier, lateResultsDecider } = ctx.options;
428
+ const ended = lateResultsDecider?.ended?.bind(lateResultsDecider);
429
+ if (!notifier && !ended)
426
430
  return service;
431
+ const notify = async () => {
432
+ await notifier?.publish(sessionId);
433
+ };
427
434
  return {
428
435
  detached(call) {
429
436
  service.detached(call);
430
437
  void call.done
431
- .then(() => notifier.publish(sessionId))
438
+ .then(async () => {
439
+ await notify();
440
+ if (!ended)
441
+ return;
442
+ const { operations } = await ctx.sessions.read(sessionId);
443
+ const operation = Object.hasOwn(operations, call.operationId)
444
+ ? operations[call.operationId]
445
+ : undefined;
446
+ if (operation?.status !== 'settled')
447
+ return;
448
+ await ended({
449
+ host: await ctx.options.host?.(request),
450
+ result: { operationId: call.operationId, outcome: operation.outcome },
451
+ wake: (conversation) => serverWake(ctx, request, sessionId, conversation),
452
+ notify,
453
+ });
454
+ })
432
455
  .catch((err) => ctx.options.onError?.(err, { request }));
433
456
  },
434
457
  event: (event, call) => service.event(event, call),
435
458
  };
436
459
  }
460
+ /**
461
+ * 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.
463
+ */
464
+ async function serverWake(ctx, started, sessionId, conversation) {
465
+ const request = new Request(started.url, { headers: started.headers });
466
+ const lines = await wakeLines(ctx, request, { id: sessionId }, conversation, {});
467
+ if (!lines)
468
+ return;
469
+ for await (const line of lines) {
470
+ if (line.type === 'error') {
471
+ // labels-exempt: internal diagnostic for the decider's wake; no page reads it
472
+ throw new TheoremError(line.errorKind, line.errorInternal ?? line.error ?? 'the wake failed');
473
+ }
474
+ }
475
+ }
437
476
  /** A settled call's answer, streamed again. */
438
477
  async function* once(event, labels) {
439
478
  yield withPublicLabels(event, labels);
440
479
  }
441
480
  /**
442
- * `turn.input`, with the settled ends of the conversation's detached calls the model has not read.
443
- * A call the host does not let this request replay stays unread, as its block stays withheld.
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.
444
483
  */
445
- async function withLateResults(ctx, request, turn, operations) {
446
- const settled = await readableResults(ctx, request, turn.unread ?? [], operations);
447
- if (settled.length === 0)
448
- return turn.input;
449
- const outcomes = settled.map((operation) => operation.outcome);
450
- return { ...turn.input, lateResults: [...(turn.input.lateResults ?? []), ...outcomes] };
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) {
496
+ 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));
506
+ }
507
+ function lateResult(operation) {
508
+ return { operationId: operation.operationId, outcome: operation.outcome };
451
509
  }
452
510
  /** The calls among `unread` that ended, as this request may read them. */
453
511
  async function readableResults(ctx, request, unread, operations) {
@@ -469,7 +527,7 @@ async function wakeResults(ctx, request, conversation, operations) {
469
527
  return readable.filter((operation) => operation.wokenAt === undefined);
470
528
  }
471
529
  /** One model run of a chat's reply, its gates recorded in the session as they pause. */
472
- async function* chatTurn(ctx, request, session, turn, key, stop) {
530
+ async function* chatTurn(ctx, request, session, turn, key, stop, late) {
473
531
  const state = await ctx.sessions.read(session.id);
474
532
  const provider = await providerFor(ctx, request, turn.model);
475
533
  const host = await ctx.options.host?.(request);
@@ -484,7 +542,8 @@ async function* chatTurn(ctx, request, session, turn, key, stop) {
484
542
  execution: sessionToolCoordinator(ctx.sessions, session.id),
485
543
  ...backgroundWiring(ctx, request, session.id),
486
544
  pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
487
- input: await withLateResults(ctx, request, turn, state.operations),
545
+ input: turn.input,
546
+ ...(await openingLateResults(ctx, request, host, turn, state.operations, late)),
488
547
  ...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
489
548
  ...(turn.providerState ? { providerState: turn.providerState } : {}),
490
549
  sessionPermissions: state.permissions,
@@ -512,12 +571,15 @@ async function* chatTurn(ctx, request, session, turn, key, stop) {
512
571
  }
513
572
  }
514
573
  /** How this request runs the model for a reply: its generation, and its abort (the request's, or a stop). */
515
- function chatRunner(ctx, request, session, generation) {
574
+ function chatRunner(ctx, request, session, generation, given) {
516
575
  const key = generation.turnId ? inboxKey(session.id, generation.turnId) : undefined;
517
576
  const stop = new AbortController();
518
577
  const signal = AbortSignal.any([request.signal, stop.signal]);
519
578
  return {
520
- run: (turn) => chatTurn(ctx, request, session, turn, key, stop),
579
+ run: (turn) => chatTurn(ctx, request, session, turn, key, stop, {
580
+ ...(generation.conversation === undefined ? {} : { conversation: generation.conversation }),
581
+ ...(given ? { given } : {}),
582
+ }),
521
583
  async compact(history, tokens, model) {
522
584
  const provider = await providerFor(ctx, request, model);
523
585
  const compacted = await compactHistory({
@@ -586,47 +648,70 @@ async function conversation(ctx, request, session) {
586
648
  if (!host)
587
649
  throw statelessRefusal('read');
588
650
  const opened = await openConversation(host, body.conversation, { kind: 'read' });
589
- return jsonResponse(200, await currentView(ctx, request, session, host, opened.conversation));
651
+ return jsonResponse(200, await currentView(ctx, request, session, host, body.conversation, opened.conversation));
590
652
  }
591
653
  /**
592
654
  * A reply to no message, for results that ended since the model last ran. Each result is taken by
593
- * one wake, before the model runs, so two pages that wake at once run it once, and a wake that
594
- * fails or is refused is not tried again; the next message reads what it left.
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.
595
657
  */
596
658
  async function wake(ctx, request, session) {
597
659
  const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
660
+ 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) {
598
666
  const host = conversationHost(ctx, session);
599
667
  if (!host)
600
668
  throw statelessRefusal('wake');
601
- const opened = await openConversation(host, body.conversation, { kind: 'read' });
669
+ if (!ctx.options.lateResultsDecider)
670
+ return undefined;
671
+ const opened = await openConversation(host, conversation, { kind: 'read' });
602
672
  const { operations } = await ctx.sessions.read(session.id);
603
673
  const due = await wakeResults(ctx, request, opened.conversation, operations);
674
+ if (due.length === 0)
675
+ return undefined;
604
676
  const now = Date.now();
605
- const taken = due.length
606
- ? await ctx.sessions.mutate(session.id, (state) => due.filter(({ operationId }) => {
607
- const operation = state.operations[operationId];
608
- if (operation?.status !== 'settled' || operation.wokenAt !== undefined)
609
- return false;
610
- state.operations[operationId] = { ...operation, wokenAt: now };
611
- return true;
612
- }))
613
- : [];
614
- const { authorizeWake } = ctx.options;
615
- const allowed = taken.length > 0 &&
616
- (!authorizeWake ||
617
- (await authorizeWake({
618
- host: await ctx.options.host?.(request),
619
- conversation: body.conversation,
620
- })));
621
- if (!allowed)
622
- return eventStream(ctx, request, async function* () { });
623
- const runner = chatRunner(ctx, request, session, body);
624
- const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
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);
625
698
  const { notifier } = ctx.options;
626
- return eventStream(ctx, request, async function* () {
627
- yield* wakeReply({ host, opened, runner, input });
699
+ return (async function* () {
700
+ yield* wakeReply({ host, opened, runner, ...(input ? { input } : {}) });
628
701
  // why: The page that woke draws its reply; any other page open on the session reads it now.
629
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
+ }
630
715
  });
631
716
  }
632
717
  const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
@@ -673,23 +758,38 @@ async function notify(ctx, request, session, notifier) {
673
758
  * why: The transcript keeps a detached call as the turn left it. The session holds what became of
674
759
  * it, so a call that has ended does not read as running.
675
760
  */
676
- async function currentView(ctx, request, session, host, conversation) {
761
+ async function currentView(ctx, request, session, host, ref, conversation) {
677
762
  const view = conversationView(host, conversation);
678
763
  if (!view.transcript.some(isDetachedBlock))
679
764
  return view;
680
765
  const { operations } = await ctx.sessions.read(session.id);
681
766
  const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, request, block, operations, host) : block));
682
767
  const { notifier, notifyRetryMs } = ctx.options;
683
- const due = await wakeResults(ctx, request, conversation, operations);
684
768
  return {
685
769
  ...view,
686
770
  transcript,
687
771
  ...(notifier && transcript.some(isDetachedBlock)
688
772
  ? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
689
773
  : {}),
690
- ...(due.length > 0 ? { wake: true } : {}),
774
+ ...((await wakeDue(ctx, request, ref, conversation, operations))
775
+ ? { wake: true }
776
+ : {}),
691
777
  };
692
778
  }
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)
783
+ return false;
784
+ const results = await wakeResults(ctx, request, conversation, operations);
785
+ if (results.length === 0)
786
+ 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
+ });
792
+ }
693
793
  function isDetachedBlock(block) {
694
794
  return block.kind === 'tool' && block.tool.state?.phase === 'background';
695
795
  }
@@ -764,7 +864,7 @@ async function rewind(ctx, request, session) {
764
864
  throw new TheoremError('internal', labelText('error.internal'));
765
865
  const rewound = {
766
866
  conversation: next.ref,
767
- view: await currentView(ctx, request, session, host, next.conversation),
867
+ view: await currentView(ctx, request, session, host, next.ref, next.conversation),
768
868
  };
769
869
  return jsonResponse(200, rewound);
770
870
  }
package/server/mod.d.ts CHANGED
@@ -17,6 +17,7 @@ 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';
20
21
  export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from './request-check.ts';
21
22
  export { sessionStateStore } from './session-authority.ts';
22
23
  export { createTheoremSessionBoundary, type PreparedLiveOpen, type SessionBoundaryOptions, type TheoremSessionBoundary, } from './session-boundary.ts';
package/server/mod.js CHANGED
@@ -16,6 +16,7 @@ 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";
19
20
  export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from "./request-check.js";
20
21
  export { sessionStateStore } from "./session-authority.js";
21
22
  export { createTheoremSessionBoundary, } from "./session-boundary.js";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @module
3
+ * The ready-made decider for an app with no server of its own: the page open on the chat wakes it.
4
+ */
5
+ import type { LateResultsDecider } from '@theoremjs/agents';
6
+ /**
7
+ * The page open on a chat wakes it when a background call ends, and a reply reads every result
8
+ * that waits. It keeps no count: each result is read once, by the first reply that runs.
9
+ */
10
+ export declare const pageWakes: LateResultsDecider;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The page open on a chat wakes it when a background call ends, and a reply reads every result
3
+ * that waits. It keeps no count: each result is read once, by the first reply that runs.
4
+ */
5
+ export const pageWakes = {
6
+ give: ({ results }) => results.map((result) => result.operationId),
7
+ due: ({ results }) => results.length > 0,
8
+ };
@@ -44,7 +44,6 @@ const inputSchema = z.strictObject({
44
44
  .optional(),
45
45
  voice: z.array(blobSchema).optional(),
46
46
  history: z.array(turnHistoryMessageSchema).optional(),
47
- lateResults: z.array(toolOperationOutcomeSchema).optional(),
48
47
  repair: z
49
48
  .strictObject({ previousOutput: z.string(), rejection: z.string(), guidance: z.string() })
50
49
  .optional(),
@@ -2,7 +2,7 @@
2
2
  * The application's turn wiring (`TurnWiring.prepare`) laid over the turn the handler builds.
3
3
  * The handler keeps the fields it owns; the application's stage handler and credentials go
4
4
  * first, and the handler's own run when the application's have nothing. An application's own
5
- * tool record and background service run with the session's, never in place of it.
5
+ * tool record, background service, and late results run with the session's, never in place of it.
6
6
  *
7
7
  * @module
8
8
  */
@@ -10,8 +10,11 @@ import type { NormalizedTurnRequest, StageHandler, TurnRequest, TurnWiring } fro
10
10
  import type { ToolBackgroundService, ToolCredentialSource } from '@theoremjs/agents/kernel';
11
11
  /** The fields a handler sets on every turn, which `prepare` cannot replace. */
12
12
  export type HandlerOwned = Pick<TurnRequest, 'profile' | 'pageExecution' | 'providerState' | 'signal'>;
13
- /** The session's tool record and the handler's background service, which `prepare` can add to. */
14
- export type HandlerTools = Pick<TurnRequest, 'execution' | 'background'>;
13
+ /**
14
+ * The session's tool record, the handler's background service, and the session's late results,
15
+ * which `prepare` can add to.
16
+ */
17
+ export type HandlerTools = Pick<TurnRequest, 'execution' | 'background' | 'lateResults'>;
15
18
  /** What the handler adds to a turn of its own: the session's credentials and its steering. */
16
19
  export type HandlerTurnParts = {
17
20
  credentials: ToolCredentialSource;
@@ -2,7 +2,7 @@
2
2
  * The application's turn wiring (`TurnWiring.prepare`) laid over the turn the handler builds.
3
3
  * The handler keeps the fields it owns; the application's stage handler and credentials go
4
4
  * first, and the handler's own run when the application's have nothing. An application's own
5
- * tool record and background service run with the session's, never in place of it.
5
+ * tool record, background service, and late results run with the session's, never in place of it.
6
6
  *
7
7
  * @module
8
8
  */
@@ -23,11 +23,13 @@ export async function preparedTurn(prepare, turn, handler) {
23
23
  const onStage = stagesInOrder(app.onStage, handler.onStage);
24
24
  const execution = toolsInOrder(app.execution, turn.execution);
25
25
  const background = backgroundInOrder(app.background, turn.background, handler.announce);
26
+ const lateResults = lateResultsInOrder(app.lateResults, turn.lateResults);
26
27
  return {
27
28
  ...app,
28
29
  ...owned,
29
30
  ...(execution ? { execution } : {}),
30
31
  ...(background ? { background } : {}),
32
+ ...(lateResults ? { lateResults } : {}),
31
33
  credentials: credentialsInOrder(app.credentials, handler.credentials),
32
34
  ...(onStage ? { onStage } : {}),
33
35
  };
@@ -50,6 +52,15 @@ function backgroundInOrder(app, own, announce) {
50
52
  return own;
51
53
  return announce ? announce(app) : app;
52
54
  }
55
+ /**
56
+ * The application's late results, then the session's, at each moment the turn asks. The session's
57
+ * are the results it marked given, so an application's `prepare` cannot drop them.
58
+ */
59
+ function lateResultsInOrder(app, session) {
60
+ if (!app || !session || app === session)
61
+ return session ?? app;
62
+ return async (moment) => [...(await app(moment)), ...(await session(moment))];
63
+ }
53
64
  /**
54
65
  * The application's stage handler, then the handler's own when the application's asks for
55
66
  * nothing. What the second one would have done waits for the next stage that allows it.