@theoremjs/web 0.3.5-next.1012.g714018f → 0.3.5-next.1014.g14db6b7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -8
- package/client/chat.js +98 -2
- package/client/index.d.ts +1 -1
- package/client/transport.d.ts +18 -4
- package/client/transport.js +6 -0
- package/package.json +2 -2
- package/server/conversation-core.d.ts +50 -19
- package/server/conversation-core.js +368 -117
- package/server/conversation-inbox.d.ts +19 -14
- package/server/conversation-inbox.js +57 -7
- package/server/conversation.d.ts +1 -0
- package/server/conversation.js +5 -1
- package/server/create-conversation-core.d.ts +1 -1
- package/server/create-conversation-core.js +3 -2
- package/server/handler.d.ts +11 -5
- package/server/handler.js +41 -12
- package/server/mod.d.ts +4 -3
- package/server/mod.js +4 -3
- package/server/own-inbox.d.ts +83 -0
- package/server/own-inbox.js +175 -0
- package/server/reply-feed.d.ts +41 -0
- package/server/reply-feed.js +48 -0
- package/server/steer-inbox.d.ts +0 -41
- package/server/steer-inbox.js +0 -84
|
@@ -9,11 +9,11 @@ import { compactHistory, defaultKernelScope, defineProfile, labelText, runTurn,
|
|
|
9
9
|
import { runConversation, } from '@theoremjs/agents/conversation';
|
|
10
10
|
import { interfaceFromProfile, refuseInterfacePick, } from '@theoremjs/agents/interface';
|
|
11
11
|
import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
|
|
12
|
-
import {
|
|
12
|
+
import { arrivePersonMessage, detachedEnd, readerEnding, readerOf, sessionConversationInbox, } from "./conversation-inbox.js";
|
|
13
13
|
import { endedBlock, unknownConversation, } from "./conversation-store.js";
|
|
14
|
+
import { openRun, ownKey, ownPolicy, ownReads, personMessageOf, scopedStop, steerRun, } from "./own-inbox.js";
|
|
14
15
|
import { sessionPageDispatch } from "./page-dispatch.js";
|
|
15
16
|
import { announced, backgroundWiring, pausedWaits, recorded, replayAllowed, saveEnded, sessionCredentials, settlingOf, takeLapsed, takeWalkedAway, withAuthorizationUrls, } from "./session-calls.js";
|
|
16
|
-
import { steerStage, steerUnitOf, stopOnRequest } from "./steer-inbox.js";
|
|
17
17
|
import { sessionToolCoordinator } from "./tool-operations.js";
|
|
18
18
|
import { isRefusal, preparedTurn, stagesInOrder } from "./turn-wiring.js";
|
|
19
19
|
/**
|
|
@@ -63,6 +63,10 @@ function chatInterface(chat) {
|
|
|
63
63
|
}
|
|
64
64
|
/** Refuses an app's inbox beside a decider for the session's: one inbox holds what a reply is told. */
|
|
65
65
|
export function oneInbox(options) {
|
|
66
|
+
if (options.replyFeed !== undefined && options.notifier === undefined) {
|
|
67
|
+
// labels-exempt: builder config error; the user reads error.config
|
|
68
|
+
throw new TheoremError('config', '`replyFeed` needs `notifier`: the notifier tells the pages that a reply starts and ends');
|
|
69
|
+
}
|
|
66
70
|
if (options.inbox === undefined || options.lateResultsDecider === undefined)
|
|
67
71
|
return;
|
|
68
72
|
// labels-exempt: builder config error; the user reads error.config
|
|
@@ -73,20 +77,23 @@ async function* unheld(lines) {
|
|
|
73
77
|
yield* lines;
|
|
74
78
|
return { outcome: 'released' };
|
|
75
79
|
}
|
|
76
|
-
/**
|
|
80
|
+
/** Aborts `target` when the stop asks for the reply; `over` ends the wait. */
|
|
81
|
+
function abortOnStop(stop, over, target, onError) {
|
|
82
|
+
stop.stopped(over).then((stopped) => {
|
|
83
|
+
if (stopped)
|
|
84
|
+
target.abort();
|
|
85
|
+
}, onError);
|
|
86
|
+
}
|
|
77
87
|
/**
|
|
78
|
-
* The refusal of a stop or steer by conversation
|
|
79
|
-
*
|
|
88
|
+
* The refusal of a stop or steer by conversation for a reply the store says runs, which this
|
|
89
|
+
* process does not hold. Not `turn_ended`: the reply may still be running.
|
|
80
90
|
*/
|
|
81
|
-
|
|
91
|
+
function replyUnreachable() {
|
|
82
92
|
// labels-exempt: internal diagnostic; the user reads session.reply_unreachable
|
|
83
93
|
return new TheoremError('request', 'this host cannot reach a reply that runs elsewhere', {
|
|
84
94
|
copy: { key: 'session.reply_unreachable' },
|
|
85
95
|
});
|
|
86
96
|
}
|
|
87
|
-
function inboxKey(sessionId, turnId) {
|
|
88
|
-
return `${sessionId}\u0000${turnId}`;
|
|
89
|
-
}
|
|
90
97
|
const DEFAULT_CONVERSATION_LEASE_MS = 60_000;
|
|
91
98
|
/**
|
|
92
99
|
* The session's inbox for the chat: the chat as this context last wrote it, and the results this
|
|
@@ -107,6 +114,7 @@ function chatInbox(ctx, at, host, opened, ref) {
|
|
|
107
114
|
},
|
|
108
115
|
readable: (operation) => replayAllowed(ctx, at, operation),
|
|
109
116
|
labels: ctx.profile.labels,
|
|
117
|
+
shelf: ctx.own.shelf,
|
|
110
118
|
});
|
|
111
119
|
return { inbox, key: opened.conversation.id, leaseMs };
|
|
112
120
|
}
|
|
@@ -167,14 +175,10 @@ function holdingOver(kept, chat) {
|
|
|
167
175
|
for (const id of ids)
|
|
168
176
|
told.add(id);
|
|
169
177
|
},
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
clear: () => stop.clear(key, run.hold),
|
|
175
|
-
},
|
|
176
|
-
}
|
|
177
|
-
: {}),
|
|
178
|
+
stop: {
|
|
179
|
+
stopped: (over) => stop.stopped(key, run.hold, over),
|
|
180
|
+
clear: () => stop.clear(key, run.hold),
|
|
181
|
+
},
|
|
178
182
|
};
|
|
179
183
|
const ref = chat.ref();
|
|
180
184
|
// why: The page moves a message it shows as waiting into the reply that reads it, as the reply starts.
|
|
@@ -248,30 +252,54 @@ function appHolding(ctx, at, ref) {
|
|
|
248
252
|
policy: app.policy,
|
|
249
253
|
reads: (run) => ({ from: 'app', run }),
|
|
250
254
|
gaveUp: gaveUp(ctx, at, 'inbox_items_given_up'),
|
|
251
|
-
|
|
255
|
+
stop: app.stop ?? scopedStop(ctx.own.stop, at.sessionId),
|
|
252
256
|
}, chatRef(ref));
|
|
253
257
|
}
|
|
254
258
|
/**
|
|
255
|
-
* The inbox
|
|
256
|
-
*
|
|
259
|
+
* The inbox a reply holds when the app passes none: Theorem's own, named `key`. It holds the
|
|
260
|
+
* person's messages beside the late results the decider tells.
|
|
257
261
|
*/
|
|
262
|
+
function ownHolding(own, chat) {
|
|
263
|
+
const { decider } = own;
|
|
264
|
+
return holdingOver({
|
|
265
|
+
inbox: own.inbox,
|
|
266
|
+
key: own.key,
|
|
267
|
+
leaseMs: own.leaseMs,
|
|
268
|
+
policy: ownPolicy({ ...(decider ? { decider } : {}), host: own.host }),
|
|
269
|
+
reads: (run) => {
|
|
270
|
+
const reads = ownReads(run);
|
|
271
|
+
return {
|
|
272
|
+
from: 'own',
|
|
273
|
+
...(decider ? { late: reads.late } : {}),
|
|
274
|
+
stage: reads.stage,
|
|
275
|
+
settle: (ids) => own.settle(run, reads.mine(ids)),
|
|
276
|
+
settles: own.settles,
|
|
277
|
+
};
|
|
278
|
+
},
|
|
279
|
+
gaveUp: own.gaveUp,
|
|
280
|
+
stop: scopedStop(own.stop, own.scope),
|
|
281
|
+
}, chat);
|
|
282
|
+
}
|
|
283
|
+
/** The inbox this context's replies hold: the app's when it passes one, Theorem's own otherwise. */
|
|
258
284
|
function holdingOf(ctx, at, host, opened) {
|
|
259
285
|
const app = appHolding(ctx, at, opened.ref);
|
|
260
286
|
if (app)
|
|
261
287
|
return app;
|
|
262
288
|
const chat = chatRef(opened.ref);
|
|
289
|
+
const { inbox, key, leaseMs } = chatInbox(ctx, at, host, opened, chat.ref);
|
|
263
290
|
const decider = ctx.options.lateResultsDecider;
|
|
264
|
-
if (!decider)
|
|
265
|
-
return undefined;
|
|
266
291
|
let whose;
|
|
267
|
-
return
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
292
|
+
return ownHolding({
|
|
293
|
+
scope: at.sessionId,
|
|
294
|
+
stop: ctx.own.stop,
|
|
295
|
+
inbox,
|
|
296
|
+
key,
|
|
297
|
+
leaseMs,
|
|
298
|
+
...(decider ? { decider } : {}),
|
|
299
|
+
host: () => (whose ??= Promise.resolve(at.host)),
|
|
274
300
|
gaveUp: gaveUp(ctx, at, 'late_results_given_up'),
|
|
301
|
+
settle: (_run, ids) => inbox.settle(key, ids),
|
|
302
|
+
settles: 'save',
|
|
275
303
|
}, chat);
|
|
276
304
|
}
|
|
277
305
|
/**
|
|
@@ -283,9 +311,8 @@ function holdingOf(ctx, at, host, opened) {
|
|
|
283
311
|
*/
|
|
284
312
|
function heldLines(ctx, at, host, opened, start, reply) {
|
|
285
313
|
const holding = holdingOf(ctx, at, host, opened);
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
return sent(async (send) => {
|
|
314
|
+
const feed = (lines) => fed(ctx, at, opened.conversation.id, lines);
|
|
315
|
+
return feed(sent(async (send) => {
|
|
289
316
|
const run = await holding.run(start, (held) => reply(held, holding.ref), send);
|
|
290
317
|
if (run.outcome === 'held')
|
|
291
318
|
return { outcome: 'held', leasedUntil: run.leasedUntil };
|
|
@@ -304,7 +331,109 @@ function heldLines(ctx, at, host, opened, start, reply) {
|
|
|
304
331
|
if (run.failure !== undefined)
|
|
305
332
|
throw run.failure;
|
|
306
333
|
return { outcome: run.outcome === 'lost' ? 'lost' : 'released' };
|
|
334
|
+
}));
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* `lines`, each also sent to the reply feed under the conversation's id, and the pages told when
|
|
338
|
+
* the reply starts and ends. A reply that yields no line (nothing waited to tell, or the chat
|
|
339
|
+
* was held) starts nothing. The feed's failure goes to `onError`, never into the reply.
|
|
340
|
+
* invariant: The reply ends in the feed however `lines` ends: its end, a throw, or the caller
|
|
341
|
+
* stopping the read, so a follower is never left waiting for a reply that is over.
|
|
342
|
+
*/
|
|
343
|
+
async function* fed(ctx, at, conversation, lines) {
|
|
344
|
+
const { replyFeed: feed, notifier } = ctx.options;
|
|
345
|
+
if (!feed)
|
|
346
|
+
return yield* lines;
|
|
347
|
+
const reply = crypto.randomUUID();
|
|
348
|
+
const tell = async (step) => {
|
|
349
|
+
try {
|
|
350
|
+
await step();
|
|
351
|
+
}
|
|
352
|
+
catch (err) {
|
|
353
|
+
ctx.options.onError?.(err, at);
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
let begun = false;
|
|
357
|
+
let over = false;
|
|
358
|
+
try {
|
|
359
|
+
for (;;) {
|
|
360
|
+
const next = await lines.next();
|
|
361
|
+
if (next.done) {
|
|
362
|
+
over = true;
|
|
363
|
+
return next.value;
|
|
364
|
+
}
|
|
365
|
+
if (!begun) {
|
|
366
|
+
begun = true;
|
|
367
|
+
await tell(() => feed.start(conversation, reply));
|
|
368
|
+
await tell(() => notifier?.publish(at.sessionId));
|
|
369
|
+
}
|
|
370
|
+
await tell(() => feed.append(conversation, reply, next.value));
|
|
371
|
+
yield next.value;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
finally {
|
|
375
|
+
if (!over)
|
|
376
|
+
await lines.return({ outcome: 'released' }).catch(() => undefined);
|
|
377
|
+
if (begun) {
|
|
378
|
+
await tell(() => feed.end(conversation, reply));
|
|
379
|
+
await tell(() => notifier?.publish(at.sessionId));
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* The lines of the reply that runs on the conversation under `args.ref`, from its first, then
|
|
385
|
+
* each as it comes, until it ends or `at.signal` aborts. Ends at once when no reply runs.
|
|
386
|
+
*/
|
|
387
|
+
async function follow(ctx, at, args) {
|
|
388
|
+
const feed = ctx.options.replyFeed;
|
|
389
|
+
if (!feed) {
|
|
390
|
+
// labels-exempt: builder config error; the user reads error.config
|
|
391
|
+
throw new TheoremError('config', 'following a reply needs `replyFeed`');
|
|
392
|
+
}
|
|
393
|
+
const host = conversationHost(ctx, at);
|
|
394
|
+
if (!host)
|
|
395
|
+
throw statelessRefusal('follow');
|
|
396
|
+
const opened = await openConversation(host, args.ref, { kind: 'read' });
|
|
397
|
+
const queue = [];
|
|
398
|
+
let over = false;
|
|
399
|
+
let wake = () => { };
|
|
400
|
+
const stop = await feed.follow(opened.conversation.id, {
|
|
401
|
+
line(line) {
|
|
402
|
+
queue.push(line);
|
|
403
|
+
wake();
|
|
404
|
+
},
|
|
405
|
+
end() {
|
|
406
|
+
over = true;
|
|
407
|
+
wake();
|
|
408
|
+
},
|
|
307
409
|
});
|
|
410
|
+
const leave = () => {
|
|
411
|
+
over = true;
|
|
412
|
+
wake();
|
|
413
|
+
};
|
|
414
|
+
if (at.signal.aborted)
|
|
415
|
+
leave();
|
|
416
|
+
else
|
|
417
|
+
at.signal.addEventListener('abort', leave, { once: true });
|
|
418
|
+
return (async function* () {
|
|
419
|
+
try {
|
|
420
|
+
for (;;) {
|
|
421
|
+
if (queue.length > 0) {
|
|
422
|
+
yield queue.splice(0, 1)[0];
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
if (over)
|
|
426
|
+
return;
|
|
427
|
+
await new Promise((resolve) => {
|
|
428
|
+
wake = resolve;
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
finally {
|
|
433
|
+
at.signal.removeEventListener('abort', leave);
|
|
434
|
+
stop();
|
|
435
|
+
}
|
|
436
|
+
})();
|
|
308
437
|
}
|
|
309
438
|
/**
|
|
310
439
|
* A run, then what `choose` says for each `continue` it and its follow-ups end with. It ends as
|
|
@@ -335,45 +464,25 @@ async function isPaused(host, ref, fallback) {
|
|
|
335
464
|
const conversation = ref === null ? fallback : (await host.store.read(host.sessionId, ref))?.conversation;
|
|
336
465
|
return conversation?.paused !== undefined;
|
|
337
466
|
}
|
|
338
|
-
/** The late results a reply's model reads: what it opened with, then what each later moment hands it. */
|
|
339
|
-
function lateSource(run) {
|
|
340
|
-
let opening = true;
|
|
341
|
-
return async ({ stage, step }) => {
|
|
342
|
-
if (opening && stage === 'pre_turn') {
|
|
343
|
-
opening = false;
|
|
344
|
-
return run.opened.map((item) => item.outcome);
|
|
345
|
-
}
|
|
346
|
-
return (await run.take({ stage, step })).map((item) => item.outcome);
|
|
347
|
-
};
|
|
348
|
-
}
|
|
349
467
|
/** One model run of a chat's reply, its gates recorded in the session as they pause. */
|
|
350
|
-
async function* chatTurn(ctx, at, turn,
|
|
468
|
+
async function* chatTurn(ctx, at, turn, signal, stop, held, refused) {
|
|
351
469
|
const state = await ctx.sessions.read(at.sessionId);
|
|
352
470
|
const provider = await ctx.options.provider(at, turn.model);
|
|
353
471
|
const host = await at.host;
|
|
354
472
|
const over = new AbortController();
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
if (held?.stop) {
|
|
358
|
-
held.stop.stopped(over.signal).then((stopped) => {
|
|
359
|
-
if (stopped)
|
|
360
|
-
stop.abort();
|
|
361
|
-
}, (err) => ctx.options.onError?.(err, at));
|
|
362
|
-
}
|
|
363
|
-
else if (key) {
|
|
364
|
-
stopOnRequest(ctx.steer, key, stop);
|
|
365
|
-
}
|
|
473
|
+
abortOnStop(held.stop, over.signal, stop, (err) => ctx.options.onError?.(err, at));
|
|
474
|
+
const landed = [];
|
|
366
475
|
try {
|
|
367
|
-
const onStage = stagesInOrder(ctx.options.onStage,
|
|
476
|
+
const onStage = stagesInOrder(ctx.options.onStage, held.reads.from === 'own' ? held.reads.stage : undefined);
|
|
368
477
|
const { prepare } = ctx.options;
|
|
369
|
-
const run = held
|
|
478
|
+
const run = held.reads.from === 'app' ? held.reads.run : undefined;
|
|
370
479
|
const prepared = await preparedTurn(prepare && ((request) => prepare(request, run)), {
|
|
371
480
|
profile: ctx.profile.id,
|
|
372
481
|
execution: sessionToolCoordinator(ctx.sessions, at.sessionId),
|
|
373
482
|
...backgroundWiring(ctx, at),
|
|
374
483
|
pageExecution: sessionPageDispatch(ctx.sessions, at.sessionId, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
|
|
375
484
|
input: turn.input,
|
|
376
|
-
...(held
|
|
485
|
+
...(held.reads.from === 'own' && held.reads.late ? { lateResults: held.reads.late } : {}),
|
|
377
486
|
...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
|
|
378
487
|
...(turn.providerState ? { providerState: turn.providerState } : {}),
|
|
379
488
|
sessionPermissions: state.permissions,
|
|
@@ -395,18 +504,20 @@ async function* chatTurn(ctx, at, turn, key, signal, stop, held, refused) {
|
|
|
395
504
|
return;
|
|
396
505
|
}
|
|
397
506
|
const events = runTurn(prepared, provider);
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
}
|
|
507
|
+
for await (const event of recorded(ctx.sessions, at.sessionId, withAuthorizationUrls(ctx, at, events), { profileId: ctx.profile.id, turnInput: turn.input, model: turn.model })) {
|
|
508
|
+
if (event.type === 'stage')
|
|
509
|
+
landed.push(...(event.injected ?? []).map((inject) => inject.id));
|
|
510
|
+
yield event;
|
|
511
|
+
}
|
|
403
512
|
}
|
|
404
513
|
finally {
|
|
405
514
|
over.abort();
|
|
406
515
|
// why: A stop that stays set would stop the follow-up, which keeps this hold.
|
|
407
|
-
await held
|
|
408
|
-
|
|
409
|
-
|
|
516
|
+
await held.stop.clear().catch((err) => ctx.options.onError?.(err, at));
|
|
517
|
+
// why: A chat that keeps no conversation saves no reply, so its turn tells the message it landed.
|
|
518
|
+
if (held.reads.from === 'own' && held.reads.settles === 'turn') {
|
|
519
|
+
await held.reads.settle(landed).catch((err) => ctx.options.onError?.(err, at));
|
|
520
|
+
}
|
|
410
521
|
}
|
|
411
522
|
}
|
|
412
523
|
/**
|
|
@@ -416,12 +527,11 @@ async function* chatTurn(ctx, at, turn, key, signal, stop, held, refused) {
|
|
|
416
527
|
function chatRunner(ctx, at, generation, held) {
|
|
417
528
|
// invariant: The page's pick is checked here, before prepare; a model prepare sets is the host's own.
|
|
418
529
|
refuseInterfacePick(ctx.profile, generation);
|
|
419
|
-
const key = generation.turnId ? inboxKey(at.sessionId, generation.turnId) : undefined;
|
|
420
530
|
const stop = new AbortController();
|
|
421
|
-
const signal = AbortSignal.any([at.signal, stop.signal,
|
|
531
|
+
const signal = AbortSignal.any([at.signal, stop.signal, held.run.signal]);
|
|
422
532
|
let refusal;
|
|
423
533
|
return {
|
|
424
|
-
run: (turn) => chatTurn(ctx, at, turn,
|
|
534
|
+
run: (turn) => chatTurn(ctx, at, turn, signal, stop, held, (refused) => {
|
|
425
535
|
refusal = refused;
|
|
426
536
|
}),
|
|
427
537
|
refused: () => refusal,
|
|
@@ -440,7 +550,9 @@ function chatRunner(ctx, at, generation, held) {
|
|
|
440
550
|
...(generation.effort ? { effort: generation.effort } : {}),
|
|
441
551
|
...(generation.stated ? { stated: generation.stated } : {}),
|
|
442
552
|
signal,
|
|
443
|
-
|
|
553
|
+
reply: held.run.reply,
|
|
554
|
+
hold: held.run.hold,
|
|
555
|
+
held: held.renew,
|
|
444
556
|
saving: replySaving(ctx, at, held),
|
|
445
557
|
};
|
|
446
558
|
}
|
|
@@ -452,14 +564,18 @@ function replySaving(ctx, at, held) {
|
|
|
452
564
|
? {
|
|
453
565
|
before: (reply) => beforeSave(at, {
|
|
454
566
|
...reply,
|
|
455
|
-
...(held
|
|
567
|
+
...(held.reads.from === 'app' ? { held: held.reads.run } : {}),
|
|
456
568
|
}),
|
|
457
569
|
}
|
|
458
570
|
: {}),
|
|
459
571
|
written: (appended) => saveEnded(ctx, at, appended),
|
|
460
|
-
after: async (
|
|
461
|
-
held
|
|
462
|
-
|
|
572
|
+
after: async ({ ended, told, landed }) => {
|
|
573
|
+
held.told(told);
|
|
574
|
+
// invariant: A reply whose hold lost the chat tells nothing, and its messages wait for the hold that has it.
|
|
575
|
+
if (held.reads.from === 'own' && held.reads.settles === 'save' && ended !== 'lost') {
|
|
576
|
+
await held.reads.settle(landed);
|
|
577
|
+
}
|
|
578
|
+
await afterSave?.(at, { ended, told });
|
|
463
579
|
},
|
|
464
580
|
...(compact ? { compact: (signal) => compact(at, signal) } : {}),
|
|
465
581
|
report: (err) => onError?.(err, at),
|
|
@@ -484,8 +600,6 @@ function conversationHost(ctx, at) {
|
|
|
484
600
|
*/
|
|
485
601
|
async function wakeLines(ctx, at, host, ref, generation, input) {
|
|
486
602
|
const opened = await openConversation(host, ref, { kind: 'read' });
|
|
487
|
-
if (!holds(ctx))
|
|
488
|
-
return unheld(noLines());
|
|
489
603
|
const waits = await pausedWaits(ctx, at, opened.conversation);
|
|
490
604
|
if (waits)
|
|
491
605
|
return waiting(waits);
|
|
@@ -505,7 +619,7 @@ async function* waiting(waits) {
|
|
|
505
619
|
}
|
|
506
620
|
/**
|
|
507
621
|
* A reply to no message under `held`, on the chat as it stands now. The page that woke draws it;
|
|
508
|
-
* any other page open on the session reads it once it ends.
|
|
622
|
+
* with a `replyFeed`, any other page open on the session follows it, and without one reads it once it ends.
|
|
509
623
|
*/
|
|
510
624
|
async function* wakeReplyLines(ctx, at, host, ref, generation, held, input) {
|
|
511
625
|
if (ref === null)
|
|
@@ -534,18 +648,23 @@ async function* wakeReplyLines(ctx, at, host, ref, generation, held, input) {
|
|
|
534
648
|
async function currentView(ctx, at, host, ref, opened) {
|
|
535
649
|
const { conversation, running } = opened;
|
|
536
650
|
const view = { ...conversationView(host, conversation), ...(running ? { running } : {}) };
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
651
|
+
const { replyFeed, inbox } = ctx.options;
|
|
652
|
+
const following = replyFeed ? { follow: true } : {};
|
|
653
|
+
// why: a person's message can wait in any chat, so every view asks whether the chat wakes
|
|
540
654
|
const wake = (await wakeDue(ctx, at, host, ref, conversation)) ? { wake: true } : {};
|
|
541
655
|
if (!view.transcript.some(isDetachedBlock)) {
|
|
542
|
-
return {
|
|
656
|
+
return {
|
|
657
|
+
...view,
|
|
658
|
+
...(inbox || replyFeed ? notifyOffer(ctx) : {}),
|
|
659
|
+
...following,
|
|
660
|
+
...wake,
|
|
661
|
+
};
|
|
543
662
|
}
|
|
544
663
|
const { operations } = await ctx.sessions.read(at.sessionId);
|
|
545
664
|
const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, at, block, operations, host) : block));
|
|
546
665
|
// why: an app's inbox saves replies the page did not ask for, so its page always listens
|
|
547
|
-
const listens =
|
|
548
|
-
return { ...view, transcript, ...(listens ? notifyOffer(ctx) : {}), ...wake };
|
|
666
|
+
const listens = inbox !== undefined || replyFeed !== undefined || transcript.some(isDetachedBlock);
|
|
667
|
+
return { ...view, transcript, ...(listens ? notifyOffer(ctx) : {}), ...following, ...wake };
|
|
549
668
|
}
|
|
550
669
|
/** The view's offer to listen on `/notify`: none without a notifier. */
|
|
551
670
|
function notifyOffer(ctx) {
|
|
@@ -561,20 +680,11 @@ function notifyOffer(ctx) {
|
|
|
561
680
|
async function wakeDue(ctx, at, host, ref, conversation) {
|
|
562
681
|
if (await pausedWaits(ctx, at, conversation))
|
|
563
682
|
return false;
|
|
564
|
-
|
|
565
|
-
return holding ? holding.due() : false;
|
|
566
|
-
}
|
|
567
|
-
/** Whether a reply runs under a hold of the chat: the app passes an inbox, or a decider tells late results. */
|
|
568
|
-
function holds(ctx) {
|
|
569
|
-
return ctx.options.inbox !== undefined || ctx.options.lateResultsDecider !== undefined;
|
|
683
|
+
return holdingOf(ctx, at, host, { ref, conversation }).due();
|
|
570
684
|
}
|
|
571
685
|
function isDetachedBlock(block) {
|
|
572
686
|
return block.kind === 'tool' && block.tool.state?.phase === 'background';
|
|
573
687
|
}
|
|
574
|
-
/** A detached call's block, whether its end is saved on it or not. */
|
|
575
|
-
function wasDetached(block) {
|
|
576
|
-
return block.kind === 'tool' && detachedAt(block.tool) !== undefined;
|
|
577
|
-
}
|
|
578
688
|
/**
|
|
579
689
|
* A detached call's block as its operation stands, for a block whose end no save put on it. One
|
|
580
690
|
* the session no longer holds has no known end.
|
|
@@ -609,7 +719,7 @@ async function lateBlock(ctx, at, block, operations, host) {
|
|
|
609
719
|
}
|
|
610
720
|
/** The answer's reply, handed first what the paused reply read, so it tells them as it goes on. */
|
|
611
721
|
async function* answered(held, paused, reply) {
|
|
612
|
-
if (
|
|
722
|
+
if (paused)
|
|
613
723
|
await held.run.resume(paused);
|
|
614
724
|
yield* reply();
|
|
615
725
|
}
|
|
@@ -635,6 +745,90 @@ async function messageOpened(ctx, at, args) {
|
|
|
635
745
|
});
|
|
636
746
|
return { posted, kept: { host, opened } };
|
|
637
747
|
}
|
|
748
|
+
/**
|
|
749
|
+
* Runs `lines` under a hold of the run's own inbox, opened with `openRun`. The reply takes each
|
|
750
|
+
* message `steerRun` puts in, one at each step, and a stop asked of the run's name (the stop of
|
|
751
|
+
* `own`) aborts `NamedHold.signal`. A message that waits when the run ends is not told.
|
|
752
|
+
*/
|
|
753
|
+
export function namedRun(args, lines) {
|
|
754
|
+
return namedHolding(args, (held) => {
|
|
755
|
+
const stop = new AbortController();
|
|
756
|
+
const over = new AbortController();
|
|
757
|
+
abortOnStop(held.stop, over.signal, stop, (err) => args.onError?.(err));
|
|
758
|
+
const signal = AbortSignal.any([args.signal, stop.signal, held.run.signal]);
|
|
759
|
+
return (async function* () {
|
|
760
|
+
const landed = [];
|
|
761
|
+
try {
|
|
762
|
+
for await (const line of lines({
|
|
763
|
+
stage: held.reads.from === 'own' ? held.reads.stage : () => undefined,
|
|
764
|
+
signal,
|
|
765
|
+
})) {
|
|
766
|
+
if (line.type === 'stage') {
|
|
767
|
+
landed.push(...(line.injected ?? []).map((inject) => inject.id));
|
|
768
|
+
}
|
|
769
|
+
yield line;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
finally {
|
|
773
|
+
over.abort();
|
|
774
|
+
// why: A stop that stays set would stop the next run under this hold.
|
|
775
|
+
await held.stop.clear().catch((err) => args.onError?.(err));
|
|
776
|
+
if (held.reads.from === 'own' && held.reads.settles === 'turn') {
|
|
777
|
+
await held.reads.settle(landed).catch((err) => args.onError?.(err));
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
})();
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
/** The reply of a run, as `namedRun` and a chat that keeps no conversation run it. */
|
|
784
|
+
function namedHolding(args, lines, report) {
|
|
785
|
+
const { memory } = args.run;
|
|
786
|
+
const holding = ownHolding({
|
|
787
|
+
scope: args.scope,
|
|
788
|
+
stop: args.own.stop,
|
|
789
|
+
inbox: memory,
|
|
790
|
+
key: args.name,
|
|
791
|
+
leaseMs: args.leaseMs,
|
|
792
|
+
host: () => Promise.resolve(undefined),
|
|
793
|
+
gaveUp: report ?? (() => undefined),
|
|
794
|
+
settle: (run, ids) => {
|
|
795
|
+
memory.settle(args.name, run.hold, run.reply, ids);
|
|
796
|
+
return Promise.resolve();
|
|
797
|
+
},
|
|
798
|
+
settles: 'turn',
|
|
799
|
+
}, chatRef(null));
|
|
800
|
+
return sent(async (send) => {
|
|
801
|
+
const run = await holding.run({ opening: 'message', takeOver: true }, lines, send);
|
|
802
|
+
if (run.outcome === 'held')
|
|
803
|
+
return { outcome: 'held', leasedUntil: run.leasedUntil };
|
|
804
|
+
if (run.outcome === 'continue')
|
|
805
|
+
await holding.letGo(run.hold);
|
|
806
|
+
if (run.failure !== undefined)
|
|
807
|
+
throw run.failure;
|
|
808
|
+
return { outcome: run.outcome === 'lost' ? 'lost' : 'released' };
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* The reply of a chat that keeps no conversation. Its inbox is its run's: Theorem's own, in
|
|
813
|
+
* memory, named by the `turnId` the page sent (a random one when it sent none), for as long as the
|
|
814
|
+
* run lasts. A message that waits when the run ends is not told; the page sends it again.
|
|
815
|
+
*/
|
|
816
|
+
async function* runLines(ctx, at, generation, posted) {
|
|
817
|
+
const name = generation.turnId ?? crypto.randomUUID();
|
|
818
|
+
const leaseMs = ctx.options.conversationLeaseMs ?? DEFAULT_CONVERSATION_LEASE_MS;
|
|
819
|
+
const run = openRun(ctx.own, at.sessionId, name, leaseMs);
|
|
820
|
+
try {
|
|
821
|
+
return yield* namedHolding({ own: ctx.own, scope: at.sessionId, name, run, leaseMs }, (held) => chatRunner(ctx, at, generation, held).run({
|
|
822
|
+
input: posted.input,
|
|
823
|
+
model: generation.model,
|
|
824
|
+
effort: generation.effort,
|
|
825
|
+
...(generation.stated ? { stated: generation.stated } : {}),
|
|
826
|
+
}), gaveUp(ctx, at, 'inbox_items_given_up'));
|
|
827
|
+
}
|
|
828
|
+
finally {
|
|
829
|
+
run.close();
|
|
830
|
+
}
|
|
831
|
+
}
|
|
638
832
|
/** The person's message: a new reply, run against the conversation the app keeps. */
|
|
639
833
|
async function message(ctx, at, args) {
|
|
640
834
|
const { generation = {}, saved } = args;
|
|
@@ -643,15 +837,8 @@ async function message(ctx, at, args) {
|
|
|
643
837
|
throw new TheoremError('config', "a `saved` message needs `inbox`: its hold is in the app's inbox");
|
|
644
838
|
}
|
|
645
839
|
const { posted, kept } = await messageOpened(ctx, at, args);
|
|
646
|
-
if (!kept)
|
|
647
|
-
|
|
648
|
-
return unheld(runner.run({
|
|
649
|
-
input: posted.input,
|
|
650
|
-
model: generation.model,
|
|
651
|
-
effort: generation.effort,
|
|
652
|
-
...(generation.stated ? { stated: generation.stated } : {}),
|
|
653
|
-
}));
|
|
654
|
-
}
|
|
840
|
+
if (!kept)
|
|
841
|
+
return runLines(ctx, at, generation, posted);
|
|
655
842
|
const { host, opened } = kept;
|
|
656
843
|
// why: Take the walked-away calls before streaming, so a stale one is a reply status, not a stream error.
|
|
657
844
|
const walkAway = args.abandon
|
|
@@ -660,7 +847,7 @@ async function message(ctx, at, args) {
|
|
|
660
847
|
const start = saved
|
|
661
848
|
? { opening: 'message', hold: saved.hold }
|
|
662
849
|
: { opening: 'message', takeOver: true };
|
|
663
|
-
|
|
850
|
+
const lines = heldLines(ctx, at, host, opened, start, (held) => messageReply({
|
|
664
851
|
host,
|
|
665
852
|
opened,
|
|
666
853
|
message: posted,
|
|
@@ -668,6 +855,24 @@ async function message(ctx, at, args) {
|
|
|
668
855
|
...(saved ? { saved: saved.blocks } : {}),
|
|
669
856
|
runner: chatRunner(ctx, at, generation, held),
|
|
670
857
|
}));
|
|
858
|
+
return generation.turnId === undefined
|
|
859
|
+
? lines
|
|
860
|
+
: namedTurn(ctx.own, at.sessionId, generation.turnId, opened.conversation.id, lines);
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* A reply of a stored chat, known by the page's `turnId` for as long as it runs, so a steer or stop
|
|
864
|
+
* that names the turn reaches the conversation's inbox and hold.
|
|
865
|
+
*/
|
|
866
|
+
async function* namedTurn(own, scope, turnId, conversation, lines) {
|
|
867
|
+
const key = ownKey(scope, turnId);
|
|
868
|
+
own.turns.set(key, conversation);
|
|
869
|
+
try {
|
|
870
|
+
return yield* lines;
|
|
871
|
+
}
|
|
872
|
+
finally {
|
|
873
|
+
if (own.turns.get(key) === conversation)
|
|
874
|
+
own.turns.delete(key);
|
|
875
|
+
}
|
|
671
876
|
}
|
|
672
877
|
/** The answered call's events, for a session that keeps no conversation. */
|
|
673
878
|
export async function unconversedAnswer(ctx, at, body) {
|
|
@@ -716,15 +921,13 @@ async function followUp(ctx, at, args) {
|
|
|
716
921
|
const host = conversationHost(ctx, at);
|
|
717
922
|
if (!host)
|
|
718
923
|
throw statelessRefusal('wake');
|
|
719
|
-
if (!holds(ctx))
|
|
720
|
-
return unheld(noLines());
|
|
721
924
|
const opened = await openConversation(host, args.ref, { kind: 'read' }).catch(async (err) => {
|
|
722
925
|
// why: a follow-up that cannot open its chat runs nothing, so the hold is let go at once
|
|
723
926
|
await appHolding(ctx, at, args.ref)?.letGo(args.hold);
|
|
724
927
|
throw err;
|
|
725
928
|
});
|
|
726
929
|
if (await pausedWaits(ctx, at, opened.conversation)) {
|
|
727
|
-
await holdingOf(ctx, at, host, opened)
|
|
930
|
+
await holdingOf(ctx, at, host, opened).letGo(args.hold);
|
|
728
931
|
return unheld(noLines());
|
|
729
932
|
}
|
|
730
933
|
const start = { opening: 'follow_up', hold: args.hold };
|
|
@@ -742,7 +945,7 @@ async function release(ctx, at, args) {
|
|
|
742
945
|
if (!host)
|
|
743
946
|
throw statelessRefusal('wake');
|
|
744
947
|
const opened = await openConversation(host, args.ref, { kind: 'read' });
|
|
745
|
-
await holdingOf(ctx, at, host, opened)
|
|
948
|
+
await holdingOf(ctx, at, host, opened).letGo(args.hold);
|
|
746
949
|
}
|
|
747
950
|
/** The conversation as a page draws it. */
|
|
748
951
|
async function read(ctx, at, args) {
|
|
@@ -789,18 +992,66 @@ export function createConversationCore(state) {
|
|
|
789
992
|
release: (at, args) => release(state, at, args),
|
|
790
993
|
read: (at, args) => read(state, at, args),
|
|
791
994
|
rewind: (at, args) => rewind(state, at, args),
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
995
|
+
follow: (at, args) => follow(state, at, args),
|
|
996
|
+
steer: async (at, args) => {
|
|
997
|
+
if (state.options.inbox) {
|
|
998
|
+
// labels-exempt: builder config error; the user reads error.config
|
|
999
|
+
throw new TheoremError('config', "a steer goes through `intake`: the app's inbox holds the message");
|
|
1000
|
+
}
|
|
1001
|
+
postedMessage(chatInterface(state.chat), args.input);
|
|
1002
|
+
const message = personMessageOf(args);
|
|
1003
|
+
const arrive = async (conversation) => {
|
|
1004
|
+
if (!state.own.stop.running(ownKey(at.sessionId, conversation)))
|
|
1005
|
+
return false;
|
|
1006
|
+
await arrivePersonMessage({ sessions: state.sessions, sessionId: at.sessionId, shelf: state.own.shelf }, conversation, message);
|
|
1007
|
+
return true;
|
|
1008
|
+
};
|
|
1009
|
+
if ('turnId' in args) {
|
|
1010
|
+
const held = state.own.turns.get(ownKey(at.sessionId, args.turnId));
|
|
1011
|
+
return held === undefined
|
|
1012
|
+
? steerRun(state.own, at.sessionId, args.turnId, message)
|
|
1013
|
+
: arrive(held);
|
|
1014
|
+
}
|
|
1015
|
+
const host = conversationHost(state, at);
|
|
1016
|
+
if (!host)
|
|
1017
|
+
throw statelessRefusal('steer');
|
|
1018
|
+
const { conversation, running } = await openConversation(host, args.ref, { kind: 'read' });
|
|
1019
|
+
if (await arrive(conversation.id))
|
|
1020
|
+
return true;
|
|
1021
|
+
if (running)
|
|
1022
|
+
throw replyUnreachable();
|
|
1023
|
+
return false;
|
|
795
1024
|
},
|
|
796
|
-
stop: (at, args) => {
|
|
1025
|
+
stop: async (at, args) => {
|
|
797
1026
|
const app = state.options.inbox?.(at);
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
1027
|
+
const own = scopedStop(state.own.stop, at.sessionId);
|
|
1028
|
+
if (app) {
|
|
1029
|
+
if (await (app.stop ?? own).ask(app.conversation))
|
|
1030
|
+
return true;
|
|
1031
|
+
if (app.stop || 'turnId' in args)
|
|
1032
|
+
return false;
|
|
1033
|
+
const host = conversationHost(state, at);
|
|
1034
|
+
if (!host)
|
|
1035
|
+
return false;
|
|
1036
|
+
const { running } = await openConversation(host, args.conversation, { kind: 'read' });
|
|
1037
|
+
if (running)
|
|
1038
|
+
throw replyUnreachable();
|
|
1039
|
+
return false;
|
|
1040
|
+
}
|
|
1041
|
+
if ('turnId' in args) {
|
|
1042
|
+
return own.ask(state.own.turns.get(ownKey(at.sessionId, args.turnId)) ?? args.turnId);
|
|
1043
|
+
}
|
|
1044
|
+
const host = conversationHost(state, at);
|
|
1045
|
+
if (!host)
|
|
1046
|
+
throw statelessRefusal('stop');
|
|
1047
|
+
const { conversation, running } = await openConversation(host, args.conversation, {
|
|
1048
|
+
kind: 'read',
|
|
1049
|
+
});
|
|
1050
|
+
if (await own.ask(conversation.id))
|
|
1051
|
+
return true;
|
|
1052
|
+
if (running)
|
|
802
1053
|
throw replyUnreachable();
|
|
803
|
-
return
|
|
1054
|
+
return false;
|
|
804
1055
|
},
|
|
805
1056
|
};
|
|
806
1057
|
}
|