@theoremjs/web 0.3.5-next.1013.g9b838d0 → 0.3.5-next.1016.gc4ded01
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 +21 -8
- package/client/transport.d.ts +5 -4
- package/package.json +2 -2
- package/server/conversation-core.d.ts +37 -19
- package/server/conversation-core.js +278 -129
- package/server/conversation-inbox.d.ts +19 -14
- package/server/conversation-inbox.js +57 -7
- package/server/conversation.d.ts +1 -0
- package/server/conversation.js +5 -1
- package/server/create-conversation-core.d.ts +1 -1
- package/server/create-conversation-core.js +2 -2
- package/server/handler.d.ts +2 -5
- package/server/handler.js +19 -11
- package/server/mod.d.ts +2 -2
- package/server/mod.js +2 -2
- package/server/own-inbox.d.ts +83 -0
- package/server/own-inbox.js +175 -0
- package/server/steer-inbox.d.ts +0 -41
- package/server/steer-inbox.js +0 -84
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The handler's conversation inbox: each chat's late results, kept in the session store
|
|
3
|
-
* is a detached call that ended; the transcript
|
|
4
|
-
* session keeps who holds the chat and which replies
|
|
2
|
+
* The handler's conversation inbox: each chat's late results, kept in the session store, and the
|
|
3
|
+
* person's messages, kept in memory. A late result is a detached call that ended; the transcript
|
|
4
|
+
* says whether a saved reply told it, and the session keeps who holds the chat and which replies
|
|
5
|
+
* were handed what. A message is told once a saved reply landed it.
|
|
5
6
|
*
|
|
6
7
|
* @module
|
|
7
8
|
*/
|
|
8
|
-
import { type LabelOverrides, type
|
|
9
|
+
import { type LabelOverrides, type Profile, type ToolOperationOutcome, type TurnEvent } from '@theoremjs/agents';
|
|
9
10
|
import type { ConversationInbox } from '@theoremjs/agents/conversation';
|
|
10
11
|
import { type ClientTurnOptions } from '@theoremjs/agents/host';
|
|
11
|
-
import type { TranscriptBlock } from '@theoremjs/agents/interface';
|
|
12
12
|
import type { DetachedEnding, StoredConversation } from './conversation-store.ts';
|
|
13
|
+
import { type MessageShelf, type OwnItem, type PersonMessage } from './own-inbox.ts';
|
|
13
14
|
import type { MutableStore } from './session-authority.ts';
|
|
14
15
|
import type { SessionToolOperation, TheoremSessionState } from './session-store.ts';
|
|
15
16
|
/** A background call that ended, as the session keeps it. */
|
|
@@ -29,14 +30,6 @@ export type DetachedCall = {
|
|
|
29
30
|
* dropped). Undefined while it runs.
|
|
30
31
|
*/
|
|
31
32
|
export declare function detachedEnd(call: DetachedCall, operation: SessionToolOperation | undefined, labels: Profile['labels']): ToolOperationOutcome | undefined;
|
|
32
|
-
/**
|
|
33
|
-
* When a call detached, epoch ms: kept after its end is saved on its block, so the end is told
|
|
34
|
-
* apart. A block saved before `detached` was kept has only its background phase. Undefined for a
|
|
35
|
-
* call that never detached.
|
|
36
|
-
*/
|
|
37
|
-
export declare function detachedAt(tool: Extract<TranscriptBlock, {
|
|
38
|
-
kind: 'tool';
|
|
39
|
-
}>['tool']): number | undefined;
|
|
40
33
|
/** Who reads a chat's events: the host's `clientEvents`, in the profile's `labels`. */
|
|
41
34
|
export type ChatReader = {
|
|
42
35
|
clientEvents?: ClientTurnOptions;
|
|
@@ -68,7 +61,19 @@ export type SessionConversationInboxOptions = {
|
|
|
68
61
|
readable: (operation: SettledOperation) => Promise<boolean>;
|
|
69
62
|
/** The profile's labels, for the words of an end the session does not hold. */
|
|
70
63
|
labels: Profile['labels'];
|
|
64
|
+
/** The person's messages, by session and chat: the handler's, so every request reads them. */
|
|
65
|
+
shelf: MessageShelf;
|
|
71
66
|
now?: () => number;
|
|
72
67
|
};
|
|
68
|
+
/** The inbox of one session's chats, and the save that tells a message. */
|
|
69
|
+
export type SessionOwnInbox = ConversationInbox<OwnItem> & {
|
|
70
|
+
/** Marks the messages `ids` told: a saved reply landed them. */
|
|
71
|
+
settle(key: string, ids: readonly string[]): Promise<void>;
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Saves the person's message for the reply that holds the chat, and moves the inbox's version so a
|
|
75
|
+
* hold that is about to let go reads it.
|
|
76
|
+
*/
|
|
77
|
+
export declare function arrivePersonMessage(options: Pick<SessionConversationInboxOptions, 'sessions' | 'sessionId' | 'shelf'>, key: string, message: PersonMessage): Promise<void>;
|
|
73
78
|
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
74
|
-
export declare function sessionConversationInbox(options: SessionConversationInboxOptions):
|
|
79
|
+
export declare function sessionConversationInbox(options: SessionConversationInboxOptions): SessionOwnInbox;
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The handler's conversation inbox: each chat's late results, kept in the session store
|
|
3
|
-
* is a detached call that ended; the transcript
|
|
4
|
-
* session keeps who holds the chat and which replies
|
|
2
|
+
* The handler's conversation inbox: each chat's late results, kept in the session store, and the
|
|
3
|
+
* person's messages, kept in memory. A late result is a detached call that ended; the transcript
|
|
4
|
+
* says whether a saved reply told it, and the session keeps who holds the chat and which replies
|
|
5
|
+
* were handed what. A message is told once a saved reply landed it.
|
|
5
6
|
*
|
|
6
7
|
* @module
|
|
7
8
|
*/
|
|
8
9
|
import { labelText, } from '@theoremjs/agents';
|
|
9
10
|
import { withPublicLabels } from '@theoremjs/agents/guardrails';
|
|
10
11
|
import { forClient } from '@theoremjs/agents/host';
|
|
12
|
+
import { ownKey } from "./own-inbox.js";
|
|
11
13
|
/**
|
|
12
14
|
* What became of a detached call, as the model and the page read it: the end the session saved, or
|
|
13
15
|
* that it is unresolved when the session holds no end (the call was cut off, or its saved end was
|
|
@@ -40,7 +42,7 @@ export function detachedEnd(call, operation, labels) {
|
|
|
40
42
|
* apart. A block saved before `detached` was kept has only its background phase. Undefined for a
|
|
41
43
|
* call that never detached.
|
|
42
44
|
*/
|
|
43
|
-
|
|
45
|
+
function detachedAt(tool) {
|
|
44
46
|
return tool.detached?.at ?? (tool.state?.phase === 'background' ? tool.state.at : undefined);
|
|
45
47
|
}
|
|
46
48
|
/**
|
|
@@ -68,6 +70,20 @@ export function readerEnding(outcome, forReader) {
|
|
|
68
70
|
const { tool } = event;
|
|
69
71
|
return tool.phase === 'complete' || tool.phase === 'error' ? tool : undefined;
|
|
70
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Saves the person's message for the reply that holds the chat, and moves the inbox's version so a
|
|
75
|
+
* hold that is about to let go reads it.
|
|
76
|
+
*/
|
|
77
|
+
export async function arrivePersonMessage(options, key, message) {
|
|
78
|
+
const scoped = ownKey(options.sessionId, key);
|
|
79
|
+
const kept = options.shelf.get(scoped) ?? new Map();
|
|
80
|
+
kept.set(message.id, message);
|
|
81
|
+
options.shelf.set(scoped, kept);
|
|
82
|
+
await options.sessions.mutate(options.sessionId, (state) => {
|
|
83
|
+
state.inbox ??= { version: 0, conversations: {} };
|
|
84
|
+
state.inbox.version += 1;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
71
87
|
/** The operation ids a chat's saved replies told, those its paused reply holds, and its untold calls. */
|
|
72
88
|
function transcriptState(conversation) {
|
|
73
89
|
const told = new Set();
|
|
@@ -132,6 +148,18 @@ export function sessionConversationInbox(options) {
|
|
|
132
148
|
handovers: [...(entry?.handovers ?? [])],
|
|
133
149
|
outcome,
|
|
134
150
|
});
|
|
151
|
+
const messageItem = (message, entry) => ({
|
|
152
|
+
...message,
|
|
153
|
+
handovers: [...(entry?.handovers ?? [])],
|
|
154
|
+
});
|
|
155
|
+
const shelfKey = (key) => ownKey(sessionId, key);
|
|
156
|
+
/** The person's messages that wait: not told, not given up, and no live hold has them. */
|
|
157
|
+
const waitingMessages = (inbox, key, at) => [...(options.shelf.get(shelfKey(key))?.values() ?? [])].filter((message) => {
|
|
158
|
+
const entry = Object.hasOwn(inbox.entries, message.id)
|
|
159
|
+
? inbox.entries[message.id]
|
|
160
|
+
: undefined;
|
|
161
|
+
return !entry?.givenUp && !(entry && heldLive(inbox, entry, at));
|
|
162
|
+
});
|
|
135
163
|
/** The call's end; undefined while it runs. */
|
|
136
164
|
const endOf = (state, call) => detachedEnd(call, operationOf(state, call.operationId), options.labels);
|
|
137
165
|
const handTo = (entry, hold, handover, at) => {
|
|
@@ -168,7 +196,7 @@ export function sessionConversationInbox(options) {
|
|
|
168
196
|
return change(key, (inbox, state, at) => {
|
|
169
197
|
if (!has(inbox, hold, at))
|
|
170
198
|
return [];
|
|
171
|
-
|
|
199
|
+
const ended = wanted.flatMap((call) => {
|
|
172
200
|
const outcome = waiting(inbox, state, call, at);
|
|
173
201
|
if (!outcome)
|
|
174
202
|
return [];
|
|
@@ -176,6 +204,14 @@ export function sessionConversationInbox(options) {
|
|
|
176
204
|
act(entry, at);
|
|
177
205
|
return [item(call.operationId, outcome, entry)];
|
|
178
206
|
});
|
|
207
|
+
const messages = waitingMessages(inbox, key, at)
|
|
208
|
+
.filter((message) => ids.includes(message.id))
|
|
209
|
+
.map((message) => {
|
|
210
|
+
const entry = entryOf(inbox, message.id);
|
|
211
|
+
act(entry, at);
|
|
212
|
+
return messageItem(message, entry);
|
|
213
|
+
});
|
|
214
|
+
return [...messages, ...ended];
|
|
179
215
|
});
|
|
180
216
|
};
|
|
181
217
|
const lease = (inbox, hold, at) => {
|
|
@@ -208,7 +244,7 @@ export function sessionConversationInbox(options) {
|
|
|
208
244
|
const state = await sessions.read(sessionId);
|
|
209
245
|
const inbox = state.inbox?.conversations[key] ?? { leasedUntil: 0, entries: {} };
|
|
210
246
|
const at = now();
|
|
211
|
-
const items = [];
|
|
247
|
+
const items = waitingMessages(inbox, key, at).map((message) => messageItem(message, inbox.entries[message.id]));
|
|
212
248
|
for (const call of calls) {
|
|
213
249
|
const id = call.operationId;
|
|
214
250
|
const outcome = waiting(inbox, state, call, at);
|
|
@@ -227,7 +263,10 @@ export function sessionConversationInbox(options) {
|
|
|
227
263
|
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
228
264
|
if (entry?.handed?.hold !== hold || entry.handed.reply !== reply)
|
|
229
265
|
continue;
|
|
230
|
-
|
|
266
|
+
const kept = options.shelf.get(shelfKey(key))?.has(id) ||
|
|
267
|
+
chat.untold.some((call) => call.operationId === id);
|
|
268
|
+
const gone = chat.told.has(id) || !kept;
|
|
269
|
+
if (gone) {
|
|
231
270
|
delete inbox.entries[id];
|
|
232
271
|
continue;
|
|
233
272
|
}
|
|
@@ -253,6 +292,17 @@ export function sessionConversationInbox(options) {
|
|
|
253
292
|
});
|
|
254
293
|
});
|
|
255
294
|
},
|
|
295
|
+
async settle(key, ids) {
|
|
296
|
+
const kept = options.shelf.get(shelfKey(key));
|
|
297
|
+
for (const id of ids)
|
|
298
|
+
kept?.delete(id);
|
|
299
|
+
if (kept?.size === 0)
|
|
300
|
+
options.shelf.delete(shelfKey(key));
|
|
301
|
+
await change(key, (inbox) => {
|
|
302
|
+
for (const id of ids)
|
|
303
|
+
delete inbox.entries[id];
|
|
304
|
+
});
|
|
305
|
+
},
|
|
256
306
|
giveUp(key, hold, ids) {
|
|
257
307
|
return actOnWaiting(key, hold, ids, (entry) => {
|
|
258
308
|
if (entry.handed)
|
package/server/conversation.d.ts
CHANGED
|
@@ -189,6 +189,7 @@ export type ReplySaving = {
|
|
|
189
189
|
after?: (saved: {
|
|
190
190
|
ended: ReplyEnd;
|
|
191
191
|
told: readonly string[];
|
|
192
|
+
landed: readonly string[];
|
|
192
193
|
}) => Promise<void>;
|
|
193
194
|
/**
|
|
194
195
|
* Runs once any write of the reply lands, with the blocks it added: saves the end of each call
|
package/server/conversation.js
CHANGED
|
@@ -237,7 +237,11 @@ async function saveReply(host, opened, runner, saving) {
|
|
|
237
237
|
runner.saving?.report(err);
|
|
238
238
|
}
|
|
239
239
|
try {
|
|
240
|
-
await runner.saving?.after?.({
|
|
240
|
+
await runner.saving?.after?.({
|
|
241
|
+
ended: saving.ended,
|
|
242
|
+
told: reply.context.told,
|
|
243
|
+
landed: landedIn(saving.events),
|
|
244
|
+
});
|
|
241
245
|
}
|
|
242
246
|
catch (err) {
|
|
243
247
|
runner.saving?.report(err);
|
|
@@ -15,7 +15,7 @@ import { type CallHooks, type CoreContext } from './session-calls.ts';
|
|
|
15
15
|
* `TheoremHandlerOptions` means what it means there. The others take the run's `CoreContext`
|
|
16
16
|
* where the handler's take the `Request`.
|
|
17
17
|
*/
|
|
18
|
-
export type TheoremConversationCoreOptions<Item extends InboxItem = InboxItem> = Pick<TheoremHandlerOptions, 'profile' | 'onStage' | 'sessionStore' | 'conversationStore' | 'credentialStore' | 'gateTtlMs' | 'operationRetentionMs' | 'pageToolBroker' | 'pageToolTimeoutMs' | 'notifier' | 'replyFeed' | 'notifyRetryMs' | 'lateResultsDecider' | 'conversationLeaseMs' | '
|
|
18
|
+
export type TheoremConversationCoreOptions<Item extends InboxItem = InboxItem> = Pick<TheoremHandlerOptions, 'profile' | 'onStage' | 'sessionStore' | 'conversationStore' | 'credentialStore' | 'gateTtlMs' | 'operationRetentionMs' | 'pageToolBroker' | 'pageToolTimeoutMs' | 'notifier' | 'replyFeed' | 'notifyRetryMs' | 'lateResultsDecider' | 'conversationLeaseMs' | 'clientEvents'> & ReplyWiring<Item> & {
|
|
19
19
|
/** Host options for registered providers, or a factory for apps that pick keys per run. */
|
|
20
20
|
provider: ProviderHostOptions | ((at: CoreContext, model?: string) => ProviderHostOptions | Promise<ProviderHostOptions>);
|
|
21
21
|
/**
|
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { TheoremError } from '@theoremjs/agents';
|
|
9
9
|
import { chatOf, createConversationCore, endingsOf, } from "./conversation-core.js";
|
|
10
|
+
import { createOwnInbox } from "./own-inbox.js";
|
|
10
11
|
import { sessionParts } from "./session-calls.js";
|
|
11
|
-
import { createMemorySteerInbox } from "./steer-inbox.js";
|
|
12
12
|
/** Creates the conversation core for `options.profile`. */
|
|
13
13
|
export function createTheoremConversationCore(options) {
|
|
14
14
|
const name = 'createTheoremConversationCore';
|
|
@@ -22,7 +22,7 @@ export function createTheoremConversationCore(options) {
|
|
|
22
22
|
...sessionParts(name, chat.profile, options),
|
|
23
23
|
...endingsOf(chat, options),
|
|
24
24
|
chat,
|
|
25
|
-
|
|
25
|
+
own: createOwnInbox(),
|
|
26
26
|
options: {
|
|
27
27
|
prepare: options.prepare,
|
|
28
28
|
onStage: options.onStage,
|
package/server/handler.d.ts
CHANGED
|
@@ -55,7 +55,6 @@ import type { TheoremReplyFeed } from './reply-feed.ts';
|
|
|
55
55
|
import { type CoreContext } from './session-calls.ts';
|
|
56
56
|
export { theoremSession, theoremSessionId } from './session-identity.ts';
|
|
57
57
|
import type { SessionToolOperation, TheoremSessionStore } from './session-store.ts';
|
|
58
|
-
import { type SteerInbox } from './steer-inbox.ts';
|
|
59
58
|
export type TheoremRequestContext = {
|
|
60
59
|
request: Request;
|
|
61
60
|
/** Selected model id, when the client picked one. */
|
|
@@ -196,7 +195,7 @@ export type TheoremHandlerOptions<Item extends InboxItem = InboxItem> = ReplyWir
|
|
|
196
195
|
* Your app's own save of a person's message, for `/turn` and `/steer`. It saves the message
|
|
197
196
|
* under `sent.id` one time, and in the same write takes the conversation in your `inbox` when
|
|
198
197
|
* no reply holds it. `sent.ref` is the page's ref of the conversation, when it has one. Needs
|
|
199
|
-
* `inbox`.
|
|
198
|
+
* `inbox`. Without it, a steer goes to Theorem's own inbox of the reply that runs in this process.
|
|
200
199
|
*/
|
|
201
200
|
intake?: (at: CoreContext, sent: {
|
|
202
201
|
id: string;
|
|
@@ -220,8 +219,6 @@ export type TheoremHandlerOptions<Item extends InboxItem = InboxItem> = ReplyWir
|
|
|
220
219
|
request: Request;
|
|
221
220
|
sessionId: string;
|
|
222
221
|
}) => string | Promise<string>;
|
|
223
|
-
/** Default: in-process memory. Use a shared store when turns and steers can land on different instances. */
|
|
224
|
-
steerInbox?: SteerInbox;
|
|
225
222
|
/**
|
|
226
223
|
* Who reads this host's replies, and what an event keeps for them: forwarded to `forClient`
|
|
227
224
|
* for each event and to `clientError` for a failure the handler catches.
|
|
@@ -258,7 +255,7 @@ export type MessageIntake = {
|
|
|
258
255
|
landsAs: readonly string[];
|
|
259
256
|
};
|
|
260
257
|
/** A host profile runs no model, and takes no turns to steer. */
|
|
261
|
-
export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | '
|
|
258
|
+
export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'conversationStore' | 'prepare' | 'inbox' | 'beforeSave' | 'afterSave' | 'compact' | 'notifier' | 'replyFeed' | 'notifyRetryMs' | 'conversationLeaseMs'> & {
|
|
262
259
|
/** Host profile to serve. Registered with the kernel when the handler is created. */
|
|
263
260
|
profile: Extract<Profile, {
|
|
264
261
|
type: 'host';
|
package/server/handler.js
CHANGED
|
@@ -47,15 +47,15 @@ import { blockWithoutToolData, clientProfileInterface, eventWithoutToolData, pro
|
|
|
47
47
|
import { hostInterface, theoremHostCallRequestSchema } from "../client/host-transport.js";
|
|
48
48
|
import { theoremConversationRequestSchema, theoremFollowRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
49
49
|
import { statelessRefusal } from "./conversation.js";
|
|
50
|
-
import { chatOf, createConversationCore, endingsOf, followedUp, oneInbox,
|
|
50
|
+
import { chatOf, createConversationCore, endingsOf, followedUp, oneInbox, unconversedAnswer, } from "./conversation-core.js";
|
|
51
51
|
import { callEvents, sessionParts } from "./session-calls.js";
|
|
52
52
|
import { theoremSession } from "./session-identity.js";
|
|
53
53
|
import { kernelTurnInput } from "./turn-input.js";
|
|
54
54
|
export { theoremSession, theoremSessionId } from "./session-identity.js";
|
|
55
55
|
import { jsonResponse } from "./json-response.js";
|
|
56
|
+
import { createOwnInbox } from "./own-inbox.js";
|
|
56
57
|
import { boundedRequestJson, requestByteLimit } from "./request-body.js";
|
|
57
58
|
import { checkRequest } from "./request-check.js";
|
|
58
|
-
import { createMemorySteerInbox } from "./steer-inbox.js";
|
|
59
59
|
const NDJSON_HEADERS = {
|
|
60
60
|
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
61
61
|
'cache-control': 'no-store',
|
|
@@ -241,7 +241,7 @@ function coreOf(ctx, chat, request) {
|
|
|
241
241
|
return ctx.wire({
|
|
242
242
|
...calls,
|
|
243
243
|
chat,
|
|
244
|
-
|
|
244
|
+
own: ctx.own,
|
|
245
245
|
options: {
|
|
246
246
|
...calls.options,
|
|
247
247
|
provider: (_at, model) => providerFor(ctx, request, model),
|
|
@@ -460,13 +460,22 @@ async function steer(ctx, chat, request, session) {
|
|
|
460
460
|
const saved = { conversation: taken.ref, landsAs: [...taken.landsAs] };
|
|
461
461
|
return jsonResponse(200, { ok: true, saved });
|
|
462
462
|
}
|
|
463
|
-
// why:
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
const steered = await core.steer(at, { turnId: body.turnId, id: body.id, input: body.input });
|
|
467
|
-
if (!steered)
|
|
463
|
+
// why: A chat is named by its conversation; a run that keeps none is named by its `turnId`.
|
|
464
|
+
const target = steerTarget(body);
|
|
465
|
+
if (!(await core.steer(at, { ...target, id: body.id, input: body.input }))) {
|
|
468
466
|
throw replyNotRunning(body);
|
|
469
|
-
|
|
467
|
+
}
|
|
468
|
+
const saved = 'ref' in target ? { conversation: target.ref, landsAs: [body.id] } : undefined;
|
|
469
|
+
return jsonResponse(200, { ok: true, ...(saved ? { saved } : {}) });
|
|
470
|
+
}
|
|
471
|
+
/** The reply a steer joins: the conversation the page names, else the run it started. */
|
|
472
|
+
function steerTarget(body) {
|
|
473
|
+
if (body.conversation !== undefined)
|
|
474
|
+
return { ref: body.conversation };
|
|
475
|
+
// invariant: A body with no `conversation` is the `turnId` variant, which the schema checks.
|
|
476
|
+
if ('turnId' in body)
|
|
477
|
+
return { turnId: body.turnId };
|
|
478
|
+
throw replyNotRunning(body);
|
|
470
479
|
}
|
|
471
480
|
/** The refusal of a steer or stop for a reply that is not running. */
|
|
472
481
|
function replyNotRunning(target) {
|
|
@@ -573,7 +582,6 @@ export function createTheoremHandler(options) {
|
|
|
573
582
|
}
|
|
574
583
|
const { prepare, inbox, beforeSave, afterSave, compact } = options;
|
|
575
584
|
return serve('createTheoremHandler', chat.profile, options, {
|
|
576
|
-
steerInbox: options.steerInbox,
|
|
577
585
|
chat,
|
|
578
586
|
wire: (state) => createConversationCore({
|
|
579
587
|
...state,
|
|
@@ -608,7 +616,7 @@ function serve(name, profile, options, chatOptions = {}) {
|
|
|
608
616
|
options,
|
|
609
617
|
...sessionParts(name, profile, options),
|
|
610
618
|
...(chatOptions.chat ? { chat: chatOptions.chat } : {}),
|
|
611
|
-
|
|
619
|
+
own: createOwnInbox(),
|
|
612
620
|
wire: chatOptions.wire ?? createConversationCore,
|
|
613
621
|
};
|
|
614
622
|
return async (request) => {
|
package/server/mod.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export { transcriptBlockSchema } from '../client/transcript-schema.ts';
|
|
|
11
11
|
export { type StatedTurn, theoremConversationRequestSchema, theoremFollowRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from '../client/transport.ts';
|
|
12
12
|
export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplySaving, type ReplyToSave, type ReplyTurn, readerConversationHost, rewindConversation, type ShapedReply, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeReply, } from './conversation.ts';
|
|
13
13
|
export type { AppInbox, ContinueChoice, ConversationCore, FollowUpArgs, Generation, HoldStop, MessageArgs, Reply, ReplyPrepare, ReplyWiring, RunEnd, SaveHooks, WakeArgs, } from './conversation-core.ts';
|
|
14
|
-
export { followedUp } from './conversation-core.ts';
|
|
14
|
+
export { followedUp, type NamedHold, namedRun } from './conversation-core.ts';
|
|
15
15
|
export { type ChatReader, detachedEnding } from './conversation-inbox.ts';
|
|
16
16
|
export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, type DetachedEnding, emptyConversation, endedBlock, type PausedReply, type ReplyEnd, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, type UncompactedBase, unknownConversation, type WriteContext, } from './conversation-store.ts';
|
|
17
17
|
export { createTheoremConversationCore, type TheoremConversationCoreOptions, } from './create-conversation-core.ts';
|
|
@@ -21,6 +21,7 @@ export { createTheoremEmbeddingHandler, embedBodySchema, embedRequest, type Theo
|
|
|
21
21
|
export { createTheoremHandler, createTheoremHostHandler, type MessageIntake, readBody, type TheoremHandlerOptions, type TheoremHostHandlerOptions, type TheoremRequestContext, theoremSession, theoremSessionId, } from './handler.ts';
|
|
22
22
|
export { createTheoremMcpHandler, type TheoremMcpHandlerOptions } from './mcp-handler.ts';
|
|
23
23
|
export { createMemoryNotifier, type TheoremNotifier } from './notifier.ts';
|
|
24
|
+
export { createOwnInbox, type OwnInbox, openRun, personMessageOf, type RunInbox, scopedStop, steerRun, } from './own-inbox.ts';
|
|
24
25
|
export { createMemoryPageToolBroker, type PageToolBroker, type PageToolResult, pageToolResultSchema, sessionPageDispatch, } from './page-dispatch.ts';
|
|
25
26
|
export { createMemoryReplyFeed, type ReplyFeedListener, type TheoremReplyFeed, } from './reply-feed.ts';
|
|
26
27
|
export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from './request-check.ts';
|
|
@@ -29,7 +30,6 @@ export { createTheoremSessionBoundary, type PreparedLiveOpen, type SessionBounda
|
|
|
29
30
|
export type { CoreContext } from './session-calls.ts';
|
|
30
31
|
export type { TheoremSessionCapacity } from './session-limits.ts';
|
|
31
32
|
export { createMemorySessionStore, type MemorySessionStoreOptions, type PendingToolGate, type SessionSnapshot, type SessionToolOperation, type SessionWriteResult, type TheoremSessionState, type TheoremSessionStore, theoremSessionStateSchema, } from './session-store.ts';
|
|
32
|
-
export { createMemorySteerInbox, type SteerInbox, type SteerUnit, steerStage, steerUnitOf, stopOnRequest, } from './steer-inbox.ts';
|
|
33
33
|
export { tellEveryResult } from './tell-every-result.ts';
|
|
34
34
|
export { sessionToolCoordinator } from './tool-operations.ts';
|
|
35
35
|
export { kernelTurnInput, liveSessionOpen } from './turn-input.ts';
|
package/server/mod.js
CHANGED
|
@@ -9,7 +9,7 @@ export { theoremHostCallRequestSchema } from "../client/host-transport.js";
|
|
|
9
9
|
export { transcriptBlockSchema } from "../client/transcript-schema.js";
|
|
10
10
|
export { theoremConversationRequestSchema, theoremFollowRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
11
11
|
export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
|
|
12
|
-
export { followedUp } from "./conversation-core.js";
|
|
12
|
+
export { followedUp, namedRun } from "./conversation-core.js";
|
|
13
13
|
export { detachedEnding } from "./conversation-inbox.js";
|
|
14
14
|
export { createMemoryConversationStore, createSealedConversationStore, emptyConversation, endedBlock, storedConversationSchema, unknownConversation, } from "./conversation-store.js";
|
|
15
15
|
export { createTheoremConversationCore, } from "./create-conversation-core.js";
|
|
@@ -19,13 +19,13 @@ export { createTheoremEmbeddingHandler, embedBodySchema, embedRequest, } from ".
|
|
|
19
19
|
export { createTheoremHandler, createTheoremHostHandler, readBody, theoremSession, theoremSessionId, } from "./handler.js";
|
|
20
20
|
export { createTheoremMcpHandler } from "./mcp-handler.js";
|
|
21
21
|
export { createMemoryNotifier } from "./notifier.js";
|
|
22
|
+
export { createOwnInbox, openRun, personMessageOf, scopedStop, steerRun, } from "./own-inbox.js";
|
|
22
23
|
export { createMemoryPageToolBroker, pageToolResultSchema, sessionPageDispatch, } from "./page-dispatch.js";
|
|
23
24
|
export { createMemoryReplyFeed, } from "./reply-feed.js";
|
|
24
25
|
export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from "./request-check.js";
|
|
25
26
|
export { sessionStateStore } from "./session-authority.js";
|
|
26
27
|
export { createTheoremSessionBoundary, } from "./session-boundary.js";
|
|
27
28
|
export { createMemorySessionStore, theoremSessionStateSchema, } from "./session-store.js";
|
|
28
|
-
export { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
|
|
29
29
|
export { tellEveryResult } from "./tell-every-result.js";
|
|
30
30
|
export { sessionToolCoordinator } from "./tool-operations.js";
|
|
31
31
|
export { kernelTurnInput, liveSessionOpen } from "./turn-input.js";
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Theorem's own conversation inbox, for the replies that hold no app `inbox`. A message the person
|
|
3
|
+
* sends while a reply runs is an item in it, beside the session's ended background calls. The
|
|
4
|
+
* reply takes one message at each `pre_turn`, `post_tool` and `before_end`, and a save of the
|
|
5
|
+
* reply that landed it tells it once. A stop reaches the reply that holds the conversation.
|
|
6
|
+
*
|
|
7
|
+
* The inbox is named by the chat's conversation. A chat that keeps no conversation (`'stateless'`)
|
|
8
|
+
* is named by its run: the `turnId` the page sent. Both live in process memory, so a steer and the
|
|
9
|
+
* reply it joins must reach the same process.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import { type LateResultItem, type LateResultsDecider, type LateResultsSource, type StageHandler, type TurnHistoryMessage } from '@theoremjs/agents';
|
|
14
|
+
import { type InboxItem, type InboxPolicy, type MemoryInbox, type ReplyRun } from '@theoremjs/agents/conversation';
|
|
15
|
+
import type { TheoremSteerRequest } from '../client/transport.ts';
|
|
16
|
+
import type { HoldStop } from './conversation-core.ts';
|
|
17
|
+
/** A message the person sent into a running reply, as the one user message the model reads. */
|
|
18
|
+
export interface PersonMessage extends InboxItem<'person_message'> {
|
|
19
|
+
messages: TurnHistoryMessage[];
|
|
20
|
+
}
|
|
21
|
+
/** What Theorem's own inbox holds: ended background calls and the person's messages. */
|
|
22
|
+
export type OwnItem = LateResultItem | PersonMessage;
|
|
23
|
+
/**
|
|
24
|
+
* A steer as a client posts it (a checked `TheoremSteerRequest`) as an inbox item: its id is the
|
|
25
|
+
* client's, and a reply names it in `stage.injected` once it lands. A message with no text and no
|
|
26
|
+
* file is refused.
|
|
27
|
+
*/
|
|
28
|
+
export declare function personMessageOf(steer: Pick<TheoremSteerRequest, 'id' | 'input'>): PersonMessage;
|
|
29
|
+
/** The person's messages the session inbox keeps in memory, by session and conversation. */
|
|
30
|
+
export type MessageShelf = Map<string, Map<string, PersonMessage>>;
|
|
31
|
+
/** The stop of replies run by this process, which Theorem's own inbox uses when the app gives none. */
|
|
32
|
+
export type MemoryHoldStop = HoldStop & {
|
|
33
|
+
/** Whether a model run of a reply holding `conversation` is running now. */
|
|
34
|
+
running(conversation: string): boolean;
|
|
35
|
+
};
|
|
36
|
+
/** What every request of one handler shares: the memory the own inbox keeps. */
|
|
37
|
+
export type OwnInbox = {
|
|
38
|
+
/** The messages a stored chat's session inbox tells beside the decider's late results. */
|
|
39
|
+
shelf: MessageShelf;
|
|
40
|
+
/** The inbox of each run of a chat that keeps no conversation, by session and `turnId`, while it runs. */
|
|
41
|
+
runs: Map<string, MemoryInbox<OwnItem>>;
|
|
42
|
+
/** The conversation each running reply of a stored chat holds, by session and the page's `turnId`. */
|
|
43
|
+
turns: Map<string, string>;
|
|
44
|
+
stop: MemoryHoldStop;
|
|
45
|
+
};
|
|
46
|
+
/** Creates the memory one handler's replies share. */
|
|
47
|
+
export declare function createOwnInbox(): OwnInbox;
|
|
48
|
+
/** A stop whose names are scoped, so no scope reaches another's reply. */
|
|
49
|
+
export declare function scopedStop(stop: HoldStop, scope: string): HoldStop;
|
|
50
|
+
/** The inbox of one run of a chat that keeps no conversation: Theorem's own, in memory, while it runs. */
|
|
51
|
+
export type RunInbox = {
|
|
52
|
+
memory: MemoryInbox<OwnItem>;
|
|
53
|
+
close(): void;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Opens the inbox of the run `name` in `scope`. A person's message reaches it with `steerRun`,
|
|
57
|
+
* and a reply under a hold of it (`namedRun`) takes it. `close` ends it; a message still waiting is lost.
|
|
58
|
+
*/
|
|
59
|
+
export declare function openRun(own: OwnInbox, scope: string, name: string, leaseMs: number): RunInbox;
|
|
60
|
+
/** Puts a person's message into the run `name` in `scope`. False when no such run is open. */
|
|
61
|
+
export declare function steerRun(own: OwnInbox, scope: string, name: string, message: PersonMessage): boolean;
|
|
62
|
+
/** The inbox's name for a conversation or a run in one session: no session reaches another's. */
|
|
63
|
+
export declare function ownKey(sessionId: string, name: string): string;
|
|
64
|
+
/**
|
|
65
|
+
* The rule for what a reply takes: the first waiting message, one at each moment, and the
|
|
66
|
+
* decider's choice among the late results.
|
|
67
|
+
*/
|
|
68
|
+
export declare function ownPolicy(options: {
|
|
69
|
+
decider?: LateResultsDecider;
|
|
70
|
+
host: () => Promise<unknown>;
|
|
71
|
+
}): InboxPolicy<OwnItem>;
|
|
72
|
+
/** What a reply takes from its hold: late results for the kernel's source, messages for a stage. */
|
|
73
|
+
export type OwnReads = {
|
|
74
|
+
late: LateResultsSource;
|
|
75
|
+
stage: StageHandler;
|
|
76
|
+
/** The ids among `ids` that this reply took as messages. */
|
|
77
|
+
mine(ids: readonly string[]): string[];
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* One take of the hold at each moment, shared by the two readers: the kernel asks for late results,
|
|
81
|
+
* and the stage handler for a message. Each reader reads a moment once.
|
|
82
|
+
*/
|
|
83
|
+
export declare function ownReads(run: ReplyRun<OwnItem>): OwnReads;
|