@theoremjs/web 0.3.4 → 0.3.5-next.1001.g68d8dcf

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
@@ -0,0 +1,797 @@
1
+ /**
2
+ * The conversation core: a person's message, an answer to a paused call, a reply to no message,
3
+ * a read and a rewind, each run against the conversation the app keeps, with no `Request`. The
4
+ * HTTP handler builds one for each request and streams what it returns.
5
+ *
6
+ * @module
7
+ */
8
+ import { compactHistory, defaultKernelScope, defineProfile, labelText, runTurn, TheoremError, } from '@theoremjs/agents';
9
+ import { runConversation, } from '@theoremjs/agents/conversation';
10
+ import { interfaceFromProfile, refuseInterfacePick, } from '@theoremjs/agents/interface';
11
+ import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
12
+ import { detachedEnd, sessionConversationInbox } from "./conversation-inbox.js";
13
+ import { unknownConversation, } from "./conversation-store.js";
14
+ import { sessionPageDispatch } from "./page-dispatch.js";
15
+ import { announced, backgroundWiring, pausedWaits, recorded, replayAllowed, sessionCredentials, settlingOf, takeLapsed, takeWalkedAway, withAuthorizationUrls, } from "./session-calls.js";
16
+ import { steerStage, steerUnitOf, stopOnRequest } from "./steer-inbox.js";
17
+ import { sessionToolCoordinator } from "./tool-operations.js";
18
+ import { isRefusal, preparedTurn, stagesInOrder } from "./turn-wiring.js";
19
+ /**
20
+ * The chat `definition` serves, with the store that keeps its conversation. `name` is the function
21
+ * the app called, for the error a wrong profile throws.
22
+ */
23
+ export function chatOf(name, definition, conversations) {
24
+ const profile = defineProfile(definition);
25
+ if (profile.type === 'decision') {
26
+ // labels-exempt: builder config error at setup; no user sees it
27
+ throw new Error(`${name} serves turn-based profiles; serve type 'decision' with createTheoremDecisionHandler.`);
28
+ }
29
+ if (profile.type === 'host') {
30
+ // labels-exempt: builder config error at setup; no user sees it
31
+ throw new Error(`${name} serves turn-based profiles; serve type 'host' with createTheoremHostHandler.`);
32
+ }
33
+ if (profile.type === 'live' || profile.type === 'embedding') {
34
+ // labels-exempt: builder config error at setup; no user sees it
35
+ throw new Error(`${name} serves turn-based profiles; got type '${profile.type}'.`);
36
+ }
37
+ const stateless = profile.providerContinuation?.history === 'stateless';
38
+ if (stateless === (conversations !== undefined)) {
39
+ throw new TheoremError('config', labelText('error.config'), {
40
+ cause: {
41
+ code: stateless ? 'conversation_store_stateless' : 'conversation_store_missing',
42
+ profile: profile.id,
43
+ },
44
+ });
45
+ }
46
+ return { profile, ...(conversations ? { conversations } : {}) };
47
+ }
48
+ /** The profile as the server reads a message against it, its tools as registered now. */
49
+ function chatInterface(chat) {
50
+ return interfaceFromProfile(chat.profile, defaultKernelScope.tools);
51
+ }
52
+ /** Refuses an app's inbox beside a decider for the session's: one inbox holds what a reply is told. */
53
+ export function oneInbox(options) {
54
+ if (options.inbox === undefined || options.lateResultsDecider === undefined)
55
+ return;
56
+ // labels-exempt: builder config error; the user reads error.config
57
+ throw new TheoremError('config', "pass `inbox` or `lateResultsDecider`, not both: the app's inbox holds every item a reply is told");
58
+ }
59
+ /** Lines that run under no hold. */
60
+ async function* unheld(lines) {
61
+ yield* lines;
62
+ return { outcome: 'released' };
63
+ }
64
+ /** Steer inboxes are scoped to the session, so a turn id alone can't reach another user's turn. */
65
+ /**
66
+ * The refusal of a stop or steer by conversation on a host that can't reach a reply it does not
67
+ * run: no app stop, or no intake for a steer. Not `turn_ended`: the reply may still be running.
68
+ */
69
+ export function replyUnreachable() {
70
+ // labels-exempt: internal diagnostic; the user reads session.reply_unreachable
71
+ return new TheoremError('request', 'this host cannot reach a reply that runs elsewhere', {
72
+ copy: { key: 'session.reply_unreachable' },
73
+ });
74
+ }
75
+ function inboxKey(sessionId, turnId) {
76
+ return `${sessionId}\u0000${turnId}`;
77
+ }
78
+ const DEFAULT_CONVERSATION_LEASE_MS = 60_000;
79
+ /**
80
+ * The session's inbox for the chat: the chat as this context last wrote it, and the results this
81
+ * context may read. `ref` is the chat's ref now, because a store's ref can change with each write.
82
+ */
83
+ function chatInbox(ctx, at, host, opened, ref) {
84
+ const leaseMs = ctx.options.conversationLeaseMs ?? DEFAULT_CONVERSATION_LEASE_MS;
85
+ const inbox = sessionConversationInbox({
86
+ sessions: ctx.sessions,
87
+ sessionId: at.sessionId,
88
+ leaseMs,
89
+ conversation: async (key) => {
90
+ const current = ref();
91
+ const conversation = current === null
92
+ ? opened.conversation
93
+ : (await host.store.read(at.sessionId, current))?.conversation;
94
+ return conversation?.id === key ? conversation : undefined;
95
+ },
96
+ readable: (operation) => replayAllowed(ctx, at, operation),
97
+ labels: ctx.profile.labels,
98
+ });
99
+ return { inbox, key: opened.conversation.id, leaseMs };
100
+ }
101
+ /** The values `produce` sends, as it sends them, then its end or what it threw. */
102
+ async function* sent(produce) {
103
+ const queue = [];
104
+ let ended;
105
+ let wake = () => { };
106
+ produce((value) => {
107
+ queue.push(value);
108
+ wake();
109
+ }).then((value) => {
110
+ ended = { failed: false, value };
111
+ wake();
112
+ }, (failure) => {
113
+ ended = { failed: true, failure };
114
+ wake();
115
+ });
116
+ for (;;) {
117
+ if (queue.length > 0) {
118
+ yield queue.splice(0, 1)[0];
119
+ continue;
120
+ }
121
+ if (ended?.failed)
122
+ throw ended.failure;
123
+ if (ended)
124
+ return ended.value;
125
+ await new Promise((resolve) => {
126
+ wake = resolve;
127
+ });
128
+ }
129
+ }
130
+ function holdingOver(kept, chat) {
131
+ const { inbox, key, policy, stop } = kept;
132
+ const letGo = async (hold) => {
133
+ for (;;) {
134
+ const { version } = await inbox.read(key);
135
+ if ((await inbox.release(key, hold, version)) !== 'moved')
136
+ return;
137
+ }
138
+ };
139
+ return {
140
+ run: async (start, lines, send) => {
141
+ const told = new Set();
142
+ const run = await runConversation({
143
+ conversation: key,
144
+ inbox,
145
+ policy,
146
+ start,
147
+ newId: () => crypto.randomUUID(),
148
+ renewEveryMs: kept.leaseMs / 3,
149
+ reply: async (run) => {
150
+ const held = {
151
+ run,
152
+ renew: () => inbox.renew(key, run.hold),
153
+ reads: kept.reads(run),
154
+ told: (ids) => {
155
+ for (const id of ids)
156
+ told.add(id);
157
+ },
158
+ ...(stop
159
+ ? {
160
+ stop: {
161
+ stopped: (over) => stop.stopped(key, run.hold, over),
162
+ clear: () => stop.clear(key, run.hold),
163
+ },
164
+ }
165
+ : {}),
166
+ };
167
+ const ref = chat.ref();
168
+ // why: The page moves a message it shows as waiting into the reply that reads it, as the reply starts.
169
+ if (run.opened.length > 0 && ref !== null) {
170
+ send({ type: 'conversation', ref, opened: run.opened.map((item) => item.id) });
171
+ }
172
+ for await (const line of lines(held)) {
173
+ chat.seen(line);
174
+ send(line);
175
+ }
176
+ },
177
+ gaveUp: kept.gaveUp,
178
+ });
179
+ if (run.outcome !== 'continue' || told.size === 0)
180
+ return run;
181
+ // why: A follow-up would tell these items again, and each follow-up after it, with no end.
182
+ const { items } = await inbox.read(key);
183
+ // why: An item that arrived again under a told id has no handover of this hold, and is new.
184
+ const unmarked = (item) => told.has(item.id) && item.handovers.some((handover) => handover.hold === run.hold);
185
+ if (!items.some(unmarked))
186
+ return run;
187
+ await letGo(run.hold);
188
+ throw new TheoremError('config',
189
+ // labels-exempt: builder config error; onError receives it and the user reads error.config
190
+ "the reply's save did not mark its `told` items in the inbox: the store's `write` marks them");
191
+ },
192
+ letGo,
193
+ async due() {
194
+ const { items } = await inbox.read(key);
195
+ if (items.length === 0)
196
+ return false;
197
+ const { tell } = await policy(items, { stage: 'pre_turn', step: 0, opening: 'wake' });
198
+ return tell.length > 0;
199
+ },
200
+ ref: chat.ref,
201
+ };
202
+ }
203
+ /** The chat's ref, as each `conversation` line of a run changes it. */
204
+ function chatRef(first) {
205
+ let ref = first;
206
+ return {
207
+ ref: () => ref,
208
+ seen(line) {
209
+ if (line.type === 'conversation')
210
+ ref = line.ref;
211
+ },
212
+ };
213
+ }
214
+ /** Reports the items an inbox policy gave up, under `code`. */
215
+ function gaveUp(ctx, at, code) {
216
+ return (items) => {
217
+ ctx.options.onError?.(
218
+ // labels-exempt: internal diagnostic; no reader sees a given-up item
219
+ new TheoremError('unavailable', 'The inbox policy gave up items', {
220
+ cause: { code, operationIds: items.map((item) => item.id) },
221
+ }), at);
222
+ };
223
+ }
224
+ /**
225
+ * The app's inbox, when it passes one. Its key is the app's, so it holds one conversation for
226
+ * every session and stored chat that names that key.
227
+ */
228
+ function appHolding(ctx, at, ref) {
229
+ const app = ctx.options.inbox?.(at);
230
+ if (!app)
231
+ return undefined;
232
+ return holdingOver({
233
+ inbox: app.inbox,
234
+ key: app.conversation,
235
+ leaseMs: app.leaseMs,
236
+ policy: app.policy,
237
+ reads: (run) => ({ from: 'app', run }),
238
+ gaveUp: gaveUp(ctx, at, 'inbox_items_given_up'),
239
+ ...(app.stop ? { stop: app.stop } : {}),
240
+ }, chatRef(ref));
241
+ }
242
+ /**
243
+ * The inbox this context's replies hold: the app's when it passes one, the session's when a
244
+ * decider tells its late results, and none otherwise.
245
+ */
246
+ function holdingOf(ctx, at, host, opened) {
247
+ const app = appHolding(ctx, at, opened.ref);
248
+ if (app)
249
+ return app;
250
+ const chat = chatRef(opened.ref);
251
+ const decider = ctx.options.lateResultsDecider;
252
+ if (!decider)
253
+ return undefined;
254
+ let whose;
255
+ return holdingOver({
256
+ ...chatInbox(ctx, at, host, opened, chat.ref),
257
+ policy: async (items, moment) => {
258
+ whose ??= Promise.resolve(at.host);
259
+ return decider.policy(items, { ...moment, host: await whose });
260
+ },
261
+ reads: (run) => ({ from: 'session', late: lateSource(run) }),
262
+ gaveUp: gaveUp(ctx, at, 'late_results_given_up'),
263
+ }, chat);
264
+ }
265
+ /**
266
+ * Runs a reply under a hold of the chat, and streams its lines. The reply reads the items the
267
+ * policy tells it. With no inbox to hold, no reply reads one, and no hold is taken.
268
+ * invariant: One hold has a chat at a time, and lets it go only once nothing waits that may be told.
269
+ * A run that leaves items waiting ends `continue`, with its hold: the caller runs the follow-up or
270
+ * lets the chat go. Never while the chat waits on gates: the answer that goes on reads what waits.
271
+ */
272
+ function heldLines(ctx, at, host, opened, start, reply) {
273
+ const holding = holdingOf(ctx, at, host, opened);
274
+ if (!holding)
275
+ return unheld(reply(undefined, () => opened.ref));
276
+ return sent(async (send) => {
277
+ const run = await holding.run(start, (held) => reply(held, holding.ref), send);
278
+ if (run.outcome === 'held')
279
+ return { outcome: 'held', leasedUntil: run.leasedUntil };
280
+ if (run.outcome === 'continue') {
281
+ const ref = holding.ref();
282
+ if (ref !== null && !(await isPaused(host, ref, opened.conversation))) {
283
+ return {
284
+ outcome: 'continue',
285
+ ref,
286
+ hold: run.hold,
287
+ ...(run.failure === undefined ? {} : { failure: run.failure }),
288
+ };
289
+ }
290
+ await holding.letGo(run.hold);
291
+ }
292
+ if (run.failure !== undefined)
293
+ throw run.failure;
294
+ return { outcome: run.outcome === 'lost' ? 'lost' : 'released' };
295
+ });
296
+ }
297
+ /**
298
+ * A run, then what `choose` says for each `continue` it and its follow-ups end with. It ends as
299
+ * the last run ended, `continue` only when the app took it, and throws the first failure.
300
+ */
301
+ export async function* followedUp(core, at, reply, choose) {
302
+ let end = yield* reply;
303
+ let failure;
304
+ while (end.outcome === 'continue') {
305
+ failure ??= end.failure;
306
+ const { ref, hold } = end;
307
+ const choice = await choose({ ref, hold });
308
+ if (choice === 'taken')
309
+ break;
310
+ if (choice === 'let_go') {
311
+ await core.release(at, { ref, hold });
312
+ end = { outcome: 'released' };
313
+ break;
314
+ }
315
+ end = yield* await core.followUp(at, { ref, hold });
316
+ }
317
+ if (failure !== undefined)
318
+ throw failure;
319
+ return end;
320
+ }
321
+ /** Whether the chat waits on gates: a wake leaves it to the answer that goes on. */
322
+ async function isPaused(host, ref, fallback) {
323
+ const conversation = ref === null ? fallback : (await host.store.read(host.sessionId, ref))?.conversation;
324
+ return conversation?.paused !== undefined;
325
+ }
326
+ /** The late results a reply's model reads: what it opened with, then what each later moment hands it. */
327
+ function lateSource(run) {
328
+ let opening = true;
329
+ return async ({ stage, step }) => {
330
+ if (opening && stage === 'pre_turn') {
331
+ opening = false;
332
+ return run.opened.map((item) => item.outcome);
333
+ }
334
+ return (await run.take({ stage, step })).map((item) => item.outcome);
335
+ };
336
+ }
337
+ /** One model run of a chat's reply, its gates recorded in the session as they pause. */
338
+ async function* chatTurn(ctx, at, turn, key, signal, stop, held, refused) {
339
+ const state = await ctx.sessions.read(at.sessionId);
340
+ const provider = await ctx.options.provider(at, turn.model);
341
+ const host = await at.host;
342
+ const over = new AbortController();
343
+ if (key)
344
+ await ctx.steer.open(key);
345
+ if (held?.stop) {
346
+ held.stop.stopped(over.signal).then((stopped) => {
347
+ if (stopped)
348
+ stop.abort();
349
+ }, (err) => ctx.options.onError?.(err, at));
350
+ }
351
+ else if (key) {
352
+ stopOnRequest(ctx.steer, key, stop);
353
+ }
354
+ try {
355
+ const onStage = stagesInOrder(ctx.options.onStage, key ? steerStage(ctx.steer, key) : undefined);
356
+ const { prepare } = ctx.options;
357
+ const run = held?.reads.from === 'app' ? held.reads.run : undefined;
358
+ const prepared = await preparedTurn(prepare && ((request) => prepare(request, run)), {
359
+ profile: ctx.profile.id,
360
+ execution: sessionToolCoordinator(ctx.sessions, at.sessionId),
361
+ ...backgroundWiring(ctx, at),
362
+ pageExecution: sessionPageDispatch(ctx.sessions, at.sessionId, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
363
+ input: turn.input,
364
+ ...(held?.reads.from === 'session' ? { lateResults: held.reads.late } : {}),
365
+ ...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
366
+ ...(turn.providerState ? { providerState: turn.providerState } : {}),
367
+ sessionPermissions: state.permissions,
368
+ signal,
369
+ host,
370
+ ...(turn.model ? { model: turn.model } : {}),
371
+ ...(turn.effort ? { effort: turn.effort } : {}),
372
+ ...turn.carried,
373
+ ...turn.stated,
374
+ }, {
375
+ credentials: sessionCredentials(ctx, at.sessionId),
376
+ ...(onStage ? { onStage } : {}),
377
+ announce: (service) => announced(ctx, at, service),
378
+ });
379
+ if (isRefusal(prepared)) {
380
+ refused(prepared.refuse);
381
+ yield { type: 'text', text: prepared.refuse.text };
382
+ yield { type: 'done', stop: { kind: 'completed' } };
383
+ return;
384
+ }
385
+ const events = runTurn(prepared, provider);
386
+ yield* recorded(ctx.sessions, at.sessionId, withAuthorizationUrls(ctx, at, events), {
387
+ profileId: ctx.profile.id,
388
+ turnInput: turn.input,
389
+ model: turn.model,
390
+ });
391
+ }
392
+ finally {
393
+ over.abort();
394
+ // why: A stop that stays set would stop the follow-up, which keeps this hold.
395
+ await held?.stop?.clear().catch((err) => ctx.options.onError?.(err, at));
396
+ if (key)
397
+ await ctx.steer.close(key);
398
+ }
399
+ }
400
+ /**
401
+ * How this request runs the model for a reply: its generation, its abort (the request's, a stop,
402
+ * or its hold losing the chat), and the chat's hold it saves under.
403
+ */
404
+ function chatRunner(ctx, at, generation, held) {
405
+ // invariant: The page's pick is checked here, before prepare; a model prepare sets is the host's own.
406
+ refuseInterfacePick(ctx.profile, generation);
407
+ const key = generation.turnId ? inboxKey(at.sessionId, generation.turnId) : undefined;
408
+ const stop = new AbortController();
409
+ const signal = AbortSignal.any([at.signal, stop.signal, ...(held ? [held.run.signal] : [])]);
410
+ let refusal;
411
+ return {
412
+ run: (turn) => chatTurn(ctx, at, turn, key, signal, stop, held, (refused) => {
413
+ refusal = refused;
414
+ }),
415
+ refused: () => refusal,
416
+ async compact(history, tokens, model) {
417
+ const provider = await ctx.options.provider(at, model);
418
+ const compacted = await compactHistory({
419
+ profile: ctx.profile.id,
420
+ history,
421
+ tokens,
422
+ signal,
423
+ ...(model ? { model } : {}),
424
+ }, provider);
425
+ return compacted?.history;
426
+ },
427
+ ...(generation.model ? { model: generation.model } : {}),
428
+ ...(generation.effort ? { effort: generation.effort } : {}),
429
+ ...(generation.stated ? { stated: generation.stated } : {}),
430
+ signal,
431
+ ...(held ? { reply: held.run.reply, hold: held.run.hold, held: held.renew } : {}),
432
+ saving: replySaving(ctx, at, held),
433
+ };
434
+ }
435
+ /** The app's steps around a reply's save, bound to `at` and to the reply's hold. */
436
+ function replySaving(ctx, at, held) {
437
+ const { beforeSave, afterSave, compact, onError } = ctx.options;
438
+ return {
439
+ ...(beforeSave
440
+ ? {
441
+ before: (reply) => beforeSave(at, {
442
+ ...reply,
443
+ ...(held?.reads.from === 'app' ? { held: held.reads.run } : {}),
444
+ }),
445
+ }
446
+ : {}),
447
+ after: async (saved) => {
448
+ held?.told(saved.told);
449
+ await afterSave?.(at, saved);
450
+ },
451
+ ...(compact ? { compact: (signal) => compact(at, signal) } : {}),
452
+ report: (err) => onError?.(err, at),
453
+ };
454
+ }
455
+ /** The chat's conversation as this session's runs read and write it; undefined when the profile keeps none. */
456
+ function conversationHost(ctx, at) {
457
+ const store = ctx.chat.conversations;
458
+ if (!store)
459
+ return undefined;
460
+ return readerConversationHost({
461
+ sessionId: at.sessionId,
462
+ store,
463
+ profile: { outputs: ctx.chat.profile.outputs, labels: ctx.profile.labels },
464
+ clientEvents: ctx.options.clientEvents,
465
+ });
466
+ }
467
+ /**
468
+ * The wake's reply under a hold of the chat; nothing when no decider tells a result, or while a
469
+ * paused reply still waits: the answer that goes on reads what waits. Once every gate of a paused
470
+ * reply has lapsed, the wake walks away from it and runs.
471
+ */
472
+ async function wakeLines(ctx, at, host, ref, generation, input) {
473
+ const opened = await openConversation(host, ref, { kind: 'read' });
474
+ if (!holds(ctx))
475
+ return unheld(noLines());
476
+ const waits = await pausedWaits(ctx, at, opened.conversation);
477
+ if (waits)
478
+ return waiting(waits);
479
+ return heldLines(ctx, at, host, opened, { opening: 'wake' }, (held, current) => wakeReplyLines(ctx, at, host, current(), generation, held, input));
480
+ }
481
+ /** No reply lines. */
482
+ async function* noLines() { }
483
+ /**
484
+ * No run, while a paused reply waits: `held` until its last gate lapses. A gate with no time limit
485
+ * never lapses, so the run ends `released` and only the person's answer or next message goes on.
486
+ */
487
+ async function* waiting(waits) {
488
+ yield* noLines();
489
+ return waits.until === undefined
490
+ ? { outcome: 'released' }
491
+ : { outcome: 'held', leasedUntil: waits.until };
492
+ }
493
+ /**
494
+ * A reply to no message under `held`, on the chat as it stands now. The page that woke draws it;
495
+ * any other page open on the session reads it once it ends.
496
+ */
497
+ async function* wakeReplyLines(ctx, at, host, ref, generation, held, input) {
498
+ if (ref === null)
499
+ return;
500
+ const opened = await openConversation(host, ref, { kind: 'read' });
501
+ const walkAway = opened.conversation.paused
502
+ ? await takeLapsed(ctx, at, opened.conversation)
503
+ : undefined;
504
+ // why: an answer landed since the run was let in, so the reply still waits and the answer goes on
505
+ if (opened.conversation.paused && !walkAway)
506
+ return;
507
+ const runner = chatRunner(ctx, at, generation, held);
508
+ yield* wakeReply({
509
+ host,
510
+ opened,
511
+ runner,
512
+ ...(input ? { input } : {}),
513
+ ...(walkAway ? { walkAway } : {}),
514
+ });
515
+ ctx.options.notifier?.publish(at.sessionId);
516
+ }
517
+ /**
518
+ * why: The transcript keeps a detached call as the turn left it. The session holds what became of
519
+ * it, so a call that has ended does not read as running.
520
+ */
521
+ async function currentView(ctx, at, host, ref, opened) {
522
+ const { conversation, running } = opened;
523
+ const view = { ...conversationView(host, conversation), ...(running ? { running } : {}) };
524
+ const detached = view.transcript.some(isDetachedBlock);
525
+ // why: a session's late results come from detached calls only; an app's items come from anywhere
526
+ if (!detached && !ctx.options.inbox)
527
+ return view;
528
+ const wake = (await wakeDue(ctx, at, host, ref, conversation)) ? { wake: true } : {};
529
+ if (!detached)
530
+ return { ...view, ...notifyOffer(ctx), ...wake };
531
+ const { operations } = await ctx.sessions.read(at.sessionId);
532
+ const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, at, block, operations, host) : block));
533
+ // why: an app's inbox saves replies the page did not ask for, so its page always listens
534
+ const listens = ctx.options.inbox !== undefined || transcript.some(isDetachedBlock);
535
+ return { ...view, transcript, ...(listens ? notifyOffer(ctx) : {}), ...wake };
536
+ }
537
+ /** The view's offer to listen on `/notify`: none without a notifier. */
538
+ function notifyOffer(ctx) {
539
+ const { notifier, notifyRetryMs } = ctx.options;
540
+ if (!notifier)
541
+ return {};
542
+ return { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } };
543
+ }
544
+ /**
545
+ * Whether the page wakes the chat now: the decider's policy tells a waiting result to a reply to no
546
+ * message. Never while a paused reply still waits: the answer that goes on reads what waits.
547
+ */
548
+ async function wakeDue(ctx, at, host, ref, conversation) {
549
+ if (await pausedWaits(ctx, at, conversation))
550
+ return false;
551
+ const holding = holdingOf(ctx, at, host, { ref, conversation });
552
+ return holding ? holding.due() : false;
553
+ }
554
+ /** Whether a reply runs under a hold of the chat: the app passes an inbox, or a decider tells late results. */
555
+ function holds(ctx) {
556
+ return ctx.options.inbox !== undefined || ctx.options.lateResultsDecider !== undefined;
557
+ }
558
+ function isDetachedBlock(block) {
559
+ return block.kind === 'tool' && block.tool.state?.phase === 'background';
560
+ }
561
+ /** A detached call's block as its operation stands. One the session no longer holds has no known end. */
562
+ async function lateBlock(ctx, at, block, operations, host) {
563
+ const { tool } = block;
564
+ const id = tool.operationId;
565
+ const operation = id && Object.hasOwn(operations, id) ? operations[id] : undefined;
566
+ if (operation?.status === 'running' || operation?.status === 'background')
567
+ return block;
568
+ const { labels } = ctx.profile;
569
+ if (operation?.status === 'settled' &&
570
+ ctx.options.authorizeToolReplay &&
571
+ !(await ctx.options.authorizeToolReplay(at, operation))) {
572
+ const message = labelText('error.blocked', {}, labels);
573
+ const failure = { code: 'outcome_withheld', kind: 'blocked', message };
574
+ const { name, callId } = tool;
575
+ const at = operation.settledAt;
576
+ return {
577
+ ...block,
578
+ tool: {
579
+ ...tool,
580
+ state: { name, callId, at, phase: 'error', failure, readBack: message },
581
+ endedAt: at,
582
+ },
583
+ };
584
+ }
585
+ if (operation?.status === 'settled') {
586
+ const settled = host.forReader(operation.outcome.event);
587
+ if (settled.type !== 'tool')
588
+ return block;
589
+ const { tool: state } = settled;
590
+ if (!('phase' in state) || (state.phase !== 'complete' && state.phase !== 'error'))
591
+ return block;
592
+ return { ...block, tool: { ...tool, state, endedAt: operation.settledAt } };
593
+ }
594
+ const { name, callId } = tool;
595
+ const unresolved = detachedEnd({ operationId: id ?? '', callId, name, at: tool.state?.at ?? Date.now() }, operation, labels);
596
+ if (!unresolved)
597
+ return block;
598
+ const { operationId: _id, ...state } = unresolved.event.tool;
599
+ return { ...block, tool: { ...tool, state, endedAt: state.at } };
600
+ }
601
+ /** The answer's reply, handed first what the paused reply read, so it tells them as it goes on. */
602
+ async function* answered(held, paused, reply) {
603
+ if (held && paused)
604
+ await held.run.resume(paused);
605
+ yield* reply();
606
+ }
607
+ /**
608
+ * The message as the profile accepts it, and the conversation it posts to, when the host keeps
609
+ * one. Refuses a message the profile does not take, a conversation the host does not have, and a
610
+ * walk-away that does not name the calls the paused reply waits on. Changes nothing.
611
+ */
612
+ async function messageOpened(ctx, at, args) {
613
+ const posted = postedMessage(chatInterface(ctx.chat), args.input, args.context);
614
+ const host = conversationHost(ctx, at);
615
+ if (!host) {
616
+ if (args.ref !== undefined)
617
+ throw statelessRefusal('continue');
618
+ // labels-exempt: internal diagnostic; the user reads error.request
619
+ if (args.abandon)
620
+ throw statelessRefusal('walk away from');
621
+ return { posted };
622
+ }
623
+ const opened = await openConversation(host, args.ref, {
624
+ kind: 'message',
625
+ ...(args.abandon ? { abandon: args.abandon } : {}),
626
+ });
627
+ return { posted, kept: { host, opened } };
628
+ }
629
+ /** The person's message: a new reply, run against the conversation the app keeps. */
630
+ async function message(ctx, at, args) {
631
+ const { generation = {}, saved } = args;
632
+ if (saved && !ctx.options.inbox) {
633
+ // labels-exempt: builder config error; the user reads error.config
634
+ throw new TheoremError('config', "a `saved` message needs `inbox`: its hold is in the app's inbox");
635
+ }
636
+ const { posted, kept } = await messageOpened(ctx, at, args);
637
+ if (!kept) {
638
+ const runner = chatRunner(ctx, at, generation);
639
+ return unheld(runner.run({
640
+ input: posted.input,
641
+ model: generation.model,
642
+ effort: generation.effort,
643
+ ...(generation.stated ? { stated: generation.stated } : {}),
644
+ }));
645
+ }
646
+ const { host, opened } = kept;
647
+ // why: Take the walked-away calls before streaming, so a stale one is a reply status, not a stream error.
648
+ const walkAway = args.abandon
649
+ ? await takeWalkedAway(ctx, at, args.abandon, opened.conversation)
650
+ : undefined;
651
+ const start = saved
652
+ ? { opening: 'message', hold: saved.hold }
653
+ : { opening: 'message', takeOver: true };
654
+ return heldLines(ctx, at, host, opened, start, (held) => messageReply({
655
+ host,
656
+ opened,
657
+ message: posted,
658
+ ...(walkAway ? { walkAway } : {}),
659
+ ...(saved ? { saved: saved.blocks } : {}),
660
+ runner: chatRunner(ctx, at, generation, held),
661
+ }));
662
+ }
663
+ /** The answered call's events, for a session that keeps no conversation. */
664
+ export async function unconversedAnswer(ctx, at, body) {
665
+ if (body.conversation !== undefined)
666
+ throw statelessRefusal('continue');
667
+ return unheld((await settlingOf(ctx, at, body))());
668
+ }
669
+ /**
670
+ * The person's answer to a paused call. In a kept conversation the reply goes on in the same
671
+ * run once no call waits; otherwise the run is the call's.
672
+ */
673
+ async function answer(ctx, at, body) {
674
+ const host = conversationHost(ctx, at);
675
+ if (!host)
676
+ return unconversedAnswer(ctx, at, body);
677
+ if (body.conversation === undefined)
678
+ throw unknownConversation();
679
+ const call = { callId: body.gateId, operationId: body.operationId };
680
+ const opened = await openConversation(host, body.conversation, { kind: 'answer', call });
681
+ const settling = await settlingOf(ctx, at, body);
682
+ const paused = opened.conversation.paused?.reply;
683
+ return heldLines(ctx, at, host, opened, { opening: 'message', takeOver: true }, (held) => answered(held, paused, () => answerReply({
684
+ host,
685
+ opened,
686
+ call,
687
+ settling: settling(),
688
+ runner: chatRunner(ctx, at, body, held),
689
+ })));
690
+ }
691
+ /**
692
+ * A reply to no message, for results that ended since the model last ran. It runs under a hold of
693
+ * the chat, so two wakes at once run it once, and reads what the decider's policy tells.
694
+ */
695
+ async function wake(ctx, at, args) {
696
+ const host = conversationHost(ctx, at);
697
+ if (!host)
698
+ throw statelessRefusal('wake');
699
+ return await wakeLines(ctx, at, host, args.ref, args.generation ?? {}, args.input);
700
+ }
701
+ /**
702
+ * One follow-up, under the hold a run ended `continue` with. `ref` is the chat the follow-up
703
+ * answers in, which is `at`'s to read: under an app inbox it can be another session's than the
704
+ * run's.
705
+ */
706
+ async function followUp(ctx, at, args) {
707
+ const host = conversationHost(ctx, at);
708
+ if (!host)
709
+ throw statelessRefusal('wake');
710
+ if (!holds(ctx))
711
+ return unheld(noLines());
712
+ const opened = await openConversation(host, args.ref, { kind: 'read' }).catch(async (err) => {
713
+ // why: a follow-up that cannot open its chat runs nothing, so the hold is let go at once
714
+ await appHolding(ctx, at, args.ref)?.letGo(args.hold);
715
+ throw err;
716
+ });
717
+ if (await pausedWaits(ctx, at, opened.conversation)) {
718
+ await holdingOf(ctx, at, host, opened)?.letGo(args.hold);
719
+ return unheld(noLines());
720
+ }
721
+ const start = { opening: 'follow_up', hold: args.hold };
722
+ return heldLines(ctx, at, host, opened, start, (held, current) => wakeReplyLines(ctx, at, host, current(), args.generation ?? {}, held, args.input));
723
+ }
724
+ /**
725
+ * Lets the conversation go under the hold a run ended `continue` with. Under an app inbox no chat
726
+ * is read: the hold is of the app's key.
727
+ */
728
+ async function release(ctx, at, args) {
729
+ const app = appHolding(ctx, at, args.ref);
730
+ if (app)
731
+ return app.letGo(args.hold);
732
+ const host = conversationHost(ctx, at);
733
+ if (!host)
734
+ throw statelessRefusal('wake');
735
+ const opened = await openConversation(host, args.ref, { kind: 'read' });
736
+ await holdingOf(ctx, at, host, opened)?.letGo(args.hold);
737
+ }
738
+ /** The conversation as a page draws it. */
739
+ async function read(ctx, at, args) {
740
+ const host = conversationHost(ctx, at);
741
+ if (!host)
742
+ throw statelessRefusal('read');
743
+ const opened = await openConversation(host, args.ref, { kind: 'read' });
744
+ return currentView(ctx, at, host, args.ref, opened);
745
+ }
746
+ /** The conversation cut after one block; a reply that waits on gates is walked away from first. */
747
+ async function rewind(ctx, at, args) {
748
+ const host = conversationHost(ctx, at);
749
+ if (!host)
750
+ throw statelessRefusal('rewind');
751
+ const opened = await openConversation(host, args.ref, { kind: 'rewind', at: args.at });
752
+ const waiting = waitingCalls(opened.conversation);
753
+ const walkAway = waiting.length
754
+ ? await takeWalkedAway(ctx, at, waiting, opened.conversation)
755
+ : undefined;
756
+ const next = await rewindConversation({
757
+ host,
758
+ opened,
759
+ at: args.at,
760
+ ...(walkAway ? { walkAway } : {}),
761
+ });
762
+ if (next.ref === null)
763
+ throw new TheoremError('internal', labelText('error.internal'));
764
+ return {
765
+ conversation: next.ref,
766
+ view: await currentView(ctx, at, host, next.ref, next),
767
+ };
768
+ }
769
+ /** The conversation core over `state`. */
770
+ export function createConversationCore(state) {
771
+ oneInbox(state.options);
772
+ return {
773
+ message: (at, args) => message(state, at, args),
774
+ checkMessage: async (at, args) => {
775
+ await messageOpened(state, at, args);
776
+ },
777
+ answer: (at, body) => answer(state, at, body),
778
+ wake: (at, args) => wake(state, at, args),
779
+ followUp: (at, args) => followUp(state, at, args),
780
+ release: (at, args) => release(state, at, args),
781
+ read: (at, args) => read(state, at, args),
782
+ rewind: (at, args) => rewind(state, at, args),
783
+ steer: async (at, { turnId, ...steer }) => {
784
+ postedMessage(chatInterface(state.chat), steer.input);
785
+ return await state.steer.enqueue(inboxKey(at.sessionId, turnId), steerUnitOf(steer));
786
+ },
787
+ stop: (at, args) => {
788
+ const app = state.options.inbox?.(at);
789
+ if (app?.stop)
790
+ return app.stop.ask(app.conversation);
791
+ // why: without the app's stop, only this server's turns are known, each by its id
792
+ if (!('turnId' in args))
793
+ throw replyUnreachable();
794
+ return Promise.resolve(state.steer.stop(inboxKey(at.sessionId, args.turnId)));
795
+ },
796
+ };
797
+ }