@theoremjs/web 0.3.5-next.980.g83e419d → 0.3.5-next.982.g16b31de

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/server/handler.js CHANGED
@@ -1,5 +1,4 @@
1
- import { withPublicLabels } from '@theoremjs/agents/guardrails';
2
- import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema, sessionPageDispatch, } from "./page-dispatch.js";
1
+ import { pageToolResultSchema, sessionPageDispatch } from "./page-dispatch.js";
3
2
  /**
4
3
  * One Web-standard handler that serves a Theorem chat UI for a single profile.
5
4
  *
@@ -14,8 +13,9 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
14
13
  * - `POST <base>/stop` → stop a running turn where it stands
15
14
  * - `POST <base>/page-result` → the page's result for a tool the turn ran in the page
16
15
  * - `POST <base>/conversation` → the transcript and the paused reply, to draw
17
- * - `POST <base>/notify` → NDJSON that stays open: one line now, and one each time a background
18
- * call in this session ends. Set `notifier` to serve it
16
+ * - `POST <base>/notify` → NDJSON that stays open: one line now, and one for each `publish` under
17
+ * this session: a background call ended, or the app saved a reply.
18
+ * Set `notifier` to serve it
19
19
  * - `POST <base>/rewind` → `{ conversation, view }` the conversation cut after one block, and its new ref
20
20
  * - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
21
21
  * background calls that ended since it last ran. Empty when none waits
@@ -39,28 +39,21 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
39
39
  *
40
40
  * @module
41
41
  */
42
- import { authorizeToolReplay, compactHistory, defaultKernelScope, defineProfile, invokeTool, jsonObjectSchema, labelText, registerProfile, runTurn, TheoremError, toolInvocationHash, } from '@theoremjs/agents';
43
- import { runConversation } from '@theoremjs/agents/conversation';
42
+ import { defaultKernelScope, defineProfile, labelText, TheoremError, } from '@theoremjs/agents';
44
43
  import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremjs/agents/host';
45
- import { clientProfileInterface, gatedToolsFromEvents, interfaceFromProfile, promotedToolIdsFromEvents, refuseInterfacePick, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
46
- import { answerGatedCall, isSealedSource, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
47
- import { hostInterface, theoremHostCallRequestSchema, } from "../client/host-transport.js";
44
+ import { clientProfileInterface } from '@theoremjs/agents/interface';
45
+ import { hostInterface, theoremHostCallRequestSchema } from "../client/host-transport.js";
48
46
  import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.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";
51
- import { unknownConversation, } from "./conversation-store.js";
52
- import { createMemoryCredentialStore, } from "./credential-store.js";
53
- import { sessionStateStore, } from "./session-authority.js";
47
+ import { statelessRefusal } from "./conversation.js";
48
+ import { chatOf, createConversationCore, followedUp, oneInbox, unconversedAnswer, } from "./conversation-core.js";
49
+ import { callEvents, sessionParts } from "./session-calls.js";
54
50
  import { theoremSession } from "./session-identity.js";
55
51
  import { kernelTurnInput } from "./turn-input.js";
56
52
  export { theoremSession, theoremSessionId } from "./session-identity.js";
57
53
  import { jsonResponse } from "./json-response.js";
58
54
  import { boundedRequestJson, requestByteLimit } from "./request-body.js";
59
55
  import { checkRequest } from "./request-check.js";
60
- import { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, } from "./session-store.js";
61
- import { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
62
- import { sameAcceptedAnswer, sessionToolCoordinator } from "./tool-operations.js";
63
- import { preparedTurn, stagesInOrder } from "./turn-wiring.js";
56
+ import { createMemorySteerInbox, steerUnitOf } from "./steer-inbox.js";
64
57
  const NDJSON_HEADERS = {
65
58
  'content-type': 'application/x-ndjson; charset=utf-8',
66
59
  'cache-control': 'no-store',
@@ -109,32 +102,6 @@ function routeOf(request) {
109
102
  ? last
110
103
  : '';
111
104
  }
112
- function lockedStore(store, loaded) {
113
- const locks = new Map();
114
- const read = async (sessionId) => loaded(await store.load(sessionId));
115
- return {
116
- read,
117
- mutate(sessionId, change) {
118
- const next = (locks.get(sessionId) ?? Promise.resolve()).then(async () => {
119
- const value = await read(sessionId);
120
- const result = change(value);
121
- await store.save(sessionId, value);
122
- return result;
123
- });
124
- const settled = next.catch(() => { });
125
- locks.set(sessionId, settled);
126
- void settled.then(() => {
127
- if (locks.get(sessionId) === settled)
128
- locks.delete(sessionId);
129
- });
130
- return next;
131
- },
132
- };
133
- }
134
- /** The profile as the server reads a message against it, its tools as registered now. */
135
- function chatInterface(chat) {
136
- return interfaceFromProfile(chat.profile, defaultKernelScope.tools);
137
- }
138
105
  async function sessionOf(ctx, request) {
139
106
  if (!ctx.options.session)
140
107
  return theoremSession(request);
@@ -190,287 +157,74 @@ function providerFor(ctx, request, model) {
190
157
  return provider({ request, model });
191
158
  return provider;
192
159
  }
193
- /** Steer inboxes are scoped to the session, so a turn id alone can't reach another user's turn. */
194
- function inboxKey(sessionId, turnId) {
195
- return `${sessionId}\u0000${turnId}`;
196
- }
197
- /** The exact paused calls the user may now approve, when the stream stopped on gates. */
198
- function pendingGatesFrom(events, context) {
199
- return gatedToolsFromEvents(events).map((gated) => ({
200
- callId: gated.callId,
201
- gate: {
202
- profileId: context.profileId,
203
- operationId: requiredOperationId(gated),
204
- callId: gated.callId,
205
- name: gated.name,
206
- arguments: gated.arguments,
207
- gate: {
208
- kind: gated.gateKind,
209
- permission: gated.permission,
210
- ...(gated.auth ? { auth: gated.auth } : {}),
211
- },
212
- snapshot: toolSnapshotFromEvents(events),
213
- promoted: [...new Set([...(context.promoted ?? []), ...promotedToolIdsFromEvents(events)])],
214
- turnInput: context.turnInput,
215
- model: context.model,
216
- createdAt: Date.now(),
217
- },
218
- }));
219
- }
220
- /** When the stream paused on gates, record the exact calls the user may now approve. */
221
- async function recordOutcome(sessions, sessionId, events, context) {
222
- const pending = pendingGatesFrom(events, context);
223
- if (!pending.length)
224
- return;
225
- await sessions.mutate(sessionId, (state) => {
226
- for (const { gate } of pending) {
227
- const operation = state.operations[gate.operationId];
228
- if (operation && operation.status !== 'ready')
229
- throw new TheoremError('unavailable', `Tool operation ${gate.operationId} is ${operation.status}, not ready, so its gate was not saved`, // labels-exempt: internal diagnostic; the user reads session.busy
230
- { copy: { key: 'session.busy' } });
231
- delete state.operations[gate.operationId];
232
- Object.defineProperty(state.gates, gate.operationId, {
233
- value: gate,
234
- writable: true,
235
- enumerable: true,
236
- configurable: true,
237
- });
238
- }
239
- });
240
- }
241
- async function* recorded(sessions, sessionId, events, context, seed = []) {
242
- const seen = [...seed];
243
- for await (const event of events) {
244
- seen.push(event);
245
- if (event.type === 'done' || event.type === 'provider_checkpoint')
246
- await recordOutcome(sessions, sessionId, seen, context);
247
- yield event;
248
- }
249
- }
250
- /** Save one credential, leaving the session's others as they are. */
251
- function saveCredential(ctx, sessionId, slot, credential) {
252
- return ctx.credentials.mutate(sessionId, (saved) => {
253
- saved[slot] = credential;
254
- });
255
- }
256
- /**
257
- * The session's credentials as a call reads them: one slot when a tool needs it,
258
- * saved the moment the kernel sets one, so a rotated refresh token is never lost
259
- * to a closed stream.
260
- */
261
- function sessionCredentials(ctx, sessionId) {
160
+ /** What a run reads in place of `request`. */
161
+ function contextOf(ctx, request, sessionId) {
162
+ let asked;
262
163
  return {
263
- get: async (slot) => (await ctx.credentials.read(sessionId))[slot],
264
- set: (slot, credential) => saveCredential(ctx, sessionId, slot, credential),
265
- delete: (slot) => ctx.credentials.mutate(sessionId, (saved) => {
266
- delete saved[slot];
267
- }),
164
+ sessionId,
165
+ signal: request.signal,
166
+ // why: The app's `host` is asked when a run first reads it, so a route that reads none asks
167
+ // none, and a reply and the app's steps around its save read the same value.
168
+ get host() {
169
+ asked ??= { host: ctx.options.host?.(request) };
170
+ return asked.host;
171
+ },
268
172
  };
269
173
  }
270
- /** An OAuth gate given the host's sign-in URL. */
271
- async function withAuthorizationUrl(ctx, request, sessionId, event) {
272
- if (event.type !== 'tool' || event.tool.phase !== 'gate')
273
- return event;
274
- const { tool } = event;
275
- const gate = tool.gate.kind === 'auth' ? tool.gate : undefined;
276
- if (gate?.authChallenge.authType !== 'oauth2' || !ctx.options.authorizationUrl)
277
- return event;
278
- const challenge = gate.authChallenge;
279
- const authorizationUrl = await ctx.options.authorizationUrl(challenge, { request, sessionId });
174
+ /** The session's calls as `request` runs them: each of the app's callbacks is given `request`. */
175
+ function callsOf(ctx, request) {
176
+ const { options } = ctx;
177
+ const { background, authorizeToolReplay, authorizationUrl } = options;
280
178
  return {
281
- ...event,
282
- tool: { ...tool, gate: { ...gate, authChallenge: { ...challenge, authorizationUrl } } },
283
- };
284
- }
285
- /** Every OAuth gate in the stream, given the host's sign-in URL. */
286
- async function* withAuthorizationUrls(ctx, request, sessionId, events) {
287
- for await (const event of events)
288
- yield await withAuthorizationUrl(ctx, request, sessionId, event);
289
- }
290
- function answerPendingGate(state, request, profileId) {
291
- const operation = Object.hasOwn(state.operations, request.operationId)
292
- ? state.operations[request.operationId]
293
- : undefined;
294
- if (operation?.status === 'ready' &&
295
- operation.profileId === profileId &&
296
- operation.pending.callId === request.callId) {
297
- const accepted = answerGatedCall(request, {
298
- name: operation.pending.name,
299
- arguments: operation.pending.arguments,
300
- permission: operation.pending.gate.permission,
301
- gateKind: operation.pending.gate.kind,
302
- ...(operation.pending.gate.kind === 'auth' && operation.pending.gate.auth
303
- ? { auth: operation.pending.gate.auth }
179
+ profile: ctx.profile,
180
+ sessions: ctx.sessions,
181
+ credentials: ctx.credentials,
182
+ pageToolBroker: ctx.pageToolBroker,
183
+ options: {
184
+ prepare: options.prepare,
185
+ onStage: options.onStage,
186
+ pageToolTimeoutMs: options.pageToolTimeoutMs,
187
+ notifier: options.notifier,
188
+ lateResultsDecider: options.lateResultsDecider,
189
+ ...(background
190
+ ? { background: (at) => background({ request, sessionId: at.sessionId }) }
304
191
  : {}),
305
- }, operation.answer.sessionPermissions);
306
- const { typed: _typed, ...plain } = accepted;
307
- if (!sameAcceptedAnswer(plain, operation.answer))
308
- throw new TheoremError('request', labelText('error.request'));
309
- return {
310
- callId: request.callId,
311
- pending: operation.pending,
312
- answer: { ...operation.answer, ...(accepted.typed ? { typed: accepted.typed } : {}) },
313
- };
314
- }
315
- const pending = Object.hasOwn(state.gates, request.operationId)
316
- ? state.gates[request.operationId]
317
- : undefined;
318
- if (!pending || pending.profileId !== profileId || pending.callId !== request.callId) {
319
- throw new TheoremError('request', labelText('session.gate_expired'), {
320
- copy: { key: 'session.gate_expired' },
321
- });
322
- }
323
- // why: A refused answer (a refused secret, an edit without an approval) throws here and leaves the gate pending.
324
- const answer = answerGatedCall(request, {
325
- name: pending.name,
326
- arguments: pending.arguments,
327
- permission: pending.gate.permission,
328
- gateKind: pending.gate.kind,
329
- ...(pending.gate.kind === 'auth' && pending.gate.auth ? { auth: pending.gate.auth } : {}),
330
- }, state.permissions);
331
- delete state.gates[request.operationId];
332
- const { typed: _typed, ...accepted } = answer;
333
- state.operations[request.operationId] = {
334
- status: 'ready',
335
- profileId,
336
- pending,
337
- answer: accepted,
338
- readyAt: Date.now(),
192
+ ...(authorizeToolReplay
193
+ ? { authorizeToolReplay: (_at, operation) => authorizeToolReplay({ request, operation }) }
194
+ : {}),
195
+ ...(authorizationUrl
196
+ ? {
197
+ authorizationUrl: (challenge, at) => authorizationUrl(challenge, { request, sessionId: at.sessionId }),
198
+ }
199
+ : {}),
200
+ onError: (err) => options.onError?.(err, { request }),
201
+ wake: (at, ref) => serverWake(ctx, request, at.sessionId, ref),
202
+ },
339
203
  };
340
- state.permissions = answer.sessionPermissions;
341
- return { callId: request.callId, pending, answer };
342
- }
343
- function walkedCallOf(state, reference, profileId, paused) {
344
- const settled = Object.hasOwn(state.operations, reference.operationId)
345
- ? state.operations[reference.operationId]
346
- : undefined;
347
- // why: A gate that lapsed is gone from the session while the reply still waits on its call. The call is only ever cancelled here, so the next message is never refused for it.
348
- if (!settled && !Object.hasOwn(state.gates, reference.operationId)) {
349
- const lapsed = pendingGatesFrom(paused, { profileId, turnInput: {} }).find(({ callId }) => callId === reference.callId);
350
- if (lapsed)
351
- state.gates[reference.operationId] = lapsed.gate;
352
- }
353
- return settled?.status === 'settled' &&
354
- settled.callId === reference.callId &&
355
- settled.profileId === profileId
356
- ? { callId: reference.callId, settled }
357
- : answerPendingGate(state, { ...reference, decision: 'abandon' }, profileId);
358
- }
359
- /**
360
- * Take the calls a message or a rewind walks away from out of the session,
361
- * answered `abandon`: every one of them, or none when one is neither waiting
362
- * nor settled. Each comes back with the run that settles it.
363
- */
364
- async function takeWalkedAway(ctx, request, session, abandon, conversation) {
365
- const paused = conversation.paused?.events ?? [];
366
- // why: A throw leaves the session unsaved, so no call is taken unless all are.
367
- const calls = await ctx.sessions.mutate(session.id, (state) => abandon.map((reference) => ({
368
- reference,
369
- call: walkedCallOf(state, reference, ctx.profile.id, paused),
370
- })));
371
- return calls.map(({ reference, call }) => ({
372
- ...reference,
373
- events: 'settled' in call
374
- ? replayOperation(ctx, request, call.settled)
375
- : settleAnswered(ctx, request, session, call),
376
- }));
377
- }
378
- async function* settleAnswered(ctx, request, session, answered) {
379
- yield* invokeAnswered(ctx, request, session.id, answered);
380
204
  }
381
- async function* invokeAnswered(ctx, request, sessionId, { callId, pending, answer }) {
382
- const host = await ctx.options.host?.(request);
383
- // why: The held call goes on with what the application set for its turn: its context, stage handler and credentials.
384
- const prepared = await preparedTurn(ctx.options.prepare, {
385
- profile: ctx.profile.id,
386
- execution: sessionToolCoordinator(ctx.sessions, sessionId),
387
- ...backgroundWiring(ctx, request, sessionId),
388
- input: pending.turnInput ?? {},
389
- host,
390
- signal: request.signal,
391
- answersHeldCall: true,
392
- }, {
393
- credentials: sessionCredentials(ctx, sessionId),
394
- ...(ctx.options.onStage ? { onStage: ctx.options.onStage } : {}),
395
- announce: (service) => announced(ctx, request, sessionId, service),
396
- });
397
- if (answer.typed) {
398
- // invariant: a sealed source keeps every key where the run cannot read it, so a key typed
399
- // here would be saved and never sent; the person enters it where the keys are kept.
400
- if (prepared.credentials && isSealedSource(prepared.credentials)) {
401
- throw new TheoremError('request', `call ${callId} runs with a sealed credential source, which takes no typed secret`);
402
- }
403
- await saveCredential(ctx, sessionId, answer.typed.slot, answer.typed.credential);
404
- }
405
- yield* invokeTool({
406
- profile: ctx.profile.id,
407
- ...(prepared.execution ? { execution: prepared.execution } : {}),
408
- ...(prepared.background ? { background: prepared.background } : {}),
409
- pageExecution: sessionPageDispatch(ctx.sessions, sessionId, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
410
- name: pending.name,
411
- callId,
412
- operationId: pending.operationId,
413
- input: answer.input,
414
- resume: answer.resume,
415
- // why: An approval that names no answer is the page saying it has none, so the call is not held again.
416
- ...(pending.gate.kind === 'page' && answer.resume.granted
417
- ? { page: answer.page ?? { unanswered: true } }
418
- : {}),
419
- sessionPermissions: answer.sessionPermissions,
420
- credentials: prepared.credentials,
421
- ...(prepared.onStage ? { onStage: prepared.onStage } : {}),
422
- turnInput: pending.turnInput,
423
- snapshot: pending.snapshot,
424
- promoted: pending.promoted,
425
- model: pending.model,
426
- signal: request.signal,
427
- host: prepared.host,
205
+ /** The chat's conversation core as `request` runs it. */
206
+ function coreOf(ctx, chat, request) {
207
+ const calls = callsOf(ctx, request);
208
+ return ctx.wire({
209
+ ...calls,
210
+ chat,
211
+ steer: ctx.inbox,
212
+ options: {
213
+ ...calls.options,
214
+ provider: (_at, model) => providerFor(ctx, request, model),
215
+ conversationLeaseMs: ctx.options.conversationLeaseMs,
216
+ notifyRetryMs: ctx.options.notifyRetryMs,
217
+ clientEvents: ctx.options.clientEvents,
218
+ },
428
219
  });
429
220
  }
430
- /** The host's service for a call in this session, for a request that runs a tool. */
431
- function backgroundWiring(ctx, request, sessionId) {
432
- const service = ctx.options.background?.({ request, sessionId });
433
- return service ? { background: announced(ctx, request, sessionId, service) } : {};
434
- }
435
221
  /**
436
- * `service`, telling the session's open pages when each of its calls ends, and the decider's
437
- * `ended`, with the wake and the notify it may use.
222
+ * A page's run: when it ends with items that wait, `onContinue` says who runs the next reply.
223
+ * Unset, the chat is let go, and the page wakes it.
438
224
  */
439
- function announced(ctx, request, sessionId, service) {
440
- const { notifier, lateResultsDecider } = ctx.options;
441
- const ended = lateResultsDecider?.ended?.bind(lateResultsDecider);
442
- if (!notifier && !ended)
443
- return service;
444
- const notify = async () => {
445
- await notifier?.publish(sessionId);
446
- };
447
- return {
448
- detached(call) {
449
- service.detached(call);
450
- void call.done
451
- .then(async () => {
452
- await notify();
453
- if (!ended)
454
- return;
455
- const { operations } = await ctx.sessions.read(sessionId);
456
- const { operationId, callId, toolId } = call;
457
- const operation = Object.hasOwn(operations, operationId)
458
- ? operations[operationId]
459
- : undefined;
460
- const outcome = detachedEnd({ operationId, callId, name: toolId, at: Date.now() }, operation, ctx.profile.labels);
461
- if (!outcome)
462
- return;
463
- await ended({
464
- host: await ctx.options.host?.(request),
465
- result: { operationId, outcome },
466
- wake: (conversation) => serverWake(ctx, request, sessionId, conversation),
467
- notify,
468
- });
469
- })
470
- .catch((err) => ctx.options.onError?.(err, { request }));
471
- },
472
- event: (event, call) => service.event(event, call),
473
- };
225
+ function pageRun(ctx, request, core, at, reply) {
226
+ const { onContinue } = ctx.options;
227
+ return followedUp(core, at, reply, (run) => onContinue ? onContinue(run, { request, sessionId: at.sessionId }) : 'let_go');
474
228
  }
475
229
  /**
476
230
  * The decider's wake, with no page: the reply runs on a request of its own, with the headers of
@@ -479,342 +233,114 @@ function announced(ctx, request, sessionId, service) {
479
233
  */
480
234
  async function serverWake(ctx, started, sessionId, ref) {
481
235
  const request = new Request(started.url, { headers: started.headers });
482
- const session = { id: sessionId };
483
- const host = conversationHost(ctx, session);
484
- if (!host)
236
+ if (!ctx.chat)
485
237
  throw statelessRefusal('wake');
486
- const retry = (leasedUntil) => {
487
- setTimeout(() => {
488
- serverWake(ctx, started, sessionId, ref).catch((err) => ctx.options.onError?.(err, { request }));
489
- }, Math.max(0, leasedUntil - Date.now()));
490
- };
491
- const lines = await wakeLines(ctx, request, session, host, ref, {}, { retry });
492
- for await (const line of lines) {
493
- if (line.type === 'error') {
238
+ const core = coreOf(ctx, ctx.chat, request);
239
+ const at = contextOf(ctx, request, sessionId);
240
+ // why: no page is open to wake the chat, so this wake runs each next reply itself
241
+ const lines = followedUp(core, at, await core.wake(at, { ref }), () => 'here');
242
+ // why: the run lets the chat go as it ends, so its lines are read to the end before a failure is thrown
243
+ let failed;
244
+ for (;;) {
245
+ const next = await lines.next();
246
+ if (next.done) {
247
+ if (failed)
248
+ throw failed;
249
+ if (next.value.outcome !== 'held')
250
+ return;
251
+ setTimeout(() => {
252
+ serverWake(ctx, started, sessionId, ref).catch((err) => ctx.options.onError?.(err, { request }));
253
+ }, Math.max(0, next.value.leasedUntil - Date.now()));
254
+ return;
255
+ }
256
+ if (next.value.type === 'error') {
494
257
  // labels-exempt: internal diagnostic for the decider's wake; no page reads it
495
- throw new TheoremError(line.errorKind, line.errorInternal ?? line.error ?? 'the wake failed');
258
+ failed ??= new TheoremError(next.value.errorKind, next.value.errorInternal ?? next.value.error ?? 'the wake failed');
496
259
  }
497
260
  }
498
261
  }
499
- /** A settled call's answer, streamed again. */
500
- async function* once(event, labels) {
501
- yield withPublicLabels(event, labels);
502
- }
503
- /** Whether this request may read a settled call's result: the host's `authorizeToolReplay`. */
504
- async function replayAllowed(ctx, request, operation) {
505
- const { authorizeToolReplay } = ctx.options;
506
- return !authorizeToolReplay || (await authorizeToolReplay({ request, operation }));
507
- }
508
- const DEFAULT_CONVERSATION_LEASE_MS = 60_000;
509
- /**
510
- * The chat's inbox as this request reads it: the chat as this request last wrote it, and the
511
- * results this request may read. `seen` follows each line's ref, because a store's ref can change
512
- * with each write.
513
- */
514
- function chatInbox(ctx, request, session, host, opened) {
515
- let ref = opened.ref;
516
- const leaseMs = ctx.options.conversationLeaseMs ?? DEFAULT_CONVERSATION_LEASE_MS;
517
- const inbox = sessionConversationInbox({
518
- sessions: ctx.sessions,
519
- sessionId: session.id,
520
- leaseMs,
521
- conversation: async (key) => {
522
- const conversation = ref === null ? opened.conversation : (await host.store.read(session.id, ref))?.conversation;
523
- return conversation?.id === key ? conversation : undefined;
524
- },
525
- readable: (operation) => replayAllowed(ctx, request, operation),
526
- labels: ctx.profile.labels,
527
- });
528
- return {
529
- inbox,
530
- key: opened.conversation.id,
531
- leaseMs,
532
- seen(line) {
533
- if (line.type === 'conversation')
534
- ref = line.ref;
535
- },
536
- get ref() {
537
- return ref;
538
- },
262
+ /** The person's message: a new reply, run against the conversation the host keeps. */
263
+ async function turn(ctx, chat, request, session) {
264
+ const body = await readBody(request, theoremTurnRequestSchema, ctx.options.maxRequestBytes);
265
+ if (body.stated && !ctx.options.pageStatesTurn) {
266
+ throw new TheoremError('request', labelText('error.request'));
267
+ }
268
+ const context = await ctx.options.context?.(request);
269
+ const core = coreOf(ctx, chat, request);
270
+ const at = contextOf(ctx, request, session.id);
271
+ const message = {
272
+ ref: body.conversation,
273
+ input: body.input,
274
+ ...(context === undefined ? {} : { context }),
275
+ generation: body,
276
+ ...(body.abandon ? { abandon: body.abandon } : {}),
539
277
  };
540
- }
541
- /** The values `produce` sends, as it sends them, then its end or what it threw. */
542
- async function* sent(produce) {
543
- const queue = [];
544
- let ended;
545
- let wake = () => { };
546
- produce((value) => {
547
- queue.push(value);
548
- wake();
549
- }).then(() => {
550
- ended = { failed: false };
551
- wake();
552
- }, (failure) => {
553
- ended = { failed: true, failure };
554
- wake();
555
- });
556
- for (;;) {
557
- if (queue.length > 0) {
558
- yield queue.splice(0, 1)[0];
559
- continue;
278
+ if (ctx.options.intake) {
279
+ if (body.id === undefined) {
280
+ // labels-exempt: internal diagnostic; the user reads error.request
281
+ throw new TheoremError('request', 'a message needs an `id` where the host saves it itself');
560
282
  }
561
- if (ended?.failed)
562
- throw ended.failure;
563
- if (ended)
564
- return;
565
- await new Promise((resolve) => {
566
- wake = resolve;
567
- });
283
+ const taken = await savedMessage(ctx.options.intake, core, at, { id: body.id, message });
284
+ return eventStream(ctx, request, () => taken.outcome === 'saved'
285
+ ? lines([savedLine(taken)])
286
+ : openedRun(ctx, request, core, at, taken, message));
568
287
  }
288
+ const reply = await core.message(at, message);
289
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
569
290
  }
570
291
  /**
571
- * Runs a reply under a hold of the chat, and streams its lines. The reply reads the late results
572
- * the decider's policy tells it. Without a decider no reply reads one, and no hold is taken.
573
- * invariant: One hold has a chat at a time, and lets it go only once nothing waits that may be told.
574
- * A page's reply that leaves results waiting lets the chat go, so the page wakes for them; a
575
- * server's wake runs the next reply under its hold.
292
+ * The app's save of a message, after the checks that can refuse it.
293
+ * invariant: Nothing refuses a message the app has saved, so the page never takes a saved message back.
576
294
  */
577
- function heldLines(ctx, request, session, host, opened, start, reply, follow = {}) {
578
- const decider = ctx.options.lateResultsDecider;
579
- if (!decider)
580
- return reply(undefined, () => opened.ref);
581
- const chat = chatInbox(ctx, request, session, host, opened);
582
- const ref = () => chat.ref;
583
- return sent(async (send) => {
584
- const whose = await ctx.options.host?.(request);
585
- const runOnce = (begin, lines) => runConversation({
586
- conversation: chat.key,
587
- inbox: chat.inbox,
588
- policy: (items, moment) => decider.policy(items, { ...moment, host: whose }),
589
- start: begin,
590
- newId: () => crypto.randomUUID(),
591
- renewEveryMs: chat.leaseMs / 3,
592
- reply: async (run) => {
593
- const renew = () => chat.inbox.renew(chat.key, run.hold);
594
- for await (const line of lines({ run, renew })) {
595
- chat.seen(line);
596
- send(line);
597
- }
598
- },
599
- gaveUp: (items) => {
600
- ctx.options.onError?.(
601
- // labels-exempt: internal diagnostic; no reader sees a given-up result
602
- new TheoremError('unavailable', 'The late-results policy gave up results', {
603
- cause: { code: 'late_results_given_up', operationIds: items.map((item) => item.id) },
604
- }), { request });
605
- },
606
- });
607
- let run = await runOnce(start, (held) => reply(held, ref));
608
- let failure = run.outcome === 'held' ? undefined : run.failure;
609
- while (run.outcome === 'continue') {
610
- const paused = await isPaused(host, session, chat.ref, opened.conversation);
611
- if (follow.retry === undefined || paused) {
612
- await letGo(chat.inbox, chat.key, run.hold);
613
- break;
614
- }
615
- run = await runOnce({ opening: 'follow_up', hold: run.hold }, (held) => wakeReplyLines(ctx, request, session, host, chat.ref, {}, held));
616
- if (run.outcome !== 'held' && run.failure !== undefined)
617
- failure ??= run.failure;
618
- }
619
- if (run.outcome === 'held')
620
- follow.retry?.(run.leasedUntil);
621
- if (failure !== undefined)
622
- throw failure;
623
- });
295
+ async function savedMessage(intake, core, at, sent) {
296
+ await core.checkMessage(at, sent.message);
297
+ const { ref, input } = sent.message;
298
+ return intake(at, { id: sent.id, ...(ref === undefined ? {} : { ref }), message: input });
624
299
  }
625
- /** Whether the chat waits on gates: a wake leaves it to the answer that goes on. */
626
- async function isPaused(host, session, ref, fallback) {
627
- const conversation = ref === null ? fallback : (await host.store.read(session.id, ref))?.conversation;
628
- return conversation?.paused !== undefined;
300
+ /** The line that tells the page the app saved its message, and how a reply names it. */
301
+ function savedLine(taken) {
302
+ return { type: 'conversation', ref: taken.ref, posted: true, landsAs: [...taken.landsAs] };
629
303
  }
630
- /** Lets the chat go under `hold`, reading again each time a result arrives first. */
631
- async function letGo(inbox, key, hold) {
632
- for (;;) {
633
- const { version } = await inbox.read(key);
634
- if ((await inbox.release(key, hold, version)) !== 'moved')
635
- return;
636
- }
637
- }
638
- /** The late results a reply's model reads: what it opened with, then what each later moment hands it. */
639
- function lateSource(run) {
640
- let opening = true;
641
- return async ({ stage, step }) => {
642
- if (opening && stage === 'pre_turn') {
643
- opening = false;
644
- return run.opened.map((item) => item.outcome);
645
- }
646
- return (await run.take({ stage, step })).map((item) => item.outcome);
647
- };
648
- }
649
- /** One model run of a chat's reply, its gates recorded in the session as they pause. */
650
- async function* chatTurn(ctx, request, session, turn, key, signal, stop, late) {
651
- const state = await ctx.sessions.read(session.id);
652
- const provider = await providerFor(ctx, request, turn.model);
653
- const host = await ctx.options.host?.(request);
654
- if (key) {
655
- await ctx.inbox.open(key);
656
- stopOnRequest(ctx.inbox, key, stop);
657
- }
658
- try {
659
- const onStage = stagesInOrder(ctx.options.onStage, key ? steerStage(ctx.inbox, key) : undefined);
660
- const prepared = await preparedTurn(ctx.options.prepare, {
661
- profile: ctx.profile.id,
662
- execution: sessionToolCoordinator(ctx.sessions, session.id),
663
- ...backgroundWiring(ctx, request, session.id),
664
- pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
665
- input: turn.input,
666
- ...(late ? { lateResults: lateSource(late) } : {}),
667
- ...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
668
- ...(turn.providerState ? { providerState: turn.providerState } : {}),
669
- sessionPermissions: state.permissions,
670
- signal,
671
- host,
672
- ...(turn.model ? { model: turn.model } : {}),
673
- ...(turn.effort ? { effort: turn.effort } : {}),
674
- ...turn.carried,
675
- ...turn.stated,
676
- }, {
677
- credentials: sessionCredentials(ctx, session.id),
678
- ...(onStage ? { onStage } : {}),
679
- announce: (service) => announced(ctx, request, session.id, service),
680
- });
681
- const events = runTurn(prepared, provider);
682
- yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
683
- profileId: ctx.profile.id,
684
- turnInput: turn.input,
685
- model: turn.model,
686
- });
687
- }
688
- finally {
689
- if (key)
690
- await ctx.inbox.close(key);
691
- }
304
+ async function* lines(values) {
305
+ yield* values;
692
306
  }
693
307
  /**
694
- * How this request runs the model for a reply: its generation, its abort (the request's, a stop,
695
- * or its hold losing the chat), and the chat's hold it saves under.
308
+ * The reply to a message whose save took the conversation. The saved line goes first: whatever
309
+ * the reply does after it, the message stays saved.
696
310
  */
697
- function chatRunner(ctx, request, session, generation, held) {
698
- // invariant: The page's pick is checked here, before prepare; a model prepare sets is the host's own.
699
- refuseInterfacePick(ctx.profile, generation);
700
- const key = generation.turnId ? inboxKey(session.id, generation.turnId) : undefined;
701
- const stop = new AbortController();
702
- const signal = AbortSignal.any([request.signal, stop.signal, ...(held ? [held.run.signal] : [])]);
703
- return {
704
- run: (turn) => chatTurn(ctx, request, session, turn, key, signal, stop, held?.run),
705
- async compact(history, tokens, model) {
706
- const provider = await providerFor(ctx, request, model);
707
- const compacted = await compactHistory({
708
- profile: ctx.profile.id,
709
- history,
710
- tokens,
711
- signal,
712
- ...(model ? { model } : {}),
713
- }, provider);
714
- return compacted?.history;
715
- },
716
- ...(generation.model ? { model: generation.model } : {}),
717
- ...(generation.effort ? { effort: generation.effort } : {}),
718
- ...(generation.stated ? { stated: generation.stated } : {}),
719
- signal,
720
- ...(held ? { reply: held.run.reply, held: held.renew } : {}),
721
- };
722
- }
723
- /** The chat's conversation as this session's runs read and write it; undefined when the profile keeps none. */
724
- function conversationHost(ctx, session) {
725
- const store = ctx.chat?.conversations;
726
- if (!ctx.chat || !store)
727
- return undefined;
728
- return readerConversationHost({
729
- sessionId: session.id,
730
- store,
731
- profile: { outputs: ctx.chat.profile.outputs, labels: ctx.profile.labels },
732
- clientEvents: ctx.options.clientEvents,
733
- });
734
- }
735
- /** The person's message: a new reply, run against the conversation the host keeps. */
736
- async function turn(ctx, chat, request, session) {
737
- const body = await readBody(request, theoremTurnRequestSchema, ctx.options.maxRequestBytes);
738
- if (body.stated && !ctx.options.pageStatesTurn) {
739
- throw new TheoremError('request', labelText('error.request'));
311
+ async function* openedRun(ctx, request, core, at, taken, message) {
312
+ const { ref, hold, blocks } = taken;
313
+ yield savedLine(taken);
314
+ let reply;
315
+ try {
316
+ reply = await core.message(at, { ...message, ref, saved: { hold, blocks } });
740
317
  }
741
- const message = postedMessage(chatInterface(chat), body.input, await ctx.options.context?.(request));
742
- const host = conversationHost(ctx, session);
743
- if (!host) {
744
- if (body.conversation !== undefined)
745
- throw statelessRefusal('continue');
746
- // labels-exempt: internal diagnostic; the user reads error.request
747
- if (body.abandon)
748
- throw statelessRefusal('walk away from');
749
- const runner = chatRunner(ctx, request, session, body);
750
- return eventStream(ctx, request, () => runner.run({
751
- input: message.input,
752
- model: body.model,
753
- effort: body.effort,
754
- ...(body.stated ? { stated: body.stated } : {}),
755
- }));
318
+ catch (err) {
319
+ // why: No reply took the hold, so the handler lets the conversation go for the next one.
320
+ await core.release(at, { ref, hold });
321
+ throw err;
756
322
  }
757
- const opened = await openConversation(host, body.conversation, {
758
- kind: 'message',
759
- ...(body.abandon ? { abandon: body.abandon } : {}),
760
- });
761
- // why: Take the walked-away calls before streaming, so a stale one is a reply status, not a stream error.
762
- const walkAway = body.abandon
763
- ? await takeWalkedAway(ctx, request, session, body.abandon, opened.conversation)
764
- : undefined;
765
- return eventStream(ctx, request, () => heldLines(ctx, request, session, host, opened, { opening: 'message', takeOver: true }, (held) => messageReply({
766
- host,
767
- opened,
768
- message,
769
- ...(walkAway ? { walkAway } : {}),
770
- runner: chatRunner(ctx, request, session, body, held),
771
- })));
323
+ yield* pageRun(ctx, request, core, at, reply);
772
324
  }
773
325
  /** The conversation as the browser draws it. */
774
- async function conversation(ctx, request, session) {
326
+ async function conversation(ctx, chat, request, session) {
775
327
  const body = await readBody(request, theoremConversationRequestSchema, ctx.options.maxRequestBytes);
776
- const host = conversationHost(ctx, session);
777
- if (!host)
778
- throw statelessRefusal('read');
779
- const opened = await openConversation(host, body.conversation, { kind: 'read' });
780
- return jsonResponse(200, await currentView(ctx, request, session, host, body.conversation, opened.conversation));
328
+ const view = await coreOf(ctx, chat, request).read(contextOf(ctx, request, session.id), {
329
+ ref: body.conversation,
330
+ });
331
+ return jsonResponse(200, view);
781
332
  }
782
333
  /**
783
334
  * A reply to no message, for results that ended since the model last ran. It runs under a hold of
784
335
  * the chat, so two pages that wake at once run it once, and reads what the decider's policy tells.
785
336
  */
786
- async function wake(ctx, request, session) {
337
+ async function wake(ctx, chat, request, session) {
787
338
  const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
788
339
  const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
789
- const host = conversationHost(ctx, session);
790
- if (!host)
791
- throw statelessRefusal('wake');
792
- const lines = await wakeLines(ctx, request, session, host, body.conversation, body, {}, input);
793
- return eventStream(ctx, request, () => lines);
794
- }
795
- /**
796
- * The wake's reply under a hold of the chat; nothing when no decider tells a result, or while a
797
- * reply waits on gates: the answer that goes on reads what waits.
798
- */
799
- async function wakeLines(ctx, request, session, host, ref, generation, follow, input) {
800
- const opened = await openConversation(host, ref, { kind: 'read' });
801
- if (!ctx.options.lateResultsDecider || opened.conversation.paused)
802
- return noLines();
803
- return heldLines(ctx, request, session, host, opened, { opening: 'wake' }, (held, current) => wakeReplyLines(ctx, request, session, host, current(), generation, held, input), follow);
804
- }
805
- /** No reply lines. */
806
- async function* noLines() { }
807
- /**
808
- * A reply to no message under `held`, on the chat as it stands now. The page that woke draws it;
809
- * any other page open on the session reads it once it ends.
810
- */
811
- async function* wakeReplyLines(ctx, request, session, host, ref, generation, held, input) {
812
- if (ref === null)
813
- return;
814
- const opened = await openConversation(host, ref, { kind: 'read' });
815
- const runner = chatRunner(ctx, request, session, generation, held);
816
- yield* wakeReply({ host, opened, runner, ...(input ? { input } : {}) });
817
- ctx.options.notifier?.publish(session.id);
340
+ const core = coreOf(ctx, chat, request);
341
+ const at = contextOf(ctx, request, session.id);
342
+ const reply = await core.wake(at, { ref: body.conversation, generation: body, input });
343
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
818
344
  }
819
345
  const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
820
346
  /**
@@ -856,139 +382,39 @@ async function notify(ctx, request, session, notifier) {
856
382
  });
857
383
  return new Response(stream, { headers: NDJSON_HEADERS });
858
384
  }
859
- /**
860
- * why: The transcript keeps a detached call as the turn left it. The session holds what became of
861
- * it, so a call that has ended does not read as running.
862
- */
863
- async function currentView(ctx, request, session, host, ref, conversation) {
864
- const view = conversationView(host, conversation);
865
- if (!view.transcript.some(isDetachedBlock))
866
- return view;
867
- const { operations } = await ctx.sessions.read(session.id);
868
- const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, request, block, operations, host) : block));
869
- const { notifier, notifyRetryMs } = ctx.options;
870
- return {
871
- ...view,
872
- transcript,
873
- ...(notifier && transcript.some(isDetachedBlock)
874
- ? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
875
- : {}),
876
- ...((await wakeDue(ctx, request, session, host, ref, conversation))
877
- ? { wake: true }
878
- : {}),
879
- };
880
- }
881
- /**
882
- * Whether the page wakes the chat now: the decider's policy tells a waiting result to a reply to no
883
- * message. Never while a reply waits on gates: the answer that goes on reads what waits.
884
- */
885
- async function wakeDue(ctx, request, session, host, ref, conversation) {
886
- const decider = ctx.options.lateResultsDecider;
887
- if (!decider || conversation.paused)
888
- return false;
889
- const chat = chatInbox(ctx, request, session, host, { ref, conversation });
890
- const { items } = await chat.inbox.read(chat.key);
891
- if (items.length === 0)
892
- return false;
893
- const { tell } = await decider.policy(items, {
894
- stage: 'pre_turn',
895
- step: 0,
896
- opening: 'wake',
897
- host: await ctx.options.host?.(request),
898
- });
899
- return tell.length > 0;
900
- }
901
- function isDetachedBlock(block) {
902
- return block.kind === 'tool' && block.tool.state?.phase === 'background';
903
- }
904
- /** A detached call's block as its operation stands. One the session no longer holds has no known end. */
905
- async function lateBlock(ctx, request, block, operations, host) {
906
- const { tool } = block;
907
- const id = tool.operationId;
908
- const operation = id && Object.hasOwn(operations, id) ? operations[id] : undefined;
909
- if (operation?.status === 'running' || operation?.status === 'background')
910
- return block;
911
- const { labels } = ctx.profile;
912
- if (operation?.status === 'settled' &&
913
- ctx.options.authorizeToolReplay &&
914
- !(await ctx.options.authorizeToolReplay({ request, operation }))) {
915
- const message = labelText('error.blocked', {}, labels);
916
- const failure = { code: 'outcome_withheld', kind: 'blocked', message };
917
- const { name, callId } = tool;
918
- const at = operation.settledAt;
919
- return {
920
- ...block,
921
- tool: {
922
- ...tool,
923
- state: { name, callId, at, phase: 'error', failure, readBack: message },
924
- endedAt: at,
925
- },
926
- };
927
- }
928
- if (operation?.status === 'settled') {
929
- const settled = host.forReader(operation.outcome.event);
930
- if (settled.type !== 'tool')
931
- return block;
932
- const { tool: state } = settled;
933
- if (!('phase' in state) || (state.phase !== 'complete' && state.phase !== 'error'))
934
- return block;
935
- return { ...block, tool: { ...tool, state, endedAt: operation.settledAt } };
936
- }
937
- const { name, callId } = tool;
938
- const unresolved = detachedEnd({ operationId: id ?? '', callId, name, at: tool.state?.at ?? Date.now() }, operation, labels);
939
- if (!unresolved)
940
- return block;
941
- const { operationId: _id, ...state } = unresolved.event.tool;
942
- return { ...block, tool: { ...tool, state, endedAt: state.at } };
943
- }
944
385
  /** The conversation cut after one block; a reply that waits on gates is walked away from first. */
945
- async function rewind(ctx, request, session) {
386
+ async function rewind(ctx, chat, request, session) {
946
387
  const body = await readBody(request, theoremRewindRequestSchema, ctx.options.maxRequestBytes);
947
- const host = conversationHost(ctx, session);
948
- if (!host)
949
- throw statelessRefusal('rewind');
950
- const opened = await openConversation(host, body.conversation, { kind: 'rewind', at: body.at });
951
- const waiting = waitingCalls(opened.conversation);
952
- const walkAway = waiting.length
953
- ? await takeWalkedAway(ctx, request, session, waiting, opened.conversation)
954
- : undefined;
955
- const next = await rewindConversation({
956
- host,
957
- opened,
388
+ const rewound = await coreOf(ctx, chat, request).rewind(contextOf(ctx, request, session.id), {
389
+ ref: body.conversation,
958
390
  at: body.at,
959
- ...(walkAway ? { walkAway } : {}),
960
391
  });
961
- if (next.ref === null)
962
- throw new TheoremError('internal', labelText('error.internal'));
963
- const rewound = {
964
- conversation: next.ref,
965
- view: await currentView(ctx, request, session, host, next.ref, next.conversation),
966
- };
967
392
  return jsonResponse(200, rewound);
968
393
  }
969
- async function* invokeEvents(ctx, request, session, answered) {
970
- const events = settleAnswered(ctx, request, session, answered);
971
- const { pending, answer } = answered;
972
- yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
973
- profileId: ctx.profile.id,
974
- turnInput: pending.turnInput,
975
- model: pending.model,
976
- promoted: pending.promoted,
977
- }, [
978
- {
979
- type: 'tool',
980
- tool: {
981
- name: pending.name,
982
- callId: pending.callId,
983
- operationId: pending.operationId,
984
- arguments: jsonObjectSchema.parse(answer.input),
985
- },
986
- },
987
- ]);
988
- }
989
- async function steer(ctx, request, session) {
394
+ async function steer(ctx, chat, request, session) {
990
395
  const body = await readBody(request, theoremSteerRequestSchema, ctx.options.maxRequestBytes);
991
- if (!(await ctx.inbox.enqueue(inboxKey(session.id, body.turnId), steerUnitOf(body)))) {
396
+ const core = coreOf(ctx, chat, request);
397
+ const at = contextOf(ctx, request, session.id);
398
+ if (ctx.options.intake) {
399
+ const message = {
400
+ ...(body.conversation === undefined ? {} : { ref: body.conversation }),
401
+ input: body.input,
402
+ };
403
+ const taken = await savedMessage(ctx.options.intake, core, at, { id: body.id, message });
404
+ if (taken.outcome === 'opened') {
405
+ const run = { ref: taken.ref, hold: taken.hold };
406
+ const { onContinue } = ctx.options;
407
+ const who = onContinue
408
+ ? await onContinue(run, { request, sessionId: at.sessionId })
409
+ : 'let_go';
410
+ // why: A steer has no stream for a reply, so `here` is the page's own wake.
411
+ if (who !== 'taken')
412
+ await core.release(at, run);
413
+ }
414
+ const saved = { conversation: taken.ref, landsAs: [...taken.landsAs] };
415
+ return jsonResponse(200, { ok: true, saved });
416
+ }
417
+ if (!(await core.steer(at, { turnId: body.turnId, unit: steerUnitOf(body) }))) {
992
418
  // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
993
419
  throw new TheoremError('request', `turn ${body.turnId} is not running`, {
994
420
  copy: { key: 'session.turn_ended' },
@@ -997,9 +423,10 @@ async function steer(ctx, request, session) {
997
423
  return jsonResponse(200, { ok: true });
998
424
  }
999
425
  /** Stops a running turn where it stands; its stream goes on to save and send what the reply left. */
1000
- async function stop(ctx, request, session) {
426
+ async function stop(ctx, chat, request, session) {
1001
427
  const body = await readBody(request, theoremStopRequestSchema, ctx.options.maxRequestBytes);
1002
- if (!(await ctx.inbox.stop(inboxKey(session.id, body.turnId)))) {
428
+ const core = coreOf(ctx, chat, request);
429
+ if (!(await core.stop(contextOf(ctx, request, session.id), { turnId: body.turnId }))) {
1003
430
  // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
1004
431
  throw new TheoremError('request', `turn ${body.turnId} is not running`, {
1005
432
  copy: { key: 'session.turn_ended' },
@@ -1007,38 +434,6 @@ async function stop(ctx, request, session) {
1007
434
  }
1008
435
  return jsonResponse(200, { ok: true });
1009
436
  }
1010
- /** One call of one of a host's tools, run as the page asked it; a gate it pauses on waits in the session. */
1011
- async function* callEvents(ctx, request, session, body) {
1012
- const state = await ctx.sessions.read(session.id);
1013
- const host = await ctx.options.host?.(request);
1014
- const events = invokeTool({
1015
- profile: ctx.profile.id,
1016
- execution: sessionToolCoordinator(ctx.sessions, session.id),
1017
- ...backgroundWiring(ctx, request, session.id),
1018
- pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
1019
- name: body.name,
1020
- input: body.input,
1021
- sessionPermissions: state.permissions,
1022
- credentials: sessionCredentials(ctx, session.id),
1023
- ...(ctx.options.onStage ? { onStage: ctx.options.onStage } : {}),
1024
- signal: request.signal,
1025
- host,
1026
- });
1027
- yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
1028
- profileId: ctx.profile.id,
1029
- turnInput: {},
1030
- });
1031
- }
1032
- function answerRequest(body) {
1033
- return {
1034
- callId: body.gateId,
1035
- operationId: body.operationId,
1036
- decision: body.decision,
1037
- input: body.input,
1038
- secret: body.secret,
1039
- page: body.page,
1040
- };
1041
- }
1042
437
  /** A route this profile doesn't serve. */
1043
438
  function refused(ctx) {
1044
439
  return jsonResponse(HTTP_NOT_FOUND, {
@@ -1046,26 +441,6 @@ function refused(ctx) {
1046
441
  errorKind: 'not_found',
1047
442
  });
1048
443
  }
1049
- async function* replayOperation(ctx, request, operation) {
1050
- const tool = defaultKernelScope.tools.get(operation.toolId);
1051
- if (operation.profileId !== ctx.profile.id ||
1052
- !tool ||
1053
- tool.type === 'builtin' ||
1054
- !('tools' in ctx.profile) ||
1055
- !ctx.profile.tools?.allow.includes(operation.toolId) ||
1056
- (operation.status === 'settled' &&
1057
- ctx.options.authorizeToolReplay &&
1058
- !(await ctx.options.authorizeToolReplay({ request, operation }))))
1059
- throw new TheoremError('blocked', labelText('error.blocked'));
1060
- authorizeToolReplay({
1061
- tools: defaultKernelScope.tools,
1062
- profile: ctx.profile,
1063
- name: operation.toolId,
1064
- resume: undefined,
1065
- ...(operation.status === 'settled' ? { outcome: operation.outcome } : {}),
1066
- });
1067
- yield* once(operation.status === 'settled' ? operation.outcome.event : operation.reply.event, ctx.profile.labels);
1068
- }
1069
444
  /**
1070
445
  * The user's answer to a paused call. In a kept conversation the reply goes on
1071
446
  * in the same stream once no call waits; otherwise the stream is the call's.
@@ -1074,61 +449,14 @@ async function invoke(ctx, request, session) {
1074
449
  const body = await readBody(request, theoremInvokeRequestSchema, ctx.options.maxRequestBytes);
1075
450
  if (body.page && 'output' in body.page)
1076
451
  throw new TheoremError('request', labelText('error.request'));
1077
- const host = conversationHost(ctx, session);
1078
- if (!host) {
1079
- if (body.conversation !== undefined)
1080
- throw statelessRefusal('continue');
1081
- return eventStream(ctx, request, await settlingOf(ctx, request, session, body));
1082
- }
1083
- if (body.conversation === undefined)
1084
- throw unknownConversation();
1085
- const call = { callId: body.gateId, operationId: body.operationId };
1086
- const opened = await openConversation(host, body.conversation, { kind: 'answer', call });
1087
- const settling = await settlingOf(ctx, request, session, body);
1088
- const paused = opened.conversation.paused?.reply;
1089
- return eventStream(ctx, request, () => heldLines(ctx, request, session, host, opened, { opening: 'message', takeOver: true }, (held) => answered(held, paused, () => answerReply({
1090
- host,
1091
- opened,
1092
- call,
1093
- settling: settling(),
1094
- runner: chatRunner(ctx, request, session, body, held),
1095
- }))));
1096
- }
1097
- /** The answer's reply, handed first what the paused reply read, so it tells them as it goes on. */
1098
- async function* answered(held, paused, reply) {
1099
- if (held && paused)
1100
- await held.run.resume(paused);
1101
- yield* reply();
1102
- }
1103
- /** The answered call's events: its saved outcome again, or the call run as answered. */
1104
- async function settlingOf(ctx, request, session, body) {
1105
- const saved = await ctx.sessions.read(session.id);
1106
- const operation = Object.hasOwn(saved.operations, body.operationId)
1107
- ? saved.operations[body.operationId]
1108
- : undefined;
1109
- if (operation &&
1110
- operation.status !== 'ready' &&
1111
- operation.callId === body.gateId &&
1112
- operation.profileId === ctx.profile.id &&
1113
- (operation.status === 'running' || operation.status === 'uncertain')) {
1114
- throw new TheoremError('conflict', `The tool operation is ${operation.status}, so it does not run again until the host settles it`, // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
1115
- { copy: { key: 'tool.execution_uncertain' } });
1116
- }
1117
- if ((operation?.status === 'settled' || operation?.status === 'background') &&
1118
- operation.profileId === ctx.profile.id &&
1119
- operation.callId === body.gateId) {
1120
- if (body.input !== undefined &&
1121
- (!operation.invocation ||
1122
- (await toolInvocationHash(body.input)) !==
1123
- (await toolInvocationHash(operation.invocation.accepted.input))))
1124
- throw new TheoremError('request', labelText('error.request'), {
1125
- copy: { key: 'error.request' },
1126
- });
1127
- return () => replayOperation(ctx, request, operation);
452
+ const at = contextOf(ctx, request, session.id);
453
+ if (!ctx.chat) {
454
+ const lines = await unconversedAnswer(callsOf(ctx, request), at, body);
455
+ return eventStream(ctx, request, () => lines);
1128
456
  }
1129
- // why: Take the answered call before streaming, so a stale answer is a reply status, not a stream error.
1130
- const answered = await ctx.sessions.mutate(session.id, (state) => answerPendingGate(state, answerRequest(body), ctx.profile.id));
1131
- return () => invokeEvents(ctx, request, session, answered);
457
+ const core = coreOf(ctx, ctx.chat, request);
458
+ const reply = await core.answer(at, body);
459
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
1132
460
  }
1133
461
  async function hostRoute(ctx, request, session) {
1134
462
  const target = routeOf(request);
@@ -1136,7 +464,7 @@ async function hostRoute(ctx, request, session) {
1136
464
  return jsonResponse(200, { interface: hostInterface(ctx.profile, hostTool) });
1137
465
  if (request.method === 'POST' && target === 'call') {
1138
466
  const body = await readBody(request, theoremHostCallRequestSchema, ctx.options.maxRequestBytes);
1139
- return eventStream(ctx, request, () => callEvents(ctx, request, session, body));
467
+ return eventStream(ctx, request, () => callEvents(callsOf(ctx, request), contextOf(ctx, request, session.id), body));
1140
468
  }
1141
469
  if (request.method === 'POST' && target === 'invoke')
1142
470
  return invoke(ctx, request, session);
@@ -1165,7 +493,7 @@ async function route(ctx, request, session) {
1165
493
  if (target === 'invoke')
1166
494
  return invoke(ctx, request, session);
1167
495
  if (target === 'conversation')
1168
- return conversation(ctx, request, session);
496
+ return conversation(ctx, chat, request, session);
1169
497
  if (target === 'notify') {
1170
498
  const { notifier } = ctx.options;
1171
499
  if (!notifier || !chat.conversations)
@@ -1173,42 +501,28 @@ async function route(ctx, request, session) {
1173
501
  return notify(ctx, request, session, notifier);
1174
502
  }
1175
503
  if (target === 'rewind')
1176
- return rewind(ctx, request, session);
504
+ return rewind(ctx, chat, request, session);
1177
505
  if (target === 'wake')
1178
- return wake(ctx, request, session);
506
+ return wake(ctx, chat, request, session);
1179
507
  if (target === 'stop')
1180
- return stop(ctx, request, session);
1181
- return steer(ctx, request, session);
508
+ return stop(ctx, chat, request, session);
509
+ return steer(ctx, chat, request, session);
1182
510
  }
1183
511
  export function createTheoremHandler(options) {
1184
- const profile = defineProfile(options.profile);
1185
- if (profile.type === 'decision') {
1186
- // labels-exempt: builder config error at setup; no user sees it
1187
- throw new Error("createTheoremHandler serves turn-based profiles; serve type 'decision' with createTheoremDecisionHandler.");
1188
- }
1189
- if (profile.type === 'host') {
512
+ const chat = chatOf('createTheoremHandler', options.profile, options.conversationStore);
513
+ oneInbox(options);
514
+ if (options.intake && !options.inbox) {
1190
515
  // labels-exempt: builder config error at setup; no user sees it
1191
- throw new Error("createTheoremHandler serves turn-based profiles; serve type 'host' with createTheoremHostHandler.");
516
+ throw new TheoremError('config', 'createTheoremHandler needs `inbox` with `intake`');
1192
517
  }
1193
- if (profile.type === 'live' || profile.type === 'embedding') {
1194
- // labels-exempt: builder config error at setup; no user sees it
1195
- throw new Error(`createTheoremHandler serves turn-based profiles; got type '${profile.type}'.`);
1196
- }
1197
- const stateless = profile.providerContinuation?.history === 'stateless';
1198
- if (stateless === (options.conversationStore !== undefined)) {
1199
- throw new TheoremError('config', labelText('error.config'), {
1200
- cause: {
1201
- code: stateless ? 'conversation_store_stateless' : 'conversation_store_missing',
1202
- profile: profile.id,
1203
- },
1204
- });
1205
- }
1206
- return serve('createTheoremHandler', profile, options, {
518
+ const { prepare, inbox, beforeSave, afterSave, compact } = options;
519
+ return serve('createTheoremHandler', chat.profile, options, {
1207
520
  steerInbox: options.steerInbox,
1208
- chat: {
1209
- profile,
1210
- ...(options.conversationStore ? { conversations: options.conversationStore } : {}),
1211
- },
521
+ chat,
522
+ wire: (state) => createConversationCore({
523
+ ...state,
524
+ options: { ...state.options, prepare, inbox, beforeSave, afterSave, compact },
525
+ }),
1212
526
  });
1213
527
  }
1214
528
  /**
@@ -1232,33 +546,14 @@ export function hostTool(name) {
1232
546
  const registered = defaultKernelScope.tools.get(name);
1233
547
  return registered?.type === 'builtin' ? undefined : registered;
1234
548
  }
1235
- function checkNotifyRetry(ms) {
1236
- if (ms === undefined || (Number.isFinite(ms) && ms >= 0))
1237
- return;
1238
- throw new TheoremError('config', labelText('error.config'), {
1239
- cause: { code: 'notify_retry' },
1240
- });
1241
- }
1242
549
  function serve(name, profile, options, chatOptions = {}) {
1243
- const gateTtlMs = resolveGateTtlMs(name, options.gateTtlMs);
1244
- const operationRetentionMs = options.operationRetentionMs ?? DEFAULT_OPERATION_RETENTION_MS;
1245
- if (!Number.isSafeInteger(operationRetentionMs) || operationRetentionMs <= 0) {
1246
- throw new TheoremError('config', labelText('error.config'), {
1247
- cause: { code: 'operation_retention' },
1248
- });
1249
- }
1250
550
  requestByteLimit(options.maxRequestBytes);
1251
- checkPageToolTimeout(options.pageToolTimeoutMs);
1252
- checkNotifyRetry(options.notifyRetryMs);
1253
- registerProfile(profile);
1254
551
  const ctx = {
1255
552
  options,
1256
- pageToolBroker: options.pageToolBroker ?? createMemoryPageToolBroker(),
1257
- profile,
553
+ ...sessionParts(name, profile, options),
1258
554
  ...(chatOptions.chat ? { chat: chatOptions.chat } : {}),
1259
555
  inbox: chatOptions.steerInbox ?? createMemorySteerInbox(),
1260
- sessions: sessionStateStore(options.sessionStore ?? createMemorySessionStore(), gateTtlMs, operationRetentionMs),
1261
- credentials: lockedStore(options.credentialStore ?? createMemoryCredentialStore(), (saved = {}) => saved),
556
+ wire: chatOptions.wire ?? createConversationCore,
1262
557
  };
1263
558
  return async (request) => {
1264
559
  let session;