@theoremjs/web 0.3.5-next.933.gfc0e83b → 0.3.5-next.936.ga984349
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 +10 -6
- package/client/transcript-schema.js +1 -0
- package/package.json +2 -2
- package/server/conversation-inbox.d.ts +30 -0
- package/server/conversation-inbox.js +201 -0
- package/server/conversation-store.d.ts +2 -0
- package/server/conversation-store.js +1 -0
- package/server/conversation.d.ts +7 -12
- package/server/conversation.js +30 -42
- package/server/handler.d.ts +9 -2
- package/server/handler.js +227 -128
- package/server/mod.d.ts +2 -2
- package/server/mod.js +2 -2
- package/server/session-authority.js +3 -1
- package/server/session-store.d.ts +32 -2
- package/server/session-store.js +40 -3
- package/server/tell-every-result.d.ts +10 -0
- package/server/tell-every-result.js +7 -0
- package/server/tool-operations.js +7 -0
- package/server/turn-wiring.d.ts +6 -3
- package/server/turn-wiring.js +12 -1
- package/server/page-wakes.d.ts +0 -10
- package/server/page-wakes.js +0 -8
package/server/handler.js
CHANGED
|
@@ -40,12 +40,14 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
|
|
|
40
40
|
* @module
|
|
41
41
|
*/
|
|
42
42
|
import { authorizeToolReplay, compactHistory, defaultKernelScope, defineProfile, invokeTool, jsonObjectSchema, labelText, registerProfile, runTurn, TheoremError, toolInvocationHash, } from '@theoremjs/agents';
|
|
43
|
+
import { runConversation } from '@theoremjs/agents/conversation';
|
|
43
44
|
import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremjs/agents/host';
|
|
44
45
|
import { clientProfileInterface, gatedToolsFromEvents, interfaceFromProfile, promotedToolIdsFromEvents, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
|
|
45
46
|
import { answerGatedCall, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
|
|
46
47
|
import { hostInterface, theoremHostCallRequestSchema, } from "../client/host-transport.js";
|
|
47
48
|
import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
48
|
-
import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls,
|
|
49
|
+
import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
|
|
50
|
+
import { sessionConversationInbox } from "./conversation-inbox.js";
|
|
49
51
|
import { unknownConversation, } from "./conversation-store.js";
|
|
50
52
|
import { createMemoryCredentialStore, } from "./credential-store.js";
|
|
51
53
|
import { sessionStateStore, } from "./session-authority.js";
|
|
@@ -459,13 +461,21 @@ function announced(ctx, request, sessionId, service) {
|
|
|
459
461
|
}
|
|
460
462
|
/**
|
|
461
463
|
* The decider's wake, with no page: the reply runs on a request of its own, with the headers of
|
|
462
|
-
* the one that started the call and no signal, because that request has ended.
|
|
464
|
+
* the one that started the call and no signal, because that request has ended. When another reply
|
|
465
|
+
* holds the chat, it tries again as that hold's lease runs out.
|
|
463
466
|
*/
|
|
464
|
-
async function serverWake(ctx, started, sessionId,
|
|
467
|
+
async function serverWake(ctx, started, sessionId, ref) {
|
|
465
468
|
const request = new Request(started.url, { headers: started.headers });
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
|
|
469
|
+
const session = { id: sessionId };
|
|
470
|
+
const host = conversationHost(ctx, session);
|
|
471
|
+
if (!host)
|
|
472
|
+
throw statelessRefusal('wake');
|
|
473
|
+
const retry = (leasedUntil) => {
|
|
474
|
+
setTimeout(() => {
|
|
475
|
+
serverWake(ctx, started, sessionId, ref).catch((err) => ctx.options.onError?.(err, { request }));
|
|
476
|
+
}, Math.max(0, leasedUntil - Date.now()));
|
|
477
|
+
};
|
|
478
|
+
const lines = await wakeLines(ctx, request, session, host, ref, {}, { retry });
|
|
469
479
|
for await (const line of lines) {
|
|
470
480
|
if (line.type === 'error') {
|
|
471
481
|
// labels-exempt: internal diagnostic for the decider's wake; no page reads it
|
|
@@ -477,57 +487,152 @@ async function serverWake(ctx, started, sessionId, conversation) {
|
|
|
477
487
|
async function* once(event, labels) {
|
|
478
488
|
yield withPublicLabels(event, labels);
|
|
479
489
|
}
|
|
490
|
+
/** Whether this request may read a settled call's result: the host's `authorizeToolReplay`. */
|
|
491
|
+
async function replayAllowed(ctx, request, operation) {
|
|
492
|
+
const { authorizeToolReplay } = ctx.options;
|
|
493
|
+
return !authorizeToolReplay || (await authorizeToolReplay({ request, operation }));
|
|
494
|
+
}
|
|
495
|
+
const DEFAULT_CONVERSATION_LEASE_MS = 60_000;
|
|
480
496
|
/**
|
|
481
|
-
*
|
|
482
|
-
*
|
|
497
|
+
* The chat's inbox as this request reads it: the chat as this request last wrote it, and the
|
|
498
|
+
* results this request may read. `seen` follows each line's ref, because a store's ref can change
|
|
499
|
+
* with each write.
|
|
483
500
|
*/
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
const
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
501
|
+
function chatInbox(ctx, request, session, host, opened) {
|
|
502
|
+
let ref = opened.ref;
|
|
503
|
+
const leaseMs = ctx.options.conversationLeaseMs ?? DEFAULT_CONVERSATION_LEASE_MS;
|
|
504
|
+
const inbox = sessionConversationInbox({
|
|
505
|
+
sessions: ctx.sessions,
|
|
506
|
+
sessionId: session.id,
|
|
507
|
+
leaseMs,
|
|
508
|
+
conversation: async (key) => {
|
|
509
|
+
const conversation = ref === null ? opened.conversation : (await host.store.read(session.id, ref))?.conversation;
|
|
510
|
+
return conversation?.id === key ? conversation : undefined;
|
|
511
|
+
},
|
|
512
|
+
readable: (operation) => replayAllowed(ctx, request, operation),
|
|
513
|
+
});
|
|
514
|
+
return {
|
|
515
|
+
inbox,
|
|
516
|
+
key: opened.conversation.id,
|
|
517
|
+
leaseMs,
|
|
518
|
+
seen(line) {
|
|
519
|
+
if (line.type === 'conversation')
|
|
520
|
+
ref = line.ref;
|
|
521
|
+
},
|
|
522
|
+
get ref() {
|
|
523
|
+
return ref;
|
|
524
|
+
},
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/** The values `produce` sends, as it sends them, then its end or what it threw. */
|
|
528
|
+
async function* sent(produce) {
|
|
529
|
+
const queue = [];
|
|
530
|
+
let ended;
|
|
531
|
+
let wake = () => { };
|
|
532
|
+
produce((value) => {
|
|
533
|
+
queue.push(value);
|
|
534
|
+
wake();
|
|
535
|
+
}).then(() => {
|
|
536
|
+
ended = { failed: false };
|
|
537
|
+
wake();
|
|
538
|
+
}, (failure) => {
|
|
539
|
+
ended = { failed: true, failure };
|
|
540
|
+
wake();
|
|
541
|
+
});
|
|
542
|
+
for (;;) {
|
|
543
|
+
if (queue.length > 0) {
|
|
544
|
+
yield queue.splice(0, 1)[0];
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
if (ended?.failed)
|
|
548
|
+
throw ended.failure;
|
|
549
|
+
if (ended)
|
|
550
|
+
return;
|
|
551
|
+
await new Promise((resolve) => {
|
|
552
|
+
wake = resolve;
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Runs a reply under a hold of the chat, and streams its lines. The reply reads the late results
|
|
558
|
+
* the decider's policy tells it. Without a decider no reply reads one, and no hold is taken.
|
|
559
|
+
* invariant: One hold has a chat at a time, and lets it go only once nothing waits that may be told.
|
|
560
|
+
* A page's reply that leaves results waiting lets the chat go, so the page wakes for them; a
|
|
561
|
+
* server's wake runs the next reply under its hold.
|
|
562
|
+
*/
|
|
563
|
+
function heldLines(ctx, request, session, host, opened, start, reply, follow = {}) {
|
|
496
564
|
const decider = ctx.options.lateResultsDecider;
|
|
497
|
-
if (!decider
|
|
498
|
-
return
|
|
499
|
-
const
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
565
|
+
if (!decider)
|
|
566
|
+
return reply(undefined, () => opened.ref);
|
|
567
|
+
const chat = chatInbox(ctx, request, session, host, opened);
|
|
568
|
+
const ref = () => chat.ref;
|
|
569
|
+
return sent(async (send) => {
|
|
570
|
+
const runOnce = (begin, lines) => runConversation({
|
|
571
|
+
conversation: chat.key,
|
|
572
|
+
inbox: chat.inbox,
|
|
573
|
+
policy: decider.policy,
|
|
574
|
+
start: begin,
|
|
575
|
+
newId: () => crypto.randomUUID(),
|
|
576
|
+
renewEveryMs: chat.leaseMs / 3,
|
|
577
|
+
reply: async (run) => {
|
|
578
|
+
const renew = () => chat.inbox.renew(chat.key, run.hold);
|
|
579
|
+
for await (const line of lines({ run, renew })) {
|
|
580
|
+
chat.seen(line);
|
|
581
|
+
send(line);
|
|
582
|
+
}
|
|
583
|
+
},
|
|
584
|
+
gaveUp: (items) => {
|
|
585
|
+
ctx.options.onError?.(
|
|
586
|
+
// labels-exempt: internal diagnostic; no reader sees a given-up result
|
|
587
|
+
new TheoremError('unavailable', 'The late-results policy gave up results', {
|
|
588
|
+
cause: { code: 'late_results_given_up', operationIds: items.map((item) => item.id) },
|
|
589
|
+
}), { request });
|
|
590
|
+
},
|
|
591
|
+
});
|
|
592
|
+
let run = await runOnce(start, (held) => reply(held, ref));
|
|
593
|
+
let failure = run.outcome === 'held' ? undefined : run.failure;
|
|
594
|
+
while (run.outcome === 'continue') {
|
|
595
|
+
const paused = await isPaused(host, session, chat.ref, opened.conversation);
|
|
596
|
+
if (follow.retry === undefined || paused) {
|
|
597
|
+
await letGo(chat.inbox, chat.key, run.hold);
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
600
|
+
run = await runOnce({ opening: 'follow_up', hold: run.hold }, (held) => wakeReplyLines(ctx, request, session, host, chat.ref, {}, held));
|
|
601
|
+
if (run.outcome !== 'held' && run.failure !== undefined)
|
|
602
|
+
failure ??= run.failure;
|
|
603
|
+
}
|
|
604
|
+
if (run.outcome === 'held')
|
|
605
|
+
follow.retry?.(run.leasedUntil);
|
|
606
|
+
if (failure !== undefined)
|
|
607
|
+
throw failure;
|
|
608
|
+
});
|
|
506
609
|
}
|
|
507
|
-
|
|
508
|
-
|
|
610
|
+
/** Whether the chat waits on gates: a wake leaves it to the answer that goes on. */
|
|
611
|
+
async function isPaused(host, session, ref, fallback) {
|
|
612
|
+
const conversation = ref === null ? fallback : (await host.store.read(session.id, ref))?.conversation;
|
|
613
|
+
return conversation?.paused !== undefined;
|
|
509
614
|
}
|
|
510
|
-
/**
|
|
511
|
-
async function
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
continue;
|
|
517
|
-
const { authorizeToolReplay } = ctx.options;
|
|
518
|
-
if (authorizeToolReplay && !(await authorizeToolReplay({ request, operation })))
|
|
519
|
-
continue;
|
|
520
|
-
readable.push(operation);
|
|
615
|
+
/** Lets the chat go under `hold`, reading again each time a result arrives first. */
|
|
616
|
+
async function letGo(inbox, key, hold) {
|
|
617
|
+
for (;;) {
|
|
618
|
+
const { version } = await inbox.read(key);
|
|
619
|
+
if ((await inbox.release(key, hold, version)) !== 'moved')
|
|
620
|
+
return;
|
|
521
621
|
}
|
|
522
|
-
return readable;
|
|
523
622
|
}
|
|
524
|
-
/** The results a
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
return
|
|
623
|
+
/** The late results a reply's model reads: what it opened with, then what each later moment hands it. */
|
|
624
|
+
function lateSource(run) {
|
|
625
|
+
let opening = true;
|
|
626
|
+
return async ({ stage, step }) => {
|
|
627
|
+
if (opening && stage === 'pre_turn') {
|
|
628
|
+
opening = false;
|
|
629
|
+
return run.opened.map((item) => item.outcome);
|
|
630
|
+
}
|
|
631
|
+
return (await run.take({ stage, step })).map((item) => item.outcome);
|
|
632
|
+
};
|
|
528
633
|
}
|
|
529
634
|
/** One model run of a chat's reply, its gates recorded in the session as they pause. */
|
|
530
|
-
async function* chatTurn(ctx, request, session, turn, key, stop, late) {
|
|
635
|
+
async function* chatTurn(ctx, request, session, turn, key, signal, stop, late) {
|
|
531
636
|
const state = await ctx.sessions.read(session.id);
|
|
532
637
|
const provider = await providerFor(ctx, request, turn.model);
|
|
533
638
|
const host = await ctx.options.host?.(request);
|
|
@@ -542,11 +647,12 @@ async function* chatTurn(ctx, request, session, turn, key, stop, late) {
|
|
|
542
647
|
execution: sessionToolCoordinator(ctx.sessions, session.id),
|
|
543
648
|
...backgroundWiring(ctx, request, session.id),
|
|
544
649
|
pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
|
|
545
|
-
input:
|
|
650
|
+
input: turn.input,
|
|
651
|
+
...(late ? { lateResults: lateSource(late) } : {}),
|
|
546
652
|
...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
|
|
547
653
|
...(turn.providerState ? { providerState: turn.providerState } : {}),
|
|
548
654
|
sessionPermissions: state.permissions,
|
|
549
|
-
signal
|
|
655
|
+
signal,
|
|
550
656
|
host,
|
|
551
657
|
...(turn.model ? { model: turn.model } : {}),
|
|
552
658
|
...(turn.effort ? { effort: turn.effort } : {}),
|
|
@@ -569,16 +675,16 @@ async function* chatTurn(ctx, request, session, turn, key, stop, late) {
|
|
|
569
675
|
await ctx.inbox.close(key);
|
|
570
676
|
}
|
|
571
677
|
}
|
|
572
|
-
/**
|
|
573
|
-
|
|
678
|
+
/**
|
|
679
|
+
* How this request runs the model for a reply: its generation, its abort (the request's, a stop,
|
|
680
|
+
* or its hold losing the chat), and the chat's hold it saves under.
|
|
681
|
+
*/
|
|
682
|
+
function chatRunner(ctx, request, session, generation, held) {
|
|
574
683
|
const key = generation.turnId ? inboxKey(session.id, generation.turnId) : undefined;
|
|
575
684
|
const stop = new AbortController();
|
|
576
|
-
const signal = AbortSignal.any([request.signal, stop.signal]);
|
|
685
|
+
const signal = AbortSignal.any([request.signal, stop.signal, ...(held ? [held.run.signal] : [])]);
|
|
577
686
|
return {
|
|
578
|
-
run: (turn) => chatTurn(ctx, request, session, turn, key, stop,
|
|
579
|
-
...(generation.conversation === undefined ? {} : { conversation: generation.conversation }),
|
|
580
|
-
...(given ? { given } : {}),
|
|
581
|
-
}),
|
|
687
|
+
run: (turn) => chatTurn(ctx, request, session, turn, key, signal, stop, held?.run),
|
|
582
688
|
async compact(history, tokens, model) {
|
|
583
689
|
const provider = await providerFor(ctx, request, model);
|
|
584
690
|
const compacted = await compactHistory({
|
|
@@ -594,6 +700,7 @@ function chatRunner(ctx, request, session, generation, given) {
|
|
|
594
700
|
...(generation.effort ? { effort: generation.effort } : {}),
|
|
595
701
|
...(generation.stated ? { stated: generation.stated } : {}),
|
|
596
702
|
signal,
|
|
703
|
+
...(held ? { reply: held.run.reply, held: held.renew } : {}),
|
|
597
704
|
};
|
|
598
705
|
}
|
|
599
706
|
/** The chat's conversation as this session's runs read and write it; undefined when the profile keeps none. */
|
|
@@ -615,7 +722,6 @@ async function turn(ctx, chat, request, session) {
|
|
|
615
722
|
throw new TheoremError('request', labelText('error.request'));
|
|
616
723
|
}
|
|
617
724
|
const message = postedMessage(chatInterface(chat), body.input, await ctx.options.context?.(request));
|
|
618
|
-
const runner = chatRunner(ctx, request, session, body);
|
|
619
725
|
const host = conversationHost(ctx, session);
|
|
620
726
|
if (!host) {
|
|
621
727
|
if (body.conversation !== undefined)
|
|
@@ -623,6 +729,7 @@ async function turn(ctx, chat, request, session) {
|
|
|
623
729
|
// labels-exempt: internal diagnostic; the user reads error.request
|
|
624
730
|
if (body.abandon)
|
|
625
731
|
throw statelessRefusal('walk away from');
|
|
732
|
+
const runner = chatRunner(ctx, request, session, body);
|
|
626
733
|
return eventStream(ctx, request, () => runner.run({
|
|
627
734
|
input: message.input,
|
|
628
735
|
model: body.model,
|
|
@@ -638,7 +745,13 @@ async function turn(ctx, chat, request, session) {
|
|
|
638
745
|
const walkAway = body.abandon
|
|
639
746
|
? await takeWalkedAway(ctx, request, session, body.abandon, opened.conversation)
|
|
640
747
|
: undefined;
|
|
641
|
-
return eventStream(ctx, request, () =>
|
|
748
|
+
return eventStream(ctx, request, () => heldLines(ctx, request, session, host, opened, { opening: 'message', takeOver: true }, (held) => messageReply({
|
|
749
|
+
host,
|
|
750
|
+
opened,
|
|
751
|
+
message,
|
|
752
|
+
...(walkAway ? { walkAway } : {}),
|
|
753
|
+
runner: chatRunner(ctx, request, session, body, held),
|
|
754
|
+
})));
|
|
642
755
|
}
|
|
643
756
|
/** The conversation as the browser draws it. */
|
|
644
757
|
async function conversation(ctx, request, session) {
|
|
@@ -650,68 +763,41 @@ async function conversation(ctx, request, session) {
|
|
|
650
763
|
return jsonResponse(200, await currentView(ctx, request, session, host, body.conversation, opened.conversation));
|
|
651
764
|
}
|
|
652
765
|
/**
|
|
653
|
-
* A reply to no message, for results that ended since the model last ran.
|
|
654
|
-
*
|
|
655
|
-
* `give` picks what the reply reads; what it leaves is let go, for a later reply.
|
|
766
|
+
* A reply to no message, for results that ended since the model last ran. It runs under a hold of
|
|
767
|
+
* the chat, so two pages that wake at once run it once, and reads what the decider's policy tells.
|
|
656
768
|
*/
|
|
657
769
|
async function wake(ctx, request, session) {
|
|
658
770
|
const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
|
|
659
771
|
const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
|
|
660
|
-
const lines = await wakeLines(ctx, request, session, body.conversation, body, input);
|
|
661
|
-
return eventStream(ctx, request, lines ? () => lines : async function* () { });
|
|
662
|
-
}
|
|
663
|
-
/** The wake's reply, or undefined when the decider gives it nothing to read. */
|
|
664
|
-
async function wakeLines(ctx, request, session, conversation, generation, input) {
|
|
665
772
|
const host = conversationHost(ctx, session);
|
|
666
773
|
if (!host)
|
|
667
774
|
throw statelessRefusal('wake');
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
const
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
if (given.length === 0)
|
|
695
|
-
return undefined;
|
|
696
|
-
const runner = chatRunner(ctx, request, session, { ...generation, conversation }, given);
|
|
697
|
-
const { notifier } = ctx.options;
|
|
698
|
-
return (async function* () {
|
|
699
|
-
yield* wakeReply({ host, opened, runner, ...(input ? { input } : {}) });
|
|
700
|
-
// why: The page that woke draws its reply; any other page open on the session reads it now.
|
|
701
|
-
notifier?.publish(session.id);
|
|
702
|
-
})();
|
|
703
|
-
}
|
|
704
|
-
/** Takes the wake's mark off results it did not read. */
|
|
705
|
-
async function letGo(ctx, session, left, wokenAt) {
|
|
706
|
-
await ctx.sessions.mutate(session.id, (state) => {
|
|
707
|
-
for (const { operationId } of left) {
|
|
708
|
-
const operation = state.operations[operationId];
|
|
709
|
-
if (operation?.status !== 'settled' || operation.wokenAt !== wokenAt)
|
|
710
|
-
continue;
|
|
711
|
-
const { wokenAt: _taken, ...rest } = operation;
|
|
712
|
-
state.operations[operationId] = rest;
|
|
713
|
-
}
|
|
714
|
-
});
|
|
775
|
+
const lines = await wakeLines(ctx, request, session, host, body.conversation, body, {}, input);
|
|
776
|
+
return eventStream(ctx, request, () => lines);
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* The wake's reply under a hold of the chat; nothing when no decider tells a result, or while a
|
|
780
|
+
* reply waits on gates: the answer that goes on reads what waits.
|
|
781
|
+
*/
|
|
782
|
+
async function wakeLines(ctx, request, session, host, ref, generation, follow, input) {
|
|
783
|
+
const opened = await openConversation(host, ref, { kind: 'read' });
|
|
784
|
+
if (!ctx.options.lateResultsDecider || opened.conversation.paused)
|
|
785
|
+
return noLines();
|
|
786
|
+
return heldLines(ctx, request, session, host, opened, { opening: 'wake' }, (held, current) => wakeReplyLines(ctx, request, session, host, current(), generation, held, input), follow);
|
|
787
|
+
}
|
|
788
|
+
/** No reply lines. */
|
|
789
|
+
async function* noLines() { }
|
|
790
|
+
/**
|
|
791
|
+
* A reply to no message under `held`, on the chat as it stands now. The page that woke draws it;
|
|
792
|
+
* any other page open on the session reads it once it ends.
|
|
793
|
+
*/
|
|
794
|
+
async function* wakeReplyLines(ctx, request, session, host, ref, generation, held, input) {
|
|
795
|
+
if (ref === null)
|
|
796
|
+
return;
|
|
797
|
+
const opened = await openConversation(host, ref, { kind: 'read' });
|
|
798
|
+
const runner = chatRunner(ctx, request, session, generation, held);
|
|
799
|
+
yield* wakeReply({ host, opened, runner, ...(input ? { input } : {}) });
|
|
800
|
+
ctx.options.notifier?.publish(session.id);
|
|
715
801
|
}
|
|
716
802
|
const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
|
|
717
803
|
/**
|
|
@@ -770,24 +856,25 @@ async function currentView(ctx, request, session, host, ref, conversation) {
|
|
|
770
856
|
...(notifier && transcript.some(isDetachedBlock)
|
|
771
857
|
? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
|
|
772
858
|
: {}),
|
|
773
|
-
...((await wakeDue(ctx, request, ref, conversation
|
|
859
|
+
...((await wakeDue(ctx, request, session, host, ref, conversation))
|
|
774
860
|
? { wake: true }
|
|
775
861
|
: {}),
|
|
776
862
|
};
|
|
777
863
|
}
|
|
778
|
-
/**
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
864
|
+
/**
|
|
865
|
+
* Whether the page wakes the chat now: the decider's policy tells a waiting result to a reply to no
|
|
866
|
+
* message. Never while a reply waits on gates: the answer that goes on reads what waits.
|
|
867
|
+
*/
|
|
868
|
+
async function wakeDue(ctx, request, session, host, ref, conversation) {
|
|
869
|
+
const decider = ctx.options.lateResultsDecider;
|
|
870
|
+
if (!decider || conversation.paused)
|
|
782
871
|
return false;
|
|
783
|
-
const
|
|
784
|
-
|
|
872
|
+
const chat = chatInbox(ctx, request, session, host, { ref, conversation });
|
|
873
|
+
const { items } = await chat.inbox.read(chat.key);
|
|
874
|
+
if (items.length === 0)
|
|
785
875
|
return false;
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
conversation: ref,
|
|
789
|
-
results: results.map(lateResult),
|
|
790
|
-
});
|
|
876
|
+
const { tell } = await decider.policy(items, { stage: 'pre_turn', step: 0, opening: 'wake' });
|
|
877
|
+
return tell.length > 0;
|
|
791
878
|
}
|
|
792
879
|
function isDetachedBlock(block) {
|
|
793
880
|
return block.kind === 'tool' && block.tool.state?.phase === 'background';
|
|
@@ -988,8 +1075,20 @@ async function invoke(ctx, request, session) {
|
|
|
988
1075
|
const call = { callId: body.gateId, operationId: body.operationId };
|
|
989
1076
|
const opened = await openConversation(host, body.conversation, { kind: 'answer', call });
|
|
990
1077
|
const settling = await settlingOf(ctx, request, session, body);
|
|
991
|
-
const
|
|
992
|
-
return eventStream(ctx, request, () =>
|
|
1078
|
+
const paused = opened.conversation.paused?.reply;
|
|
1079
|
+
return eventStream(ctx, request, () => heldLines(ctx, request, session, host, opened, { opening: 'message', takeOver: true }, (held) => answered(held, paused, () => answerReply({
|
|
1080
|
+
host,
|
|
1081
|
+
opened,
|
|
1082
|
+
call,
|
|
1083
|
+
settling: settling(),
|
|
1084
|
+
runner: chatRunner(ctx, request, session, body, held),
|
|
1085
|
+
}))));
|
|
1086
|
+
}
|
|
1087
|
+
/** The answer's reply, handed first what the paused reply read, so it tells them as it goes on. */
|
|
1088
|
+
async function* answered(held, paused, reply) {
|
|
1089
|
+
if (held && paused)
|
|
1090
|
+
await held.run.resume(paused);
|
|
1091
|
+
yield* reply();
|
|
993
1092
|
}
|
|
994
1093
|
/** The answered call's events: its saved outcome again, or the call run as answered. */
|
|
995
1094
|
async function settlingOf(ctx, request, session, body) {
|
package/server/mod.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
export { theoremHostCallRequestSchema } from '../client/host-transport.ts';
|
|
9
9
|
export type { LiveClientMessage, LiveOpenMessage } from '../client/live-messages.ts';
|
|
10
10
|
export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from '../client/transport.ts';
|
|
11
|
-
export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplyTurn, readerConversationHost, rewindConversation, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls,
|
|
11
|
+
export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplyTurn, readerConversationHost, rewindConversation, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeReply, } from './conversation.ts';
|
|
12
12
|
export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, unknownConversation, } from './conversation-store.ts';
|
|
13
13
|
export { createMemoryCredentialStore, type TheoremCredentialStore, type TheoremCredentials, } from './credential-store.ts';
|
|
14
14
|
export { createTheoremDecisionHandler, type DecisionQuestionsBuilder, isQuestionsBuilder, type TheoremDecisionHandlerOptions, } from './decision-handler.ts';
|
|
@@ -17,12 +17,12 @@ export { createTheoremHandler, createTheoremHostHandler, readBody, type TheoremH
|
|
|
17
17
|
export { createTheoremMcpHandler, type TheoremMcpHandlerOptions } from './mcp-handler.ts';
|
|
18
18
|
export { createMemoryNotifier, type TheoremNotifier } from './notifier.ts';
|
|
19
19
|
export { createMemoryPageToolBroker, type PageToolBroker, type PageToolResult, pageToolResultSchema, sessionPageDispatch, } from './page-dispatch.ts';
|
|
20
|
-
export { pageWakes } from './page-wakes.ts';
|
|
21
20
|
export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from './request-check.ts';
|
|
22
21
|
export { sessionStateStore } from './session-authority.ts';
|
|
23
22
|
export { createTheoremSessionBoundary, type PreparedLiveOpen, type SessionBoundaryOptions, type TheoremSessionBoundary, } from './session-boundary.ts';
|
|
24
23
|
export type { TheoremSessionCapacity } from './session-limits.ts';
|
|
25
24
|
export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, type MemorySessionStoreOptions, type PendingToolGate, type SessionSnapshot, type SessionToolOperation, type SessionWriteResult, type TheoremSessionState, type TheoremSessionStore, theoremSessionStateSchema, } from './session-store.ts';
|
|
26
25
|
export { createMemorySteerInbox, type SteerInbox, type SteerUnit, steerStage, steerUnitOf, stopOnRequest, } from './steer-inbox.ts';
|
|
26
|
+
export { tellEveryResult } from './tell-every-result.ts';
|
|
27
27
|
export { sessionToolCoordinator } from './tool-operations.ts';
|
|
28
28
|
export { kernelTurnInput, liveSessionOpen } from './turn-input.ts';
|
package/server/mod.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export { theoremHostCallRequestSchema } from "../client/host-transport.js";
|
|
9
9
|
export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
10
|
-
export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls,
|
|
10
|
+
export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
|
|
11
11
|
export { createMemoryConversationStore, createSealedConversationStore, emptyConversation, storedConversationSchema, unknownConversation, } from "./conversation-store.js";
|
|
12
12
|
export { createMemoryCredentialStore, } from "./credential-store.js";
|
|
13
13
|
export { createTheoremDecisionHandler, isQuestionsBuilder, } from "./decision-handler.js";
|
|
@@ -16,11 +16,11 @@ export { createTheoremHandler, createTheoremHostHandler, readBody, theoremSessio
|
|
|
16
16
|
export { createTheoremMcpHandler } from "./mcp-handler.js";
|
|
17
17
|
export { createMemoryNotifier } from "./notifier.js";
|
|
18
18
|
export { createMemoryPageToolBroker, pageToolResultSchema, sessionPageDispatch, } from "./page-dispatch.js";
|
|
19
|
-
export { pageWakes } from "./page-wakes.js";
|
|
20
19
|
export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from "./request-check.js";
|
|
21
20
|
export { sessionStateStore } from "./session-authority.js";
|
|
22
21
|
export { createTheoremSessionBoundary, } from "./session-boundary.js";
|
|
23
22
|
export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, theoremSessionStateSchema, } from "./session-store.js";
|
|
24
23
|
export { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
|
|
24
|
+
export { tellEveryResult } from "./tell-every-result.js";
|
|
25
25
|
export { sessionToolCoordinator } from "./tool-operations.js";
|
|
26
26
|
export { kernelTurnInput, liveSessionOpen } from "./turn-input.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { labelText, TheoremError, z } from '@theoremjs/agents';
|
|
2
2
|
import { checkedCapacity, fitSession } from "./session-limits.js";
|
|
3
|
-
import { emptySessionState, pruneGates, theoremSessionStateSchema, } from "./session-store.js";
|
|
3
|
+
import { emptySessionState, pruneGates, pruneInbox, theoremSessionStateSchema, } from "./session-store.js";
|
|
4
4
|
/** Session state, with expired gates dropped as it loads so they can't be answered. */
|
|
5
5
|
export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
|
|
6
6
|
if (typeof store.compareAndSwap !== 'function') {
|
|
@@ -33,6 +33,7 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
|
|
|
33
33
|
}
|
|
34
34
|
state.operations = Object.fromEntries(Object.entries(state.operations).filter(([, operation]) => operation.status !== 'settled' ||
|
|
35
35
|
now < (operation.retainUntil ?? operation.settledAt + operationRetentionMs)));
|
|
36
|
+
pruneInbox(state, now);
|
|
36
37
|
return { revision: snapshot?.revision ?? null, state };
|
|
37
38
|
};
|
|
38
39
|
return {
|
|
@@ -54,6 +55,7 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
|
|
|
54
55
|
}
|
|
55
56
|
if (capacity)
|
|
56
57
|
fitSession(state, capacity);
|
|
58
|
+
pruneInbox(state, now);
|
|
57
59
|
const next = theoremSessionStateSchema.safeParse(state);
|
|
58
60
|
if (!next.success) {
|
|
59
61
|
throw new TheoremError('config', labelText('error.config'), {
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @module
|
|
10
10
|
*/
|
|
11
11
|
import { z } from '@theoremjs/agents';
|
|
12
|
+
import type { Handover } from '@theoremjs/agents/conversation';
|
|
12
13
|
import type { ToolGateAuth } from '@theoremjs/agents/interface';
|
|
13
14
|
import type { AnsweredGate, ToolGate, ToolId, ToolOperationIdentity, ToolOperationOutcome, ToolOperationReply, ToolOperationUncertainty, TurnInput, TurnToolSnapshot } from '@theoremjs/agents/kernel';
|
|
14
15
|
import { type TheoremSessionCapacity } from './session-limits.ts';
|
|
@@ -61,8 +62,6 @@ export type SessionToolOperation = {
|
|
|
61
62
|
reply?: ToolOperationReply;
|
|
62
63
|
settledAt: number;
|
|
63
64
|
retainUntil?: number;
|
|
64
|
-
/** When a wake took this result up. invariant: one wake per result; a message still reads it. */
|
|
65
|
-
wokenAt?: number;
|
|
66
65
|
}) | (ToolOperationIdentity & {
|
|
67
66
|
status: 'uncertain';
|
|
68
67
|
pageGrant?: SessionPageGrant;
|
|
@@ -74,6 +73,30 @@ export type SessionToolOperation = {
|
|
|
74
73
|
/** The reply the model read for a call that detached, whatever has happened to the call since. */
|
|
75
74
|
export declare function detachedReply(operation: SessionToolOperation): ToolOperationReply | undefined;
|
|
76
75
|
export declare const DEFAULT_OPERATION_RETENTION_MS: number;
|
|
76
|
+
/** What the replies of one conversation did with one late result, until a saved reply tells it. */
|
|
77
|
+
export type SessionInboxEntry = {
|
|
78
|
+
/** The reply it is handed to now, while that reply's hold has the conversation. */
|
|
79
|
+
handed?: Handover;
|
|
80
|
+
/** Each reply it was handed to that ended without telling it, oldest first. */
|
|
81
|
+
handovers: Handover[];
|
|
82
|
+
/** The policy gave it up: no reply reads it. */
|
|
83
|
+
givenUp?: true;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* One conversation's hold, and what its replies did with the session's late results, by
|
|
87
|
+
* operation id. Whether a result was told is the transcript's to say.
|
|
88
|
+
*/
|
|
89
|
+
export type SessionConversationInbox = {
|
|
90
|
+
/** The hold that has the conversation until `leasedUntil` (epoch ms). */
|
|
91
|
+
hold?: string;
|
|
92
|
+
leasedUntil: number;
|
|
93
|
+
entries: Record<string, SessionInboxEntry>;
|
|
94
|
+
};
|
|
95
|
+
/** The session's conversation inboxes, and the version each result's end moves. */
|
|
96
|
+
export type SessionInbox = {
|
|
97
|
+
version: number;
|
|
98
|
+
conversations: Record<string, SessionConversationInbox>;
|
|
99
|
+
};
|
|
77
100
|
export type TheoremSessionState = {
|
|
78
101
|
version: 3;
|
|
79
102
|
operations: Record<string, SessionToolOperation>;
|
|
@@ -83,6 +106,8 @@ export type TheoremSessionState = {
|
|
|
83
106
|
gates: Record<string, PendingToolGate>;
|
|
84
107
|
/** Checkpoint identities this session produced, newest last. */
|
|
85
108
|
providerCheckpoints: string[];
|
|
109
|
+
/** Unset until a call first ends or a reply first holds a conversation. */
|
|
110
|
+
inbox?: SessionInbox;
|
|
86
111
|
};
|
|
87
112
|
/** Stored authority is checked before the handler reads or changes it. */
|
|
88
113
|
export declare const theoremSessionStateSchema: z.ZodType<TheoremSessionState>;
|
|
@@ -116,6 +141,11 @@ export declare function pruneGates<Gate extends {
|
|
|
116
141
|
createdAt: number;
|
|
117
142
|
expiresAt?: number;
|
|
118
143
|
}>(gates: Record<string, Gate>, now: number, ttlMs: number | undefined): Record<string, Gate>;
|
|
144
|
+
/**
|
|
145
|
+
* Drops what the inbox keeps for results the session no longer holds, and conversations no hold
|
|
146
|
+
* has with nothing kept.
|
|
147
|
+
*/
|
|
148
|
+
export declare function pruneInbox(state: TheoremSessionState, now: number): void;
|
|
119
149
|
export type MemorySessionStoreOptions = {
|
|
120
150
|
/** What it holds for one session. Unset, it holds any size. */
|
|
121
151
|
capacity?: TheoremSessionCapacity;
|