@theoremjs/web 0.3.5-next.926.g05c82e3 → 0.3.5-next.927.g1f89ea0

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,6 +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` | Called with `{ request, conversation }` before a wake turn runs. Return `false` to skip it, for example to cap wakes. The results stay unread for the next message. Unset, every due wake runs. See [the background section](#share-session-authority). |
274
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). |
275
276
  | `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
276
277
  | `authorizationUrl` | Returns the sign-in URL for an OAuth gate. Without it, an OAuth gate has no URL. |
@@ -457,7 +458,11 @@ Browser dispatch uses a host-owned `PageToolExecution` service beside the execut
457
458
  `createTheoremHandler` supplies both services. Live relays put the session boundary's `pageExecution` and `toolExecution` on `SessionRequest`.
458
459
 
459
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`.
460
- 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 on the conversation's next turn: the handler passes the session's stored outcome in `input.lateResults`, once for each call. A call is read when a `late-results` block in the transcript names it. A call `authorizeToolReplay` withholds from the request stays unread.
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, so nothing is lost. A message the person sends during a wake wins: the wake writes nothing, and its stream ends with no error. `authorizeWake` decides whether a wake runs, for example to cap wakes for each person. A refused wake still marks its results taken. A call `authorizeToolReplay` withholds from the request stays unread and does not wake.
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.
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: `createSealedConversationStore` gives a new one on each write, which only the page holds.
461
466
 
462
467
  `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.
463
468
 
package/client/chat.js CHANGED
@@ -8,7 +8,7 @@ import { followGenerationDefaults } from "./generation-selection.js";
8
8
  import { warnPageToolMismatch } from "./live/live-page-tool.js";
9
9
  import { withPageToolDispatch } from "./page-dispatch.js";
10
10
  import { sessionAfter, stampWorked, stoppedReply } from "./run-commit.js";
11
- import { keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, } from "./run-session.js";
11
+ import { keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
12
12
  import { isUnknownConversation, } from "./transport.js";
13
13
  import { foldAssistantTurn, issuedOperationId } from "./turn-client.js";
14
14
  const DELIVERY_ORDER = ['sending', 'sent', 'delivered', 'read'];
@@ -123,6 +123,8 @@ class Chat {
123
123
  /** What the last view said about the host's push; unset, nothing is listened for. */
124
124
  #notify;
125
125
  #listening = null;
126
+ /** The last view said results wait that no reply has read: the chat wakes once it is idle. */
127
+ #wakeDue = false;
126
128
  #reading = null;
127
129
  #readAgain = false;
128
130
  constructor(options) {
@@ -495,6 +497,28 @@ class Chat {
495
497
  this.#resume(iface);
496
498
  this.#answerPageGate();
497
499
  this.#drain();
500
+ this.#wake();
501
+ }
502
+ /**
503
+ * Wakes the conversation when the host said results wait. A message the queue sends goes first:
504
+ * its reply reads them. The host takes each result once, so a wake is never run twice for it.
505
+ */
506
+ #wake() {
507
+ const ref = this.#conversation;
508
+ if (!this.#wakeDue || ref === undefined || this.#busy || this.#draining)
509
+ return;
510
+ if (this.#state.phase !== 'idle' || !this.#options.transport.wake)
511
+ return;
512
+ this.#wakeDue = false;
513
+ void this.#runTurn(({ iface, view, transport, scope, signal }) => streamInterfaceWake({
514
+ iface,
515
+ transport,
516
+ session: this.#state.session,
517
+ scope: { ...scope, conversation: ref },
518
+ view,
519
+ signal,
520
+ began: () => this.#set({ failure: null, streaming: true }),
521
+ }), { turn: true, wake: true });
498
522
  }
499
523
  #clearedComposer() {
500
524
  return { draftText: '', pendingFiles: [], pendingVoice: [] };
@@ -537,6 +561,7 @@ class Chat {
537
561
  session: this.#sessionAfter(session, view.paused?.events ?? events),
538
562
  chatStarted: view.transcript.length > 0 || view.paused !== undefined,
539
563
  });
564
+ this.#wakeDue = view.wake === true;
540
565
  this.#setPush(view.notify);
541
566
  }
542
567
  /**
@@ -780,6 +805,25 @@ class Chat {
780
805
  ...base,
781
806
  turn: (request, onLine, signal) => base.turn(this.#withValues(request), tap(onLine), signal),
782
807
  invoke: (request, onLine, signal) => base.invoke(request, tap(onLine), signal),
808
+ ...(base.wake
809
+ ? {
810
+ wake: (request, onLine, signal) => base.wake?.(this.#wakeValues(request), tap(onLine), signal) ?? Promise.resolve(),
811
+ }
812
+ : {}),
813
+ };
814
+ }
815
+ /** A wake carries the option picks and context a message would. */
816
+ #wakeValues(request) {
817
+ const { iface, options: fixed, context } = this.#options;
818
+ const options = picksOf(iface, fixed, this.#picked).values;
819
+ if (options === undefined && context === undefined)
820
+ return request;
821
+ return {
822
+ ...request,
823
+ input: {
824
+ ...(options === undefined ? {} : { options }),
825
+ ...(context === undefined ? {} : { context }),
826
+ },
783
827
  };
784
828
  }
785
829
  #withValues(request) {
@@ -846,7 +890,9 @@ class Chat {
846
890
  this.#stopped = false;
847
891
  this.#drainArmed = false;
848
892
  // why: A message streams once it posts, so the previous reply never shows as streaming before it.
849
- this.#set({ failure: null, ...(message ? {} : { streaming: true }) });
893
+ // A wake shows only once the host's reply begins; one with nothing to wake for shows nothing.
894
+ if (!options.wake)
895
+ this.#set({ failure: null, ...(message ? {} : { streaming: true }) });
850
896
  const start = { blocks: this.#state.blocks, streamBlocks: this.#state.streamBlocks };
851
897
  // why: A run that answers a gate continues its reply; any other starts one.
852
898
  if (!this.#state.session.gatedTool)
package/client/index.d.ts CHANGED
@@ -33,5 +33,5 @@ export { hasLead, layoutResult, type ResultChart, type ResultFigure, type Result
33
33
  export type { AnsweringGate, ToolDecisionAction, ToolGateResolution, } from './tool-resume.ts';
34
34
  export { continueGatedToolInvocation, type PersonGateResolution } from './tool-resume.ts';
35
35
  export { createTraceFeed, recordedFeed, type TraceFeed } from './trace-feed.ts';
36
- export { CHAT_LINES, type ChatLine, type ChatLineSink, type ClientTurnEvent, type ConversationLine, type ConversationView, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, type HostErrorBody, type HttpOptions, type HttpTransportOptions, hostError, isTheoremStreamError, type MalformedEvent, type NotifyLine, postJson, postNdjson, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremStartRequest, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
36
+ export { CHAT_LINES, type ChatLine, type ChatLineSink, type ClientTurnEvent, type ConversationLine, type ConversationView, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, type HostErrorBody, type HttpOptions, type HttpTransportOptions, hostError, isTheoremStreamError, type MalformedEvent, type NotifyLine, postJson, postNdjson, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremStartRequest, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TheoremWakeRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
37
37
  export { buildInvokeRequest, buildTurnRequest, foldAssistantTurn, issuedOperationId, type RunScope, type WalkAway, } from './turn-client.ts';
@@ -55,6 +55,11 @@ export function withPageToolDispatch(transport, tools) {
55
55
  describe: transport.describe.bind(transport),
56
56
  invoke: (request, onLine, signal) => transport.invoke(request, chatSink(onLine, signal), signal),
57
57
  turn: (request, onLine, signal) => transport.turn(request, chatSink(onLine, signal), signal),
58
+ ...(transport.wake
59
+ ? {
60
+ wake: (request, onLine, signal) => transport.wake?.(request, chatSink(onLine, signal), signal) ?? Promise.resolve(),
61
+ }
62
+ : {}),
58
63
  steer: transport.steer.bind(transport),
59
64
  stop: transport.stop.bind(transport),
60
65
  conversation: transport.conversation.bind(transport),
@@ -77,3 +77,18 @@ export declare function resumeInterfaceTool(args: {
77
77
  resolution: ToolGateResolution;
78
78
  view: StreamView;
79
79
  }): Promise<RunOutcome>;
80
+ /**
81
+ * Wake the conversation: stream the reply the host runs for results no reply has read. `began`
82
+ * fires on its first line; a host with nothing to wake for sends none, and the run leaves nothing.
83
+ */
84
+ export declare function streamInterfaceWake(args: {
85
+ iface: ComposerProfileInterface;
86
+ transport: TheoremTransport;
87
+ session: InterfaceTurnSession;
88
+ scope: RunScope & {
89
+ conversation: string;
90
+ };
91
+ view: StreamView;
92
+ signal?: AbortSignal;
93
+ began(): void;
94
+ }): Promise<RunOutcome>;
@@ -5,7 +5,7 @@ import { turnFailure } from "./failure.js";
5
5
  import { streamFoldedTurn } from "./run-commit.js";
6
6
  import { continueGatedToolInvocation } from "./tool-resume.js";
7
7
  import { isUnknownConversation, } from "./transport.js";
8
- import { buildInvokeRequest, buildTurnRequest, foldAssistantTurn, issuedOperationId, prepareComposerTurn, projectUserTurn, } from "./turn-client.js";
8
+ import { buildInvokeRequest, buildTurnRequest, buildWakeRequest, foldAssistantTurn, issuedOperationId, prepareComposerTurn, projectUserTurn, } from "./turn-client.js";
9
9
  /**
10
10
  * Whether the host keeps this chat's conversation. A stateless profile keeps
11
11
  * none: the page holds its transcript, and nothing goes on from a ref.
@@ -205,3 +205,33 @@ export async function resumeInterfaceTool(args) {
205
205
  }
206
206
  return { session, events, posted: true };
207
207
  }
208
+ /**
209
+ * Wake the conversation: stream the reply the host runs for results no reply has read. `began`
210
+ * fires on its first line; a host with nothing to wake for sends none, and the run leaves nothing.
211
+ */
212
+ export async function streamInterfaceWake(args) {
213
+ const { iface, transport, session, scope, signal } = args;
214
+ const events = [];
215
+ const wake = transport.wake?.bind(transport);
216
+ if (!wake)
217
+ return { session, events, posted: false };
218
+ let begun = false;
219
+ try {
220
+ await streamFoldedTurn({
221
+ iface,
222
+ view: args.view,
223
+ events,
224
+ stream: (onLine) => wake(buildWakeRequest(iface, session, scope.conversation, scope), (line) => {
225
+ if (!begun) {
226
+ begun = true;
227
+ args.began();
228
+ }
229
+ onLine(line);
230
+ }, signal),
231
+ });
232
+ }
233
+ catch (err) {
234
+ return { session, events, posted: false, failure: turnFailure(err, iface.labels, signal) };
235
+ }
236
+ return { session, events, posted: false };
237
+ }
@@ -160,6 +160,8 @@ export type ConversationView = {
160
160
  notify?: {
161
161
  retryMs?: number;
162
162
  };
163
+ /** Results wait that no reply has read: the page wakes the conversation (`transport.wake`). */
164
+ wake?: true;
163
165
  };
164
166
  /** Read a conversation: a `/conversation` body. */
165
167
  export type TheoremConversationRequest = {
@@ -167,6 +169,22 @@ export type TheoremConversationRequest = {
167
169
  };
168
170
  /** A `/conversation` body as `createTheoremHandler` reads it. */
169
171
  export declare const theoremConversationRequestSchema: z.ZodType<TheoremConversationRequest>;
172
+ /**
173
+ * Wake the conversation: the model takes up the results of its background calls that ended and it
174
+ * has not read, in a reply to no message. A `/wake` body. The host does nothing when no result
175
+ * waits, a reply waits on gates or answers a message, or another wake took them already.
176
+ */
177
+ export type TheoremWakeRequest = {
178
+ conversation: string;
179
+ /** What the page sends with every message: its option picks and context. */
180
+ input?: Pick<TheoremTurnInput, 'options' | 'context'>;
181
+ model?: string;
182
+ effort?: string;
183
+ /** Client-generated id so the page can stop this reply, as it stops a message's. */
184
+ turnId?: string;
185
+ };
186
+ /** A `/wake` body as `createTheoremHandler` reads it. */
187
+ export declare const theoremWakeRequestSchema: z.ZodType<TheoremWakeRequest>;
170
188
  /** Listen for the ends of this session's background calls: a `/notify` body. */
171
189
  export type TheoremNotifyRequest = Record<string, never>;
172
190
  /** A `/notify` body as `createTheoremHandler` reads it. */
@@ -214,6 +232,8 @@ export interface TheoremTransport {
214
232
  conversation(request: TheoremConversationRequest, signal?: AbortSignal): Promise<ConversationView>;
215
233
  /** Calls `changed` for each line of the host's push, and settles when the push ends. */
216
234
  notify?(changed: () => void, signal: AbortSignal): Promise<void>;
235
+ /** Streams the reply a wake runs; no line at all when the host had nothing to wake for. */
236
+ wake?(request: TheoremWakeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
217
237
  /** The conversation cut after a transcript block, under the ref the host issued for it. */
218
238
  rewind(request: TheoremRewindRequest, signal?: AbortSignal): Promise<TheoremRewound>;
219
239
  pageResult?(result: PageDispatchResult, signal?: AbortSignal): Promise<void>;
@@ -112,12 +112,23 @@ const conversationView = z.object({
112
112
  .object({ events: z.array(turnEventSchema), blocks: z.array(transcriptBlockSchema) })
113
113
  .optional(),
114
114
  notify: z.object({ retryMs: z.number().optional() }).optional(),
115
+ wake: z.literal(true).optional(),
115
116
  });
116
117
  true;
117
118
  const theoremConversationRequest = z.object({ conversation: z.string().min(1) });
118
119
  true;
119
120
  /** A `/conversation` body as `createTheoremHandler` reads it. */
120
121
  export const theoremConversationRequestSchema = theoremConversationRequest;
122
+ const theoremWakeRequest = z.object({
123
+ conversation: z.string().min(1),
124
+ input: theoremTurnInput.pick({ options: true, context: true }).optional(),
125
+ model: z.string().optional(),
126
+ effort: z.string().optional(),
127
+ turnId: clientId.optional(),
128
+ });
129
+ true;
130
+ /** A `/wake` body as `createTheoremHandler` reads it. */
131
+ export const theoremWakeRequestSchema = theoremWakeRequest;
121
132
  const theoremNotifyRequest = z.strictObject({});
122
133
  /** A `/notify` body as `createTheoremHandler` reads it. */
123
134
  export const theoremNotifyRequestSchema = theoremNotifyRequest;
@@ -353,6 +364,7 @@ export function createHttpTransport(options = {}) {
353
364
  turn: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/turn`, body, CHAT_LINES, onEvent, { ...options, signal }),
354
365
  invoke: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/invoke`, body, CHAT_LINES, onEvent, { ...options, signal }),
355
366
  conversation: (body, signal) => fetchConversation(`${base}/conversation`, body, { ...options, signal }),
367
+ wake: (body, onLine, signal) => postNdjson(`${base}/wake`, body, CHAT_LINES, onLine, { ...options, signal }),
356
368
  notify: (changed, signal) => postNdjson(`${base}/notify`, {}, NOTIFY_LINES, (line) => {
357
369
  if (line.type === 'changed')
358
370
  changed();
@@ -1,7 +1,7 @@
1
1
  import { type TurnEvent } from '@theoremjs/agents';
2
2
  import { type AttachmentValidationIssue, type ComposerProfileInterface, type GatedToolContext, type InterfaceTurnSession, type TranscriptBlock, type UserTurnDraft } from '@theoremjs/agents/interface';
3
3
  import type { PagePart } from './tool-resume.ts';
4
- import type { TheoremInvokeRequest, TheoremReplay, TheoremTurnInput, TheoremTurnRequest } from './transport.ts';
4
+ import type { TheoremInvokeRequest, TheoremReplay, TheoremTurnInput, TheoremTurnRequest, TheoremWakeRequest } from './transport.ts';
5
5
  export declare function issuedOperationId(call: {
6
6
  operationId?: string;
7
7
  }): string;
@@ -25,6 +25,8 @@ export type RunScope = {
25
25
  export declare function buildTurnRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, input: TheoremTurnInput, options?: RunScope & {
26
26
  walkAway?: WalkAway;
27
27
  }): TheoremTurnRequest;
28
+ /** A wake of `conversation` with the model and effort picked now, as a message would carry them. */
29
+ export declare function buildWakeRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, conversation: string, scope?: RunScope): TheoremWakeRequest;
28
30
  export declare function buildInvokeRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, args: HeldCall & {
29
31
  gateId: string;
30
32
  operationId: string;
@@ -60,6 +60,14 @@ export function buildTurnRequest(iface, session, input, options = {}) {
60
60
  replay: { sessionPermissions: session.sessionPermissions },
61
61
  };
62
62
  }
63
+ /** A wake of `conversation` with the model and effort picked now, as a message would carry them. */
64
+ export function buildWakeRequest(iface, session, conversation, scope = {}) {
65
+ return {
66
+ conversation,
67
+ ...(scope.turnId ? { turnId: scope.turnId } : {}),
68
+ ...generationFields(iface, session),
69
+ };
70
+ }
63
71
  export function buildInvokeRequest(iface, session, args, scope = {}) {
64
72
  return {
65
73
  ...scopeFields(scope),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/web",
3
- "version": "0.3.5-next.926.g05c82e3",
3
+ "version": "0.3.5-next.927.g1f89ea0",
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.926.g05c82e3"
28
+ "@theoremjs/agents": "^0.3.5-next.927.g1f89ea0"
29
29
  }
30
30
  }
@@ -130,6 +130,11 @@ export type DetachedCall = {
130
130
  callId: string;
131
131
  operationId: string;
132
132
  };
133
+ /**
134
+ * The calls a wake would read: none while a reply waits on gates or answers a message just posted.
135
+ * invariant: A wake never runs beside a reply, so it never takes a person's message from one.
136
+ */
137
+ export declare function wakeableCalls(conversation: StoredConversation): DetachedCall[];
133
138
  /** What a reply's model run takes from the host. */
134
139
  export type ReplyRunner = {
135
140
  /** The reply's events for one run (`runTurn` with the host's own options). */
@@ -174,6 +179,18 @@ export declare function messageReply(args: {
174
179
  walkAway?: readonly IssuedWalkAway[];
175
180
  runner: ReplyRunner;
176
181
  }): AsyncGenerator<ReplyLine>;
182
+ /**
183
+ * The model takes up the results of calls that ended while nothing ran: a reply to no message.
184
+ * It writes nothing until it ends, so a message posted meanwhile keeps the conversation, and this
185
+ * reply ends with no write: that message's reply read the same results.
186
+ */
187
+ export declare function wakeReply(args: {
188
+ host: ConversationHost;
189
+ opened: OpenedConversation;
190
+ runner: ReplyRunner;
191
+ /** What the page sends with every message: its option picks and context. */
192
+ input?: Pick<TurnInput, 'options' | 'context'>;
193
+ }): AsyncGenerator<ReplyLine>;
177
194
  /**
178
195
  * The person answers one call the reply waits on. `settling` streams the
179
196
  * call's events; once no call waits, the reply goes on in the same stream.
@@ -131,13 +131,14 @@ export function conversationView(host, conversation) {
131
131
  : {}),
132
132
  };
133
133
  }
134
+ const CONFLICT = { code: 'conversation_conflict' };
134
135
  /** Writes `next` over what the request read; a write another request beat is refused. */
135
136
  async function save(host, opened, next) {
136
137
  const result = await host.store.write(host.sessionId, opened.ref, opened.revision, next);
137
138
  if (!result.written) {
138
139
  // labels-exempt: internal diagnostic; the user reads error.unavailable
139
140
  throw new TheoremError('unavailable', 'the conversation changed while this reply ran', {
140
- cause: { code: 'conversation_conflict' },
141
+ cause: CONFLICT,
141
142
  });
142
143
  }
143
144
  return { ref: result.ref, revision: result.revision, conversation: next };
@@ -161,6 +162,18 @@ function unreadDetachedCalls(transcript) {
161
162
  ? [{ callId: block.tool.callId, operationId: block.tool.operationId }]
162
163
  : []);
163
164
  }
165
+ /**
166
+ * The calls a wake would read: none while a reply waits on gates or answers a message just posted.
167
+ * invariant: A wake never runs beside a reply, so it never takes a person's message from one.
168
+ */
169
+ export function wakeableCalls(conversation) {
170
+ if (conversation.paused)
171
+ return [];
172
+ const last = conversation.transcript.at(-1);
173
+ if (!last || last.kind.startsWith('user-'))
174
+ return [];
175
+ return unreadDetachedCalls(conversation.transcript);
176
+ }
164
177
  /** The model's history once the reply's events enter it. */
165
178
  function replyHistory(reply) {
166
179
  return appendAssistantEventsToHistory(reply.base, reply.events.slice(reply.baseEvents));
@@ -457,14 +470,34 @@ export async function* messageReply(args) {
457
470
  baseEvents: 0,
458
471
  workedMs: 0,
459
472
  };
460
- yield* runReply(host, opened, reply, runner, {
461
- ...message.input,
473
+ yield* runReply(host, opened, reply, runner, { ...message.input, ...historyInput(conversation) }, withMessage);
474
+ }
475
+ /** The conversation's history as a run reads it, with its meters. */
476
+ function historyInput(conversation) {
477
+ return {
462
478
  history: conversation.history,
463
479
  ...(conversation.inputTokens === undefined ? {} : { inputTokens: conversation.inputTokens }),
464
480
  ...(conversation.historyTokens === undefined
465
481
  ? {}
466
482
  : { historyTokens: conversation.historyTokens }),
467
- }, withMessage);
483
+ };
484
+ }
485
+ /**
486
+ * The model takes up the results of calls that ended while nothing ran: a reply to no message.
487
+ * It writes nothing until it ends, so a message posted meanwhile keeps the conversation, and this
488
+ * reply ends with no write: that message's reply read the same results.
489
+ */
490
+ export async function* wakeReply(args) {
491
+ const { host, opened, runner } = args;
492
+ const { conversation } = opened;
493
+ const reply = { base: conversation.history, events: [], baseEvents: 0, workedMs: 0 };
494
+ try {
495
+ yield* runReply(host, opened, reply, runner, { ...args.input, ...historyInput(conversation) }, (history) => history);
496
+ }
497
+ catch (err) {
498
+ if (!(err instanceof TheoremError && err.cause === CONFLICT))
499
+ throw err;
500
+ }
468
501
  }
469
502
  /**
470
503
  * The person answers one call the reply waits on. `settling` streams the
@@ -16,6 +16,8 @@ import { type PageToolBroker } from './page-dispatch.ts';
16
16
  * - `POST <base>/notify` → NDJSON that stays open: one line now, and one each time a background
17
17
  * call in this session ends. Set `notifier` to serve it
18
18
  * - `POST <base>/rewind` → `{ conversation, view }` the conversation cut after one block, and its new ref
19
+ * - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
20
+ * background calls that ended since it last ran. Empty when none waits
19
21
  *
20
22
  * `createTheoremHostHandler` serves a host profile the same way, with no model:
21
23
  *
@@ -151,6 +153,15 @@ export type TheoremHandlerOptions = {
151
153
  status: 'settled';
152
154
  }>;
153
155
  }) => boolean | Promise<boolean>;
156
+ /**
157
+ * Whether this wake may run its reply: your limit on replies no person asked for. A wake you
158
+ * refuse is not tried again for the same results; the next message reads them. Unset, every wake
159
+ * runs.
160
+ */
161
+ authorizeWake?: (context: {
162
+ request: Request;
163
+ conversation: string;
164
+ }) => boolean | Promise<boolean>;
154
165
  /**
155
166
  * Tool credentials by session. Your OAuth callback route saves the token here
156
167
  * under the same session id; every turn reads from here. Default: in-process
package/server/handler.js CHANGED
@@ -17,6 +17,8 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
17
17
  * - `POST <base>/notify` → NDJSON that stays open: one line now, and one each time a background
18
18
  * call in this session ends. Set `notifier` to serve it
19
19
  * - `POST <base>/rewind` → `{ conversation, view }` the conversation cut after one block, and its new ref
20
+ * - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
21
+ * background calls that ended since it last ran. Empty when none waits
20
22
  *
21
23
  * `createTheoremHostHandler` serves a host profile the same way, with no model:
22
24
  *
@@ -42,12 +44,13 @@ import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremj
42
44
  import { clientProfileInterface, gatedToolsFromEvents, interfaceFromProfile, promotedToolIdsFromEvents, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
43
45
  import { answerGatedCall, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
44
46
  import { hostInterface, theoremHostCallRequestSchema, } from "../client/host-transport.js";
45
- import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, } from "../client/transport.js";
46
- import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, } from "./conversation.js";
47
+ 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";
47
49
  import { unknownConversation, } from "./conversation-store.js";
48
50
  import { createMemoryCredentialStore, } from "./credential-store.js";
49
51
  import { sessionStateStore, } from "./session-authority.js";
50
52
  import { theoremSession } from "./session-identity.js";
53
+ import { kernelTurnInput } from "./turn-input.js";
51
54
  export { theoremSession, theoremSessionId } from "./session-identity.js";
52
55
  import { jsonResponse } from "./json-response.js";
53
56
  import { boundedRequestJson, requestByteLimit } from "./request-body.js";
@@ -98,6 +101,7 @@ function routeOf(request) {
98
101
  last === 'conversation' ||
99
102
  last === 'notify' ||
100
103
  last === 'rewind' ||
104
+ last === 'wake' ||
101
105
  last === 'call' ||
102
106
  last === 'page-result'
103
107
  ? last
@@ -439,19 +443,30 @@ async function* once(event, labels) {
439
443
  * A call the host does not let this request replay stays unread, as its block stays withheld.
440
444
  */
441
445
  async function withLateResults(ctx, request, turn, operations) {
442
- const outcomes = [];
443
- for (const { operationId } of turn.unread ?? []) {
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] };
451
+ }
452
+ /** The calls among `unread` that ended, as this request may read them. */
453
+ async function readableResults(ctx, request, unread, operations) {
454
+ const readable = [];
455
+ for (const { operationId } of unread) {
444
456
  const operation = Object.hasOwn(operations, operationId) ? operations[operationId] : undefined;
445
457
  if (operation?.status !== 'settled')
446
458
  continue;
447
459
  const { authorizeToolReplay } = ctx.options;
448
460
  if (authorizeToolReplay && !(await authorizeToolReplay({ request, operation })))
449
461
  continue;
450
- outcomes.push(operation.outcome);
462
+ readable.push(operation);
451
463
  }
452
- if (outcomes.length === 0)
453
- return turn.input;
454
- return { ...turn.input, lateResults: [...(turn.input.lateResults ?? []), ...outcomes] };
464
+ return readable;
465
+ }
466
+ /** The results a wake would take up: readable, and no wake has taken them. */
467
+ async function wakeResults(ctx, request, conversation, operations) {
468
+ const readable = await readableResults(ctx, request, wakeableCalls(conversation), operations);
469
+ return readable.filter((operation) => operation.wokenAt === undefined);
455
470
  }
456
471
  /** One model run of a chat's reply, its gates recorded in the session as they pause. */
457
472
  async function* chatTurn(ctx, request, session, turn, key, stop) {
@@ -573,6 +588,43 @@ async function conversation(ctx, request, session) {
573
588
  const opened = await openConversation(host, body.conversation, { kind: 'read' });
574
589
  return jsonResponse(200, await currentView(ctx, request, session, host, opened.conversation));
575
590
  }
591
+ /**
592
+ * 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.
595
+ */
596
+ async function wake(ctx, request, session) {
597
+ const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
598
+ const host = conversationHost(ctx, session);
599
+ if (!host)
600
+ throw statelessRefusal('wake');
601
+ const opened = await openConversation(host, body.conversation, { kind: 'read' });
602
+ const { operations } = await ctx.sessions.read(session.id);
603
+ const due = await wakeResults(ctx, request, opened.conversation, operations);
604
+ 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 || (await authorizeWake({ request, conversation: body.conversation })));
617
+ if (!allowed)
618
+ return eventStream(ctx, request, async function* () { });
619
+ const runner = chatRunner(ctx, request, session, body);
620
+ const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
621
+ const { notifier } = ctx.options;
622
+ return eventStream(ctx, request, async function* () {
623
+ yield* wakeReply({ host, opened, runner, input });
624
+ // why: The page that woke draws its reply; any other page open on the session reads it now.
625
+ notifier?.publish(session.id);
626
+ });
627
+ }
576
628
  const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
577
629
  /**
578
630
  * One line now, then one for each background call that ends. The stream names no conversation,
@@ -624,12 +676,14 @@ async function currentView(ctx, request, session, host, conversation) {
624
676
  const { operations } = await ctx.sessions.read(session.id);
625
677
  const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, request, block, operations, host) : block));
626
678
  const { notifier, notifyRetryMs } = ctx.options;
679
+ const due = await wakeResults(ctx, request, conversation, operations);
627
680
  return {
628
681
  ...view,
629
682
  transcript,
630
683
  ...(notifier && transcript.some(isDetachedBlock)
631
684
  ? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
632
685
  : {}),
686
+ ...(due.length > 0 ? { wake: true } : {}),
633
687
  };
634
688
  }
635
689
  function isDetachedBlock(block) {
@@ -908,6 +962,8 @@ async function route(ctx, request, session) {
908
962
  }
909
963
  if (target === 'rewind')
910
964
  return rewind(ctx, request, session);
965
+ if (target === 'wake')
966
+ return wake(ctx, request, session);
911
967
  if (target === 'stop')
912
968
  return stop(ctx, request, session);
913
969
  return steer(ctx, request, session);
package/server/mod.d.ts CHANGED
@@ -7,8 +7,8 @@
7
7
  */
8
8
  export { theoremHostCallRequestSchema } from '../client/host-transport.ts';
9
9
  export type { LiveClientMessage, LiveOpenMessage } from '../client/live-messages.ts';
10
- export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, } 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, } from './conversation.ts';
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
12
  export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, 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';
package/server/mod.js CHANGED
@@ -6,8 +6,8 @@
6
6
  * @module
7
7
  */
8
8
  export { theoremHostCallRequestSchema } from "../client/host-transport.js";
9
- export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, } from "../client/transport.js";
10
- export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, } from "./conversation.js";
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";
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";
@@ -61,6 +61,8 @@ export type SessionToolOperation = {
61
61
  reply?: ToolOperationReply;
62
62
  settledAt: number;
63
63
  retainUntil?: number;
64
+ /** When a wake took this result up. invariant: one wake per result; a message still reads it. */
65
+ wokenAt?: number;
64
66
  }) | (ToolOperationIdentity & {
65
67
  status: 'uncertain';
66
68
  pageGrant?: SessionPageGrant;
@@ -144,6 +144,7 @@ const operationSchema = z.discriminatedUnion('status', [
144
144
  reply: toolOperationReplySchema.optional(),
145
145
  settledAt: z.number().finite().nonnegative(),
146
146
  retainUntil: z.number().finite().nonnegative().optional(),
147
+ wokenAt: z.number().finite().nonnegative().optional(),
147
148
  }),
148
149
  z.strictObject({
149
150
  ...identityFields,