@theoremjs/web 0.3.4 → 0.3.5-next.1000.g569f044

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.
Files changed (59) hide show
  1. package/README.md +330 -13
  2. package/client/chat.d.ts +14 -2
  3. package/client/chat.js +302 -34
  4. package/client/composer-hints.d.ts +18 -10
  5. package/client/composer-hints.js +23 -6
  6. package/client/host-transport.d.ts +7 -2
  7. package/client/host-transport.js +9 -3
  8. package/client/index.d.ts +4 -4
  9. package/client/index.js +3 -3
  10. package/client/page-dispatch.js +5 -0
  11. package/client/run-session.d.ts +27 -2
  12. package/client/run-session.js +34 -4
  13. package/client/schema-fields.d.ts +28 -1
  14. package/client/schema-fields.js +172 -13
  15. package/client/tool-result.d.ts +9 -5
  16. package/client/tool-result.js +23 -42
  17. package/client/transcript-schema.d.ts +4 -0
  18. package/client/transcript-schema.js +25 -6
  19. package/client/transport.d.ts +90 -9
  20. package/client/transport.js +56 -11
  21. package/client/turn-client.d.ts +8 -2
  22. package/client/turn-client.js +9 -0
  23. package/package.json +2 -2
  24. package/server/conversation-core.d.ts +273 -0
  25. package/server/conversation-core.js +797 -0
  26. package/server/conversation-inbox.d.ts +45 -0
  27. package/server/conversation-inbox.js +240 -0
  28. package/server/conversation-store.d.ts +43 -2
  29. package/server/conversation-store.js +15 -2
  30. package/server/conversation.d.ts +82 -2
  31. package/server/conversation.js +357 -60
  32. package/server/create-conversation-core.d.ts +28 -0
  33. package/server/create-conversation-core.js +46 -0
  34. package/server/embedding-handler.js +2 -0
  35. package/server/handler.d.ts +84 -20
  36. package/server/handler.js +279 -659
  37. package/server/mcp-handler.js +25 -11
  38. package/server/mod.d.ts +11 -4
  39. package/server/mod.js +6 -2
  40. package/server/notifier.d.ts +3 -2
  41. package/server/notifier.js +3 -2
  42. package/server/session-authority.d.ts +3 -1
  43. package/server/session-authority.js +26 -1
  44. package/server/session-boundary.d.ts +5 -3
  45. package/server/session-boundary.js +2 -2
  46. package/server/session-calls.d.ts +122 -0
  47. package/server/session-calls.js +512 -0
  48. package/server/session-store.d.ts +33 -0
  49. package/server/session-store.js +37 -2
  50. package/server/steer-inbox.d.ts +3 -4
  51. package/server/steer-inbox.js +6 -5
  52. package/server/tell-every-result.d.ts +11 -0
  53. package/server/tell-every-result.js +17 -0
  54. package/server/tool-operations.d.ts +8 -0
  55. package/server/tool-operations.js +71 -0
  56. package/server/turn-input.d.ts +4 -2
  57. package/server/turn-input.js +5 -2
  58. package/server/turn-wiring.d.ts +31 -6
  59. package/server/turn-wiring.js +59 -5
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,9 +13,12 @@ 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
+ * - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
21
+ * background calls that ended since it last ran. Empty when none waits
20
22
  *
21
23
  * `createTheoremHostHandler` serves a host profile the same way, with no model:
22
24
  *
@@ -37,25 +39,21 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
37
39
  *
38
40
  * @module
39
41
  */
40
- import { authorizeToolReplay, compactHistory, defaultKernelScope, defineProfile, invokeTool, jsonObjectSchema, labelText, registerProfile, runTurn, TheoremError, toolInvocationHash, } from '@theoremjs/agents';
42
+ import { defaultKernelScope, defineProfile, labelText, TheoremError, } from '@theoremjs/agents';
41
43
  import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremjs/agents/host';
42
- import { clientProfileInterface, gatedToolsFromEvents, interfaceFromProfile, promotedToolIdsFromEvents, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
43
- import { answerGatedCall, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
44
- import { hostInterface, theoremHostCallRequestSchema, } from "../client/host-transport.js";
45
- import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, } from "../client/transport.js";
46
- import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, } from "./conversation.js";
47
- import { unknownConversation, } from "./conversation-store.js";
48
- import { createMemoryCredentialStore, } from "./credential-store.js";
49
- import { sessionStateStore, } from "./session-authority.js";
44
+ import { blockWithoutToolData, clientProfileInterface, eventWithoutToolData, profileShowsToolData, } from '@theoremjs/agents/interface';
45
+ import { hostInterface, theoremHostCallRequestSchema } from "../client/host-transport.js";
46
+ import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
47
+ import { statelessRefusal } from "./conversation.js";
48
+ import { chatOf, createConversationCore, followedUp, oneInbox, replyUnreachable, unconversedAnswer, } from "./conversation-core.js";
49
+ import { callEvents, sessionParts } from "./session-calls.js";
50
50
  import { theoremSession } from "./session-identity.js";
51
+ import { kernelTurnInput } from "./turn-input.js";
51
52
  export { theoremSession, theoremSessionId } from "./session-identity.js";
52
53
  import { jsonResponse } from "./json-response.js";
53
54
  import { boundedRequestJson, requestByteLimit } from "./request-body.js";
54
55
  import { checkRequest } from "./request-check.js";
55
- import { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, } from "./session-store.js";
56
- import { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
57
- import { sameAcceptedAnswer, sessionToolCoordinator } from "./tool-operations.js";
58
- import { preparedTurn, stagesInOrder } from "./turn-wiring.js";
56
+ import { createMemorySteerInbox } from "./steer-inbox.js";
59
57
  const NDJSON_HEADERS = {
60
58
  'content-type': 'application/x-ndjson; charset=utf-8',
61
59
  'cache-control': 'no-store',
@@ -98,37 +96,12 @@ function routeOf(request) {
98
96
  last === 'conversation' ||
99
97
  last === 'notify' ||
100
98
  last === 'rewind' ||
99
+ last === 'wake' ||
101
100
  last === 'call' ||
102
101
  last === 'page-result'
103
102
  ? last
104
103
  : '';
105
104
  }
106
- function lockedStore(store, loaded) {
107
- const locks = new Map();
108
- const read = async (sessionId) => loaded(await store.load(sessionId));
109
- return {
110
- read,
111
- mutate(sessionId, change) {
112
- const next = (locks.get(sessionId) ?? Promise.resolve()).then(async () => {
113
- const value = await read(sessionId);
114
- const result = change(value);
115
- await store.save(sessionId, value);
116
- return result;
117
- });
118
- const settled = next.catch(() => { });
119
- locks.set(sessionId, settled);
120
- void settled.then(() => {
121
- if (locks.get(sessionId) === settled)
122
- locks.delete(sessionId);
123
- });
124
- return next;
125
- },
126
- };
127
- }
128
- /** The profile as the server reads a message against it, its tools as registered now. */
129
- function chatInterface(chat) {
130
- return interfaceFromProfile(chat.profile, defaultKernelScope.tools);
131
- }
132
105
  async function sessionOf(ctx, request) {
133
106
  if (!ctx.options.session)
134
107
  return theoremSession(request);
@@ -146,6 +119,33 @@ function caughtError(ctx, err, request) {
146
119
  ctx.options.onError?.(err, { request });
147
120
  return clientError(err, ctx.profile.labels, ctx.options.clientEvents);
148
121
  }
122
+ /** A line as the page may have it: under `tools.showData: false`, none of a tool call's data. */
123
+ function shownLine(ctx, line) {
124
+ if (line.type === 'conversation')
125
+ return line;
126
+ const event = forClient(line, ctx.options.clientEvents);
127
+ return profileShowsToolData(ctx.profile) ? event : eventWithoutToolData(event);
128
+ }
129
+ /** The conversation as the page may have it, by `shownLine`'s rule. */
130
+ function shownView(ctx, view) {
131
+ if (profileShowsToolData(ctx.profile))
132
+ return view;
133
+ const blocks = (list) => list.flatMap((block) => blockWithoutToolData(block) ?? []);
134
+ const { paused, running, ...rest } = view;
135
+ return {
136
+ ...rest,
137
+ transcript: blocks(view.transcript),
138
+ ...(running ? { running: { ...running, prompt: blocks(running.prompt) } } : {}),
139
+ ...(paused
140
+ ? {
141
+ paused: {
142
+ events: paused.events.flatMap((event) => eventWithoutToolData(event) ?? []),
143
+ blocks: blocks(paused.blocks),
144
+ },
145
+ }
146
+ : {}),
147
+ };
148
+ }
149
149
  function eventStream(ctx, request, source) {
150
150
  const encoder = new TextEncoder();
151
151
  const line = (value) => encoder.encode(`${JSON.stringify(value)}\n`);
@@ -158,8 +158,10 @@ function eventStream(ctx, request, source) {
158
158
  controller.enqueue(line(value));
159
159
  };
160
160
  try {
161
- for await (const event of source()) {
162
- send(event.type === 'conversation' ? event : forClient(event, ctx.options.clientEvents));
161
+ for await (const line of source()) {
162
+ const shown = shownLine(ctx, line);
163
+ if (shown)
164
+ send(shown);
163
165
  }
164
166
  }
165
167
  catch (err) {
@@ -184,371 +186,190 @@ function providerFor(ctx, request, model) {
184
186
  return provider({ request, model });
185
187
  return provider;
186
188
  }
187
- /** Steer inboxes are scoped to the session, so a turn id alone can't reach another user's turn. */
188
- function inboxKey(sessionId, turnId) {
189
- return `${sessionId}\u0000${turnId}`;
190
- }
191
- /** The exact paused calls the user may now approve, when the stream stopped on gates. */
192
- function pendingGatesFrom(events, context) {
193
- return gatedToolsFromEvents(events).map((gated) => ({
194
- callId: gated.callId,
195
- gate: {
196
- profileId: context.profileId,
197
- operationId: requiredOperationId(gated),
198
- callId: gated.callId,
199
- name: gated.name,
200
- arguments: gated.arguments,
201
- gate: {
202
- kind: gated.gateKind,
203
- permission: gated.permission,
204
- ...(gated.auth ? { auth: gated.auth } : {}),
205
- },
206
- snapshot: toolSnapshotFromEvents(events),
207
- promoted: [...new Set([...(context.promoted ?? []), ...promotedToolIdsFromEvents(events)])],
208
- turnInput: context.turnInput,
209
- model: context.model,
210
- createdAt: Date.now(),
189
+ /** What a run reads in place of `request`. */
190
+ function contextOf(ctx, request, sessionId) {
191
+ let asked;
192
+ return {
193
+ sessionId,
194
+ signal: request.signal,
195
+ // why: The app's `host` is asked when a run first reads it, so a route that reads none asks
196
+ // none, and a reply and the app's steps around its save read the same value.
197
+ get host() {
198
+ asked ??= { host: ctx.options.host?.(request) };
199
+ return asked.host;
211
200
  },
212
- }));
213
- }
214
- /** When the stream paused on gates, record the exact calls the user may now approve. */
215
- async function recordOutcome(sessions, sessionId, events, context) {
216
- const pending = pendingGatesFrom(events, context);
217
- if (!pending.length)
218
- return;
219
- await sessions.mutate(sessionId, (state) => {
220
- for (const { gate } of pending) {
221
- const operation = state.operations[gate.operationId];
222
- if (operation && operation.status !== 'ready')
223
- 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
224
- { copy: { key: 'session.busy' } });
225
- delete state.operations[gate.operationId];
226
- Object.defineProperty(state.gates, gate.operationId, {
227
- value: gate,
228
- writable: true,
229
- enumerable: true,
230
- configurable: true,
231
- });
232
- }
233
- });
201
+ };
234
202
  }
235
- async function* recorded(sessions, sessionId, events, context, seed = []) {
236
- const seen = [...seed];
237
- for await (const event of events) {
238
- seen.push(event);
239
- if (event.type === 'done' || event.type === 'provider_checkpoint')
240
- await recordOutcome(sessions, sessionId, seen, context);
241
- yield event;
242
- }
203
+ /** The session's calls as `request` runs them: each of the app's callbacks is given `request`. */
204
+ function callsOf(ctx, request) {
205
+ const { options } = ctx;
206
+ const { background, authorizeToolReplay, authorizationUrl } = options;
207
+ return {
208
+ profile: ctx.profile,
209
+ sessions: ctx.sessions,
210
+ credentials: ctx.credentials,
211
+ pageToolBroker: ctx.pageToolBroker,
212
+ options: {
213
+ prepare: options.prepare,
214
+ onStage: options.onStage,
215
+ pageToolTimeoutMs: options.pageToolTimeoutMs,
216
+ notifier: options.notifier,
217
+ lateResultsDecider: options.lateResultsDecider,
218
+ ...(background
219
+ ? { background: (at) => background({ request, sessionId: at.sessionId }) }
220
+ : {}),
221
+ ...(authorizeToolReplay
222
+ ? { authorizeToolReplay: (_at, operation) => authorizeToolReplay({ request, operation }) }
223
+ : {}),
224
+ ...(authorizationUrl
225
+ ? {
226
+ authorizationUrl: (challenge, at) => authorizationUrl(challenge, { request, sessionId: at.sessionId }),
227
+ }
228
+ : {}),
229
+ onError: (err) => options.onError?.(err, { request }),
230
+ wake: (at, ref) => serverWake(ctx, request, at.sessionId, ref),
231
+ },
232
+ };
243
233
  }
244
- /** Save one credential, leaving the session's others as they are. */
245
- function saveCredential(ctx, sessionId, slot, credential) {
246
- return ctx.credentials.mutate(sessionId, (saved) => {
247
- saved[slot] = credential;
234
+ /** The chat's conversation core as `request` runs it. */
235
+ function coreOf(ctx, chat, request) {
236
+ const calls = callsOf(ctx, request);
237
+ return ctx.wire({
238
+ ...calls,
239
+ chat,
240
+ steer: ctx.inbox,
241
+ options: {
242
+ ...calls.options,
243
+ provider: (_at, model) => providerFor(ctx, request, model),
244
+ conversationLeaseMs: ctx.options.conversationLeaseMs,
245
+ notifyRetryMs: ctx.options.notifyRetryMs,
246
+ clientEvents: ctx.options.clientEvents,
247
+ },
248
248
  });
249
249
  }
250
250
  /**
251
- * The session's credentials as a call reads them: one slot when a tool needs it,
252
- * saved the moment the kernel sets one, so a rotated refresh token is never lost
253
- * to a closed stream.
251
+ * A page's run: when it ends with items that wait, `onContinue` says who runs the next reply.
252
+ * Unset, the chat is let go, and the page wakes it.
254
253
  */
255
- function sessionCredentials(ctx, sessionId) {
256
- return {
257
- get: async (slot) => (await ctx.credentials.read(sessionId))[slot],
258
- set: (slot, credential) => saveCredential(ctx, sessionId, slot, credential),
259
- };
260
- }
261
- /** An OAuth gate given the host's sign-in URL. */
262
- async function withAuthorizationUrl(ctx, request, sessionId, event) {
263
- if (event.type !== 'tool' || event.tool.phase !== 'gate')
264
- return event;
265
- const { tool } = event;
266
- const gate = tool.gate.kind === 'auth' ? tool.gate : undefined;
267
- if (gate?.authChallenge.authType !== 'oauth2' || !ctx.options.authorizationUrl)
268
- return event;
269
- const challenge = gate.authChallenge;
270
- const authorizationUrl = await ctx.options.authorizationUrl(challenge, { request, sessionId });
271
- return {
272
- ...event,
273
- tool: { ...tool, gate: { ...gate, authChallenge: { ...challenge, authorizationUrl } } },
274
- };
254
+ function pageRun(ctx, request, core, at, reply) {
255
+ const { onContinue } = ctx.options;
256
+ return followedUp(core, at, reply, (run) => onContinue ? onContinue(run, { request, sessionId: at.sessionId }) : 'let_go');
275
257
  }
276
- /** Every OAuth gate in the stream, given the host's sign-in URL. */
277
- async function* withAuthorizationUrls(ctx, request, sessionId, events) {
278
- for await (const event of events)
279
- yield await withAuthorizationUrl(ctx, request, sessionId, event);
280
- }
281
- function answerPendingGate(state, request, profileId) {
282
- const operation = Object.hasOwn(state.operations, request.operationId)
283
- ? state.operations[request.operationId]
284
- : undefined;
285
- if (operation?.status === 'ready' &&
286
- operation.profileId === profileId &&
287
- operation.pending.callId === request.callId) {
288
- const accepted = answerGatedCall(request, {
289
- name: operation.pending.name,
290
- arguments: operation.pending.arguments,
291
- permission: operation.pending.gate.permission,
292
- gateKind: operation.pending.gate.kind,
293
- ...(operation.pending.gate.kind === 'auth' && operation.pending.gate.auth
294
- ? { auth: operation.pending.gate.auth }
295
- : {}),
296
- }, operation.answer.sessionPermissions);
297
- const { typed: _typed, ...plain } = accepted;
298
- if (!sameAcceptedAnswer(plain, operation.answer))
299
- throw new TheoremError('request', labelText('error.request'));
300
- return {
301
- callId: request.callId,
302
- pending: operation.pending,
303
- answer: { ...operation.answer, ...(accepted.typed ? { typed: accepted.typed } : {}) },
304
- };
258
+ /**
259
+ * The decider's wake, with no page: the reply runs on a request of its own, with the headers of
260
+ * the one that started the call and no signal, because that request has ended. When another reply
261
+ * holds the chat, it tries again as that hold's lease runs out.
262
+ */
263
+ async function serverWake(ctx, started, sessionId, ref) {
264
+ const request = new Request(started.url, { headers: started.headers });
265
+ if (!ctx.chat)
266
+ throw statelessRefusal('wake');
267
+ const core = coreOf(ctx, ctx.chat, request);
268
+ const at = contextOf(ctx, request, sessionId);
269
+ // why: no page is open to wake the chat, so this wake runs each next reply itself
270
+ const lines = followedUp(core, at, await core.wake(at, { ref }), () => 'here');
271
+ // why: the run lets the chat go as it ends, so its lines are read to the end before a failure is thrown
272
+ let failed;
273
+ for (;;) {
274
+ const next = await lines.next();
275
+ if (next.done) {
276
+ if (failed)
277
+ throw failed;
278
+ if (next.value.outcome !== 'held')
279
+ return;
280
+ setTimeout(() => {
281
+ serverWake(ctx, started, sessionId, ref).catch((err) => ctx.options.onError?.(err, { request }));
282
+ }, Math.max(0, next.value.leasedUntil - Date.now()));
283
+ return;
284
+ }
285
+ if (next.value.type === 'error') {
286
+ // labels-exempt: internal diagnostic for the decider's wake; no page reads it
287
+ failed ??= new TheoremError(next.value.errorKind, next.value.errorInternal ?? next.value.error ?? 'the wake failed');
288
+ }
305
289
  }
306
- const pending = Object.hasOwn(state.gates, request.operationId)
307
- ? state.gates[request.operationId]
308
- : undefined;
309
- if (!pending || pending.profileId !== profileId || pending.callId !== request.callId) {
310
- throw new TheoremError('request', labelText('session.gate_expired'), {
311
- copy: { key: 'session.gate_expired' },
312
- });
290
+ }
291
+ /** The person's message: a new reply, run against the conversation the host keeps. */
292
+ async function turn(ctx, chat, request, session) {
293
+ const body = await readBody(request, theoremTurnRequestSchema, ctx.options.maxRequestBytes);
294
+ if (body.stated && !ctx.options.pageStatesTurn) {
295
+ throw new TheoremError('request', labelText('error.request'));
313
296
  }
314
- // why: A refused answer (a refused secret, an edit without an approval) throws here and leaves the gate pending.
315
- const answer = answerGatedCall(request, {
316
- name: pending.name,
317
- arguments: pending.arguments,
318
- permission: pending.gate.permission,
319
- gateKind: pending.gate.kind,
320
- ...(pending.gate.kind === 'auth' && pending.gate.auth ? { auth: pending.gate.auth } : {}),
321
- }, state.permissions);
322
- delete state.gates[request.operationId];
323
- const { typed: _typed, ...accepted } = answer;
324
- state.operations[request.operationId] = {
325
- status: 'ready',
326
- profileId,
327
- pending,
328
- answer: accepted,
329
- readyAt: Date.now(),
297
+ const context = await ctx.options.context?.(request);
298
+ const core = coreOf(ctx, chat, request);
299
+ const at = contextOf(ctx, request, session.id);
300
+ const message = {
301
+ ref: body.conversation,
302
+ input: body.input,
303
+ ...(context === undefined ? {} : { context }),
304
+ generation: body,
305
+ ...(body.abandon ? { abandon: body.abandon } : {}),
330
306
  };
331
- state.permissions = answer.sessionPermissions;
332
- return { callId: request.callId, pending, answer };
333
- }
334
- function walkedCallOf(state, reference, profileId, paused) {
335
- const settled = Object.hasOwn(state.operations, reference.operationId)
336
- ? state.operations[reference.operationId]
337
- : undefined;
338
- // 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.
339
- if (!settled && !Object.hasOwn(state.gates, reference.operationId)) {
340
- const lapsed = pendingGatesFrom(paused, { profileId, turnInput: {} }).find(({ callId }) => callId === reference.callId);
341
- if (lapsed)
342
- state.gates[reference.operationId] = lapsed.gate;
307
+ if (ctx.options.intake) {
308
+ if (body.id === undefined) {
309
+ // labels-exempt: internal diagnostic; the user reads error.request
310
+ throw new TheoremError('request', 'a message needs an `id` where the host saves it itself');
311
+ }
312
+ const taken = await savedMessage(ctx.options.intake, core, at, { id: body.id, message });
313
+ return eventStream(ctx, request, () => taken.outcome === 'saved'
314
+ ? lines([savedLine(taken)])
315
+ : openedRun(ctx, request, core, at, taken, message));
343
316
  }
344
- return settled?.status === 'settled' &&
345
- settled.callId === reference.callId &&
346
- settled.profileId === profileId
347
- ? { callId: reference.callId, settled }
348
- : answerPendingGate(state, { ...reference, decision: 'abandon' }, profileId);
317
+ const reply = await core.message(at, message);
318
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
349
319
  }
350
320
  /**
351
- * Take the calls a message or a rewind walks away from out of the session,
352
- * answered `abandon`: every one of them, or none when one is neither waiting
353
- * nor settled. Each comes back with the run that settles it.
321
+ * The app's save of a message, after the checks that can refuse it.
322
+ * invariant: Nothing refuses a message the app has saved, so the page never takes a saved message back.
354
323
  */
355
- async function takeWalkedAway(ctx, request, session, abandon, conversation) {
356
- const paused = conversation.paused?.events ?? [];
357
- // why: A throw leaves the session unsaved, so no call is taken unless all are.
358
- const calls = await ctx.sessions.mutate(session.id, (state) => abandon.map((reference) => ({
359
- reference,
360
- call: walkedCallOf(state, reference, ctx.profile.id, paused),
361
- })));
362
- return calls.map(({ reference, call }) => ({
363
- ...reference,
364
- events: 'settled' in call
365
- ? replayOperation(ctx, request, call.settled)
366
- : settleAnswered(ctx, request, session, call),
367
- }));
368
- }
369
- async function* settleAnswered(ctx, request, session, answered) {
370
- yield* invokeAnswered(ctx, request, session.id, answered);
371
- }
372
- async function* invokeAnswered(ctx, request, sessionId, { callId, pending, answer }) {
373
- const host = await ctx.options.host?.(request);
374
- // why: The held call goes on with what the application set for its turn: its context, stage handler and credentials.
375
- const prepared = await preparedTurn(ctx.options.prepare, {
376
- profile: ctx.profile.id,
377
- input: pending.turnInput ?? {},
378
- host,
379
- signal: request.signal,
380
- answersHeldCall: true,
381
- }, {
382
- credentials: sessionCredentials(ctx, sessionId),
383
- ...(ctx.options.onStage ? { onStage: ctx.options.onStage } : {}),
384
- });
385
- yield* invokeTool({
386
- profile: ctx.profile.id,
387
- execution: sessionToolCoordinator(ctx.sessions, sessionId),
388
- ...backgroundWiring(ctx, request, sessionId),
389
- pageExecution: sessionPageDispatch(ctx.sessions, sessionId, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
390
- name: pending.name,
391
- callId,
392
- operationId: pending.operationId,
393
- input: answer.input,
394
- resume: answer.resume,
395
- // why: An approval that names no answer is the page saying it has none, so the call is not held again.
396
- ...(pending.gate.kind === 'page' && answer.resume.granted
397
- ? { page: answer.page ?? { unanswered: true } }
398
- : {}),
399
- sessionPermissions: answer.sessionPermissions,
400
- credentials: prepared.credentials,
401
- ...(prepared.onStage ? { onStage: prepared.onStage } : {}),
402
- turnInput: pending.turnInput,
403
- snapshot: pending.snapshot,
404
- promoted: pending.promoted,
405
- model: pending.model,
406
- signal: request.signal,
407
- host: prepared.host,
408
- });
409
- }
410
- /** The host's service for a call in this session, for a request that runs a tool. */
411
- function backgroundWiring(ctx, request, sessionId) {
412
- const service = ctx.options.background?.({ request, sessionId });
413
- if (!service)
414
- return {};
415
- const { notifier } = ctx.options;
416
- if (!notifier)
417
- return { background: service };
418
- return {
419
- background: {
420
- detached(call) {
421
- service.detached(call);
422
- void call.done
423
- .then(() => notifier.publish(sessionId))
424
- .catch((err) => ctx.options.onError?.(err, { request }));
425
- },
426
- event: (event, call) => service.event(event, call),
427
- },
428
- };
429
- }
430
- /** A settled call's answer, streamed again. */
431
- async function* once(event, labels) {
432
- yield withPublicLabels(event, labels);
433
- }
434
- /** One model run of a chat's reply, its gates recorded in the session as they pause. */
435
- async function* chatTurn(ctx, request, session, turn, key, stop) {
436
- const state = await ctx.sessions.read(session.id);
437
- const provider = await providerFor(ctx, request, turn.model);
438
- const host = await ctx.options.host?.(request);
439
- if (key) {
440
- await ctx.inbox.open(key);
441
- stopOnRequest(ctx.inbox, key, stop);
442
- }
443
- try {
444
- const onStage = stagesInOrder(ctx.options.onStage, key ? steerStage(ctx.inbox, key) : undefined);
445
- const prepared = await preparedTurn(ctx.options.prepare, {
446
- profile: ctx.profile.id,
447
- execution: sessionToolCoordinator(ctx.sessions, session.id),
448
- ...backgroundWiring(ctx, request, session.id),
449
- pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
450
- input: turn.input,
451
- ...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
452
- ...(turn.providerState ? { providerState: turn.providerState } : {}),
453
- sessionPermissions: state.permissions,
454
- signal: AbortSignal.any([request.signal, stop.signal]),
455
- host,
456
- ...(turn.model ? { model: turn.model } : {}),
457
- ...(turn.effort ? { effort: turn.effort } : {}),
458
- ...turn.carried,
459
- ...turn.stated,
460
- }, {
461
- credentials: sessionCredentials(ctx, session.id),
462
- ...(onStage ? { onStage } : {}),
463
- });
464
- const events = runTurn(prepared, provider);
465
- yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
466
- profileId: ctx.profile.id,
467
- turnInput: turn.input,
468
- model: turn.model,
469
- });
470
- }
471
- finally {
472
- if (key)
473
- await ctx.inbox.close(key);
474
- }
324
+ async function savedMessage(intake, core, at, sent) {
325
+ await core.checkMessage(at, sent.message);
326
+ const { ref, input } = sent.message;
327
+ return intake(at, { id: sent.id, ...(ref === undefined ? {} : { ref }), message: input });
475
328
  }
476
- /** How this request runs the model for a reply: its generation, and its abort (the request's, or a stop). */
477
- function chatRunner(ctx, request, session, generation) {
478
- const key = generation.turnId ? inboxKey(session.id, generation.turnId) : undefined;
479
- const stop = new AbortController();
480
- const signal = AbortSignal.any([request.signal, stop.signal]);
481
- return {
482
- run: (turn) => chatTurn(ctx, request, session, turn, key, stop),
483
- async compact(history, tokens, model) {
484
- const provider = await providerFor(ctx, request, model);
485
- const compacted = await compactHistory({
486
- profile: ctx.profile.id,
487
- history,
488
- tokens,
489
- signal,
490
- ...(model ? { model } : {}),
491
- }, provider);
492
- return compacted?.history;
493
- },
494
- ...(generation.model ? { model: generation.model } : {}),
495
- ...(generation.effort ? { effort: generation.effort } : {}),
496
- ...(generation.stated ? { stated: generation.stated } : {}),
497
- signal,
498
- };
329
+ /** The line that tells the page the app saved its message, and how a reply names it. */
330
+ function savedLine(taken) {
331
+ return { type: 'conversation', ref: taken.ref, posted: true, landsAs: [...taken.landsAs] };
499
332
  }
500
- /** The chat's conversation as this session's runs read and write it; undefined when the profile keeps none. */
501
- function conversationHost(ctx, session) {
502
- const store = ctx.chat?.conversations;
503
- if (!ctx.chat || !store)
504
- return undefined;
505
- return readerConversationHost({
506
- sessionId: session.id,
507
- store,
508
- profile: { outputs: ctx.chat.profile.outputs, labels: ctx.profile.labels },
509
- clientEvents: ctx.options.clientEvents,
510
- });
333
+ async function* lines(values) {
334
+ yield* values;
511
335
  }
512
- /** The person's message: a new reply, run against the conversation the host keeps. */
513
- async function turn(ctx, chat, request, session) {
514
- const body = await readBody(request, theoremTurnRequestSchema, ctx.options.maxRequestBytes);
515
- if (body.stated && !ctx.options.pageStatesTurn) {
516
- throw new TheoremError('request', labelText('error.request'));
336
+ /**
337
+ * The reply to a message whose save took the conversation. The saved line goes first: whatever
338
+ * the reply does after it, the message stays saved.
339
+ */
340
+ async function* openedRun(ctx, request, core, at, taken, message) {
341
+ const { ref, hold, blocks } = taken;
342
+ yield savedLine(taken);
343
+ let reply;
344
+ try {
345
+ reply = await core.message(at, { ...message, ref, saved: { hold, blocks } });
517
346
  }
518
- const message = postedMessage(chatInterface(chat), body.input, await ctx.options.context?.(request));
519
- const runner = chatRunner(ctx, request, session, body);
520
- const host = conversationHost(ctx, session);
521
- if (!host) {
522
- if (body.conversation !== undefined)
523
- throw statelessRefusal('continue');
524
- // labels-exempt: internal diagnostic; the user reads error.request
525
- if (body.abandon)
526
- throw statelessRefusal('walk away from');
527
- return eventStream(ctx, request, () => runner.run({
528
- input: message.input,
529
- model: body.model,
530
- effort: body.effort,
531
- ...(body.stated ? { stated: body.stated } : {}),
532
- }));
347
+ catch (err) {
348
+ // why: No reply took the hold, so the handler lets the conversation go for the next one.
349
+ await core.release(at, { ref, hold });
350
+ throw err;
533
351
  }
534
- const opened = await openConversation(host, body.conversation, {
535
- kind: 'message',
536
- ...(body.abandon ? { abandon: body.abandon } : {}),
537
- });
538
- // why: Take the walked-away calls before streaming, so a stale one is a reply status, not a stream error.
539
- const walkAway = body.abandon
540
- ? await takeWalkedAway(ctx, request, session, body.abandon, opened.conversation)
541
- : undefined;
542
- return eventStream(ctx, request, () => messageReply({ host, opened, message, ...(walkAway ? { walkAway } : {}), runner }));
352
+ yield* pageRun(ctx, request, core, at, reply);
543
353
  }
544
354
  /** The conversation as the browser draws it. */
545
- async function conversation(ctx, request, session) {
355
+ async function conversation(ctx, chat, request, session) {
546
356
  const body = await readBody(request, theoremConversationRequestSchema, ctx.options.maxRequestBytes);
547
- const host = conversationHost(ctx, session);
548
- if (!host)
549
- throw statelessRefusal('read');
550
- const opened = await openConversation(host, body.conversation, { kind: 'read' });
551
- return jsonResponse(200, await currentView(ctx, request, session, host, opened.conversation));
357
+ const view = await coreOf(ctx, chat, request).read(contextOf(ctx, request, session.id), {
358
+ ref: body.conversation,
359
+ });
360
+ return jsonResponse(200, shownView(ctx, view));
361
+ }
362
+ /**
363
+ * A reply to no message, for results that ended since the model last ran. It runs under a hold of
364
+ * the chat, so two pages that wake at once run it once, and reads what the decider's policy tells.
365
+ */
366
+ async function wake(ctx, chat, request, session) {
367
+ const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
368
+ const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
369
+ const core = coreOf(ctx, chat, request);
370
+ const at = contextOf(ctx, request, session.id);
371
+ const reply = await core.wake(at, { ref: body.conversation, generation: body, input });
372
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
552
373
  }
553
374
  const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
554
375
  /**
@@ -590,178 +411,63 @@ async function notify(ctx, request, session, notifier) {
590
411
  });
591
412
  return new Response(stream, { headers: NDJSON_HEADERS });
592
413
  }
593
- /**
594
- * why: The transcript keeps a detached call as the turn left it. The session holds what became of
595
- * it, so a call that has ended does not read as running.
596
- */
597
- async function currentView(ctx, request, session, host, conversation) {
598
- const view = conversationView(host, conversation);
599
- if (!view.transcript.some(isDetachedBlock))
600
- return view;
601
- const { operations } = await ctx.sessions.read(session.id);
602
- const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, request, block, operations, host) : block));
603
- const { notifier, notifyRetryMs } = ctx.options;
604
- return {
605
- ...view,
606
- transcript,
607
- ...(notifier && transcript.some(isDetachedBlock)
608
- ? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
609
- : {}),
610
- };
611
- }
612
- function isDetachedBlock(block) {
613
- return block.kind === 'tool' && block.tool.state?.phase === 'background';
614
- }
615
- /** A detached call's block as its operation stands. One the session no longer holds has no known end. */
616
- async function lateBlock(ctx, request, block, operations, host) {
617
- const { tool } = block;
618
- const id = tool.operationId;
619
- const operation = id && Object.hasOwn(operations, id) ? operations[id] : undefined;
620
- if (operation?.status === 'running' || operation?.status === 'background')
621
- return block;
622
- const { labels } = ctx.profile;
623
- if (operation?.status === 'settled' &&
624
- ctx.options.authorizeToolReplay &&
625
- !(await ctx.options.authorizeToolReplay({ request, operation }))) {
626
- const message = labelText('error.blocked', {}, labels);
627
- const failure = { code: 'outcome_withheld', kind: 'blocked', message };
628
- const { name, callId } = tool;
629
- const at = operation.settledAt;
630
- return {
631
- ...block,
632
- tool: {
633
- ...tool,
634
- state: { name, callId, at, phase: 'error', failure, readBack: message },
635
- endedAt: at,
636
- },
637
- };
638
- }
639
- if (operation?.status === 'settled') {
640
- const settled = host.forReader(operation.outcome.event);
641
- if (settled.type !== 'tool')
642
- return block;
643
- const { tool: state } = settled;
644
- if (!('phase' in state) || (state.phase !== 'complete' && state.phase !== 'error'))
645
- return block;
646
- return { ...block, tool: { ...tool, state, endedAt: operation.settledAt } };
647
- }
648
- const message = labelText('tool.execution_uncertain', {}, labels);
649
- const failure = {
650
- code: operation?.status === 'uncertain' ? operation.reason : 'outcome_not_retained',
651
- kind: 'internal',
652
- message,
653
- };
654
- const { name, callId } = tool;
655
- const at = operation?.status === 'uncertain' ? operation.detectedAt : (tool.state?.at ?? Date.now());
656
- return {
657
- ...block,
658
- tool: {
659
- ...tool,
660
- state: { name, callId, at, phase: 'error', failure, readBack: message },
661
- endedAt: at,
662
- },
663
- };
664
- }
665
414
  /** The conversation cut after one block; a reply that waits on gates is walked away from first. */
666
- async function rewind(ctx, request, session) {
415
+ async function rewind(ctx, chat, request, session) {
667
416
  const body = await readBody(request, theoremRewindRequestSchema, ctx.options.maxRequestBytes);
668
- const host = conversationHost(ctx, session);
669
- if (!host)
670
- throw statelessRefusal('rewind');
671
- const opened = await openConversation(host, body.conversation, { kind: 'rewind', at: body.at });
672
- const waiting = waitingCalls(opened.conversation);
673
- const walkAway = waiting.length
674
- ? await takeWalkedAway(ctx, request, session, waiting, opened.conversation)
675
- : undefined;
676
- const next = await rewindConversation({
677
- host,
678
- opened,
417
+ const rewound = await coreOf(ctx, chat, request).rewind(contextOf(ctx, request, session.id), {
418
+ ref: body.conversation,
679
419
  at: body.at,
680
- ...(walkAway ? { walkAway } : {}),
681
420
  });
682
- if (next.ref === null)
683
- throw new TheoremError('internal', labelText('error.internal'));
684
- const rewound = {
685
- conversation: next.ref,
686
- view: await currentView(ctx, request, session, host, next.conversation),
687
- };
688
- return jsonResponse(200, rewound);
689
- }
690
- async function* invokeEvents(ctx, request, session, answered) {
691
- const { pending, answer } = answered;
692
- if (answer.typed)
693
- await saveCredential(ctx, session.id, answer.typed.slot, answer.typed.credential);
694
- const events = settleAnswered(ctx, request, session, answered);
695
- yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
696
- profileId: ctx.profile.id,
697
- turnInput: pending.turnInput,
698
- model: pending.model,
699
- promoted: pending.promoted,
700
- }, [
701
- {
702
- type: 'tool',
703
- tool: {
704
- name: pending.name,
705
- callId: pending.callId,
706
- operationId: pending.operationId,
707
- arguments: jsonObjectSchema.parse(answer.input),
708
- },
709
- },
710
- ]);
421
+ return jsonResponse(200, { ...rewound, view: shownView(ctx, rewound.view) });
711
422
  }
712
- async function steer(ctx, request, session) {
423
+ async function steer(ctx, chat, request, session) {
713
424
  const body = await readBody(request, theoremSteerRequestSchema, ctx.options.maxRequestBytes);
714
- if (!(await ctx.inbox.enqueue(inboxKey(session.id, body.turnId), steerUnitOf(body)))) {
715
- // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
716
- throw new TheoremError('request', `turn ${body.turnId} is not running`, {
717
- copy: { key: 'session.turn_ended' },
718
- });
425
+ const core = coreOf(ctx, chat, request);
426
+ const at = contextOf(ctx, request, session.id);
427
+ if (ctx.options.intake) {
428
+ const message = {
429
+ ...(body.conversation === undefined ? {} : { ref: body.conversation }),
430
+ input: body.input,
431
+ };
432
+ const taken = await savedMessage(ctx.options.intake, core, at, { id: body.id, message });
433
+ if (taken.outcome === 'opened') {
434
+ const run = { ref: taken.ref, hold: taken.hold };
435
+ const { onContinue } = ctx.options;
436
+ const who = onContinue
437
+ ? await onContinue(run, { request, sessionId: at.sessionId })
438
+ : 'let_go';
439
+ // why: A steer has no stream for a reply, so `here` is the page's own wake.
440
+ if (who !== 'taken')
441
+ await core.release(at, run);
442
+ }
443
+ const saved = { conversation: taken.ref, landsAs: [...taken.landsAs] };
444
+ return jsonResponse(200, { ok: true, saved });
719
445
  }
446
+ // why: without `intake`, a steer reaches only a turn this server runs, by its id
447
+ if (!('turnId' in body))
448
+ throw replyUnreachable();
449
+ const steered = await core.steer(at, { turnId: body.turnId, id: body.id, input: body.input });
450
+ if (!steered)
451
+ throw replyNotRunning(body);
720
452
  return jsonResponse(200, { ok: true });
721
453
  }
454
+ /** The refusal of a steer or stop for a reply that is not running. */
455
+ function replyNotRunning(target) {
456
+ // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
457
+ const what = 'turnId' in target ? `turn ${target.turnId}` : 'a reply on the conversation';
458
+ // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
459
+ return new TheoremError('request', `${what} is not running`, {
460
+ copy: { key: 'session.turn_ended' },
461
+ });
462
+ }
722
463
  /** Stops a running turn where it stands; its stream goes on to save and send what the reply left. */
723
- async function stop(ctx, request, session) {
464
+ async function stop(ctx, chat, request, session) {
724
465
  const body = await readBody(request, theoremStopRequestSchema, ctx.options.maxRequestBytes);
725
- if (!(await ctx.inbox.stop(inboxKey(session.id, body.turnId)))) {
726
- // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
727
- throw new TheoremError('request', `turn ${body.turnId} is not running`, {
728
- copy: { key: 'session.turn_ended' },
729
- });
730
- }
466
+ const core = coreOf(ctx, chat, request);
467
+ if (!(await core.stop(contextOf(ctx, request, session.id), body)))
468
+ throw replyNotRunning(body);
731
469
  return jsonResponse(200, { ok: true });
732
470
  }
733
- /** One call of one of a host's tools, run as the page asked it; a gate it pauses on waits in the session. */
734
- async function* callEvents(ctx, request, session, body) {
735
- const state = await ctx.sessions.read(session.id);
736
- const host = await ctx.options.host?.(request);
737
- const events = invokeTool({
738
- profile: ctx.profile.id,
739
- execution: sessionToolCoordinator(ctx.sessions, session.id),
740
- ...backgroundWiring(ctx, request, session.id),
741
- pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
742
- name: body.name,
743
- input: body.input,
744
- sessionPermissions: state.permissions,
745
- credentials: sessionCredentials(ctx, session.id),
746
- ...(ctx.options.onStage ? { onStage: ctx.options.onStage } : {}),
747
- signal: request.signal,
748
- host,
749
- });
750
- yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
751
- profileId: ctx.profile.id,
752
- turnInput: {},
753
- });
754
- }
755
- function answerRequest(body) {
756
- return {
757
- callId: body.gateId,
758
- operationId: body.operationId,
759
- decision: body.decision,
760
- input: body.input,
761
- secret: body.secret,
762
- page: body.page,
763
- };
764
- }
765
471
  /** A route this profile doesn't serve. */
766
472
  function refused(ctx) {
767
473
  return jsonResponse(HTTP_NOT_FOUND, {
@@ -769,26 +475,6 @@ function refused(ctx) {
769
475
  errorKind: 'not_found',
770
476
  });
771
477
  }
772
- async function* replayOperation(ctx, request, operation) {
773
- const tool = defaultKernelScope.tools.get(operation.toolId);
774
- if (operation.profileId !== ctx.profile.id ||
775
- !tool ||
776
- tool.type === 'builtin' ||
777
- !('tools' in ctx.profile) ||
778
- !ctx.profile.tools?.allow.includes(operation.toolId) ||
779
- (operation.status === 'settled' &&
780
- ctx.options.authorizeToolReplay &&
781
- !(await ctx.options.authorizeToolReplay({ request, operation }))))
782
- throw new TheoremError('blocked', labelText('error.blocked'));
783
- authorizeToolReplay({
784
- tools: defaultKernelScope.tools,
785
- profile: ctx.profile,
786
- name: operation.toolId,
787
- resume: undefined,
788
- ...(operation.status === 'settled' ? { outcome: operation.outcome } : {}),
789
- });
790
- yield* once(operation.status === 'settled' ? operation.outcome.event : operation.reply.event, ctx.profile.labels);
791
- }
792
478
  /**
793
479
  * The user's answer to a paused call. In a kept conversation the reply goes on
794
480
  * in the same stream once no call waits; otherwise the stream is the call's.
@@ -797,49 +483,14 @@ async function invoke(ctx, request, session) {
797
483
  const body = await readBody(request, theoremInvokeRequestSchema, ctx.options.maxRequestBytes);
798
484
  if (body.page && 'output' in body.page)
799
485
  throw new TheoremError('request', labelText('error.request'));
800
- const host = conversationHost(ctx, session);
801
- if (!host) {
802
- if (body.conversation !== undefined)
803
- throw statelessRefusal('continue');
804
- return eventStream(ctx, request, await settlingOf(ctx, request, session, body));
805
- }
806
- if (body.conversation === undefined)
807
- throw unknownConversation();
808
- const call = { callId: body.gateId, operationId: body.operationId };
809
- const opened = await openConversation(host, body.conversation, { kind: 'answer', call });
810
- const settling = await settlingOf(ctx, request, session, body);
811
- const runner = chatRunner(ctx, request, session, body);
812
- return eventStream(ctx, request, () => answerReply({ host, opened, call, settling: settling(), runner }));
813
- }
814
- /** The answered call's events: its saved outcome again, or the call run as answered. */
815
- async function settlingOf(ctx, request, session, body) {
816
- const saved = await ctx.sessions.read(session.id);
817
- const operation = Object.hasOwn(saved.operations, body.operationId)
818
- ? saved.operations[body.operationId]
819
- : undefined;
820
- if (operation &&
821
- operation.status !== 'ready' &&
822
- operation.callId === body.gateId &&
823
- operation.profileId === ctx.profile.id &&
824
- (operation.status === 'running' || operation.status === 'uncertain')) {
825
- 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)
826
- { copy: { key: 'tool.execution_uncertain' } });
486
+ const at = contextOf(ctx, request, session.id);
487
+ if (!ctx.chat) {
488
+ const lines = await unconversedAnswer(callsOf(ctx, request), at, body);
489
+ return eventStream(ctx, request, () => lines);
827
490
  }
828
- if ((operation?.status === 'settled' || operation?.status === 'background') &&
829
- operation.profileId === ctx.profile.id &&
830
- operation.callId === body.gateId) {
831
- if (body.input !== undefined &&
832
- (!operation.invocation ||
833
- (await toolInvocationHash(body.input)) !==
834
- (await toolInvocationHash(operation.invocation.accepted.input))))
835
- throw new TheoremError('request', labelText('error.request'), {
836
- copy: { key: 'error.request' },
837
- });
838
- return () => replayOperation(ctx, request, operation);
839
- }
840
- // why: Take the answered call before streaming, so a stale answer is a reply status, not a stream error.
841
- const answered = await ctx.sessions.mutate(session.id, (state) => answerPendingGate(state, answerRequest(body), ctx.profile.id));
842
- return () => invokeEvents(ctx, request, session, answered);
491
+ const core = coreOf(ctx, ctx.chat, request);
492
+ const reply = await core.answer(at, body);
493
+ return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
843
494
  }
844
495
  async function hostRoute(ctx, request, session) {
845
496
  const target = routeOf(request);
@@ -847,7 +498,7 @@ async function hostRoute(ctx, request, session) {
847
498
  return jsonResponse(200, { interface: hostInterface(ctx.profile, hostTool) });
848
499
  if (request.method === 'POST' && target === 'call') {
849
500
  const body = await readBody(request, theoremHostCallRequestSchema, ctx.options.maxRequestBytes);
850
- return eventStream(ctx, request, () => callEvents(ctx, request, session, body));
501
+ return eventStream(ctx, request, () => callEvents(callsOf(ctx, request), contextOf(ctx, request, session.id), body));
851
502
  }
852
503
  if (request.method === 'POST' && target === 'invoke')
853
504
  return invoke(ctx, request, session);
@@ -876,7 +527,7 @@ async function route(ctx, request, session) {
876
527
  if (target === 'invoke')
877
528
  return invoke(ctx, request, session);
878
529
  if (target === 'conversation')
879
- return conversation(ctx, request, session);
530
+ return conversation(ctx, chat, request, session);
880
531
  if (target === 'notify') {
881
532
  const { notifier } = ctx.options;
882
533
  if (!notifier || !chat.conversations)
@@ -884,40 +535,28 @@ async function route(ctx, request, session) {
884
535
  return notify(ctx, request, session, notifier);
885
536
  }
886
537
  if (target === 'rewind')
887
- return rewind(ctx, request, session);
538
+ return rewind(ctx, chat, request, session);
539
+ if (target === 'wake')
540
+ return wake(ctx, chat, request, session);
888
541
  if (target === 'stop')
889
- return stop(ctx, request, session);
890
- return steer(ctx, request, session);
542
+ return stop(ctx, chat, request, session);
543
+ return steer(ctx, chat, request, session);
891
544
  }
892
545
  export function createTheoremHandler(options) {
893
- const profile = defineProfile(options.profile);
894
- if (profile.type === 'decision') {
895
- // labels-exempt: builder config error at setup; no user sees it
896
- throw new Error("createTheoremHandler serves turn-based profiles; serve type 'decision' with createTheoremDecisionHandler.");
897
- }
898
- if (profile.type === 'host') {
899
- // labels-exempt: builder config error at setup; no user sees it
900
- throw new Error("createTheoremHandler serves turn-based profiles; serve type 'host' with createTheoremHostHandler.");
901
- }
902
- if (profile.type === 'live' || profile.type === 'embedding') {
546
+ const chat = chatOf('createTheoremHandler', options.profile, options.conversationStore);
547
+ oneInbox(options);
548
+ if (options.intake && !options.inbox) {
903
549
  // labels-exempt: builder config error at setup; no user sees it
904
- throw new Error(`createTheoremHandler serves turn-based profiles; got type '${profile.type}'.`);
905
- }
906
- const stateless = profile.providerContinuation?.history === 'stateless';
907
- if (stateless === (options.conversationStore !== undefined)) {
908
- throw new TheoremError('config', labelText('error.config'), {
909
- cause: {
910
- code: stateless ? 'conversation_store_stateless' : 'conversation_store_missing',
911
- profile: profile.id,
912
- },
913
- });
550
+ throw new TheoremError('config', 'createTheoremHandler needs `inbox` with `intake`');
914
551
  }
915
- return serve('createTheoremHandler', profile, options, {
552
+ const { prepare, inbox, beforeSave, afterSave, compact } = options;
553
+ return serve('createTheoremHandler', chat.profile, options, {
916
554
  steerInbox: options.steerInbox,
917
- chat: {
918
- profile,
919
- ...(options.conversationStore ? { conversations: options.conversationStore } : {}),
920
- },
555
+ chat,
556
+ wire: (state) => createConversationCore({
557
+ ...state,
558
+ options: { ...state.options, prepare, inbox, beforeSave, afterSave, compact },
559
+ }),
921
560
  });
922
561
  }
923
562
  /**
@@ -941,33 +580,14 @@ export function hostTool(name) {
941
580
  const registered = defaultKernelScope.tools.get(name);
942
581
  return registered?.type === 'builtin' ? undefined : registered;
943
582
  }
944
- function checkNotifyRetry(ms) {
945
- if (ms === undefined || (Number.isFinite(ms) && ms >= 0))
946
- return;
947
- throw new TheoremError('config', labelText('error.config'), {
948
- cause: { code: 'notify_retry' },
949
- });
950
- }
951
583
  function serve(name, profile, options, chatOptions = {}) {
952
- const gateTtlMs = resolveGateTtlMs(name, options.gateTtlMs);
953
- const operationRetentionMs = options.operationRetentionMs ?? DEFAULT_OPERATION_RETENTION_MS;
954
- if (!Number.isSafeInteger(operationRetentionMs) || operationRetentionMs <= 0) {
955
- throw new TheoremError('config', labelText('error.config'), {
956
- cause: { code: 'operation_retention' },
957
- });
958
- }
959
584
  requestByteLimit(options.maxRequestBytes);
960
- checkPageToolTimeout(options.pageToolTimeoutMs);
961
- checkNotifyRetry(options.notifyRetryMs);
962
- registerProfile(profile);
963
585
  const ctx = {
964
586
  options,
965
- pageToolBroker: options.pageToolBroker ?? createMemoryPageToolBroker(),
966
- profile,
587
+ ...sessionParts(name, profile, options),
967
588
  ...(chatOptions.chat ? { chat: chatOptions.chat } : {}),
968
589
  inbox: chatOptions.steerInbox ?? createMemorySteerInbox(),
969
- sessions: sessionStateStore(options.sessionStore ?? createMemorySessionStore(), gateTtlMs, operationRetentionMs),
970
- credentials: lockedStore(options.credentialStore ?? createMemoryCredentialStore(), (saved = {}) => saved),
590
+ wire: chatOptions.wire ?? createConversationCore,
971
591
  };
972
592
  return async (request) => {
973
593
  let session;