@theoremjs/web 0.3.5-next.980.g83e419d → 0.3.5-next.982.g16b31de
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 +270 -6
- package/client/chat.js +136 -21
- package/client/index.d.ts +1 -1
- package/client/run-session.d.ts +12 -2
- package/client/run-session.js +3 -3
- package/client/transcript-schema.d.ts +4 -0
- package/client/transcript-schema.js +9 -1
- package/client/transport.d.ts +34 -6
- package/client/transport.js +17 -5
- package/client/turn-client.d.ts +5 -1
- package/client/turn-client.js +1 -0
- package/package.json +2 -2
- package/server/conversation-core.d.ts +264 -0
- package/server/conversation-core.js +780 -0
- package/server/conversation-store.d.ts +25 -1
- package/server/conversation-store.js +8 -2
- package/server/conversation.d.ts +61 -2
- package/server/conversation.js +225 -37
- package/server/create-conversation-core.d.ts +28 -0
- package/server/create-conversation-core.js +46 -0
- package/server/handler.d.ts +67 -20
- package/server/handler.js +203 -908
- package/server/mod.d.ts +8 -3
- package/server/mod.js +2 -0
- package/server/notifier.d.ts +3 -2
- package/server/notifier.js +3 -2
- package/server/session-authority.d.ts +3 -1
- package/server/session-authority.js +23 -0
- package/server/session-calls.d.ts +122 -0
- package/server/session-calls.js +512 -0
- package/server/steer-inbox.d.ts +3 -4
- package/server/steer-inbox.js +6 -5
- package/server/turn-wiring.d.ts +19 -4
- package/server/turn-wiring.js +8 -1
package/client/chat.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TheoremError, } from '@theoremjs/agents';
|
|
2
|
-
import { branchInterfaceTurnSession, consumeNextComposerQueue, convertSteersToFrontQueued, createComposerPendingMessage, defaultInterfaceEffort, emptyInterfaceTurnSession, moveComposerPendingWithinKind, orderComposerPendingMessages, promoteComposerPendingKind, removeComposerPendingMessage, removeLandedSteers, userDraftHasPayload, userDraftToSteerInject, } from '@theoremjs/agents/interface';
|
|
2
|
+
import { branchInterfaceTurnSession, consumeNextComposerQueue, convertSteersToFrontQueued, createComposerPendingMessage, defaultInterfaceEffort, emptyInterfaceTurnSession, moveComposerPendingWithinKind, orderComposerPendingMessages, promoteComposerPendingKind, removeComposerPendingMessage, removeLandedSteers, saveComposerPendingMessage, takeSavedComposerPending, userDraftHasPayload, userDraftToSteerInject, } from '@theoremjs/agents/interface';
|
|
3
3
|
import { composerHasPayload } from "./composer-primary.js";
|
|
4
4
|
import { composerFieldsFromDraft } from "./decode-composer-draft.js";
|
|
5
5
|
import { encodeComposerDraft } from "./encode-composer-draft.js";
|
|
@@ -8,7 +8,7 @@ import { followGenerationDefaults } from "./generation-selection.js";
|
|
|
8
8
|
import { warnPageToolMismatch } from "./live/live-page-tool.js";
|
|
9
9
|
import { withPageToolDispatch } from "./page-dispatch.js";
|
|
10
10
|
import { sessionAfter, stampWorked, stoppedReply } from "./run-commit.js";
|
|
11
|
-
import { keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
|
|
11
|
+
import { extractInlineEncodedAttachments, keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
|
|
12
12
|
import { isUnknownConversation, } from "./transport.js";
|
|
13
13
|
import { foldAssistantTurn, issuedOperationId } from "./turn-client.js";
|
|
14
14
|
const DELIVERY_ORDER = ['sending', 'sent', 'delivered', 'read'];
|
|
@@ -87,9 +87,19 @@ function nextFrame(run) {
|
|
|
87
87
|
const id = setTimeout(run, 16);
|
|
88
88
|
return () => clearTimeout(id);
|
|
89
89
|
}
|
|
90
|
-
function
|
|
90
|
+
function newId() {
|
|
91
91
|
return crypto.randomUUID();
|
|
92
92
|
}
|
|
93
|
+
/** A pending message's draft as the input a steer sends. */
|
|
94
|
+
function steerInput(draft) {
|
|
95
|
+
const attachments = extractInlineEncodedAttachments(draft.attachments);
|
|
96
|
+
const voice = extractInlineEncodedAttachments(draft.voice);
|
|
97
|
+
return {
|
|
98
|
+
...(draft.text?.trim() ? { text: draft.text } : {}),
|
|
99
|
+
...(attachments ? { attachments } : {}),
|
|
100
|
+
...(voice ? { voice } : {}),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
93
103
|
class Chat {
|
|
94
104
|
#options;
|
|
95
105
|
#state;
|
|
@@ -125,6 +135,12 @@ class Chat {
|
|
|
125
135
|
#listening = null;
|
|
126
136
|
/** The last view said results wait that no reply has read: the chat wakes once it is idle. */
|
|
127
137
|
#wakeDue = false;
|
|
138
|
+
/** The ids a reply names the run's message by, once the host said it saved the message itself. */
|
|
139
|
+
#savedAs = null;
|
|
140
|
+
/** How many blocks, at the end of the transcript, are the message the run posted. */
|
|
141
|
+
#ownPosted = 0;
|
|
142
|
+
/** The run in flight has streamed an event of its reply. */
|
|
143
|
+
#streamed = false;
|
|
128
144
|
#reading = null;
|
|
129
145
|
#readAgain = false;
|
|
130
146
|
constructor(options) {
|
|
@@ -327,18 +343,33 @@ class Chat {
|
|
|
327
343
|
this.#steerAfterTurnEnded();
|
|
328
344
|
return;
|
|
329
345
|
}
|
|
330
|
-
const
|
|
331
|
-
if (
|
|
346
|
+
const input = steerInput(message.draft);
|
|
347
|
+
if (Object.keys(input).length === 0)
|
|
332
348
|
return;
|
|
349
|
+
const conversation = this.#conversation;
|
|
333
350
|
try {
|
|
334
|
-
await this.#options.transport.steer({
|
|
351
|
+
const { saved } = await this.#options.transport.steer({
|
|
352
|
+
turnId,
|
|
353
|
+
id: message.id,
|
|
354
|
+
input,
|
|
355
|
+
...(conversation === undefined ? {} : { conversation }),
|
|
356
|
+
});
|
|
357
|
+
if (!saved)
|
|
358
|
+
return;
|
|
359
|
+
this.#set({
|
|
360
|
+
pendingMessages: saveComposerPendingMessage(this.#state.pendingMessages, message.id, saved.landsAs),
|
|
361
|
+
});
|
|
362
|
+
this.#adopt(saved.conversation);
|
|
363
|
+
// why: A run in flight reads the conversation once it ends, after this save. With none, the chat reads now, and wakes for the message.
|
|
364
|
+
if (!this.#busy)
|
|
365
|
+
await this.refresh();
|
|
335
366
|
}
|
|
336
367
|
catch (err) {
|
|
337
368
|
this.#set({ failure: clientFailure(err, this.#options.iface?.labels) });
|
|
338
369
|
}
|
|
339
370
|
};
|
|
340
371
|
sendNow = async (source) => {
|
|
341
|
-
if (!this.#options.iface)
|
|
372
|
+
if (!this.#options.iface || source?.saved)
|
|
342
373
|
return;
|
|
343
374
|
const draft = source ? source.draft : await this.#composerDraft();
|
|
344
375
|
if (!draft)
|
|
@@ -351,6 +382,7 @@ class Chat {
|
|
|
351
382
|
this.#drainArmed = false;
|
|
352
383
|
// why: Sent while the reply waits on gates, the message walks away from them in its own request.
|
|
353
384
|
await this.#sendDraft(draft, {
|
|
385
|
+
id: source?.id ?? newId(),
|
|
354
386
|
walkAway: this.#state.session.gatedTool !== null,
|
|
355
387
|
// why: The sent message leaves the queue, or the composer it came from.
|
|
356
388
|
onPosted: () => this.#set(source
|
|
@@ -370,7 +402,7 @@ class Chat {
|
|
|
370
402
|
};
|
|
371
403
|
restorePending = async (id) => {
|
|
372
404
|
const message = this.#state.pendingMessages.find((m) => m.id === id);
|
|
373
|
-
if (!message)
|
|
405
|
+
if (!message || message.saved)
|
|
374
406
|
return;
|
|
375
407
|
try {
|
|
376
408
|
await this.#restore(composerFieldsFromDraft(message.draft));
|
|
@@ -557,7 +589,10 @@ class Chat {
|
|
|
557
589
|
#draw(view, session, events) {
|
|
558
590
|
const shown = [...this.#state.blocks, ...this.#state.streamBlocks];
|
|
559
591
|
const blocks = keepIds(shown, view.transcript);
|
|
592
|
+
const drawn = [...view.transcript, ...(view.paused?.blocks ?? [])].map((block) => block.id);
|
|
560
593
|
this.#set({
|
|
594
|
+
// why: A saved message the conversation now shows is no longer waiting.
|
|
595
|
+
pendingMessages: takeSavedComposerPending(this.#state.pendingMessages, drawn).remaining,
|
|
561
596
|
blocks,
|
|
562
597
|
streamBlocks: keepIds(shown.slice(blocks.length), view.paused?.blocks ?? []),
|
|
563
598
|
// why: A reply at rest leaves the run's own events (tokens, an ask); a paused one, the host's.
|
|
@@ -642,6 +677,7 @@ class Chat {
|
|
|
642
677
|
this.#draining = true;
|
|
643
678
|
// why: The message leaves the queue once it posts; one that never starts stays queued.
|
|
644
679
|
void this.#sendDraft(message.draft, {
|
|
680
|
+
id: message.id,
|
|
645
681
|
onPosted: () => this.#set({
|
|
646
682
|
pendingMessages: removeComposerPendingMessage(this.#state.pendingMessages, message.id),
|
|
647
683
|
}),
|
|
@@ -698,7 +734,8 @@ class Chat {
|
|
|
698
734
|
});
|
|
699
735
|
}
|
|
700
736
|
/** The message posted: it joins the transcript, and the reply starts streaming. */
|
|
701
|
-
#posted(blocks, patch) {
|
|
737
|
+
#posted(blocks, own, patch) {
|
|
738
|
+
this.#ownPosted = own;
|
|
702
739
|
this.#setDelivery({ status: 'sending' });
|
|
703
740
|
this.#set({
|
|
704
741
|
blocks: [...this.#state.blocks, ...blocks],
|
|
@@ -719,8 +756,19 @@ class Chat {
|
|
|
719
756
|
scope,
|
|
720
757
|
view,
|
|
721
758
|
transcript: this.#state.blocks,
|
|
722
|
-
onUserBlocks: (blocks) => this.#posted(blocks, this.#clearedComposer()),
|
|
723
|
-
}), {
|
|
759
|
+
onUserBlocks: (blocks, own) => this.#posted(blocks, own, this.#clearedComposer()),
|
|
760
|
+
}), {
|
|
761
|
+
turn: true,
|
|
762
|
+
message: {
|
|
763
|
+
id: newId(),
|
|
764
|
+
draft: () => encodeComposerDraft({
|
|
765
|
+
text: fields.text,
|
|
766
|
+
pendingFiles: fields.files,
|
|
767
|
+
pendingVoice: fields.voice,
|
|
768
|
+
}),
|
|
769
|
+
restore: () => this.#restore(fields),
|
|
770
|
+
},
|
|
771
|
+
});
|
|
724
772
|
}
|
|
725
773
|
#sendDraft(draft, options) {
|
|
726
774
|
return this.#runTurn(({ iface, view, transport, scope, signal }) => streamInterfaceDraftTurn({
|
|
@@ -733,11 +781,18 @@ class Chat {
|
|
|
733
781
|
view,
|
|
734
782
|
transcript: this.#state.blocks,
|
|
735
783
|
walkAway: options.walkAway === true,
|
|
736
|
-
onUserBlocks: (blocks) => {
|
|
737
|
-
this.#posted(blocks, { streamBlocks: [] });
|
|
784
|
+
onUserBlocks: (blocks, own) => {
|
|
785
|
+
this.#posted(blocks, own, { streamBlocks: [] });
|
|
738
786
|
options.onPosted();
|
|
739
787
|
},
|
|
740
|
-
}), {
|
|
788
|
+
}), {
|
|
789
|
+
turn: true,
|
|
790
|
+
message: {
|
|
791
|
+
id: options.id,
|
|
792
|
+
draft: () => Promise.resolve(draft),
|
|
793
|
+
restore: () => this.#restore(composerFieldsFromDraft(draft)),
|
|
794
|
+
},
|
|
795
|
+
});
|
|
741
796
|
}
|
|
742
797
|
/** The gate on the reply still running that no answer is on its way to. */
|
|
743
798
|
#drawnGate() {
|
|
@@ -802,6 +857,8 @@ class Chat {
|
|
|
802
857
|
const base = withPageToolDispatch(transport, pageTools);
|
|
803
858
|
const tap = (onLine) => (line) => {
|
|
804
859
|
this.#took(line);
|
|
860
|
+
if (line.type === 'conversation' && line.opened)
|
|
861
|
+
this.#opened(line.opened, onLine);
|
|
805
862
|
onLine(line);
|
|
806
863
|
};
|
|
807
864
|
return {
|
|
@@ -856,10 +913,43 @@ class Chat {
|
|
|
856
913
|
DELIVERY_ORDER.indexOf(reached) > DELIVERY_ORDER.indexOf(delivery.status)) {
|
|
857
914
|
this.#setDelivery({ status: reached });
|
|
858
915
|
}
|
|
859
|
-
if (line.type === 'conversation')
|
|
916
|
+
if (line.type === 'conversation') {
|
|
860
917
|
this.#adopt(line.ref);
|
|
861
|
-
|
|
862
|
-
|
|
918
|
+
if (line.landsAs)
|
|
919
|
+
this.#savedAs = line.landsAs;
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
this.#streamed = true;
|
|
923
|
+
this.#options.onTurnEvent?.(line);
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* A reply opened with messages the host saved before: they leave the pending list and join the
|
|
927
|
+
* transcript where the reply reads them. That is before the message this run posted, when the
|
|
928
|
+
* reply has streamed nothing.
|
|
929
|
+
*/
|
|
930
|
+
#opened(ids, onLine) {
|
|
931
|
+
const { iface } = this.#options;
|
|
932
|
+
const { landed, remaining } = takeSavedComposerPending(this.#state.pendingMessages, ids);
|
|
933
|
+
if (!iface || landed.length === 0)
|
|
934
|
+
return;
|
|
935
|
+
this.#set({ pendingMessages: remaining });
|
|
936
|
+
const read = {
|
|
937
|
+
type: 'stage',
|
|
938
|
+
stage: 'pre_turn',
|
|
939
|
+
injected: landed.map((m) => ({ id: m.id, messages: userDraftToSteerInject(m.draft) })),
|
|
940
|
+
};
|
|
941
|
+
if (this.#streamed || this.#ownPosted === 0) {
|
|
942
|
+
onLine(read);
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
const at = this.#state.blocks.length - this.#ownPosted;
|
|
946
|
+
this.#set({
|
|
947
|
+
blocks: [
|
|
948
|
+
...this.#state.blocks.slice(0, at),
|
|
949
|
+
...foldAssistantTurn(iface, [read]),
|
|
950
|
+
...this.#state.blocks.slice(at),
|
|
951
|
+
],
|
|
952
|
+
});
|
|
863
953
|
}
|
|
864
954
|
#streamFrame(partial) {
|
|
865
955
|
this.#frameBlocks = partial;
|
|
@@ -886,12 +976,15 @@ class Chat {
|
|
|
886
976
|
const { message } = options;
|
|
887
977
|
const priorDelivery = this.#delivery;
|
|
888
978
|
const abort = options.turn ? new AbortController() : null;
|
|
889
|
-
const turnId = options.turn ?
|
|
979
|
+
const turnId = options.turn ? newId() : undefined;
|
|
890
980
|
this.#busy = true;
|
|
891
981
|
this.#abort = abort;
|
|
892
982
|
this.#turnId = turnId ?? null;
|
|
893
983
|
this.#stopped = false;
|
|
894
984
|
this.#drainArmed = false;
|
|
985
|
+
this.#savedAs = null;
|
|
986
|
+
this.#ownPosted = 0;
|
|
987
|
+
this.#streamed = false;
|
|
895
988
|
// why: A message streams once it posts, so the previous reply never shows as streaming before it.
|
|
896
989
|
// A wake shows only once the host's reply begins; one with nothing to wake for shows nothing.
|
|
897
990
|
if (!options.wake)
|
|
@@ -906,7 +999,7 @@ class Chat {
|
|
|
906
999
|
const outcome = await run({
|
|
907
1000
|
iface,
|
|
908
1001
|
transport: this.#runTransport(),
|
|
909
|
-
scope: { conversation: this.#conversation, turnId },
|
|
1002
|
+
scope: { conversation: this.#conversation, turnId, id: message?.id },
|
|
910
1003
|
signal: abort?.signal,
|
|
911
1004
|
view: {
|
|
912
1005
|
blocks: (partial) => this.#streamFrame(partial),
|
|
@@ -923,7 +1016,7 @@ class Chat {
|
|
|
923
1016
|
await this.#takeBack(start, message);
|
|
924
1017
|
let waits;
|
|
925
1018
|
if (keepsConversation(iface)) {
|
|
926
|
-
waits = await this.#settleHosted(outcome, start);
|
|
1019
|
+
waits = await this.#settleHosted(outcome, start, options);
|
|
927
1020
|
}
|
|
928
1021
|
else if (unposted) {
|
|
929
1022
|
this.#showFailure(outcome.failure);
|
|
@@ -979,7 +1072,7 @@ class Chat {
|
|
|
979
1072
|
* in the composer unless the host's transcript closed on it. Returns whether the reply waits
|
|
980
1073
|
* on gates.
|
|
981
1074
|
*/
|
|
982
|
-
async #settleHosted(outcome, start) {
|
|
1075
|
+
async #settleHosted(outcome, start, { message, wake }) {
|
|
983
1076
|
const { failure } = outcome;
|
|
984
1077
|
if (failure)
|
|
985
1078
|
this.#setDelivery(null);
|
|
@@ -990,12 +1083,34 @@ class Chat {
|
|
|
990
1083
|
return this.#state.session.gatedTool !== null;
|
|
991
1084
|
}
|
|
992
1085
|
const view = await this.#options.transport.conversation({ conversation: ref });
|
|
1086
|
+
const savedAs = this.#savedAs;
|
|
1087
|
+
if (message && savedAs && !view.transcript.some((block) => savedAs.includes(block.id))) {
|
|
1088
|
+
await this.#keepSaved(message, savedAs);
|
|
1089
|
+
}
|
|
993
1090
|
this.#draw(view, outcome.session, outcome.events);
|
|
1091
|
+
// why: The page does not repeat a run that failed or was stopped, or a wake the host ran nothing for (another reply holds the conversation). The next read can wake.
|
|
1092
|
+
if (failure || (wake && !this.#streamed))
|
|
1093
|
+
this.#wakeDue = false;
|
|
994
1094
|
if (!view.transcript.slice(start.blocks.length).some((b) => b.kind === 'error')) {
|
|
995
1095
|
this.#showFailure(failure);
|
|
996
1096
|
}
|
|
997
1097
|
return view.paused !== undefined;
|
|
998
1098
|
}
|
|
1099
|
+
/** The host saved the message and no reply has read it: it waits with the pending messages. */
|
|
1100
|
+
async #keepSaved(message, landsAs) {
|
|
1101
|
+
this.#setDelivery(null);
|
|
1102
|
+
const waiting = createComposerPendingMessage({
|
|
1103
|
+
kind: 'steer',
|
|
1104
|
+
draft: await message.draft(),
|
|
1105
|
+
id: message.id,
|
|
1106
|
+
});
|
|
1107
|
+
this.#set({
|
|
1108
|
+
pendingMessages: orderComposerPendingMessages([
|
|
1109
|
+
...this.#state.pendingMessages,
|
|
1110
|
+
{ ...waiting, saved: { landsAs } },
|
|
1111
|
+
]),
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
999
1114
|
/**
|
|
1000
1115
|
* A stateless chat keeps the reply as the run streamed it: in the transcript once it ends
|
|
1001
1116
|
* (closed by its failure, or by the visitor's stop), or beside it while it waits on a gate.
|
package/client/index.d.ts
CHANGED
|
@@ -33,5 +33,5 @@ export { hasLead, layoutResult, type ResultChart, type ResultFigure, type Result
|
|
|
33
33
|
export type { AnsweringGate, ToolDecisionAction, ToolGateResolution, } from './tool-resume.ts';
|
|
34
34
|
export { continueGatedToolInvocation, type PersonGateResolution } from './tool-resume.ts';
|
|
35
35
|
export { createTraceFeed, recordedFeed, type TraceFeed } from './trace-feed.ts';
|
|
36
|
-
export { CHAT_LINES, type ChatLine, type ChatLineSink, type ClientTurnEvent, type ConversationLine, type ConversationView, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, type HostErrorBody, type HttpOptions, type HttpTransportOptions, hostError, isTheoremStreamError, type MalformedEvent, type NotifyLine, postJson, postNdjson, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremStartRequest, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TheoremWakeRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
|
|
36
|
+
export { CHAT_LINES, type ChatLine, type ChatLineSink, type ClientTurnEvent, type ConversationLine, type ConversationView, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, type HostErrorBody, type HttpOptions, type HttpTransportOptions, hostError, isTheoremStreamError, type MalformedEvent, type NotifyLine, postJson, postNdjson, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremSavedMessage, type TheoremStartRequest, type TheoremSteerReply, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TheoremWakeRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
|
|
37
37
|
export { buildInvokeRequest, buildTurnRequest, foldAssistantTurn, issuedOperationId, type RunScope, type WalkAway, } from './turn-client.ts';
|
package/client/run-session.d.ts
CHANGED
|
@@ -35,9 +35,10 @@ export type StreamInterfaceTurnBaseArgs = {
|
|
|
35
35
|
/**
|
|
36
36
|
* Fires once the message posts, with the blocks the transcript gains: a
|
|
37
37
|
* walked-away reply's settled blocks, then the message's own (with media
|
|
38
|
-
* preview data). Walking away, it posts once the host has it.
|
|
38
|
+
* preview data). Walking away, it posts once the host has it. `own` is how many of the blocks,
|
|
39
|
+
* at the end, are the message's.
|
|
39
40
|
*/
|
|
40
|
-
onUserBlocks: (blocks: TranscriptBlock[]) => void;
|
|
41
|
+
onUserBlocks: (blocks: TranscriptBlock[], own: number) => void;
|
|
41
42
|
signal?: AbortSignal;
|
|
42
43
|
/**
|
|
43
44
|
* Send while the reply waits on gates: the message walks away from every
|
|
@@ -60,6 +61,15 @@ export type StreamInterfaceTurnArgs = StreamInterfaceTurnBaseArgs & {
|
|
|
60
61
|
export type StreamInterfaceDraftTurnArgs = StreamInterfaceTurnBaseArgs & {
|
|
61
62
|
draft: UserTurnDraft;
|
|
62
63
|
};
|
|
64
|
+
export declare function extractInlineEncodedAttachments(attachments?: readonly {
|
|
65
|
+
name: string;
|
|
66
|
+
mimeType: string;
|
|
67
|
+
data?: unknown;
|
|
68
|
+
}[]): Array<{
|
|
69
|
+
name: string;
|
|
70
|
+
mimeType: string;
|
|
71
|
+
data: string;
|
|
72
|
+
}> | undefined;
|
|
63
73
|
export declare function streamInterfaceTurn(args: StreamInterfaceTurnArgs): Promise<RunOutcome>;
|
|
64
74
|
/** Send a turn from an already-encoded pending draft (queue drain / send now). */
|
|
65
75
|
export declare function streamInterfaceDraftTurn(args: StreamInterfaceDraftTurnArgs): Promise<RunOutcome>;
|
package/client/run-session.js
CHANGED
|
@@ -41,13 +41,13 @@ async function streamPreparedTurn(args) {
|
|
|
41
41
|
const events = walking ? [...paused] : [];
|
|
42
42
|
let posted = !keeps;
|
|
43
43
|
if (!walking)
|
|
44
|
-
args.onUserBlocks(userBlocks);
|
|
44
|
+
args.onUserBlocks(userBlocks, userBlocks.length);
|
|
45
45
|
const onConversation = (line) => {
|
|
46
46
|
if (!line.posted)
|
|
47
47
|
return;
|
|
48
48
|
posted = true;
|
|
49
49
|
if (walking) {
|
|
50
|
-
args.onUserBlocks([...foldAssistantTurn(args.iface, events), ...userBlocks]);
|
|
50
|
+
args.onUserBlocks([...foldAssistantTurn(args.iface, events), ...userBlocks], userBlocks.length);
|
|
51
51
|
events.length = 0;
|
|
52
52
|
}
|
|
53
53
|
};
|
|
@@ -87,7 +87,7 @@ async function streamPreparedTurn(args) {
|
|
|
87
87
|
}
|
|
88
88
|
return { session: args.session, events, posted };
|
|
89
89
|
}
|
|
90
|
-
function extractInlineEncodedAttachments(attachments) {
|
|
90
|
+
export function extractInlineEncodedAttachments(attachments) {
|
|
91
91
|
const filtered = attachments
|
|
92
92
|
?.filter((a) => typeof a.data === 'string')
|
|
93
93
|
.map((a) => ({ name: a.name, mimeType: a.mimeType, data: a.data }));
|
|
@@ -8,3 +8,7 @@ import { z } from '@theoremjs/agents';
|
|
|
8
8
|
import type { TranscriptBlock } from '@theoremjs/agents/interface';
|
|
9
9
|
/** One transcript block, as a host stores it and the browser reads it back. */
|
|
10
10
|
export declare const transcriptBlockSchema: z.ZodType<TranscriptBlock>;
|
|
11
|
+
/** The block without the app's own values: a page cannot state them. */
|
|
12
|
+
export declare function withoutHost(block: TranscriptBlock): TranscriptBlock;
|
|
13
|
+
/** A block as a page's request states it: `host` is the app's to set, so it is dropped. */
|
|
14
|
+
export declare const pageBlockSchema: z.ZodPipe<z.ZodType<TranscriptBlock, unknown, z.core.$ZodTypeInternals<TranscriptBlock, unknown>>, z.ZodTransform<import("../../../src/interface/types").UserTextBlock | import("../../../src/interface/types").UserAttachmentBlock | import("../../../src/interface/types").ThoughtBlock | import("../../../src/interface/types").TextBlock | import("../../../src/interface/types").ToolBlock | import("../../../src/interface/types").StructuredBlock | import("../../../src/interface/types").MediaBlock | import("../../../src/interface/types").GroundingBlock | import("../../../src/interface/types").CitationBlock | import("../../../src/interface/types").EvidenceBlock | import("../../../src/interface/types").GuardrailBlock | import("../../../src/interface/types").LateResultsBlock | import("../../../src/interface/types").ErrorBlock | import("../../../src/interface/types").TurnDoneBlock, TranscriptBlock>>;
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { MEDIA_INPUT_KIND_VALUES, reasoningPartSchema, TURN_STOP_KINDS, turnEventSchema, z, } from '@theoremjs/agents';
|
|
8
8
|
import { guardrailEventSchema } from '@theoremjs/agents/guardrails';
|
|
9
|
+
import { jsonObjectSchema } from '@theoremjs/agents/kernel';
|
|
9
10
|
// why: The block shapes' event parts have one schema, the turn event's; a probe event reuses it.
|
|
10
11
|
function eventPart(probe) {
|
|
11
12
|
return z.custom((value) => turnEventSchema.safeParse(probe(value)).success);
|
|
@@ -49,7 +50,7 @@ const toolCall = z.object({
|
|
|
49
50
|
true;
|
|
50
51
|
const turnStop = z.object({ kind: z.enum(TURN_STOP_KINDS), native: z.string().optional() });
|
|
51
52
|
true;
|
|
52
|
-
const blockId = { id: z.string() };
|
|
53
|
+
const blockId = { id: z.string(), host: jsonObjectSchema.optional() };
|
|
53
54
|
const transcriptBlock = z.discriminatedUnion('kind', [
|
|
54
55
|
z.object({ ...blockId, kind: z.literal('user-text'), text: z.string() }),
|
|
55
56
|
z.object({
|
|
@@ -131,3 +132,10 @@ const transcriptBlock = z.discriminatedUnion('kind', [
|
|
|
131
132
|
true;
|
|
132
133
|
/** One transcript block, as a host stores it and the browser reads it back. */
|
|
133
134
|
export const transcriptBlockSchema = transcriptBlock;
|
|
135
|
+
/** The block without the app's own values: a page cannot state them. */
|
|
136
|
+
export function withoutHost(block) {
|
|
137
|
+
const { host: _host, ...rest } = block;
|
|
138
|
+
return rest;
|
|
139
|
+
}
|
|
140
|
+
/** A block as a page's request states it: `host` is the app's to set, so it is dropped. */
|
|
141
|
+
export const pageBlockSchema = transcriptBlockSchema.transform(withoutHost);
|
package/client/transport.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ import type { PageDispatchResult } from './page-dispatch.ts';
|
|
|
10
10
|
*
|
|
11
11
|
* @module
|
|
12
12
|
*/
|
|
13
|
-
import { type ErrorKind, type TurnEvent, type
|
|
13
|
+
import { type ErrorKind, type TurnEvent, type TurnToolSnapshot, z } from '@theoremjs/agents';
|
|
14
14
|
import { type ErrorCopies } from '@theoremjs/agents/guardrails';
|
|
15
15
|
import { type ProfileInterface, type TranscriptBlock } from '@theoremjs/agents/interface';
|
|
16
16
|
import type { PagePart } from './tool-resume.ts';
|
|
@@ -74,6 +74,11 @@ export type TheoremTurnRequest = {
|
|
|
74
74
|
stated?: StatedTurn;
|
|
75
75
|
/** Client-generated id so mid-turn steers can find this turn's inbox. */
|
|
76
76
|
turnId?: string;
|
|
77
|
+
/**
|
|
78
|
+
* The client's id for this message. A message keeps its id when the page sends it again, so a
|
|
79
|
+
* host that saves messages itself (`intake`) saves it one time.
|
|
80
|
+
*/
|
|
81
|
+
id?: string;
|
|
77
82
|
/** invariant: Both issued IDs identify each paused action that this message abandons. */
|
|
78
83
|
abandon?: GateReference[];
|
|
79
84
|
/** The tools the person allowed for the page, for a host without a session (the studio). */
|
|
@@ -120,15 +125,34 @@ export type TheoremInvokeRequest = {
|
|
|
120
125
|
};
|
|
121
126
|
/** An `/invoke` body as `createTheoremHandler` reads it. */
|
|
122
127
|
export declare const theoremInvokeRequestSchema: z.ZodType<TheoremInvokeRequest>;
|
|
123
|
-
/**
|
|
128
|
+
/** The person's message for an in-flight turn. */
|
|
124
129
|
export type TheoremSteerRequest = {
|
|
125
130
|
turnId: string;
|
|
126
131
|
/** The client's id for this steer; the turn's `stage` event names it in `injected` once it lands. */
|
|
127
132
|
id: string;
|
|
128
|
-
|
|
133
|
+
/** The message, as a `/turn` posts one. The host makes the user message the model reads. */
|
|
134
|
+
input: Pick<TheoremTurnInput, 'text' | 'attachments' | 'voice'>;
|
|
135
|
+
/** The ref of the conversation the turn replies in, when the page has one. */
|
|
136
|
+
conversation?: string;
|
|
129
137
|
};
|
|
130
138
|
/** A `/steer` body as `createTheoremHandler` reads it. */
|
|
131
139
|
export declare const theoremSteerRequestSchema: z.ZodType<TheoremSteerRequest>;
|
|
140
|
+
/**
|
|
141
|
+
* A message the host saved itself (`intake`), with no reply to it on this request. `landsAs` is
|
|
142
|
+
* each id a reply names the message by when it reads it: an inject's id on a `stage` line, an id
|
|
143
|
+
* in a `conversation` line's `opened`, or a block's id in the conversation.
|
|
144
|
+
*/
|
|
145
|
+
export type TheoremSavedMessage = {
|
|
146
|
+
conversation: string;
|
|
147
|
+
landsAs: string[];
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* What the host did with a steer. With `saved`, the host keeps the message; without it, the steer
|
|
151
|
+
* waits in the running turn, and the page sends it again when the turn ends without it.
|
|
152
|
+
*/
|
|
153
|
+
export type TheoremSteerReply = {
|
|
154
|
+
saved?: TheoremSavedMessage;
|
|
155
|
+
};
|
|
132
156
|
/** Stop an in-flight turn where it stands; its stream ends with what the reply left. */
|
|
133
157
|
export type TheoremStopRequest = {
|
|
134
158
|
turnId: string;
|
|
@@ -139,12 +163,16 @@ export declare const theoremStopRequestSchema: z.ZodType<TheoremStopRequest>;
|
|
|
139
163
|
* The ref the store issued for the conversation a run wrote: the client sends
|
|
140
164
|
* it with its next request. It comes before the run's error, which ends the stream.
|
|
141
165
|
* `posted` marks the write that holds the person's new message: a run that
|
|
142
|
-
* fails before it leaves the message unsent.
|
|
166
|
+
* fails before it leaves the message unsent. `landsAs` says the host saved the message itself
|
|
167
|
+
* (`intake`), and is each id a reply names it by (see `TheoremSavedMessage`). `opened` is the id
|
|
168
|
+
* of each item that waited for the model and that the reply starting here reads first.
|
|
143
169
|
*/
|
|
144
170
|
export type ConversationLine = {
|
|
145
171
|
type: 'conversation';
|
|
146
172
|
ref: string;
|
|
147
173
|
posted?: true;
|
|
174
|
+
landsAs?: string[];
|
|
175
|
+
opened?: string[];
|
|
148
176
|
};
|
|
149
177
|
/** The lines a chat's reply streams: turn events, and the conversation's ref. */
|
|
150
178
|
export declare const CHAT_LINES: WireLines<TurnEvent | ConversationLine>;
|
|
@@ -185,7 +213,7 @@ export type TheoremWakeRequest = {
|
|
|
185
213
|
};
|
|
186
214
|
/** A `/wake` body as `createTheoremHandler` reads it. */
|
|
187
215
|
export declare const theoremWakeRequestSchema: z.ZodType<TheoremWakeRequest>;
|
|
188
|
-
/** Listen for
|
|
216
|
+
/** Listen for changes to this session: a background call ended, or the app saved a reply. A `/notify` body. */
|
|
189
217
|
export type TheoremNotifyRequest = Record<string, never>;
|
|
190
218
|
/** A `/notify` body as `createTheoremHandler` reads it. */
|
|
191
219
|
export declare const theoremNotifyRequestSchema: z.ZodType<TheoremNotifyRequest>;
|
|
@@ -225,7 +253,7 @@ export interface TheoremTransport {
|
|
|
225
253
|
describe(signal?: AbortSignal): Promise<ProfileInterface>;
|
|
226
254
|
turn(request: TheoremTurnRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
|
|
227
255
|
invoke(request: TheoremInvokeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
|
|
228
|
-
steer(request: TheoremSteerRequest): Promise<
|
|
256
|
+
steer(request: TheoremSteerRequest): Promise<TheoremSteerReply>;
|
|
229
257
|
/** Stops the turn; refused (`session.turn_ended`) when this host is not running it. */
|
|
230
258
|
stop(request: TheoremStopRequest): Promise<void>;
|
|
231
259
|
/** The conversation under `ref`, as the host shows it. */
|
package/client/transport.js
CHANGED
|
@@ -9,10 +9,10 @@ import { gateReferenceSchema, TOOL_GATE_KINDS, } from '@theoremjs/agents';
|
|
|
9
9
|
*
|
|
10
10
|
* @module
|
|
11
11
|
*/
|
|
12
|
-
import { describeError, errorKindSchema, isAbortError, TheoremError, TURN_EVENT_SCHEMAS, throwIfAborted, turnEventSchema,
|
|
12
|
+
import { describeError, errorKindSchema, isAbortError, TheoremError, TURN_EVENT_SCHEMAS, throwIfAborted, turnEventSchema, turnToolSnapshotSchema, z, } from '@theoremjs/agents';
|
|
13
13
|
import { errorCopiesSchema, kindOfHttpStatus, } from '@theoremjs/agents/guardrails';
|
|
14
14
|
import { profileInterfaceSchema, } from '@theoremjs/agents/interface';
|
|
15
|
-
import { transcriptBlockSchema } from "./transcript-schema.js";
|
|
15
|
+
import { pageBlockSchema, transcriptBlockSchema } from "./transcript-schema.js";
|
|
16
16
|
import { checkWire, parseWireJson, readWireLine, } from "./wire-line.js";
|
|
17
17
|
const encodedBlob = z.object({ name: z.string(), mimeType: z.string(), data: z.string() });
|
|
18
18
|
true;
|
|
@@ -53,6 +53,7 @@ const theoremTurnRequest = z.object({
|
|
|
53
53
|
effort: z.string().optional(),
|
|
54
54
|
stated: statedTurn.optional(),
|
|
55
55
|
turnId: clientId.optional(),
|
|
56
|
+
id: clientId.optional(),
|
|
56
57
|
abandon: z.array(gateReferenceSchema).min(1).optional(),
|
|
57
58
|
replay: theoremReplay.pick({ sessionPermissions: true }).optional(),
|
|
58
59
|
transcript: z.array(transcriptBlockSchema).optional(),
|
|
@@ -86,11 +87,19 @@ export const theoremInvokeRequestSchema = theoremInvokeRequest;
|
|
|
86
87
|
const theoremSteerRequest = z.object({
|
|
87
88
|
turnId: clientId,
|
|
88
89
|
id: clientId,
|
|
89
|
-
|
|
90
|
+
input: theoremTurnInput.pick({ text: true, attachments: true, voice: true }),
|
|
91
|
+
conversation: z.string().min(1).optional(),
|
|
90
92
|
});
|
|
91
93
|
true;
|
|
92
94
|
/** A `/steer` body as `createTheoremHandler` reads it. */
|
|
93
95
|
export const theoremSteerRequestSchema = theoremSteerRequest;
|
|
96
|
+
const theoremSavedMessage = z.object({
|
|
97
|
+
conversation: z.string().min(1),
|
|
98
|
+
landsAs: z.array(z.string().min(1)).min(1),
|
|
99
|
+
});
|
|
100
|
+
true;
|
|
101
|
+
const theoremSteerReply = z.object({ saved: theoremSavedMessage.optional() });
|
|
102
|
+
true;
|
|
94
103
|
const theoremStopRequest = z.object({ turnId: clientId });
|
|
95
104
|
true;
|
|
96
105
|
/** A `/stop` body as `createTheoremHandler` reads it. */
|
|
@@ -99,6 +108,8 @@ const conversationLine = z.object({
|
|
|
99
108
|
type: z.literal('conversation'),
|
|
100
109
|
ref: z.string().min(1),
|
|
101
110
|
posted: z.literal(true).optional(),
|
|
111
|
+
landsAs: z.array(z.string().min(1)).min(1).optional(),
|
|
112
|
+
opened: z.array(z.string().min(1)).min(1).optional(),
|
|
102
113
|
});
|
|
103
114
|
true;
|
|
104
115
|
/** The lines a chat's reply streams: turn events, and the conversation's ref. */
|
|
@@ -140,7 +151,8 @@ const theoremRewindRequest = z.object({
|
|
|
140
151
|
true;
|
|
141
152
|
/** A `/rewind` body as `createTheoremHandler` reads it. */
|
|
142
153
|
export const theoremRewindRequestSchema = theoremRewindRequest;
|
|
143
|
-
|
|
154
|
+
// invariant: These blocks are a page's; only the app's own save sets a block's `host`.
|
|
155
|
+
const theoremStartRequest = z.object({ blocks: z.array(pageBlockSchema) });
|
|
144
156
|
true;
|
|
145
157
|
/** A `/conversation/start` body as a host reads it. */
|
|
146
158
|
export const theoremStartRequestSchema = theoremStartRequest;
|
|
@@ -371,7 +383,7 @@ export function createHttpTransport(options = {}) {
|
|
|
371
383
|
}, { ...options, signal }),
|
|
372
384
|
rewind: (body, signal) => fetchRewound(`${base}/rewind`, body, { ...options, signal }),
|
|
373
385
|
pageResult: (body, signal) => postJson(`${base}/page-result`, body, { ...options, signal }),
|
|
374
|
-
steer: (body) =>
|
|
386
|
+
steer: async (body) => theoremSteerReply.parse(await fetchJson(`${base}/steer`, { body }, options)),
|
|
375
387
|
stop: (body) => postJson(`${base}/stop`, body, options),
|
|
376
388
|
};
|
|
377
389
|
}
|
package/client/turn-client.d.ts
CHANGED
|
@@ -17,10 +17,14 @@ export type HeldCall = {
|
|
|
17
17
|
export type WalkAway = {
|
|
18
18
|
calls: readonly GatedToolContext[];
|
|
19
19
|
};
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Where a request goes on from: the ref of the conversation the host keeps, the run's id for
|
|
22
|
+
* steers, and the id of the message a turn sends.
|
|
23
|
+
*/
|
|
21
24
|
export type RunScope = {
|
|
22
25
|
conversation?: string;
|
|
23
26
|
turnId?: string;
|
|
27
|
+
id?: string;
|
|
24
28
|
};
|
|
25
29
|
export declare function buildTurnRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, input: TheoremTurnInput, options?: RunScope & {
|
|
26
30
|
walkAway?: WalkAway;
|
package/client/turn-client.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theoremjs/web",
|
|
3
|
-
"version": "0.3.5-next.
|
|
3
|
+
"version": "0.3.5-next.982.g16b31de",
|
|
4
4
|
"description": "Theorem on the web platform, with no UI framework: Web-standard server handlers that serve a profile, and the browser client that talks to them.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -25,6 +25,6 @@
|
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
27
|
"zod": "^4.6.5",
|
|
28
|
-
"@theoremjs/agents": "^0.3.5-next.
|
|
28
|
+
"@theoremjs/agents": "^0.3.5-next.982.g16b31de"
|
|
29
29
|
}
|
|
30
30
|
}
|