@theoremjs/web 0.3.5-next.979.g76aac35 → 0.3.5-next.981.gf4729de

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
  *
@@ -39,28 +38,21 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
39
38
  *
40
39
  * @module
41
40
  */
42
- import { authorizeToolReplay, compactHistory, defaultKernelScope, defineProfile, invokeTool, jsonObjectSchema, labelText, registerProfile, runTurn, TheoremError, toolInvocationHash, } from '@theoremjs/agents';
43
- import { runConversation } from '@theoremjs/agents/conversation';
41
+ import { defaultKernelScope, defineProfile, labelText, TheoremError, } from '@theoremjs/agents';
44
42
  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";
43
+ import { clientProfileInterface } from '@theoremjs/agents/interface';
44
+ import { hostInterface, theoremHostCallRequestSchema } from "../client/host-transport.js";
48
45
  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";
46
+ import { statelessRefusal } from "./conversation.js";
47
+ import { chatOf, createConversationCore, followedUp, oneInbox, unconversedAnswer, } from "./conversation-core.js";
48
+ import { callEvents, sessionParts } from "./session-calls.js";
54
49
  import { theoremSession } from "./session-identity.js";
55
50
  import { kernelTurnInput } from "./turn-input.js";
56
51
  export { theoremSession, theoremSessionId } from "./session-identity.js";
57
52
  import { jsonResponse } from "./json-response.js";
58
53
  import { boundedRequestJson, requestByteLimit } from "./request-body.js";
59
54
  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";
55
+ import { createMemorySteerInbox, steerUnitOf } from "./steer-inbox.js";
64
56
  const NDJSON_HEADERS = {
65
57
  'content-type': 'application/x-ndjson; charset=utf-8',
66
58
  'cache-control': 'no-store',
@@ -109,32 +101,6 @@ function routeOf(request) {
109
101
  ? last
110
102
  : '';
111
103
  }
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
104
  async function sessionOf(ctx, request) {
139
105
  if (!ctx.options.session)
140
106
  return theoremSession(request);
@@ -190,287 +156,74 @@ function providerFor(ctx, request, model) {
190
156
  return provider({ request, model });
191
157
  return provider;
192
158
  }
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) {
159
+ /** What a run reads in place of `request`. */
160
+ function contextOf(ctx, request, sessionId) {
161
+ let asked;
262
162
  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
- }),
163
+ sessionId,
164
+ signal: request.signal,
165
+ // why: The app's `host` is asked when a run first reads it, so a route that reads none asks
166
+ // none, and a reply and the app's steps around its save read the same value.
167
+ get host() {
168
+ asked ??= { host: ctx.options.host?.(request) };
169
+ return asked.host;
170
+ },
268
171
  };
269
172
  }
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 });
173
+ /** The session's calls as `request` runs them: each of the app's callbacks is given `request`. */
174
+ function callsOf(ctx, request) {
175
+ const { options } = ctx;
176
+ const { background, authorizeToolReplay, authorizationUrl } = options;
280
177
  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 }
178
+ profile: ctx.profile,
179
+ sessions: ctx.sessions,
180
+ credentials: ctx.credentials,
181
+ pageToolBroker: ctx.pageToolBroker,
182
+ options: {
183
+ prepare: options.prepare,
184
+ onStage: options.onStage,
185
+ pageToolTimeoutMs: options.pageToolTimeoutMs,
186
+ notifier: options.notifier,
187
+ lateResultsDecider: options.lateResultsDecider,
188
+ ...(background
189
+ ? { background: (at) => background({ request, sessionId: at.sessionId }) }
304
190
  : {}),
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(),
191
+ ...(authorizeToolReplay
192
+ ? { authorizeToolReplay: (_at, operation) => authorizeToolReplay({ request, operation }) }
193
+ : {}),
194
+ ...(authorizationUrl
195
+ ? {
196
+ authorizationUrl: (challenge, at) => authorizationUrl(challenge, { request, sessionId: at.sessionId }),
197
+ }
198
+ : {}),
199
+ onError: (err) => options.onError?.(err, { request }),
200
+ wake: (at, ref) => serverWake(ctx, request, at.sessionId, ref),
201
+ },
339
202
  };
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
203
  }
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,
204
+ /** The chat's conversation core as `request` runs it. */
205
+ function coreOf(ctx, chat, request) {
206
+ const calls = callsOf(ctx, request);
207
+ return ctx.wire({
208
+ ...calls,
209
+ chat,
210
+ steer: ctx.inbox,
211
+ options: {
212
+ ...calls.options,
213
+ provider: (_at, model) => providerFor(ctx, request, model),
214
+ conversationLeaseMs: ctx.options.conversationLeaseMs,
215
+ notifyRetryMs: ctx.options.notifyRetryMs,
216
+ clientEvents: ctx.options.clientEvents,
217
+ },
428
218
  });
429
219
  }
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
220
  /**
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.
221
+ * A page's run: when it ends with items that wait, `onContinue` says who runs the next reply.
222
+ * Unset, the chat is let go, and the page wakes it.
438
223
  */
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
- };
224
+ function pageRun(ctx, request, core, at, reply) {
225
+ const { onContinue } = ctx.options;
226
+ return followedUp(core, at, reply, (run) => onContinue ? onContinue(run, { request, sessionId: at.sessionId }) : 'let_go');
474
227
  }
475
228
  /**
476
229
  * The decider's wake, with no page: the reply runs on a request of its own, with the headers of
@@ -479,342 +232,114 @@ function announced(ctx, request, sessionId, service) {
479
232
  */
480
233
  async function serverWake(ctx, started, sessionId, ref) {
481
234
  const request = new Request(started.url, { headers: started.headers });
482
- const session = { id: sessionId };
483
- const host = conversationHost(ctx, session);
484
- if (!host)
235
+ if (!ctx.chat)
485
236
  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') {
237
+ const core = coreOf(ctx, ctx.chat, request);
238
+ const at = contextOf(ctx, request, sessionId);
239
+ // why: no page is open to wake the chat, so this wake runs each next reply itself
240
+ const lines = followedUp(core, at, await core.wake(at, { ref }), () => 'here');
241
+ // why: the run lets the chat go as it ends, so its lines are read to the end before a failure is thrown
242
+ let failed;
243
+ for (;;) {
244
+ const next = await lines.next();
245
+ if (next.done) {
246
+ if (failed)
247
+ throw failed;
248
+ if (next.value.outcome !== 'held')
249
+ return;
250
+ setTimeout(() => {
251
+ serverWake(ctx, started, sessionId, ref).catch((err) => ctx.options.onError?.(err, { request }));
252
+ }, Math.max(0, next.value.leasedUntil - Date.now()));
253
+ return;
254
+ }
255
+ if (next.value.type === 'error') {
494
256
  // 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');
257
+ failed ??= new TheoremError(next.value.errorKind, next.value.errorInternal ?? next.value.error ?? 'the wake failed');
496
258
  }
497
259
  }
498
260
  }
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
- },
261
+ /** The person's message: a new reply, run against the conversation the host keeps. */
262
+ async function turn(ctx, chat, request, session) {
263
+ const body = await readBody(request, theoremTurnRequestSchema, ctx.options.maxRequestBytes);
264
+ if (body.stated && !ctx.options.pageStatesTurn) {
265
+ throw new TheoremError('request', labelText('error.request'));
266
+ }
267
+ const context = await ctx.options.context?.(request);
268
+ const core = coreOf(ctx, chat, request);
269
+ const at = contextOf(ctx, request, session.id);
270
+ const message = {
271
+ ref: body.conversation,
272
+ input: body.input,
273
+ ...(context === undefined ? {} : { context }),
274
+ generation: body,
275
+ ...(body.abandon ? { abandon: body.abandon } : {}),
539
276
  };
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;
277
+ if (ctx.options.intake) {
278
+ if (body.id === undefined) {
279
+ // labels-exempt: internal diagnostic; the user reads error.request
280
+ throw new TheoremError('request', 'a message needs an `id` where the host saves it itself');
560
281
  }
561
- if (ended?.failed)
562
- throw ended.failure;
563
- if (ended)
564
- return;
565
- await new Promise((resolve) => {
566
- wake = resolve;
567
- });
282
+ const taken = await savedMessage(ctx.options.intake, core, at, { id: body.id, message });
283
+ return eventStream(ctx, request, () => taken.outcome === 'saved'
284
+ ? lines([savedLine(taken)])
285
+ : openedRun(ctx, request, core, at, taken, message));
568
286
  }
287
+ const reply = await core.message(at, message);
288
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
569
289
  }
570
290
  /**
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.
291
+ * The app's save of a message, after the checks that can refuse it.
292
+ * invariant: Nothing refuses a message the app has saved, so the page never takes a saved message back.
576
293
  */
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
- });
294
+ async function savedMessage(intake, core, at, sent) {
295
+ await core.checkMessage(at, sent.message);
296
+ const { ref, input } = sent.message;
297
+ return intake(at, { id: sent.id, ...(ref === undefined ? {} : { ref }), message: input });
624
298
  }
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;
299
+ /** The line that tells the page the app saved its message, and how a reply names it. */
300
+ function savedLine(taken) {
301
+ return { type: 'conversation', ref: taken.ref, posted: true, landsAs: [...taken.landsAs] };
629
302
  }
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
- }
303
+ async function* lines(values) {
304
+ yield* values;
692
305
  }
693
306
  /**
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.
307
+ * The reply to a message whose save took the conversation. The saved line goes first: whatever
308
+ * the reply does after it, the message stays saved.
696
309
  */
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'));
310
+ async function* openedRun(ctx, request, core, at, taken, message) {
311
+ const { ref, hold, blocks } = taken;
312
+ yield savedLine(taken);
313
+ let reply;
314
+ try {
315
+ reply = await core.message(at, { ...message, ref, saved: { hold, blocks } });
740
316
  }
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
- }));
317
+ catch (err) {
318
+ // why: No reply took the hold, so the handler lets the conversation go for the next one.
319
+ await core.release(at, { ref, hold });
320
+ throw err;
756
321
  }
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
- })));
322
+ yield* pageRun(ctx, request, core, at, reply);
772
323
  }
773
324
  /** The conversation as the browser draws it. */
774
- async function conversation(ctx, request, session) {
325
+ async function conversation(ctx, chat, request, session) {
775
326
  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));
327
+ const view = await coreOf(ctx, chat, request).read(contextOf(ctx, request, session.id), {
328
+ ref: body.conversation,
329
+ });
330
+ return jsonResponse(200, view);
781
331
  }
782
332
  /**
783
333
  * A reply to no message, for results that ended since the model last ran. It runs under a hold of
784
334
  * the chat, so two pages that wake at once run it once, and reads what the decider's policy tells.
785
335
  */
786
- async function wake(ctx, request, session) {
336
+ async function wake(ctx, chat, request, session) {
787
337
  const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
788
338
  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);
339
+ const core = coreOf(ctx, chat, request);
340
+ const at = contextOf(ctx, request, session.id);
341
+ const reply = await core.wake(at, { ref: body.conversation, generation: body, input });
342
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
818
343
  }
819
344
  const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
820
345
  /**
@@ -856,139 +381,39 @@ async function notify(ctx, request, session, notifier) {
856
381
  });
857
382
  return new Response(stream, { headers: NDJSON_HEADERS });
858
383
  }
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
384
  /** The conversation cut after one block; a reply that waits on gates is walked away from first. */
945
- async function rewind(ctx, request, session) {
385
+ async function rewind(ctx, chat, request, session) {
946
386
  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,
387
+ const rewound = await coreOf(ctx, chat, request).rewind(contextOf(ctx, request, session.id), {
388
+ ref: body.conversation,
958
389
  at: body.at,
959
- ...(walkAway ? { walkAway } : {}),
960
390
  });
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
391
  return jsonResponse(200, rewound);
968
392
  }
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) {
393
+ async function steer(ctx, chat, request, session) {
990
394
  const body = await readBody(request, theoremSteerRequestSchema, ctx.options.maxRequestBytes);
991
- if (!(await ctx.inbox.enqueue(inboxKey(session.id, body.turnId), steerUnitOf(body)))) {
395
+ const core = coreOf(ctx, chat, request);
396
+ const at = contextOf(ctx, request, session.id);
397
+ if (ctx.options.intake) {
398
+ const message = {
399
+ ...(body.conversation === undefined ? {} : { ref: body.conversation }),
400
+ input: body.input,
401
+ };
402
+ const taken = await savedMessage(ctx.options.intake, core, at, { id: body.id, message });
403
+ if (taken.outcome === 'opened') {
404
+ const run = { ref: taken.ref, hold: taken.hold };
405
+ const { onContinue } = ctx.options;
406
+ const who = onContinue
407
+ ? await onContinue(run, { request, sessionId: at.sessionId })
408
+ : 'let_go';
409
+ // why: A steer has no stream for a reply, so `here` is the page's own wake.
410
+ if (who !== 'taken')
411
+ await core.release(at, run);
412
+ }
413
+ const saved = { conversation: taken.ref, landsAs: [...taken.landsAs] };
414
+ return jsonResponse(200, { ok: true, saved });
415
+ }
416
+ if (!(await core.steer(at, { turnId: body.turnId, unit: steerUnitOf(body) }))) {
992
417
  // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
993
418
  throw new TheoremError('request', `turn ${body.turnId} is not running`, {
994
419
  copy: { key: 'session.turn_ended' },
@@ -997,9 +422,10 @@ async function steer(ctx, request, session) {
997
422
  return jsonResponse(200, { ok: true });
998
423
  }
999
424
  /** 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) {
425
+ async function stop(ctx, chat, request, session) {
1001
426
  const body = await readBody(request, theoremStopRequestSchema, ctx.options.maxRequestBytes);
1002
- if (!(await ctx.inbox.stop(inboxKey(session.id, body.turnId)))) {
427
+ const core = coreOf(ctx, chat, request);
428
+ if (!(await core.stop(contextOf(ctx, request, session.id), { turnId: body.turnId }))) {
1003
429
  // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
1004
430
  throw new TheoremError('request', `turn ${body.turnId} is not running`, {
1005
431
  copy: { key: 'session.turn_ended' },
@@ -1007,38 +433,6 @@ async function stop(ctx, request, session) {
1007
433
  }
1008
434
  return jsonResponse(200, { ok: true });
1009
435
  }
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
436
  /** A route this profile doesn't serve. */
1043
437
  function refused(ctx) {
1044
438
  return jsonResponse(HTTP_NOT_FOUND, {
@@ -1046,26 +440,6 @@ function refused(ctx) {
1046
440
  errorKind: 'not_found',
1047
441
  });
1048
442
  }
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
443
  /**
1070
444
  * The user's answer to a paused call. In a kept conversation the reply goes on
1071
445
  * in the same stream once no call waits; otherwise the stream is the call's.
@@ -1074,61 +448,14 @@ async function invoke(ctx, request, session) {
1074
448
  const body = await readBody(request, theoremInvokeRequestSchema, ctx.options.maxRequestBytes);
1075
449
  if (body.page && 'output' in body.page)
1076
450
  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);
451
+ const at = contextOf(ctx, request, session.id);
452
+ if (!ctx.chat) {
453
+ const lines = await unconversedAnswer(callsOf(ctx, request), at, body);
454
+ return eventStream(ctx, request, () => lines);
1128
455
  }
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);
456
+ const core = coreOf(ctx, ctx.chat, request);
457
+ const reply = await core.answer(at, body);
458
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
1132
459
  }
1133
460
  async function hostRoute(ctx, request, session) {
1134
461
  const target = routeOf(request);
@@ -1136,7 +463,7 @@ async function hostRoute(ctx, request, session) {
1136
463
  return jsonResponse(200, { interface: hostInterface(ctx.profile, hostTool) });
1137
464
  if (request.method === 'POST' && target === 'call') {
1138
465
  const body = await readBody(request, theoremHostCallRequestSchema, ctx.options.maxRequestBytes);
1139
- return eventStream(ctx, request, () => callEvents(ctx, request, session, body));
466
+ return eventStream(ctx, request, () => callEvents(callsOf(ctx, request), contextOf(ctx, request, session.id), body));
1140
467
  }
1141
468
  if (request.method === 'POST' && target === 'invoke')
1142
469
  return invoke(ctx, request, session);
@@ -1165,7 +492,7 @@ async function route(ctx, request, session) {
1165
492
  if (target === 'invoke')
1166
493
  return invoke(ctx, request, session);
1167
494
  if (target === 'conversation')
1168
- return conversation(ctx, request, session);
495
+ return conversation(ctx, chat, request, session);
1169
496
  if (target === 'notify') {
1170
497
  const { notifier } = ctx.options;
1171
498
  if (!notifier || !chat.conversations)
@@ -1173,42 +500,28 @@ async function route(ctx, request, session) {
1173
500
  return notify(ctx, request, session, notifier);
1174
501
  }
1175
502
  if (target === 'rewind')
1176
- return rewind(ctx, request, session);
503
+ return rewind(ctx, chat, request, session);
1177
504
  if (target === 'wake')
1178
- return wake(ctx, request, session);
505
+ return wake(ctx, chat, request, session);
1179
506
  if (target === 'stop')
1180
- return stop(ctx, request, session);
1181
- return steer(ctx, request, session);
507
+ return stop(ctx, chat, request, session);
508
+ return steer(ctx, chat, request, session);
1182
509
  }
1183
510
  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') {
511
+ const chat = chatOf('createTheoremHandler', options.profile, options.conversationStore);
512
+ oneInbox(options);
513
+ if (options.intake && !options.inbox) {
1190
514
  // 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.");
515
+ throw new TheoremError('config', 'createTheoremHandler needs `inbox` with `intake`');
1192
516
  }
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, {
517
+ const { prepare, inbox, beforeSave, afterSave, compact } = options;
518
+ return serve('createTheoremHandler', chat.profile, options, {
1207
519
  steerInbox: options.steerInbox,
1208
- chat: {
1209
- profile,
1210
- ...(options.conversationStore ? { conversations: options.conversationStore } : {}),
1211
- },
520
+ chat,
521
+ wire: (state) => createConversationCore({
522
+ ...state,
523
+ options: { ...state.options, prepare, inbox, beforeSave, afterSave, compact },
524
+ }),
1212
525
  });
1213
526
  }
1214
527
  /**
@@ -1232,33 +545,14 @@ export function hostTool(name) {
1232
545
  const registered = defaultKernelScope.tools.get(name);
1233
546
  return registered?.type === 'builtin' ? undefined : registered;
1234
547
  }
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
548
  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
549
  requestByteLimit(options.maxRequestBytes);
1251
- checkPageToolTimeout(options.pageToolTimeoutMs);
1252
- checkNotifyRetry(options.notifyRetryMs);
1253
- registerProfile(profile);
1254
550
  const ctx = {
1255
551
  options,
1256
- pageToolBroker: options.pageToolBroker ?? createMemoryPageToolBroker(),
1257
- profile,
552
+ ...sessionParts(name, profile, options),
1258
553
  ...(chatOptions.chat ? { chat: chatOptions.chat } : {}),
1259
554
  inbox: chatOptions.steerInbox ?? createMemorySteerInbox(),
1260
- sessions: sessionStateStore(options.sessionStore ?? createMemorySessionStore(), gateTtlMs, operationRetentionMs),
1261
- credentials: lockedStore(options.credentialStore ?? createMemoryCredentialStore(), (saved = {}) => saved),
555
+ wire: chatOptions.wire ?? createConversationCore,
1262
556
  };
1263
557
  return async (request) => {
1264
558
  let session;