@theoremjs/web 0.3.4 → 0.3.5-next.1000.g569f044
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +330 -13
- package/client/chat.d.ts +14 -2
- package/client/chat.js +302 -34
- package/client/composer-hints.d.ts +18 -10
- package/client/composer-hints.js +23 -6
- package/client/host-transport.d.ts +7 -2
- package/client/host-transport.js +9 -3
- package/client/index.d.ts +4 -4
- package/client/index.js +3 -3
- package/client/page-dispatch.js +5 -0
- package/client/run-session.d.ts +27 -2
- package/client/run-session.js +34 -4
- package/client/schema-fields.d.ts +28 -1
- package/client/schema-fields.js +172 -13
- package/client/tool-result.d.ts +9 -5
- package/client/tool-result.js +23 -42
- package/client/transcript-schema.d.ts +4 -0
- package/client/transcript-schema.js +25 -6
- package/client/transport.d.ts +90 -9
- package/client/transport.js +56 -11
- package/client/turn-client.d.ts +8 -2
- package/client/turn-client.js +9 -0
- package/package.json +2 -2
- package/server/conversation-core.d.ts +273 -0
- package/server/conversation-core.js +797 -0
- package/server/conversation-inbox.d.ts +45 -0
- package/server/conversation-inbox.js +240 -0
- package/server/conversation-store.d.ts +43 -2
- package/server/conversation-store.js +15 -2
- package/server/conversation.d.ts +82 -2
- package/server/conversation.js +357 -60
- package/server/create-conversation-core.d.ts +28 -0
- package/server/create-conversation-core.js +46 -0
- package/server/embedding-handler.js +2 -0
- package/server/handler.d.ts +84 -20
- package/server/handler.js +279 -659
- package/server/mcp-handler.js +25 -11
- package/server/mod.d.ts +11 -4
- package/server/mod.js +6 -2
- 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 +26 -1
- package/server/session-boundary.d.ts +5 -3
- package/server/session-boundary.js +2 -2
- package/server/session-calls.d.ts +122 -0
- package/server/session-calls.js +512 -0
- package/server/session-store.d.ts +33 -0
- package/server/session-store.js +37 -2
- package/server/steer-inbox.d.ts +3 -4
- package/server/steer-inbox.js +6 -5
- package/server/tell-every-result.d.ts +11 -0
- package/server/tell-every-result.js +17 -0
- package/server/tool-operations.d.ts +8 -0
- package/server/tool-operations.js +71 -0
- package/server/turn-input.d.ts +4 -2
- package/server/turn-input.js +5 -2
- package/server/turn-wiring.d.ts +31 -6
- package/server/turn-wiring.js +59 -5
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handler's conversation inbox: each chat's late results, kept in the session store. An item
|
|
3
|
+
* is a detached call that ended; the transcript says whether a saved reply told it, and the
|
|
4
|
+
* session keeps who holds the chat and which replies were handed what.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import { type LateResultItem, type Profile, type ToolOperationOutcome } from '@theoremjs/agents';
|
|
9
|
+
import type { ConversationInbox } from '@theoremjs/agents/conversation';
|
|
10
|
+
import type { StoredConversation } from './conversation-store.ts';
|
|
11
|
+
import type { MutableStore } from './session-authority.ts';
|
|
12
|
+
import type { SessionToolOperation, TheoremSessionState } from './session-store.ts';
|
|
13
|
+
/** A background call that ended, as the session keeps it. */
|
|
14
|
+
export type SettledOperation = Extract<SessionToolOperation, {
|
|
15
|
+
status: 'settled';
|
|
16
|
+
}>;
|
|
17
|
+
/** A detached call as its chat's transcript keeps it: what an end is told about. */
|
|
18
|
+
export type DetachedCall = {
|
|
19
|
+
operationId: string;
|
|
20
|
+
callId: string;
|
|
21
|
+
name: string;
|
|
22
|
+
at: number;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* What became of a detached call, as the model and the page read it: the end the session saved, or
|
|
26
|
+
* that it is unresolved when the session holds no end (the call was cut off, or its saved end was
|
|
27
|
+
* dropped). Undefined while it runs.
|
|
28
|
+
*/
|
|
29
|
+
export declare function detachedEnd(call: DetachedCall, operation: SessionToolOperation | undefined, labels: Profile['labels']): ToolOperationOutcome | undefined;
|
|
30
|
+
/** Options for {@link sessionConversationInbox}. */
|
|
31
|
+
export type SessionConversationInboxOptions = {
|
|
32
|
+
sessions: MutableStore<TheoremSessionState>;
|
|
33
|
+
sessionId: string;
|
|
34
|
+
/** How long a hold has a chat after it opens or renews, in milliseconds. */
|
|
35
|
+
leaseMs: number;
|
|
36
|
+
/** The chat as its last save left it, by its id; undefined when the store no longer has it. */
|
|
37
|
+
conversation: (key: string) => Promise<StoredConversation | undefined>;
|
|
38
|
+
/** Whether this request may read the call's result: the handler's `authorizeToolReplay`. */
|
|
39
|
+
readable: (operation: SettledOperation) => Promise<boolean>;
|
|
40
|
+
/** The profile's labels, for the words of an end the session does not hold. */
|
|
41
|
+
labels: Profile['labels'];
|
|
42
|
+
now?: () => number;
|
|
43
|
+
};
|
|
44
|
+
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
45
|
+
export declare function sessionConversationInbox(options: SessionConversationInboxOptions): ConversationInbox<LateResultItem>;
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handler's conversation inbox: each chat's late results, kept in the session store. An item
|
|
3
|
+
* is a detached call that ended; the transcript says whether a saved reply told it, and the
|
|
4
|
+
* session keeps who holds the chat and which replies were handed what.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import { labelText, } from '@theoremjs/agents';
|
|
9
|
+
/**
|
|
10
|
+
* What became of a detached call, as the model and the page read it: the end the session saved, or
|
|
11
|
+
* that it is unresolved when the session holds no end (the call was cut off, or its saved end was
|
|
12
|
+
* dropped). Undefined while it runs.
|
|
13
|
+
*/
|
|
14
|
+
export function detachedEnd(call, operation, labels) {
|
|
15
|
+
if (operation?.status === 'settled')
|
|
16
|
+
return operation.outcome;
|
|
17
|
+
if (operation !== undefined && operation.status !== 'uncertain')
|
|
18
|
+
return undefined;
|
|
19
|
+
const message = labelText('tool.execution_uncertain', {}, labels);
|
|
20
|
+
const failure = {
|
|
21
|
+
code: operation ? operation.reason : 'outcome_not_retained',
|
|
22
|
+
kind: 'internal',
|
|
23
|
+
message,
|
|
24
|
+
};
|
|
25
|
+
const { operationId, callId, name } = call;
|
|
26
|
+
const at = operation ? operation.detectedAt : call.at;
|
|
27
|
+
return {
|
|
28
|
+
event: {
|
|
29
|
+
type: 'tool',
|
|
30
|
+
tool: { name, callId, operationId, at, phase: 'error', failure, readBack: message },
|
|
31
|
+
},
|
|
32
|
+
effects: 'unknown',
|
|
33
|
+
replay: { failure },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** The operation ids a chat's saved replies told, those its paused reply holds, and its untold calls. */
|
|
37
|
+
function transcriptState(conversation) {
|
|
38
|
+
const told = new Set();
|
|
39
|
+
const detached = [];
|
|
40
|
+
for (const block of conversation?.transcript ?? []) {
|
|
41
|
+
if (block.kind === 'late-results')
|
|
42
|
+
for (const id of block.operationIds)
|
|
43
|
+
told.add(id);
|
|
44
|
+
const { tool } = block.kind === 'tool' ? block : { tool: undefined };
|
|
45
|
+
if (tool?.state?.phase === 'background' && tool.operationId) {
|
|
46
|
+
const { operationId, callId, name } = tool;
|
|
47
|
+
detached.push({ operationId, callId, name, at: tool.state.at });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const paused = new Set();
|
|
51
|
+
const draft = [];
|
|
52
|
+
for (const event of conversation?.paused?.events ?? []) {
|
|
53
|
+
if (event.type === 'late_results')
|
|
54
|
+
for (const id of event.operationIds)
|
|
55
|
+
paused.add(id);
|
|
56
|
+
const tool = event.type === 'tool' ? event.tool : undefined;
|
|
57
|
+
if (tool?.phase === 'background' && tool.operationId) {
|
|
58
|
+
const { operationId, callId, name, at } = tool;
|
|
59
|
+
draft.push({ operationId, callId, name, at });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
told,
|
|
64
|
+
paused,
|
|
65
|
+
pausedReply: conversation?.paused?.reply,
|
|
66
|
+
untold: detached.filter((call) => !told.has(call.operationId)),
|
|
67
|
+
/** The calls the paused reply read, wherever it detached them. */
|
|
68
|
+
kept: [...detached, ...draft].filter((call) => paused.has(call.operationId)),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function operationOf(state, id) {
|
|
72
|
+
return Object.hasOwn(state.operations, id) ? state.operations[id] : undefined;
|
|
73
|
+
}
|
|
74
|
+
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
75
|
+
export function sessionConversationInbox(options) {
|
|
76
|
+
const { sessions, sessionId, leaseMs } = options;
|
|
77
|
+
const now = options.now ?? Date.now;
|
|
78
|
+
const inboxOf = (state, key) => {
|
|
79
|
+
state.inbox ??= { version: 0, conversations: {} };
|
|
80
|
+
const conversations = state.inbox.conversations;
|
|
81
|
+
if (!Object.hasOwn(conversations, key))
|
|
82
|
+
conversations[key] = { leasedUntil: 0, entries: {} };
|
|
83
|
+
return conversations[key];
|
|
84
|
+
};
|
|
85
|
+
const has = (inbox, hold, at) => inbox.hold === hold && inbox.leasedUntil > at;
|
|
86
|
+
/** Handed to a reply whose hold still has the chat. */
|
|
87
|
+
const heldLive = (inbox, entry, at) => entry.handed !== undefined && has(inbox, entry.handed.hold, at);
|
|
88
|
+
const entryOf = (inbox, id) => {
|
|
89
|
+
if (!Object.hasOwn(inbox.entries, id))
|
|
90
|
+
inbox.entries[id] = { handovers: [] };
|
|
91
|
+
return inbox.entries[id];
|
|
92
|
+
};
|
|
93
|
+
const item = (id, outcome, entry) => ({
|
|
94
|
+
id,
|
|
95
|
+
kind: 'late_result',
|
|
96
|
+
handovers: [...(entry?.handovers ?? [])],
|
|
97
|
+
outcome,
|
|
98
|
+
});
|
|
99
|
+
/** The call's end; undefined while it runs. */
|
|
100
|
+
const endOf = (state, call) => detachedEnd(call, operationOf(state, call.operationId), options.labels);
|
|
101
|
+
const handTo = (entry, hold, handover, at) => {
|
|
102
|
+
// invariant: A reply that lost its hold never gave its item back: what it was handed counts as a handover.
|
|
103
|
+
if (entry.handed)
|
|
104
|
+
entry.handovers.push(entry.handed);
|
|
105
|
+
entry.handed = { ...handover, hold, at };
|
|
106
|
+
};
|
|
107
|
+
/** The chat's untold calls that no paused reply keeps. */
|
|
108
|
+
const untoldCalls = async (key) => {
|
|
109
|
+
const conversation = await options.conversation(key);
|
|
110
|
+
const chat = transcriptState(conversation);
|
|
111
|
+
return { chat, calls: chat.untold.filter((call) => !chat.paused.has(call.operationId)) };
|
|
112
|
+
};
|
|
113
|
+
/** The call's end, while it waits for a reply: ended, not given up, and no live hold has it. */
|
|
114
|
+
const waiting = (inbox, state, call, at) => {
|
|
115
|
+
const id = call.operationId;
|
|
116
|
+
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
117
|
+
if (entry?.givenUp || (entry && heldLive(inbox, entry, at)))
|
|
118
|
+
return undefined;
|
|
119
|
+
return endOf(state, call);
|
|
120
|
+
};
|
|
121
|
+
/** Whether this request may read the end: a saved result only as the host allows; an unresolved end always. */
|
|
122
|
+
const readable = (state, id) => {
|
|
123
|
+
const operation = operationOf(state, id);
|
|
124
|
+
return operation?.status === 'settled' ? options.readable(operation) : Promise.resolve(true);
|
|
125
|
+
};
|
|
126
|
+
/** Changes one chat's lock and entries in one session write. */
|
|
127
|
+
const change = (key, apply) => sessions.mutate(sessionId, (state) => apply(inboxOf(state, key), state, now()));
|
|
128
|
+
/** Acts on each of `ids` that waits, only while `hold` has the chat; returns those it acted on. */
|
|
129
|
+
const actOnWaiting = async (key, hold, ids, act) => {
|
|
130
|
+
const { calls } = await untoldCalls(key);
|
|
131
|
+
const wanted = calls.filter((call) => ids.includes(call.operationId));
|
|
132
|
+
return change(key, (inbox, state, at) => {
|
|
133
|
+
if (!has(inbox, hold, at))
|
|
134
|
+
return [];
|
|
135
|
+
return wanted.flatMap((call) => {
|
|
136
|
+
const outcome = waiting(inbox, state, call, at);
|
|
137
|
+
if (!outcome)
|
|
138
|
+
return [];
|
|
139
|
+
const entry = entryOf(inbox, call.operationId);
|
|
140
|
+
act(entry, at);
|
|
141
|
+
return [item(call.operationId, outcome, entry)];
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
};
|
|
145
|
+
const lease = (inbox, hold, at) => {
|
|
146
|
+
inbox.hold = hold;
|
|
147
|
+
inbox.leasedUntil = at + leaseMs;
|
|
148
|
+
};
|
|
149
|
+
return {
|
|
150
|
+
open(key, hold) {
|
|
151
|
+
return change(key, (inbox, _state, at) => {
|
|
152
|
+
if (inbox.hold !== undefined && inbox.hold !== hold && inbox.leasedUntil > at) {
|
|
153
|
+
return { outcome: 'held', leasedUntil: inbox.leasedUntil };
|
|
154
|
+
}
|
|
155
|
+
lease(inbox, hold, at);
|
|
156
|
+
return { outcome: 'opened' };
|
|
157
|
+
});
|
|
158
|
+
},
|
|
159
|
+
takeOver(key, hold) {
|
|
160
|
+
return change(key, (inbox, _state, at) => lease(inbox, hold, at));
|
|
161
|
+
},
|
|
162
|
+
renew(key, hold) {
|
|
163
|
+
return change(key, (inbox, _state, at) => {
|
|
164
|
+
if (!has(inbox, hold, at))
|
|
165
|
+
return false;
|
|
166
|
+
lease(inbox, hold, at);
|
|
167
|
+
return true;
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
async read(key) {
|
|
171
|
+
const { calls } = await untoldCalls(key);
|
|
172
|
+
const state = await sessions.read(sessionId);
|
|
173
|
+
const inbox = state.inbox?.conversations[key] ?? { leasedUntil: 0, entries: {} };
|
|
174
|
+
const at = now();
|
|
175
|
+
const items = [];
|
|
176
|
+
for (const call of calls) {
|
|
177
|
+
const id = call.operationId;
|
|
178
|
+
const outcome = waiting(inbox, state, call, at);
|
|
179
|
+
if (outcome && (await readable(state, id)))
|
|
180
|
+
items.push(item(id, outcome, inbox.entries[id]));
|
|
181
|
+
}
|
|
182
|
+
return { items, version: String(state.inbox?.version ?? 0) };
|
|
183
|
+
},
|
|
184
|
+
hand(key, hold, handover, ids) {
|
|
185
|
+
return actOnWaiting(key, hold, ids, (entry, at) => handTo(entry, hold, handover, at));
|
|
186
|
+
},
|
|
187
|
+
async giveBack(key, hold, reply, ids) {
|
|
188
|
+
const { chat } = await untoldCalls(key);
|
|
189
|
+
await change(key, (inbox) => {
|
|
190
|
+
for (const id of ids) {
|
|
191
|
+
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
192
|
+
if (entry?.handed?.hold !== hold || entry.handed.reply !== reply)
|
|
193
|
+
continue;
|
|
194
|
+
if (chat.told.has(id)) {
|
|
195
|
+
delete inbox.entries[id];
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
entry.handovers.push(entry.handed);
|
|
199
|
+
delete entry.handed;
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
},
|
|
203
|
+
async resume(key, hold, paused, handover) {
|
|
204
|
+
const { chat } = await untoldCalls(key);
|
|
205
|
+
if (chat.pausedReply !== paused)
|
|
206
|
+
return [];
|
|
207
|
+
return change(key, (inbox, state, at) => {
|
|
208
|
+
if (!has(inbox, hold, at))
|
|
209
|
+
return [];
|
|
210
|
+
return chat.kept.flatMap((call) => {
|
|
211
|
+
const outcome = endOf(state, call);
|
|
212
|
+
const entry = entryOf(inbox, call.operationId);
|
|
213
|
+
if (!outcome || heldLive(inbox, entry, at))
|
|
214
|
+
return [];
|
|
215
|
+
handTo(entry, hold, handover, at);
|
|
216
|
+
return [item(call.operationId, outcome, entry)];
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
},
|
|
220
|
+
giveUp(key, hold, ids) {
|
|
221
|
+
return actOnWaiting(key, hold, ids, (entry) => {
|
|
222
|
+
if (entry.handed)
|
|
223
|
+
entry.handovers.push(entry.handed);
|
|
224
|
+
delete entry.handed;
|
|
225
|
+
entry.givenUp = true;
|
|
226
|
+
});
|
|
227
|
+
},
|
|
228
|
+
release(key, hold, version) {
|
|
229
|
+
return change(key, (inbox, state) => {
|
|
230
|
+
if (inbox.hold !== hold)
|
|
231
|
+
return 'lost';
|
|
232
|
+
if (String(state.inbox?.version ?? 0) !== version)
|
|
233
|
+
return 'moved';
|
|
234
|
+
delete inbox.hold;
|
|
235
|
+
inbox.leasedUntil = 0;
|
|
236
|
+
return 'released';
|
|
237
|
+
});
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
@@ -11,8 +11,13 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { type ProviderCheckpoint, TheoremError, type TurnEvent, type TurnHistoryMessage, z } from '@theoremjs/agents';
|
|
13
13
|
import type { TranscriptBlock } from '@theoremjs/agents/interface';
|
|
14
|
-
import { type StatedTurn } from '../client/transport.ts';
|
|
14
|
+
import { type RunningReply, type StatedTurn } from '../client/transport.ts';
|
|
15
15
|
import { type MemorySessionStoreOptions } from './session-store.ts';
|
|
16
|
+
/** A reply's base and the count of its events that base holds, as they stood before a compaction. */
|
|
17
|
+
export type UncompactedBase = {
|
|
18
|
+
base: TurnHistoryMessage[];
|
|
19
|
+
baseEvents: number;
|
|
20
|
+
};
|
|
16
21
|
/** A reply paused on gates: its events so far, and the history it was given. */
|
|
17
22
|
export type PausedReply = {
|
|
18
23
|
events: TurnEvent[];
|
|
@@ -20,6 +25,8 @@ export type PausedReply = {
|
|
|
20
25
|
base: TurnHistoryMessage[];
|
|
21
26
|
/** How many of `events` `base` already holds: a compaction mid-reply moves the base. */
|
|
22
27
|
baseEvents: number;
|
|
28
|
+
/** The base before a compaction folded in late results this reply read; a failure goes back to it. */
|
|
29
|
+
uncompacted?: UncompactedBase;
|
|
23
30
|
/** How long the reply worked before it paused (ms), approval waits excluded. */
|
|
24
31
|
workedMs: number;
|
|
25
32
|
/** When the reply last paused (epoch ms). */
|
|
@@ -28,6 +35,8 @@ export type PausedReply = {
|
|
|
28
35
|
model?: string;
|
|
29
36
|
effort?: string;
|
|
30
37
|
stated?: StatedTurn;
|
|
38
|
+
/** The reply's id under its chat's hold, so the reply that goes on after its gates resumes what it read. */
|
|
39
|
+
reply?: string;
|
|
31
40
|
};
|
|
32
41
|
/** One conversation as the host stores it. */
|
|
33
42
|
export type StoredConversation = {
|
|
@@ -55,7 +64,39 @@ export declare function emptyConversation(): StoredConversation;
|
|
|
55
64
|
export interface ConversationSnapshot {
|
|
56
65
|
revision: string;
|
|
57
66
|
conversation: StoredConversation;
|
|
67
|
+
/**
|
|
68
|
+
* A reply that runs on the conversation now, as the app's own records say: one under a hold the
|
|
69
|
+
* app keeps (`inbox`), whichever server, channel or wake runs it. Set only while that hold is
|
|
70
|
+
* live. A page reads it to show the reply working, and stops and steers it by the conversation.
|
|
71
|
+
* The app tells the page when the reply ends (`notifier.publish` after its save). Unset, no
|
|
72
|
+
* reply runs, or the store does not know.
|
|
73
|
+
*/
|
|
74
|
+
running?: RunningReply;
|
|
58
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* How the reply a write saves ended. `committed`: it is over. `failed`: it ended with an error.
|
|
78
|
+
* `stopped`: the person stopped it. `paused`: it waits on gates. `lost`: its hold no longer has
|
|
79
|
+
* the conversation, so it tells nothing.
|
|
80
|
+
*/
|
|
81
|
+
export type ReplyEnd = 'committed' | 'failed' | 'stopped' | 'paused' | 'lost' | 'refused';
|
|
82
|
+
/**
|
|
83
|
+
* What a write that saves a reply says beside the conversation. A store that keeps the app's own
|
|
84
|
+
* records honours it in the same statement as the write. A write with no context saves no reply:
|
|
85
|
+
* a new conversation, a posted message, a compaction, or a rewind.
|
|
86
|
+
*/
|
|
87
|
+
export type WriteContext = {
|
|
88
|
+
/** The hold the reply runs under. A store that keeps the holds refuses one that lost the conversation. */
|
|
89
|
+
hold?: string;
|
|
90
|
+
/** The reply's id under its hold. */
|
|
91
|
+
reply?: string;
|
|
92
|
+
/** What the app's `beforeSave` returned as `host`. Theorem never reads it. */
|
|
93
|
+
host?: unknown;
|
|
94
|
+
ended: ReplyEnd;
|
|
95
|
+
/** The ids of the inbox items this reply told, to mark in the same write. Empty when `ended` is `lost`. */
|
|
96
|
+
told: readonly string[];
|
|
97
|
+
/** The blocks this write adds to the transcript the store holds, so a store need not compare. */
|
|
98
|
+
appended: readonly TranscriptBlock[];
|
|
99
|
+
};
|
|
59
100
|
export type ConversationWriteResult = {
|
|
60
101
|
written: true;
|
|
61
102
|
ref: string;
|
|
@@ -76,7 +117,7 @@ export interface TheoremConversationStore {
|
|
|
76
117
|
* write lands only on a conversation this session can read, while its
|
|
77
118
|
* stored revision is still `expectedRevision`.
|
|
78
119
|
*/
|
|
79
|
-
write(sessionId: string, ref: string | null, expectedRevision: string | null, next: StoredConversation): Promise<ConversationWriteResult>;
|
|
120
|
+
write(sessionId: string, ref: string | null, expectedRevision: string | null, next: StoredConversation, context?: WriteContext): Promise<ConversationWriteResult>;
|
|
80
121
|
}
|
|
81
122
|
/** Refuses a ref the store does not know or cannot open: the browser reads `session.conversation_unknown`. */
|
|
82
123
|
export declare function unknownConversation(cause?: unknown): TheoremError;
|
|
@@ -18,11 +18,18 @@ const pausedReply = z.object({
|
|
|
18
18
|
events: z.array(turnEventSchema),
|
|
19
19
|
base: z.array(turnHistoryMessageSchema),
|
|
20
20
|
baseEvents: z.number().int().nonnegative(),
|
|
21
|
+
uncompacted: z
|
|
22
|
+
.object({
|
|
23
|
+
base: z.array(turnHistoryMessageSchema),
|
|
24
|
+
baseEvents: z.number().int().nonnegative(),
|
|
25
|
+
})
|
|
26
|
+
.optional(),
|
|
21
27
|
workedMs: z.number().nonnegative(),
|
|
22
28
|
endedAt: z.number(),
|
|
23
29
|
model: z.string().optional(),
|
|
24
30
|
effort: z.string().optional(),
|
|
25
31
|
stated: statedTurnSchema.optional(),
|
|
32
|
+
reply: z.string().min(1).optional(),
|
|
26
33
|
});
|
|
27
34
|
true;
|
|
28
35
|
const storedConversation = z.object({
|
|
@@ -63,7 +70,10 @@ export function createMemoryConversationStore(options = {}) {
|
|
|
63
70
|
}
|
|
64
71
|
return entry.snapshot;
|
|
65
72
|
};
|
|
66
|
-
const written = (...[sessionId, ref, expectedRevision, next]) => {
|
|
73
|
+
const written = (...[sessionId, ref, expectedRevision, next, context]) => {
|
|
74
|
+
// invariant: This store keeps no holds, so a reply whose hold lost the conversation writes nothing here.
|
|
75
|
+
if (context?.ended === 'lost')
|
|
76
|
+
return { written: false };
|
|
67
77
|
const snapshot = ref === null ? undefined : current(sessionId, ref);
|
|
68
78
|
// invariant: A ref this session cannot read takes no write, so no session overwrites another's conversation.
|
|
69
79
|
if (ref !== null && snapshot === undefined)
|
|
@@ -118,7 +128,10 @@ export function createSealedConversationStore(options) {
|
|
|
118
128
|
const conversation = storedConversation.parse(JSON.parse(plaintext));
|
|
119
129
|
return { revision: ref, conversation };
|
|
120
130
|
},
|
|
121
|
-
async write(sessionId, ref, expectedRevision, next) {
|
|
131
|
+
async write(sessionId, ref, expectedRevision, next, context) {
|
|
132
|
+
// invariant: This store keeps no holds, so a reply whose hold lost the conversation writes nothing here.
|
|
133
|
+
if (context?.ended === 'lost')
|
|
134
|
+
return { written: false };
|
|
122
135
|
if (ref !== expectedRevision)
|
|
123
136
|
return { written: false };
|
|
124
137
|
const conversation = storedConversation.parse(next);
|
package/server/conversation.d.ts
CHANGED
|
@@ -17,8 +17,9 @@
|
|
|
17
17
|
import { type GateReference, type LabelOverrides, type Profile, type ProviderCheckpoint, TheoremError, type TurnEvent, type TurnHistoryMessage, type TurnInput } from '@theoremjs/agents';
|
|
18
18
|
import { type ClientTurnOptions } from '@theoremjs/agents/host';
|
|
19
19
|
import { type ComposerProfileInterface, type ReplyCarried, streamThoughtsEnabled, type TranscriptBlock, type UserTurnDraft, type UserTurnHistoryMedia } from '@theoremjs/agents/interface';
|
|
20
|
-
import type { ConversationLine, ConversationView, StatedTurn, TheoremTurnInput } from '../client/transport.ts';
|
|
21
|
-
import { type StoredConversation, type TheoremConversationStore } from './conversation-store.ts';
|
|
20
|
+
import type { ConversationLine, ConversationView, RunningReply, StatedTurn, TheoremTurnInput } from '../client/transport.ts';
|
|
21
|
+
import { type ReplyEnd, type StoredConversation, type TheoremConversationStore } from './conversation-store.ts';
|
|
22
|
+
import type { ReplyRefusal } from './turn-wiring.ts';
|
|
22
23
|
/** One walked-away call: its id, and the run that settles it (`invokeTool` with the abandoned resume). */
|
|
23
24
|
export type WalkedAwayCall = {
|
|
24
25
|
callId: string;
|
|
@@ -59,8 +60,15 @@ export type OpenedConversation = {
|
|
|
59
60
|
ref: string | null;
|
|
60
61
|
revision: string | null;
|
|
61
62
|
conversation: StoredConversation;
|
|
63
|
+
/**
|
|
64
|
+
* How many of the transcript's blocks the store holds, when `conversation` has blocks the store
|
|
65
|
+
* has not heard of yet: a message the app saved itself, a walked-away reply not yet written.
|
|
66
|
+
*/
|
|
67
|
+
stored?: number;
|
|
62
68
|
/** What the guardrails decided reading a restored transcript, for the reply to stream first. */
|
|
63
69
|
events?: TurnEvent[];
|
|
70
|
+
/** The reply the store says runs on the conversation now (`ConversationSnapshot.running`). */
|
|
71
|
+
running?: RunningReply;
|
|
64
72
|
};
|
|
65
73
|
/**
|
|
66
74
|
* What a request opens a conversation for, checked as it opens, before the host starts any run:
|
|
@@ -137,6 +145,58 @@ export type ReplyRunner = {
|
|
|
137
145
|
stated?: StatedTurn;
|
|
138
146
|
carried?: ReplyCarried;
|
|
139
147
|
signal: AbortSignal;
|
|
148
|
+
/** The reply's id under its chat's hold: a paused reply keeps it, so the reply that goes on resumes what it read. */
|
|
149
|
+
reply?: string;
|
|
150
|
+
/**
|
|
151
|
+
* Whether the reply's hold still has its chat, asked before each save. A reply that lost it saves
|
|
152
|
+
* nothing: the hold that took the chat tells what it read.
|
|
153
|
+
*/
|
|
154
|
+
held?: () => Promise<boolean>;
|
|
155
|
+
/** The hold the reply runs under, for the store's write. */
|
|
156
|
+
hold?: string;
|
|
157
|
+
/** The app's own steps around the save. */
|
|
158
|
+
saving?: ReplySaving;
|
|
159
|
+
/**
|
|
160
|
+
* The app's refusal of the reply, once `run` ended on it: `run` then gave the line as its text
|
|
161
|
+
* and ran no model. The reply saves as `refused`.
|
|
162
|
+
*/
|
|
163
|
+
refused?: () => ReplyRefusal['refuse'] | undefined;
|
|
164
|
+
};
|
|
165
|
+
/** A reply as the app's `before` step reads it. */
|
|
166
|
+
export type ReplyToSave = {
|
|
167
|
+
ended: ReplyEnd;
|
|
168
|
+
/** The blocks the save adds to the transcript the store holds. */
|
|
169
|
+
blocks: readonly TranscriptBlock[];
|
|
170
|
+
/** Why the reply ended `failed`, or why a `paused` reply's answer did not settle its call. */
|
|
171
|
+
failure?: ErrorEvent;
|
|
172
|
+
/** The ids of the named injects that landed in this reply, in order. */
|
|
173
|
+
landed: readonly string[];
|
|
174
|
+
};
|
|
175
|
+
/** A reply as the app shaped it for the save. */
|
|
176
|
+
export type ShapedReply = {
|
|
177
|
+
/** The blocks to save in place of the reply's `blocks`. */
|
|
178
|
+
blocks: readonly TranscriptBlock[];
|
|
179
|
+
/** The ids of the inbox items the reply told. */
|
|
180
|
+
told: readonly string[];
|
|
181
|
+
/** The app's own values for its store's write. */
|
|
182
|
+
host?: unknown;
|
|
183
|
+
};
|
|
184
|
+
/** The app's own steps around a reply's save, bound to the run they belong to. */
|
|
185
|
+
export type ReplySaving = {
|
|
186
|
+
/** Shapes the reply before each save. */
|
|
187
|
+
before?: (reply: ReplyToSave) => Promise<ShapedReply>;
|
|
188
|
+
/** Runs once a save is written. What it throws is reported, and the save stands. */
|
|
189
|
+
after?: (saved: {
|
|
190
|
+
ended: ReplyEnd;
|
|
191
|
+
told: readonly string[];
|
|
192
|
+
}) => Promise<void>;
|
|
193
|
+
/** The app's compaction, in place of the runner's. What it throws is reported. */
|
|
194
|
+
compact?: (signal: {
|
|
195
|
+
history: TurnHistoryMessage[];
|
|
196
|
+
tokens: number;
|
|
197
|
+
}) => Promise<void>;
|
|
198
|
+
/** Reports an error the save does not throw. */
|
|
199
|
+
report: (err: unknown) => void;
|
|
140
200
|
};
|
|
141
201
|
/** A line of a reply's stream: an event, or the ref of what the store wrote. */
|
|
142
202
|
export type ReplyLine = TurnEvent | ConversationLine;
|
|
@@ -165,7 +225,27 @@ export declare function messageReply(args: {
|
|
|
165
225
|
message: PostedMessage;
|
|
166
226
|
/** The paused reply's calls, each with the run that settles it: exactly the calls it waits on. */
|
|
167
227
|
walkAway?: readonly IssuedWalkAway[];
|
|
228
|
+
/**
|
|
229
|
+
* The message's blocks as the app saved them itself. The reply then posts nothing: the store
|
|
230
|
+
* hears of the message first in the save that ends the reply.
|
|
231
|
+
*/
|
|
232
|
+
saved?: readonly TranscriptBlock[];
|
|
233
|
+
runner: ReplyRunner;
|
|
234
|
+
}): AsyncGenerator<ReplyLine>;
|
|
235
|
+
/**
|
|
236
|
+
* The model takes up the results of calls that ended while nothing ran: a reply to no message.
|
|
237
|
+
* It writes nothing until it ends, so a message posted meanwhile keeps the conversation, and this
|
|
238
|
+
* reply ends with no write: that message's reply read the same results. A reply that waits on
|
|
239
|
+
* gates is walked away from first, as a message does.
|
|
240
|
+
*/
|
|
241
|
+
export declare function wakeReply(args: {
|
|
242
|
+
host: ConversationHost;
|
|
243
|
+
opened: OpenedConversation;
|
|
168
244
|
runner: ReplyRunner;
|
|
245
|
+
/** What the page sends with every message: its option picks and context. */
|
|
246
|
+
input?: Pick<TurnInput, 'options' | 'context'>;
|
|
247
|
+
/** The paused reply's calls, each with the run that settles it: exactly the calls it waits on. */
|
|
248
|
+
walkAway?: readonly IssuedWalkAway[];
|
|
169
249
|
}): AsyncGenerator<ReplyLine>;
|
|
170
250
|
/**
|
|
171
251
|
* The person answers one call the reply waits on. `settling` streams the
|