@theoremjs/web 0.3.5-next.935.ga3dc485 → 0.3.5-next.936.ga984349
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -6
- package/package.json +2 -2
- package/server/conversation-inbox.d.ts +30 -0
- package/server/conversation-inbox.js +201 -0
- package/server/conversation-store.d.ts +2 -0
- package/server/conversation-store.js +1 -0
- package/server/conversation.d.ts +7 -12
- package/server/conversation.js +30 -42
- package/server/handler.d.ts +9 -2
- package/server/handler.js +226 -128
- package/server/mod.d.ts +2 -2
- package/server/mod.js +2 -2
- package/server/session-authority.js +3 -1
- package/server/session-store.d.ts +32 -2
- package/server/session-store.js +40 -2
- package/server/tell-every-result.d.ts +10 -0
- package/server/tell-every-result.js +7 -0
- package/server/tool-operations.js +7 -0
- package/server/page-wakes.d.ts +0 -10
- package/server/page-wakes.js +0 -8
package/README.md
CHANGED
|
@@ -271,7 +271,8 @@ const transport = withPageToolDispatch(
|
|
|
271
271
|
| `pageStatesTurn` | Let the page say which prompt lines a turn gets, through `stated` on a turn or a live call. Set it only for a page you trust as yourself, such as a builder's own tool. Without it, a request with `stated` is refused. |
|
|
272
272
|
| `conversationStore` | Where the conversation is kept. Required, except for a stateless profile, which must not have one. See [Keep the conversation](#keep-the-conversation). |
|
|
273
273
|
| `sessionStore`, `steerInbox` | Where open gates are kept, and where steers and stops reach a running turn. Default: process memory, which reaches only turns this process runs. On more than one instance, give a shared `SteerInbox`. |
|
|
274
|
-
| `lateResultsDecider` | Who tells the model that a background call ended: `TurnWiring.lateResultsDecider`. Set it on your `TurnWiring`, and the studio uses it too. Unset, no page wakes the chat and no reply reads a late result. `
|
|
274
|
+
| `lateResultsDecider` | Who tells the model that a background call ended: `TurnWiring.lateResultsDecider`. Set it on your `TurnWiring`, and the studio uses it too. Unset, no page wakes the chat and no reply reads a late result. `tellEveryResult` tells each result to the first reply that runs. See [the background section](#share-session-authority). |
|
|
275
|
+
| `conversationLeaseMs` | How long a reply keeps its chat after it last renewed, in milliseconds. A running reply renews every third of it. A wake that finds another reply running tries again once this runs out. Default: `60000`. |
|
|
275
276
|
| `notifier`, `notifyRetryMs` | Tell an open page that a background call ended, and how long the page waits to reopen a cut stream. Unset, the page reads the end on its next turn or reload. See [the background section](#share-session-authority). |
|
|
276
277
|
| `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
|
|
277
278
|
| `authorizationUrl` | Returns the sign-in URL for an OAuth gate. Without it, an OAuth gate has no URL. |
|
|
@@ -460,15 +461,18 @@ Browser dispatch uses a host-owned `PageToolExecution` service beside the execut
|
|
|
460
461
|
A tool with a `background` setting runs inline until you pass the `background` option to `createTheoremHandler`, or return `background` from `prepare`, with an `execution` of your own that has `detach`, when the same turns run elsewhere in your app too. The option takes `{ request, sessionId }` and returns a `ToolBackgroundService`, which receives each detached call and its late events. The session keeps the call as `background` until it settles, and a late settlement does not invalidate a checkpoint. A conversation read shows the call as it stands: running, then its result, or an error for a marked call. An open page reads it on its next turn or reload, unless you set `notifier`. When the session has dropped a settled operation, the block reads an error with the code `outcome_not_retained`. On a durable store, a worker that dies leaves the operation as `background`, so your sweep marks it `uncertain` with `worker_lost` through `compareAndSwap`. Keep the service's values valid after the request ends. A live relay passes its service to `runSession`.
|
|
461
462
|
To show an open page that a background call ended, with no turn or reload, pass `notifier: createMemoryNotifier()` to `createTheoremHandler`. While a call runs, the conversation read tells the page to open `POST <base>/notify`. The handler sends one `changed` line when the stream opens, and one when each background call in the session ends. The line carries no content, so the page calls the same conversation read as before. The page closes the stream when no call runs. The model reads the result only as your decider says.
|
|
462
463
|
|
|
463
|
-
Set `lateResultsDecider` on your `TurnWiring` and pass it to `createTheoremHandler`. Unset, nothing tells the model a background call ended: the conversation read never says `wake: true`, `<base>/wake` runs nothing, and the next message reads no late result. A result waits for the model when its call settled
|
|
464
|
+
Set `lateResultsDecider` on your `TurnWiring` and pass it to `createTheoremHandler`. Unset, nothing tells the model a background call ended: the conversation read never says `wake: true`, `<base>/wake` runs nothing, and the next message reads no late result. A result waits for the model when its call settled, no saved reply told it, and the session keeps the operation. A call `authorizeToolReplay` withholds from the request does not wait.
|
|
464
465
|
|
|
465
|
-
|
|
466
|
-
|
|
466
|
+
The handler runs each reply under a hold of the chat, with `runConversation` from `@theoremjs/agents/conversation`. One reply at a time reads the chat's results. A result is told only when the reply that read it is saved. A reply that fails gives its results back, and a later reply reads them.
|
|
467
|
+
|
|
468
|
+
- `policy(items, moment)` picks, by `id` (the call's `operationId`), the results the model reads now. Each item has the call's `outcome`, and `handovers`: the earlier replies it was given to that ended unsaved. The handler asks it as a reply opens (`stage: 'pre_turn'`), after each step whose calls settled (`'post_tool'`), and once the model has answered (`'before_end'`). `moment.opening` is `'message'` for the person's message, `'wake'` for a reply to no message, and `'follow_up'` as a reply ends, for results that ended while it ran. The handler also asks it at `opening: 'wake'` on each conversation read, to say whether the page wakes the chat. It must change nothing. A result it leaves out waits for a later reply. A result it puts in `giveUp` is never read, and is reported once to `onError` with the code `late_results_given_up`.
|
|
467
469
|
- `ended({ host, result, wake, notify })` hears each background call end. `wake(conversation)` runs a reply to no message from the server, as a page's wake does, so a chat answers with no page open. `notify()` tells the session's open pages to read again.
|
|
468
470
|
|
|
469
|
-
`
|
|
471
|
+
`tellEveryResult` is the decider for an app with no server of its own: every reply reads every result that waits, and the open page wakes the chat. Write your own to keep a count, such as a cap or quiet hours, or to reply from the server.
|
|
472
|
+
|
|
473
|
+
When the policy tells a result at `opening: 'wake'`, the conversation read says `wake: true`, and the page posts `<base>/wake` once it is idle. The handler runs a reply with no message, under a hold of the chat, so two pages that post at once run one reply. No wake runs while a reply waits on a gate: the reply that goes on after the answer reads what waits. A wake that fails gives its results back, so the chat wakes again. A message the person sends during a wake takes the chat: the wake writes nothing, and its stream ends with no error.
|
|
470
474
|
|
|
471
|
-
When
|
|
475
|
+
When a result ends while a reply runs, that reply reads it at its next moment. If it ends as the reply saves, the policy is asked once more before the reply lets the chat go. A reply from the server then runs a follow-up under the same hold. A page's reply lets the chat go, and the conversation read tells the page to wake. A server wake that finds another reply running tries again once that reply's lease runs out (`conversationLeaseMs`).
|
|
472
476
|
|
|
473
477
|
The decider is the one way a result reaches the model. If your `background` service told the model a result some other way, such as with your own `onStage`, remove that, or the model reads it twice.
|
|
474
478
|
|
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.936.ga984349",
|
|
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.936.ga984349"
|
|
29
29
|
}
|
|
30
30
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
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 } 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
|
+
/** Options for {@link sessionConversationInbox}. */
|
|
18
|
+
export type SessionConversationInboxOptions = {
|
|
19
|
+
sessions: MutableStore<TheoremSessionState>;
|
|
20
|
+
sessionId: string;
|
|
21
|
+
/** How long a hold has a chat after it opens or renews, in milliseconds. */
|
|
22
|
+
leaseMs: number;
|
|
23
|
+
/** The chat as its last save left it, by its id; undefined when the store no longer has it. */
|
|
24
|
+
conversation: (key: string) => Promise<StoredConversation | undefined>;
|
|
25
|
+
/** Whether this request may read the call's result: the handler's `authorizeToolReplay`. */
|
|
26
|
+
readable: (operation: SettledOperation) => Promise<boolean>;
|
|
27
|
+
now?: () => number;
|
|
28
|
+
};
|
|
29
|
+
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
30
|
+
export declare function sessionConversationInbox(options: SessionConversationInboxOptions): ConversationInbox<LateResultItem>;
|
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
/** The operation ids a chat's saved replies told, and those its paused reply holds. */
|
|
9
|
+
function transcriptState(conversation) {
|
|
10
|
+
const told = new Set();
|
|
11
|
+
const detached = [];
|
|
12
|
+
for (const block of conversation?.transcript ?? []) {
|
|
13
|
+
if (block.kind === 'late-results')
|
|
14
|
+
for (const id of block.operationIds)
|
|
15
|
+
told.add(id);
|
|
16
|
+
if (block.kind === 'tool' && block.tool.state?.phase === 'background' && block.tool.operationId)
|
|
17
|
+
detached.push(block.tool.operationId);
|
|
18
|
+
}
|
|
19
|
+
const paused = new Set();
|
|
20
|
+
for (const event of conversation?.paused?.events ?? []) {
|
|
21
|
+
if (event.type === 'late_results')
|
|
22
|
+
for (const id of event.operationIds)
|
|
23
|
+
paused.add(id);
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
told,
|
|
27
|
+
paused,
|
|
28
|
+
pausedReply: conversation?.paused?.reply,
|
|
29
|
+
untold: detached.filter((id) => !told.has(id)),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function settledOperation(state, id) {
|
|
33
|
+
const operation = Object.hasOwn(state.operations, id) ? state.operations[id] : undefined;
|
|
34
|
+
return operation?.status === 'settled' ? operation : undefined;
|
|
35
|
+
}
|
|
36
|
+
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
37
|
+
export function sessionConversationInbox(options) {
|
|
38
|
+
const { sessions, sessionId, leaseMs } = options;
|
|
39
|
+
const now = options.now ?? Date.now;
|
|
40
|
+
const inboxOf = (state, key) => {
|
|
41
|
+
state.inbox ??= { version: 0, conversations: {} };
|
|
42
|
+
const conversations = state.inbox.conversations;
|
|
43
|
+
if (!Object.hasOwn(conversations, key))
|
|
44
|
+
conversations[key] = { leasedUntil: 0, entries: {} };
|
|
45
|
+
return conversations[key];
|
|
46
|
+
};
|
|
47
|
+
const has = (inbox, hold, at) => inbox.hold === hold && inbox.leasedUntil > at;
|
|
48
|
+
/** Handed to a reply whose hold still has the chat. */
|
|
49
|
+
const heldLive = (inbox, entry, at) => entry.handed !== undefined && has(inbox, entry.handed.hold, at);
|
|
50
|
+
const entryOf = (inbox, id) => {
|
|
51
|
+
if (!Object.hasOwn(inbox.entries, id))
|
|
52
|
+
inbox.entries[id] = { handovers: [] };
|
|
53
|
+
return inbox.entries[id];
|
|
54
|
+
};
|
|
55
|
+
const item = (operation, entry) => ({
|
|
56
|
+
id: operation.operationId,
|
|
57
|
+
kind: 'late_result',
|
|
58
|
+
handovers: [...(entry?.handovers ?? [])],
|
|
59
|
+
outcome: operation.outcome,
|
|
60
|
+
});
|
|
61
|
+
const handTo = (entry, hold, handover, at) => {
|
|
62
|
+
// invariant: A reply that lost its hold never gave its item back: what it was handed counts as a handover.
|
|
63
|
+
if (entry.handed)
|
|
64
|
+
entry.handovers.push(entry.handed);
|
|
65
|
+
entry.handed = { ...handover, hold, at };
|
|
66
|
+
};
|
|
67
|
+
/** The untold results no live hold has and no paused reply keeps, as this request may read them. */
|
|
68
|
+
const readableIds = async (key) => {
|
|
69
|
+
const conversation = await options.conversation(key);
|
|
70
|
+
const chat = transcriptState(conversation);
|
|
71
|
+
return { chat, ids: chat.untold.filter((id) => !chat.paused.has(id)) };
|
|
72
|
+
};
|
|
73
|
+
const waiting = (inbox, state, id, at) => {
|
|
74
|
+
const operation = settledOperation(state, id);
|
|
75
|
+
if (!operation)
|
|
76
|
+
return undefined;
|
|
77
|
+
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
78
|
+
if (entry?.givenUp || (entry && heldLive(inbox, entry, at)))
|
|
79
|
+
return undefined;
|
|
80
|
+
return operation;
|
|
81
|
+
};
|
|
82
|
+
const authorized = async (operations) => {
|
|
83
|
+
const kept = [];
|
|
84
|
+
for (const operation of operations)
|
|
85
|
+
if (await options.readable(operation))
|
|
86
|
+
kept.push(operation);
|
|
87
|
+
return kept;
|
|
88
|
+
};
|
|
89
|
+
/** Changes one chat's lock and entries in one session write. */
|
|
90
|
+
const change = (key, apply) => sessions.mutate(sessionId, (state) => apply(inboxOf(state, key), state, now()));
|
|
91
|
+
/** Acts on each of `ids` that waits, only while `hold` has the chat; returns those it acted on. */
|
|
92
|
+
const actOnWaiting = async (key, hold, ids, act) => {
|
|
93
|
+
const { ids: open } = await readableIds(key);
|
|
94
|
+
const wanted = ids.filter((id) => open.includes(id));
|
|
95
|
+
return change(key, (inbox, state, at) => {
|
|
96
|
+
if (!has(inbox, hold, at))
|
|
97
|
+
return [];
|
|
98
|
+
return wanted.flatMap((id) => {
|
|
99
|
+
const operation = waiting(inbox, state, id, at);
|
|
100
|
+
if (!operation)
|
|
101
|
+
return [];
|
|
102
|
+
const entry = entryOf(inbox, id);
|
|
103
|
+
act(entry, at);
|
|
104
|
+
return [item(operation, entry)];
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
const lease = (inbox, hold, at) => {
|
|
109
|
+
inbox.hold = hold;
|
|
110
|
+
inbox.leasedUntil = at + leaseMs;
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
open(key, hold) {
|
|
114
|
+
return change(key, (inbox, _state, at) => {
|
|
115
|
+
if (inbox.hold !== undefined && inbox.hold !== hold && inbox.leasedUntil > at) {
|
|
116
|
+
return { outcome: 'held', leasedUntil: inbox.leasedUntil };
|
|
117
|
+
}
|
|
118
|
+
lease(inbox, hold, at);
|
|
119
|
+
return { outcome: 'opened' };
|
|
120
|
+
});
|
|
121
|
+
},
|
|
122
|
+
takeOver(key, hold) {
|
|
123
|
+
return change(key, (inbox, _state, at) => lease(inbox, hold, at));
|
|
124
|
+
},
|
|
125
|
+
renew(key, hold) {
|
|
126
|
+
return change(key, (inbox, _state, at) => {
|
|
127
|
+
if (!has(inbox, hold, at))
|
|
128
|
+
return false;
|
|
129
|
+
lease(inbox, hold, at);
|
|
130
|
+
return true;
|
|
131
|
+
});
|
|
132
|
+
},
|
|
133
|
+
async read(key) {
|
|
134
|
+
const { ids } = await readableIds(key);
|
|
135
|
+
const state = await sessions.read(sessionId);
|
|
136
|
+
const inbox = state.inbox?.conversations[key] ?? { leasedUntil: 0, entries: {} };
|
|
137
|
+
const at = now();
|
|
138
|
+
const found = ids.flatMap((id) => {
|
|
139
|
+
const operation = waiting(inbox, state, id, at);
|
|
140
|
+
return operation ? [operation] : [];
|
|
141
|
+
});
|
|
142
|
+
const items = (await authorized(found)).map((operation) => item(operation, inbox.entries[operation.operationId]));
|
|
143
|
+
return { items, version: String(state.inbox?.version ?? 0) };
|
|
144
|
+
},
|
|
145
|
+
hand(key, hold, handover, ids) {
|
|
146
|
+
return actOnWaiting(key, hold, ids, (entry, at) => handTo(entry, hold, handover, at));
|
|
147
|
+
},
|
|
148
|
+
async giveBack(key, hold, reply, ids) {
|
|
149
|
+
const { chat } = await readableIds(key);
|
|
150
|
+
await change(key, (inbox) => {
|
|
151
|
+
for (const id of ids) {
|
|
152
|
+
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
153
|
+
if (entry?.handed?.hold !== hold || entry.handed.reply !== reply)
|
|
154
|
+
continue;
|
|
155
|
+
if (chat.told.has(id)) {
|
|
156
|
+
delete inbox.entries[id];
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
entry.handovers.push(entry.handed);
|
|
160
|
+
delete entry.handed;
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
async resume(key, hold, paused, handover) {
|
|
165
|
+
const { chat } = await readableIds(key);
|
|
166
|
+
if (chat.pausedReply !== paused)
|
|
167
|
+
return [];
|
|
168
|
+
return change(key, (inbox, state, at) => {
|
|
169
|
+
if (!has(inbox, hold, at))
|
|
170
|
+
return [];
|
|
171
|
+
return [...chat.paused].flatMap((id) => {
|
|
172
|
+
const operation = settledOperation(state, id);
|
|
173
|
+
const entry = entryOf(inbox, id);
|
|
174
|
+
if (!operation || heldLive(inbox, entry, at))
|
|
175
|
+
return [];
|
|
176
|
+
handTo(entry, hold, handover, at);
|
|
177
|
+
return [item(operation, entry)];
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
},
|
|
181
|
+
giveUp(key, hold, ids) {
|
|
182
|
+
return actOnWaiting(key, hold, ids, (entry) => {
|
|
183
|
+
if (entry.handed)
|
|
184
|
+
entry.handovers.push(entry.handed);
|
|
185
|
+
delete entry.handed;
|
|
186
|
+
entry.givenUp = true;
|
|
187
|
+
});
|
|
188
|
+
},
|
|
189
|
+
release(key, hold, version) {
|
|
190
|
+
return change(key, (inbox, state) => {
|
|
191
|
+
if (inbox.hold !== hold)
|
|
192
|
+
return 'lost';
|
|
193
|
+
if (String(state.inbox?.version ?? 0) !== version)
|
|
194
|
+
return 'moved';
|
|
195
|
+
delete inbox.hold;
|
|
196
|
+
inbox.leasedUntil = 0;
|
|
197
|
+
return 'released';
|
|
198
|
+
});
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
@@ -28,6 +28,8 @@ export type PausedReply = {
|
|
|
28
28
|
model?: string;
|
|
29
29
|
effort?: string;
|
|
30
30
|
stated?: StatedTurn;
|
|
31
|
+
/** The reply's id under its chat's hold, so the reply that goes on after its gates resumes what it read. */
|
|
32
|
+
reply?: string;
|
|
31
33
|
};
|
|
32
34
|
/** One conversation as the host stores it. */
|
|
33
35
|
export type StoredConversation = {
|
package/server/conversation.d.ts
CHANGED
|
@@ -122,19 +122,7 @@ export type ReplyTurn = {
|
|
|
122
122
|
stated?: StatedTurn;
|
|
123
123
|
/** The tools and steps the reply had when it paused, for a reply that goes on. */
|
|
124
124
|
carried?: ReplyCarried;
|
|
125
|
-
/** The conversation's detached calls whose results its model has not read yet. */
|
|
126
|
-
unread?: DetachedCall[];
|
|
127
125
|
};
|
|
128
|
-
/** A call that detached in a conversation: the operation the session keeps its end under. */
|
|
129
|
-
export type DetachedCall = {
|
|
130
|
-
callId: string;
|
|
131
|
-
operationId: string;
|
|
132
|
-
};
|
|
133
|
-
/**
|
|
134
|
-
* The calls a wake would read: none while a reply waits on gates or answers a message just posted.
|
|
135
|
-
* invariant: A wake never runs beside a reply, so it never takes a person's message from one.
|
|
136
|
-
*/
|
|
137
|
-
export declare function wakeableCalls(conversation: StoredConversation): DetachedCall[];
|
|
138
126
|
/** What a reply's model run takes from the host. */
|
|
139
127
|
export type ReplyRunner = {
|
|
140
128
|
/** The reply's events for one run (`runTurn` with the host's own options). */
|
|
@@ -149,6 +137,13 @@ export type ReplyRunner = {
|
|
|
149
137
|
stated?: StatedTurn;
|
|
150
138
|
carried?: ReplyCarried;
|
|
151
139
|
signal: AbortSignal;
|
|
140
|
+
/** The reply's id under its chat's hold: a paused reply keeps it, so the reply that goes on resumes what it read. */
|
|
141
|
+
reply?: string;
|
|
142
|
+
/**
|
|
143
|
+
* Whether the reply's hold still has its chat, asked before each save. A reply that lost it saves
|
|
144
|
+
* nothing: the hold that took the chat tells what it read.
|
|
145
|
+
*/
|
|
146
|
+
held?: () => Promise<boolean>;
|
|
152
147
|
};
|
|
153
148
|
/** A line of a reply's stream: an event, or the ref of what the store wrote. */
|
|
154
149
|
export type ReplyLine = TurnEvent | ConversationLine;
|
package/server/conversation.js
CHANGED
|
@@ -149,31 +149,6 @@ function refLine(opened, posted) {
|
|
|
149
149
|
return [];
|
|
150
150
|
return [{ type: 'conversation', ref: opened.ref, ...(posted ? { posted: true } : {}) }];
|
|
151
151
|
}
|
|
152
|
-
/**
|
|
153
|
-
* The conversation's detached calls that no late-results block names.
|
|
154
|
-
* invariant: The transcript is the record of what the model read, so a result is fed once.
|
|
155
|
-
*/
|
|
156
|
-
function unreadDetachedCalls(transcript) {
|
|
157
|
-
const read = new Set(transcript.flatMap((block) => (block.kind === 'late-results' ? block.operationIds : [])));
|
|
158
|
-
return transcript.flatMap((block) => block.kind === 'tool' &&
|
|
159
|
-
block.tool.state?.phase === 'background' &&
|
|
160
|
-
block.tool.operationId &&
|
|
161
|
-
!read.has(block.tool.operationId)
|
|
162
|
-
? [{ callId: block.tool.callId, operationId: block.tool.operationId }]
|
|
163
|
-
: []);
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* The calls a wake would read: none while a reply waits on gates or answers a message just posted.
|
|
167
|
-
* invariant: A wake never runs beside a reply, so it never takes a person's message from one.
|
|
168
|
-
*/
|
|
169
|
-
export function wakeableCalls(conversation) {
|
|
170
|
-
if (conversation.paused)
|
|
171
|
-
return [];
|
|
172
|
-
const last = conversation.transcript.at(-1);
|
|
173
|
-
if (!last || last.kind.startsWith('user-'))
|
|
174
|
-
return [];
|
|
175
|
-
return unreadDetachedCalls(conversation.transcript);
|
|
176
|
-
}
|
|
177
152
|
/** The model's history once the reply's events enter it. */
|
|
178
153
|
function replyHistory(reply) {
|
|
179
154
|
return appendAssistantEventsToHistory(reply.base, reply.events.slice(reply.baseEvents));
|
|
@@ -219,12 +194,21 @@ function pausedOn(conversation, reply, runner) {
|
|
|
219
194
|
...(runner.model ? { model: runner.model } : {}),
|
|
220
195
|
...(runner.effort ? { effort: runner.effort } : {}),
|
|
221
196
|
...(runner.stated ? { stated: runner.stated } : {}),
|
|
197
|
+
...(runner.reply ? { reply: runner.reply } : {}),
|
|
222
198
|
};
|
|
223
199
|
return { ...conversation, ...metered(conversation, reply.events), paused };
|
|
224
200
|
}
|
|
225
|
-
/**
|
|
201
|
+
/**
|
|
202
|
+
* The reply failed: it commits as far as it got, closed by its error. The late results it read
|
|
203
|
+
* leave with it, so a later reply tells them.
|
|
204
|
+
*/
|
|
226
205
|
function failed(host, conversation, reply, failure) {
|
|
227
|
-
const
|
|
206
|
+
const unread = (events) => events.filter((event) => event.type !== 'late_results');
|
|
207
|
+
const next = committed(host, conversation, {
|
|
208
|
+
...reply,
|
|
209
|
+
events: unread(reply.events),
|
|
210
|
+
baseEvents: unread(reply.events.slice(0, reply.baseEvents)).length,
|
|
211
|
+
});
|
|
228
212
|
if (next.transcript.slice(conversation.transcript.length).some((b) => b.kind === 'error')) {
|
|
229
213
|
return next;
|
|
230
214
|
}
|
|
@@ -252,8 +236,9 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
|
|
|
252
236
|
const { conversation } = opened;
|
|
253
237
|
const startedAt = Date.now();
|
|
254
238
|
const worked = () => ({ ...reply, workedMs: reply.workedMs + (Date.now() - startedAt) });
|
|
239
|
+
// invariant: A reply whose hold lost its chat saves nothing; the hold that has it tells what this one read.
|
|
240
|
+
const held = async () => !runner.held || (await runner.held());
|
|
255
241
|
let errorEvent;
|
|
256
|
-
let current = opened;
|
|
257
242
|
try {
|
|
258
243
|
const events = runner.run({
|
|
259
244
|
input,
|
|
@@ -263,8 +248,6 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
|
|
|
263
248
|
effort: runner.effort,
|
|
264
249
|
...(runner.stated ? { stated: runner.stated } : {}),
|
|
265
250
|
...(runner.carried ? { carried: runner.carried } : {}),
|
|
266
|
-
// why: Late results open a reply; a reply that goes on after a pause reads them on the next one.
|
|
267
|
-
...(runner.carried ? {} : { unread: unreadDetachedCalls(conversation.transcript) }),
|
|
268
251
|
});
|
|
269
252
|
for await (const event of events) {
|
|
270
253
|
reply.events.push(event);
|
|
@@ -281,37 +264,40 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
|
|
|
281
264
|
}
|
|
282
265
|
}
|
|
283
266
|
catch (err) {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
267
|
+
if (await held()) {
|
|
268
|
+
const written = await save(host, opened, runner.signal.aborted
|
|
269
|
+
? stopped(host, conversation, worked())
|
|
270
|
+
: failed(host, conversation, worked(), toErrorEvent(err)));
|
|
271
|
+
yield* refLine(written);
|
|
272
|
+
}
|
|
288
273
|
// why: A stopped reply is no failure; the browser draws what it left from the ref.
|
|
289
274
|
if (!runner.signal.aborted)
|
|
290
275
|
throw err;
|
|
291
276
|
return;
|
|
292
277
|
}
|
|
293
278
|
const settled = worked();
|
|
279
|
+
if (!(await held()))
|
|
280
|
+
return;
|
|
294
281
|
if (runner.signal.aborted) {
|
|
295
|
-
|
|
282
|
+
yield* refLine(await save(host, opened, stopped(host, conversation, settled)));
|
|
296
283
|
}
|
|
297
284
|
else if (errorEvent) {
|
|
298
|
-
|
|
285
|
+
yield* refLine(await save(host, opened, failed(host, conversation, settled, errorEvent)));
|
|
286
|
+
yield errorEvent;
|
|
299
287
|
}
|
|
300
288
|
else if (gatedToolsFromEvents(settled.events).length) {
|
|
301
|
-
|
|
289
|
+
yield* refLine(await save(host, opened, pausedOn(conversation, settled, runner)));
|
|
302
290
|
}
|
|
303
291
|
else {
|
|
304
|
-
current = await save(host,
|
|
292
|
+
const current = await save(host, opened, committed(host, conversation, settled));
|
|
305
293
|
yield* refLine(current);
|
|
306
294
|
// why: The reply is the browser's before compaction runs, so a failed compaction loses none of it.
|
|
295
|
+
if (!(await held()))
|
|
296
|
+
return;
|
|
307
297
|
const compacted = await compactedAfter(host, current, settled, runner, withMessage);
|
|
308
298
|
if (compacted)
|
|
309
299
|
yield* refLine(compacted);
|
|
310
|
-
return;
|
|
311
300
|
}
|
|
312
|
-
yield* refLine(current);
|
|
313
|
-
if (errorEvent)
|
|
314
|
-
yield errorEvent;
|
|
315
301
|
}
|
|
316
302
|
/**
|
|
317
303
|
* The profile compacts after a reply (`done.compaction.needed`): the history
|
|
@@ -526,6 +512,8 @@ export async function* answerReply(args) {
|
|
|
526
512
|
// why: An answer that failed before its call settled leaves the reply as it was, to answer again.
|
|
527
513
|
const settledCall = reply.events.some((event) => settlesToolCall(event, args.call.callId));
|
|
528
514
|
const events = error && !settledCall ? paused.events : reply.events;
|
|
515
|
+
if (runner.held && !(await runner.held()))
|
|
516
|
+
return;
|
|
529
517
|
opened = await save(host, opened, {
|
|
530
518
|
...opened.conversation,
|
|
531
519
|
paused: { ...paused, events, workedMs: reply.workedMs, endedAt: Date.now() },
|
package/server/handler.d.ts
CHANGED
|
@@ -155,9 +155,16 @@ export type TheoremHandlerOptions = {
|
|
|
155
155
|
}) => boolean | Promise<boolean>;
|
|
156
156
|
/**
|
|
157
157
|
* Who tells the model that a background call ended: `TurnWiring.lateResultsDecider`. Unset, no
|
|
158
|
-
* page wakes the chat and no reply reads a late result. `
|
|
158
|
+
* page wakes the chat and no reply reads a late result. `tellEveryResult` tells each result to
|
|
159
|
+
* the first reply that runs, and lets the open page wake the chat.
|
|
159
160
|
*/
|
|
160
161
|
lateResultsDecider?: TurnWiring['lateResultsDecider'];
|
|
162
|
+
/**
|
|
163
|
+
* How long a reply keeps its chat after it last renewed, in milliseconds: it renews every third
|
|
164
|
+
* of it while it runs. A wake the chat turned away tries again once this runs out, and a reply
|
|
165
|
+
* that stopped without letting go keeps the chat no longer. Default 60000.
|
|
166
|
+
*/
|
|
167
|
+
conversationLeaseMs?: number;
|
|
161
168
|
/**
|
|
162
169
|
* Tool credentials by session. Your OAuth callback route saves the token here
|
|
163
170
|
* under the same session id; every turn reads from here. Default: in-process
|
|
@@ -191,7 +198,7 @@ export type TheoremHandlerOptions = {
|
|
|
191
198
|
}) => void;
|
|
192
199
|
};
|
|
193
200
|
/** A host profile runs no model, and takes no turns to steer. */
|
|
194
|
-
export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'steerInbox' | 'conversationStore' | 'prepare' | 'notifier' | 'notifyRetryMs'> & {
|
|
201
|
+
export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'steerInbox' | 'conversationStore' | 'prepare' | 'notifier' | 'notifyRetryMs' | 'conversationLeaseMs'> & {
|
|
195
202
|
/** Host profile to serve. Registered with the kernel when the handler is created. */
|
|
196
203
|
profile: Extract<Profile, {
|
|
197
204
|
type: 'host';
|
package/server/handler.js
CHANGED
|
@@ -40,12 +40,14 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
|
|
|
40
40
|
* @module
|
|
41
41
|
*/
|
|
42
42
|
import { authorizeToolReplay, compactHistory, defaultKernelScope, defineProfile, invokeTool, jsonObjectSchema, labelText, registerProfile, runTurn, TheoremError, toolInvocationHash, } from '@theoremjs/agents';
|
|
43
|
+
import { runConversation } from '@theoremjs/agents/conversation';
|
|
43
44
|
import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremjs/agents/host';
|
|
44
45
|
import { clientProfileInterface, gatedToolsFromEvents, interfaceFromProfile, promotedToolIdsFromEvents, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
|
|
45
46
|
import { answerGatedCall, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
|
|
46
47
|
import { hostInterface, theoremHostCallRequestSchema, } from "../client/host-transport.js";
|
|
47
48
|
import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
48
|
-
import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls,
|
|
49
|
+
import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
|
|
50
|
+
import { sessionConversationInbox } from "./conversation-inbox.js";
|
|
49
51
|
import { unknownConversation, } from "./conversation-store.js";
|
|
50
52
|
import { createMemoryCredentialStore, } from "./credential-store.js";
|
|
51
53
|
import { sessionStateStore, } from "./session-authority.js";
|
|
@@ -459,13 +461,21 @@ function announced(ctx, request, sessionId, service) {
|
|
|
459
461
|
}
|
|
460
462
|
/**
|
|
461
463
|
* The decider's wake, with no page: the reply runs on a request of its own, with the headers of
|
|
462
|
-
* the one that started the call and no signal, because that request has ended.
|
|
464
|
+
* the one that started the call and no signal, because that request has ended. When another reply
|
|
465
|
+
* holds the chat, it tries again as that hold's lease runs out.
|
|
463
466
|
*/
|
|
464
|
-
async function serverWake(ctx, started, sessionId,
|
|
467
|
+
async function serverWake(ctx, started, sessionId, ref) {
|
|
465
468
|
const request = new Request(started.url, { headers: started.headers });
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
|
|
469
|
+
const session = { id: sessionId };
|
|
470
|
+
const host = conversationHost(ctx, session);
|
|
471
|
+
if (!host)
|
|
472
|
+
throw statelessRefusal('wake');
|
|
473
|
+
const retry = (leasedUntil) => {
|
|
474
|
+
setTimeout(() => {
|
|
475
|
+
serverWake(ctx, started, sessionId, ref).catch((err) => ctx.options.onError?.(err, { request }));
|
|
476
|
+
}, Math.max(0, leasedUntil - Date.now()));
|
|
477
|
+
};
|
|
478
|
+
const lines = await wakeLines(ctx, request, session, host, ref, {}, { retry });
|
|
469
479
|
for await (const line of lines) {
|
|
470
480
|
if (line.type === 'error') {
|
|
471
481
|
// labels-exempt: internal diagnostic for the decider's wake; no page reads it
|
|
@@ -477,57 +487,152 @@ async function serverWake(ctx, started, sessionId, conversation) {
|
|
|
477
487
|
async function* once(event, labels) {
|
|
478
488
|
yield withPublicLabels(event, labels);
|
|
479
489
|
}
|
|
490
|
+
/** Whether this request may read a settled call's result: the host's `authorizeToolReplay`. */
|
|
491
|
+
async function replayAllowed(ctx, request, operation) {
|
|
492
|
+
const { authorizeToolReplay } = ctx.options;
|
|
493
|
+
return !authorizeToolReplay || (await authorizeToolReplay({ request, operation }));
|
|
494
|
+
}
|
|
495
|
+
const DEFAULT_CONVERSATION_LEASE_MS = 60_000;
|
|
480
496
|
/**
|
|
481
|
-
* The
|
|
482
|
-
*
|
|
497
|
+
* The chat's inbox as this request reads it: the chat as this request last wrote it, and the
|
|
498
|
+
* results this request may read. `seen` follows each line's ref, because a store's ref can change
|
|
499
|
+
* with each write.
|
|
483
500
|
*/
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
const
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
501
|
+
function chatInbox(ctx, request, session, host, opened) {
|
|
502
|
+
let ref = opened.ref;
|
|
503
|
+
const leaseMs = ctx.options.conversationLeaseMs ?? DEFAULT_CONVERSATION_LEASE_MS;
|
|
504
|
+
const inbox = sessionConversationInbox({
|
|
505
|
+
sessions: ctx.sessions,
|
|
506
|
+
sessionId: session.id,
|
|
507
|
+
leaseMs,
|
|
508
|
+
conversation: async (key) => {
|
|
509
|
+
const conversation = ref === null ? opened.conversation : (await host.store.read(session.id, ref))?.conversation;
|
|
510
|
+
return conversation?.id === key ? conversation : undefined;
|
|
511
|
+
},
|
|
512
|
+
readable: (operation) => replayAllowed(ctx, request, operation),
|
|
513
|
+
});
|
|
514
|
+
return {
|
|
515
|
+
inbox,
|
|
516
|
+
key: opened.conversation.id,
|
|
517
|
+
leaseMs,
|
|
518
|
+
seen(line) {
|
|
519
|
+
if (line.type === 'conversation')
|
|
520
|
+
ref = line.ref;
|
|
521
|
+
},
|
|
522
|
+
get ref() {
|
|
523
|
+
return ref;
|
|
524
|
+
},
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/** The values `produce` sends, as it sends them, then its end or what it threw. */
|
|
528
|
+
async function* sent(produce) {
|
|
529
|
+
const queue = [];
|
|
530
|
+
let ended;
|
|
531
|
+
let wake = () => { };
|
|
532
|
+
produce((value) => {
|
|
533
|
+
queue.push(value);
|
|
534
|
+
wake();
|
|
535
|
+
}).then(() => {
|
|
536
|
+
ended = { failed: false };
|
|
537
|
+
wake();
|
|
538
|
+
}, (failure) => {
|
|
539
|
+
ended = { failed: true, failure };
|
|
540
|
+
wake();
|
|
541
|
+
});
|
|
542
|
+
for (;;) {
|
|
543
|
+
if (queue.length > 0) {
|
|
544
|
+
yield queue.splice(0, 1)[0];
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
if (ended?.failed)
|
|
548
|
+
throw ended.failure;
|
|
549
|
+
if (ended)
|
|
550
|
+
return;
|
|
551
|
+
await new Promise((resolve) => {
|
|
552
|
+
wake = resolve;
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Runs a reply under a hold of the chat, and streams its lines. The reply reads the late results
|
|
558
|
+
* the decider's policy tells it. Without a decider no reply reads one, and no hold is taken.
|
|
559
|
+
* invariant: One hold has a chat at a time, and lets it go only once nothing waits that may be told.
|
|
560
|
+
* A page's reply that leaves results waiting lets the chat go, so the page wakes for them; a
|
|
561
|
+
* server's wake runs the next reply under its hold.
|
|
562
|
+
*/
|
|
563
|
+
function heldLines(ctx, request, session, host, opened, start, reply, follow = {}) {
|
|
496
564
|
const decider = ctx.options.lateResultsDecider;
|
|
497
|
-
if (!decider
|
|
498
|
-
return
|
|
499
|
-
const
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
565
|
+
if (!decider)
|
|
566
|
+
return reply(undefined, () => opened.ref);
|
|
567
|
+
const chat = chatInbox(ctx, request, session, host, opened);
|
|
568
|
+
const ref = () => chat.ref;
|
|
569
|
+
return sent(async (send) => {
|
|
570
|
+
const runOnce = (begin, lines) => runConversation({
|
|
571
|
+
conversation: chat.key,
|
|
572
|
+
inbox: chat.inbox,
|
|
573
|
+
policy: decider.policy,
|
|
574
|
+
start: begin,
|
|
575
|
+
newId: () => crypto.randomUUID(),
|
|
576
|
+
renewEveryMs: chat.leaseMs / 3,
|
|
577
|
+
reply: async (run) => {
|
|
578
|
+
const renew = () => chat.inbox.renew(chat.key, run.hold);
|
|
579
|
+
for await (const line of lines({ run, renew })) {
|
|
580
|
+
chat.seen(line);
|
|
581
|
+
send(line);
|
|
582
|
+
}
|
|
583
|
+
},
|
|
584
|
+
gaveUp: (items) => {
|
|
585
|
+
ctx.options.onError?.(
|
|
586
|
+
// labels-exempt: internal diagnostic; no reader sees a given-up result
|
|
587
|
+
new TheoremError('unavailable', 'The late-results policy gave up results', {
|
|
588
|
+
cause: { code: 'late_results_given_up', operationIds: items.map((item) => item.id) },
|
|
589
|
+
}), { request });
|
|
590
|
+
},
|
|
591
|
+
});
|
|
592
|
+
let run = await runOnce(start, (held) => reply(held, ref));
|
|
593
|
+
let failure = run.outcome === 'held' ? undefined : run.failure;
|
|
594
|
+
while (run.outcome === 'continue') {
|
|
595
|
+
const paused = await isPaused(host, session, chat.ref, opened.conversation);
|
|
596
|
+
if (follow.retry === undefined || paused) {
|
|
597
|
+
await letGo(chat.inbox, chat.key, run.hold);
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
600
|
+
run = await runOnce({ opening: 'follow_up', hold: run.hold }, (held) => wakeReplyLines(ctx, request, session, host, chat.ref, {}, held));
|
|
601
|
+
if (run.outcome !== 'held' && run.failure !== undefined)
|
|
602
|
+
failure ??= run.failure;
|
|
603
|
+
}
|
|
604
|
+
if (run.outcome === 'held')
|
|
605
|
+
follow.retry?.(run.leasedUntil);
|
|
606
|
+
if (failure !== undefined)
|
|
607
|
+
throw failure;
|
|
608
|
+
});
|
|
506
609
|
}
|
|
507
|
-
|
|
508
|
-
|
|
610
|
+
/** Whether the chat waits on gates: a wake leaves it to the answer that goes on. */
|
|
611
|
+
async function isPaused(host, session, ref, fallback) {
|
|
612
|
+
const conversation = ref === null ? fallback : (await host.store.read(session.id, ref))?.conversation;
|
|
613
|
+
return conversation?.paused !== undefined;
|
|
509
614
|
}
|
|
510
|
-
/**
|
|
511
|
-
async function
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
continue;
|
|
517
|
-
const { authorizeToolReplay } = ctx.options;
|
|
518
|
-
if (authorizeToolReplay && !(await authorizeToolReplay({ request, operation })))
|
|
519
|
-
continue;
|
|
520
|
-
readable.push(operation);
|
|
615
|
+
/** Lets the chat go under `hold`, reading again each time a result arrives first. */
|
|
616
|
+
async function letGo(inbox, key, hold) {
|
|
617
|
+
for (;;) {
|
|
618
|
+
const { version } = await inbox.read(key);
|
|
619
|
+
if ((await inbox.release(key, hold, version)) !== 'moved')
|
|
620
|
+
return;
|
|
521
621
|
}
|
|
522
|
-
return readable;
|
|
523
622
|
}
|
|
524
|
-
/** The results a
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
return
|
|
623
|
+
/** The late results a reply's model reads: what it opened with, then what each later moment hands it. */
|
|
624
|
+
function lateSource(run) {
|
|
625
|
+
let opening = true;
|
|
626
|
+
return async ({ stage, step }) => {
|
|
627
|
+
if (opening && stage === 'pre_turn') {
|
|
628
|
+
opening = false;
|
|
629
|
+
return run.opened.map((item) => item.outcome);
|
|
630
|
+
}
|
|
631
|
+
return (await run.take({ stage, step })).map((item) => item.outcome);
|
|
632
|
+
};
|
|
528
633
|
}
|
|
529
634
|
/** One model run of a chat's reply, its gates recorded in the session as they pause. */
|
|
530
|
-
async function* chatTurn(ctx, request, session, turn, key, stop, late) {
|
|
635
|
+
async function* chatTurn(ctx, request, session, turn, key, signal, stop, late) {
|
|
531
636
|
const state = await ctx.sessions.read(session.id);
|
|
532
637
|
const provider = await providerFor(ctx, request, turn.model);
|
|
533
638
|
const host = await ctx.options.host?.(request);
|
|
@@ -543,11 +648,11 @@ async function* chatTurn(ctx, request, session, turn, key, stop, late) {
|
|
|
543
648
|
...backgroundWiring(ctx, request, session.id),
|
|
544
649
|
pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
|
|
545
650
|
input: turn.input,
|
|
546
|
-
...(
|
|
651
|
+
...(late ? { lateResults: lateSource(late) } : {}),
|
|
547
652
|
...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
|
|
548
653
|
...(turn.providerState ? { providerState: turn.providerState } : {}),
|
|
549
654
|
sessionPermissions: state.permissions,
|
|
550
|
-
signal
|
|
655
|
+
signal,
|
|
551
656
|
host,
|
|
552
657
|
...(turn.model ? { model: turn.model } : {}),
|
|
553
658
|
...(turn.effort ? { effort: turn.effort } : {}),
|
|
@@ -570,16 +675,16 @@ async function* chatTurn(ctx, request, session, turn, key, stop, late) {
|
|
|
570
675
|
await ctx.inbox.close(key);
|
|
571
676
|
}
|
|
572
677
|
}
|
|
573
|
-
/**
|
|
574
|
-
|
|
678
|
+
/**
|
|
679
|
+
* How this request runs the model for a reply: its generation, its abort (the request's, a stop,
|
|
680
|
+
* or its hold losing the chat), and the chat's hold it saves under.
|
|
681
|
+
*/
|
|
682
|
+
function chatRunner(ctx, request, session, generation, held) {
|
|
575
683
|
const key = generation.turnId ? inboxKey(session.id, generation.turnId) : undefined;
|
|
576
684
|
const stop = new AbortController();
|
|
577
|
-
const signal = AbortSignal.any([request.signal, stop.signal]);
|
|
685
|
+
const signal = AbortSignal.any([request.signal, stop.signal, ...(held ? [held.run.signal] : [])]);
|
|
578
686
|
return {
|
|
579
|
-
run: (turn) => chatTurn(ctx, request, session, turn, key, stop,
|
|
580
|
-
...(generation.conversation === undefined ? {} : { conversation: generation.conversation }),
|
|
581
|
-
...(given ? { given } : {}),
|
|
582
|
-
}),
|
|
687
|
+
run: (turn) => chatTurn(ctx, request, session, turn, key, signal, stop, held?.run),
|
|
583
688
|
async compact(history, tokens, model) {
|
|
584
689
|
const provider = await providerFor(ctx, request, model);
|
|
585
690
|
const compacted = await compactHistory({
|
|
@@ -595,6 +700,7 @@ function chatRunner(ctx, request, session, generation, given) {
|
|
|
595
700
|
...(generation.effort ? { effort: generation.effort } : {}),
|
|
596
701
|
...(generation.stated ? { stated: generation.stated } : {}),
|
|
597
702
|
signal,
|
|
703
|
+
...(held ? { reply: held.run.reply, held: held.renew } : {}),
|
|
598
704
|
};
|
|
599
705
|
}
|
|
600
706
|
/** The chat's conversation as this session's runs read and write it; undefined when the profile keeps none. */
|
|
@@ -616,7 +722,6 @@ async function turn(ctx, chat, request, session) {
|
|
|
616
722
|
throw new TheoremError('request', labelText('error.request'));
|
|
617
723
|
}
|
|
618
724
|
const message = postedMessage(chatInterface(chat), body.input, await ctx.options.context?.(request));
|
|
619
|
-
const runner = chatRunner(ctx, request, session, body);
|
|
620
725
|
const host = conversationHost(ctx, session);
|
|
621
726
|
if (!host) {
|
|
622
727
|
if (body.conversation !== undefined)
|
|
@@ -624,6 +729,7 @@ async function turn(ctx, chat, request, session) {
|
|
|
624
729
|
// labels-exempt: internal diagnostic; the user reads error.request
|
|
625
730
|
if (body.abandon)
|
|
626
731
|
throw statelessRefusal('walk away from');
|
|
732
|
+
const runner = chatRunner(ctx, request, session, body);
|
|
627
733
|
return eventStream(ctx, request, () => runner.run({
|
|
628
734
|
input: message.input,
|
|
629
735
|
model: body.model,
|
|
@@ -639,7 +745,13 @@ async function turn(ctx, chat, request, session) {
|
|
|
639
745
|
const walkAway = body.abandon
|
|
640
746
|
? await takeWalkedAway(ctx, request, session, body.abandon, opened.conversation)
|
|
641
747
|
: undefined;
|
|
642
|
-
return eventStream(ctx, request, () =>
|
|
748
|
+
return eventStream(ctx, request, () => heldLines(ctx, request, session, host, opened, { opening: 'message', takeOver: true }, (held) => messageReply({
|
|
749
|
+
host,
|
|
750
|
+
opened,
|
|
751
|
+
message,
|
|
752
|
+
...(walkAway ? { walkAway } : {}),
|
|
753
|
+
runner: chatRunner(ctx, request, session, body, held),
|
|
754
|
+
})));
|
|
643
755
|
}
|
|
644
756
|
/** The conversation as the browser draws it. */
|
|
645
757
|
async function conversation(ctx, request, session) {
|
|
@@ -651,68 +763,41 @@ async function conversation(ctx, request, session) {
|
|
|
651
763
|
return jsonResponse(200, await currentView(ctx, request, session, host, body.conversation, opened.conversation));
|
|
652
764
|
}
|
|
653
765
|
/**
|
|
654
|
-
* A reply to no message, for results that ended since the model last ran.
|
|
655
|
-
*
|
|
656
|
-
* `give` picks what the reply reads; what it leaves is let go, for a later reply.
|
|
766
|
+
* A reply to no message, for results that ended since the model last ran. It runs under a hold of
|
|
767
|
+
* the chat, so two pages that wake at once run it once, and reads what the decider's policy tells.
|
|
657
768
|
*/
|
|
658
769
|
async function wake(ctx, request, session) {
|
|
659
770
|
const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
|
|
660
771
|
const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
|
|
661
|
-
const lines = await wakeLines(ctx, request, session, body.conversation, body, input);
|
|
662
|
-
return eventStream(ctx, request, lines ? () => lines : async function* () { });
|
|
663
|
-
}
|
|
664
|
-
/** The wake's reply, or undefined when the decider gives it nothing to read. */
|
|
665
|
-
async function wakeLines(ctx, request, session, conversation, generation, input) {
|
|
666
772
|
const host = conversationHost(ctx, session);
|
|
667
773
|
if (!host)
|
|
668
774
|
throw statelessRefusal('wake');
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
const
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
if (given.length === 0)
|
|
696
|
-
return undefined;
|
|
697
|
-
const runner = chatRunner(ctx, request, session, { ...generation, conversation }, given);
|
|
698
|
-
const { notifier } = ctx.options;
|
|
699
|
-
return (async function* () {
|
|
700
|
-
yield* wakeReply({ host, opened, runner, ...(input ? { input } : {}) });
|
|
701
|
-
// why: The page that woke draws its reply; any other page open on the session reads it now.
|
|
702
|
-
notifier?.publish(session.id);
|
|
703
|
-
})();
|
|
704
|
-
}
|
|
705
|
-
/** Takes the wake's mark off results it did not read. */
|
|
706
|
-
async function letGo(ctx, session, left, wokenAt) {
|
|
707
|
-
await ctx.sessions.mutate(session.id, (state) => {
|
|
708
|
-
for (const { operationId } of left) {
|
|
709
|
-
const operation = state.operations[operationId];
|
|
710
|
-
if (operation?.status !== 'settled' || operation.wokenAt !== wokenAt)
|
|
711
|
-
continue;
|
|
712
|
-
const { wokenAt: _taken, ...rest } = operation;
|
|
713
|
-
state.operations[operationId] = rest;
|
|
714
|
-
}
|
|
715
|
-
});
|
|
775
|
+
const lines = await wakeLines(ctx, request, session, host, body.conversation, body, {}, input);
|
|
776
|
+
return eventStream(ctx, request, () => lines);
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* The wake's reply under a hold of the chat; nothing when no decider tells a result, or while a
|
|
780
|
+
* reply waits on gates: the answer that goes on reads what waits.
|
|
781
|
+
*/
|
|
782
|
+
async function wakeLines(ctx, request, session, host, ref, generation, follow, input) {
|
|
783
|
+
const opened = await openConversation(host, ref, { kind: 'read' });
|
|
784
|
+
if (!ctx.options.lateResultsDecider || opened.conversation.paused)
|
|
785
|
+
return noLines();
|
|
786
|
+
return heldLines(ctx, request, session, host, opened, { opening: 'wake' }, (held, current) => wakeReplyLines(ctx, request, session, host, current(), generation, held, input), follow);
|
|
787
|
+
}
|
|
788
|
+
/** No reply lines. */
|
|
789
|
+
async function* noLines() { }
|
|
790
|
+
/**
|
|
791
|
+
* A reply to no message under `held`, on the chat as it stands now. The page that woke draws it;
|
|
792
|
+
* any other page open on the session reads it once it ends.
|
|
793
|
+
*/
|
|
794
|
+
async function* wakeReplyLines(ctx, request, session, host, ref, generation, held, input) {
|
|
795
|
+
if (ref === null)
|
|
796
|
+
return;
|
|
797
|
+
const opened = await openConversation(host, ref, { kind: 'read' });
|
|
798
|
+
const runner = chatRunner(ctx, request, session, generation, held);
|
|
799
|
+
yield* wakeReply({ host, opened, runner, ...(input ? { input } : {}) });
|
|
800
|
+
ctx.options.notifier?.publish(session.id);
|
|
716
801
|
}
|
|
717
802
|
const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
|
|
718
803
|
/**
|
|
@@ -771,24 +856,25 @@ async function currentView(ctx, request, session, host, ref, conversation) {
|
|
|
771
856
|
...(notifier && transcript.some(isDetachedBlock)
|
|
772
857
|
? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
|
|
773
858
|
: {}),
|
|
774
|
-
...((await wakeDue(ctx, request, ref, conversation
|
|
859
|
+
...((await wakeDue(ctx, request, session, host, ref, conversation))
|
|
775
860
|
? { wake: true }
|
|
776
861
|
: {}),
|
|
777
862
|
};
|
|
778
863
|
}
|
|
779
|
-
/**
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
864
|
+
/**
|
|
865
|
+
* Whether the page wakes the chat now: the decider's policy tells a waiting result to a reply to no
|
|
866
|
+
* message. Never while a reply waits on gates: the answer that goes on reads what waits.
|
|
867
|
+
*/
|
|
868
|
+
async function wakeDue(ctx, request, session, host, ref, conversation) {
|
|
869
|
+
const decider = ctx.options.lateResultsDecider;
|
|
870
|
+
if (!decider || conversation.paused)
|
|
783
871
|
return false;
|
|
784
|
-
const
|
|
785
|
-
|
|
872
|
+
const chat = chatInbox(ctx, request, session, host, { ref, conversation });
|
|
873
|
+
const { items } = await chat.inbox.read(chat.key);
|
|
874
|
+
if (items.length === 0)
|
|
786
875
|
return false;
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
conversation: ref,
|
|
790
|
-
results: results.map(lateResult),
|
|
791
|
-
});
|
|
876
|
+
const { tell } = await decider.policy(items, { stage: 'pre_turn', step: 0, opening: 'wake' });
|
|
877
|
+
return tell.length > 0;
|
|
792
878
|
}
|
|
793
879
|
function isDetachedBlock(block) {
|
|
794
880
|
return block.kind === 'tool' && block.tool.state?.phase === 'background';
|
|
@@ -989,8 +1075,20 @@ async function invoke(ctx, request, session) {
|
|
|
989
1075
|
const call = { callId: body.gateId, operationId: body.operationId };
|
|
990
1076
|
const opened = await openConversation(host, body.conversation, { kind: 'answer', call });
|
|
991
1077
|
const settling = await settlingOf(ctx, request, session, body);
|
|
992
|
-
const
|
|
993
|
-
return eventStream(ctx, request, () =>
|
|
1078
|
+
const paused = opened.conversation.paused?.reply;
|
|
1079
|
+
return eventStream(ctx, request, () => heldLines(ctx, request, session, host, opened, { opening: 'message', takeOver: true }, (held) => answered(held, paused, () => answerReply({
|
|
1080
|
+
host,
|
|
1081
|
+
opened,
|
|
1082
|
+
call,
|
|
1083
|
+
settling: settling(),
|
|
1084
|
+
runner: chatRunner(ctx, request, session, body, held),
|
|
1085
|
+
}))));
|
|
1086
|
+
}
|
|
1087
|
+
/** The answer's reply, handed first what the paused reply read, so it tells them as it goes on. */
|
|
1088
|
+
async function* answered(held, paused, reply) {
|
|
1089
|
+
if (held && paused)
|
|
1090
|
+
await held.run.resume(paused);
|
|
1091
|
+
yield* reply();
|
|
994
1092
|
}
|
|
995
1093
|
/** The answered call's events: its saved outcome again, or the call run as answered. */
|
|
996
1094
|
async function settlingOf(ctx, request, session, body) {
|
package/server/mod.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
export { theoremHostCallRequestSchema } from '../client/host-transport.ts';
|
|
9
9
|
export type { LiveClientMessage, LiveOpenMessage } from '../client/live-messages.ts';
|
|
10
10
|
export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from '../client/transport.ts';
|
|
11
|
-
export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplyTurn, readerConversationHost, rewindConversation, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls,
|
|
11
|
+
export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplyTurn, readerConversationHost, rewindConversation, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeReply, } from './conversation.ts';
|
|
12
12
|
export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, unknownConversation, } from './conversation-store.ts';
|
|
13
13
|
export { createMemoryCredentialStore, type TheoremCredentialStore, type TheoremCredentials, } from './credential-store.ts';
|
|
14
14
|
export { createTheoremDecisionHandler, type DecisionQuestionsBuilder, isQuestionsBuilder, type TheoremDecisionHandlerOptions, } from './decision-handler.ts';
|
|
@@ -17,12 +17,12 @@ export { createTheoremHandler, createTheoremHostHandler, readBody, type TheoremH
|
|
|
17
17
|
export { createTheoremMcpHandler, type TheoremMcpHandlerOptions } from './mcp-handler.ts';
|
|
18
18
|
export { createMemoryNotifier, type TheoremNotifier } from './notifier.ts';
|
|
19
19
|
export { createMemoryPageToolBroker, type PageToolBroker, type PageToolResult, pageToolResultSchema, sessionPageDispatch, } from './page-dispatch.ts';
|
|
20
|
-
export { pageWakes } from './page-wakes.ts';
|
|
21
20
|
export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from './request-check.ts';
|
|
22
21
|
export { sessionStateStore } from './session-authority.ts';
|
|
23
22
|
export { createTheoremSessionBoundary, type PreparedLiveOpen, type SessionBoundaryOptions, type TheoremSessionBoundary, } from './session-boundary.ts';
|
|
24
23
|
export type { TheoremSessionCapacity } from './session-limits.ts';
|
|
25
24
|
export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, type MemorySessionStoreOptions, type PendingToolGate, type SessionSnapshot, type SessionToolOperation, type SessionWriteResult, type TheoremSessionState, type TheoremSessionStore, theoremSessionStateSchema, } from './session-store.ts';
|
|
26
25
|
export { createMemorySteerInbox, type SteerInbox, type SteerUnit, steerStage, steerUnitOf, stopOnRequest, } from './steer-inbox.ts';
|
|
26
|
+
export { tellEveryResult } from './tell-every-result.ts';
|
|
27
27
|
export { sessionToolCoordinator } from './tool-operations.ts';
|
|
28
28
|
export { kernelTurnInput, liveSessionOpen } from './turn-input.ts';
|
package/server/mod.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export { theoremHostCallRequestSchema } from "../client/host-transport.js";
|
|
9
9
|
export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
10
|
-
export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls,
|
|
10
|
+
export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
|
|
11
11
|
export { createMemoryConversationStore, createSealedConversationStore, emptyConversation, storedConversationSchema, unknownConversation, } from "./conversation-store.js";
|
|
12
12
|
export { createMemoryCredentialStore, } from "./credential-store.js";
|
|
13
13
|
export { createTheoremDecisionHandler, isQuestionsBuilder, } from "./decision-handler.js";
|
|
@@ -16,11 +16,11 @@ export { createTheoremHandler, createTheoremHostHandler, readBody, theoremSessio
|
|
|
16
16
|
export { createTheoremMcpHandler } from "./mcp-handler.js";
|
|
17
17
|
export { createMemoryNotifier } from "./notifier.js";
|
|
18
18
|
export { createMemoryPageToolBroker, pageToolResultSchema, sessionPageDispatch, } from "./page-dispatch.js";
|
|
19
|
-
export { pageWakes } from "./page-wakes.js";
|
|
20
19
|
export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from "./request-check.js";
|
|
21
20
|
export { sessionStateStore } from "./session-authority.js";
|
|
22
21
|
export { createTheoremSessionBoundary, } from "./session-boundary.js";
|
|
23
22
|
export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, theoremSessionStateSchema, } from "./session-store.js";
|
|
24
23
|
export { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
|
|
24
|
+
export { tellEveryResult } from "./tell-every-result.js";
|
|
25
25
|
export { sessionToolCoordinator } from "./tool-operations.js";
|
|
26
26
|
export { kernelTurnInput, liveSessionOpen } from "./turn-input.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { labelText, TheoremError, z } from '@theoremjs/agents';
|
|
2
2
|
import { checkedCapacity, fitSession } from "./session-limits.js";
|
|
3
|
-
import { emptySessionState, pruneGates, theoremSessionStateSchema, } from "./session-store.js";
|
|
3
|
+
import { emptySessionState, pruneGates, pruneInbox, theoremSessionStateSchema, } from "./session-store.js";
|
|
4
4
|
/** Session state, with expired gates dropped as it loads so they can't be answered. */
|
|
5
5
|
export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
|
|
6
6
|
if (typeof store.compareAndSwap !== 'function') {
|
|
@@ -33,6 +33,7 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
|
|
|
33
33
|
}
|
|
34
34
|
state.operations = Object.fromEntries(Object.entries(state.operations).filter(([, operation]) => operation.status !== 'settled' ||
|
|
35
35
|
now < (operation.retainUntil ?? operation.settledAt + operationRetentionMs)));
|
|
36
|
+
pruneInbox(state, now);
|
|
36
37
|
return { revision: snapshot?.revision ?? null, state };
|
|
37
38
|
};
|
|
38
39
|
return {
|
|
@@ -54,6 +55,7 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
|
|
|
54
55
|
}
|
|
55
56
|
if (capacity)
|
|
56
57
|
fitSession(state, capacity);
|
|
58
|
+
pruneInbox(state, now);
|
|
57
59
|
const next = theoremSessionStateSchema.safeParse(state);
|
|
58
60
|
if (!next.success) {
|
|
59
61
|
throw new TheoremError('config', labelText('error.config'), {
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @module
|
|
10
10
|
*/
|
|
11
11
|
import { z } from '@theoremjs/agents';
|
|
12
|
+
import type { Handover } from '@theoremjs/agents/conversation';
|
|
12
13
|
import type { ToolGateAuth } from '@theoremjs/agents/interface';
|
|
13
14
|
import type { AnsweredGate, ToolGate, ToolId, ToolOperationIdentity, ToolOperationOutcome, ToolOperationReply, ToolOperationUncertainty, TurnInput, TurnToolSnapshot } from '@theoremjs/agents/kernel';
|
|
14
15
|
import { type TheoremSessionCapacity } from './session-limits.ts';
|
|
@@ -61,8 +62,6 @@ export type SessionToolOperation = {
|
|
|
61
62
|
reply?: ToolOperationReply;
|
|
62
63
|
settledAt: number;
|
|
63
64
|
retainUntil?: number;
|
|
64
|
-
/** When a wake took this result up. invariant: one wake per result; a message still reads it. */
|
|
65
|
-
wokenAt?: number;
|
|
66
65
|
}) | (ToolOperationIdentity & {
|
|
67
66
|
status: 'uncertain';
|
|
68
67
|
pageGrant?: SessionPageGrant;
|
|
@@ -74,6 +73,30 @@ export type SessionToolOperation = {
|
|
|
74
73
|
/** The reply the model read for a call that detached, whatever has happened to the call since. */
|
|
75
74
|
export declare function detachedReply(operation: SessionToolOperation): ToolOperationReply | undefined;
|
|
76
75
|
export declare const DEFAULT_OPERATION_RETENTION_MS: number;
|
|
76
|
+
/** What the replies of one conversation did with one late result, until a saved reply tells it. */
|
|
77
|
+
export type SessionInboxEntry = {
|
|
78
|
+
/** The reply it is handed to now, while that reply's hold has the conversation. */
|
|
79
|
+
handed?: Handover;
|
|
80
|
+
/** Each reply it was handed to that ended without telling it, oldest first. */
|
|
81
|
+
handovers: Handover[];
|
|
82
|
+
/** The policy gave it up: no reply reads it. */
|
|
83
|
+
givenUp?: true;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* One conversation's hold, and what its replies did with the session's late results, by
|
|
87
|
+
* operation id. Whether a result was told is the transcript's to say.
|
|
88
|
+
*/
|
|
89
|
+
export type SessionConversationInbox = {
|
|
90
|
+
/** The hold that has the conversation until `leasedUntil` (epoch ms). */
|
|
91
|
+
hold?: string;
|
|
92
|
+
leasedUntil: number;
|
|
93
|
+
entries: Record<string, SessionInboxEntry>;
|
|
94
|
+
};
|
|
95
|
+
/** The session's conversation inboxes, and the version each result's end moves. */
|
|
96
|
+
export type SessionInbox = {
|
|
97
|
+
version: number;
|
|
98
|
+
conversations: Record<string, SessionConversationInbox>;
|
|
99
|
+
};
|
|
77
100
|
export type TheoremSessionState = {
|
|
78
101
|
version: 3;
|
|
79
102
|
operations: Record<string, SessionToolOperation>;
|
|
@@ -83,6 +106,8 @@ export type TheoremSessionState = {
|
|
|
83
106
|
gates: Record<string, PendingToolGate>;
|
|
84
107
|
/** Checkpoint identities this session produced, newest last. */
|
|
85
108
|
providerCheckpoints: string[];
|
|
109
|
+
/** Unset until a call first ends or a reply first holds a conversation. */
|
|
110
|
+
inbox?: SessionInbox;
|
|
86
111
|
};
|
|
87
112
|
/** Stored authority is checked before the handler reads or changes it. */
|
|
88
113
|
export declare const theoremSessionStateSchema: z.ZodType<TheoremSessionState>;
|
|
@@ -116,6 +141,11 @@ export declare function pruneGates<Gate extends {
|
|
|
116
141
|
createdAt: number;
|
|
117
142
|
expiresAt?: number;
|
|
118
143
|
}>(gates: Record<string, Gate>, now: number, ttlMs: number | undefined): Record<string, Gate>;
|
|
144
|
+
/**
|
|
145
|
+
* Drops what the inbox keeps for results the session no longer holds, and conversations no hold
|
|
146
|
+
* has with nothing kept.
|
|
147
|
+
*/
|
|
148
|
+
export declare function pruneInbox(state: TheoremSessionState, now: number): void;
|
|
119
149
|
export type MemorySessionStoreOptions = {
|
|
120
150
|
/** What it holds for one session. Unset, it holds any size. */
|
|
121
151
|
capacity?: TheoremSessionCapacity;
|
package/server/session-store.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @module
|
|
10
10
|
*/
|
|
11
|
-
import { jsonObjectSchema, jsonValueSchema, labelText, savedToolInvocationSchema, TheoremError, TOOL_AUTH_TYPES, TOOL_GATE_KINDS, TOOL_PERMISSION, toolOperationOutcomeSchema, toolOperationReplySchema, turnHistoryMessageSchema, turnToolSnapshotSchema, z, } from '@theoremjs/agents';
|
|
11
|
+
import { jsonObjectSchema, jsonValueSchema, labelText, savedToolInvocationSchema, TheoremError, TOOL_AUTH_TYPES, TOOL_GATE_KINDS, TOOL_PERMISSION, TURN_INJECT_STAGES, toolOperationOutcomeSchema, toolOperationReplySchema, turnHistoryMessageSchema, turnToolSnapshotSchema, z, } from '@theoremjs/agents';
|
|
12
12
|
import { gateExpired } from '@theoremjs/agents/kernel';
|
|
13
13
|
import { checkedCapacity } from "./session-limits.js";
|
|
14
14
|
/** The reply the model read for a call that detached, whatever has happened to the call since. */
|
|
@@ -143,7 +143,6 @@ const operationSchema = z.discriminatedUnion('status', [
|
|
|
143
143
|
reply: toolOperationReplySchema.optional(),
|
|
144
144
|
settledAt: z.number().finite().nonnegative(),
|
|
145
145
|
retainUntil: z.number().finite().nonnegative().optional(),
|
|
146
|
-
wokenAt: z.number().finite().nonnegative().optional(),
|
|
147
146
|
}),
|
|
148
147
|
z.strictObject({
|
|
149
148
|
...identityFields,
|
|
@@ -155,6 +154,22 @@ const operationSchema = z.discriminatedUnion('status', [
|
|
|
155
154
|
detectedAt: z.number().finite().nonnegative(),
|
|
156
155
|
}),
|
|
157
156
|
]);
|
|
157
|
+
const handoverSchema = z.strictObject({
|
|
158
|
+
hold: z.string().min(1),
|
|
159
|
+
reply: z.string().min(1),
|
|
160
|
+
stage: z.enum(TURN_INJECT_STAGES),
|
|
161
|
+
step: z.number().int().nonnegative(),
|
|
162
|
+
at: z.number().finite().nonnegative(),
|
|
163
|
+
});
|
|
164
|
+
const conversationInboxSchema = z.strictObject({
|
|
165
|
+
hold: z.string().min(1).optional(),
|
|
166
|
+
leasedUntil: z.number().finite().nonnegative(),
|
|
167
|
+
entries: z.record(z.string().min(1), z.strictObject({
|
|
168
|
+
handed: handoverSchema.optional(),
|
|
169
|
+
handovers: z.array(handoverSchema),
|
|
170
|
+
givenUp: z.literal(true).optional(),
|
|
171
|
+
})),
|
|
172
|
+
});
|
|
158
173
|
/** Stored authority is checked before the handler reads or changes it. */
|
|
159
174
|
export const theoremSessionStateSchema = z
|
|
160
175
|
.strictObject({
|
|
@@ -163,6 +178,12 @@ export const theoremSessionStateSchema = z
|
|
|
163
178
|
permissions: z.array(z.string().min(1)),
|
|
164
179
|
gates: z.record(z.string().min(1), pendingSchema),
|
|
165
180
|
providerCheckpoints: z.array(z.string().min(1)),
|
|
181
|
+
inbox: z
|
|
182
|
+
.strictObject({
|
|
183
|
+
version: z.number().int().nonnegative(),
|
|
184
|
+
conversations: z.record(z.string().min(1), conversationInboxSchema),
|
|
185
|
+
})
|
|
186
|
+
.optional(),
|
|
166
187
|
})
|
|
167
188
|
.superRefine((state, ctx) => {
|
|
168
189
|
for (const [operationId, operation] of Object.entries(state.operations)) {
|
|
@@ -197,6 +218,23 @@ export function pruneGates(gates, now, ttlMs) {
|
|
|
197
218
|
? now < gate.expiresAt
|
|
198
219
|
: !gateExpired(gate.createdAt, now, ttlMs)));
|
|
199
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* Drops what the inbox keeps for results the session no longer holds, and conversations no hold
|
|
223
|
+
* has with nothing kept.
|
|
224
|
+
*/
|
|
225
|
+
export function pruneInbox(state, now) {
|
|
226
|
+
if (!state.inbox)
|
|
227
|
+
return;
|
|
228
|
+
for (const [key, conversation] of Object.entries(state.inbox.conversations)) {
|
|
229
|
+
for (const id of Object.keys(conversation.entries)) {
|
|
230
|
+
if (!Object.hasOwn(state.operations, id))
|
|
231
|
+
delete conversation.entries[id];
|
|
232
|
+
}
|
|
233
|
+
if (conversation.leasedUntil <= now && Object.keys(conversation.entries).length === 0) {
|
|
234
|
+
delete state.inbox.conversations[key];
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
200
238
|
export function memoryStoreLimits(options) {
|
|
201
239
|
const { ttlMs, maxSessions } = options;
|
|
202
240
|
if ((ttlMs !== undefined && (!Number.isFinite(ttlMs) || ttlMs <= 0)) ||
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module
|
|
3
|
+
* The ready-made decider for an app with no server of its own: the page open on the chat wakes it.
|
|
4
|
+
*/
|
|
5
|
+
import type { LateResultsDecider } from '@theoremjs/agents';
|
|
6
|
+
/**
|
|
7
|
+
* Each late result is told to the first reply that runs, and the page open on the chat wakes it
|
|
8
|
+
* when one waits. It keeps no count, and gives up nothing.
|
|
9
|
+
*/
|
|
10
|
+
export declare const tellEveryResult: LateResultsDecider;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Each late result is told to the first reply that runs, and the page open on the chat wakes it
|
|
3
|
+
* when one waits. It keeps no count, and gives up nothing.
|
|
4
|
+
*/
|
|
5
|
+
export const tellEveryResult = {
|
|
6
|
+
policy: (items) => ({ tell: items.map((item) => item.id) }),
|
|
7
|
+
};
|
|
@@ -73,6 +73,13 @@ function saveOutcome(state, identity, outcome) {
|
|
|
73
73
|
outcome,
|
|
74
74
|
settledAt,
|
|
75
75
|
};
|
|
76
|
+
// why: A detached call's end is an item in its conversation's inbox; a hold reads again before it lets go.
|
|
77
|
+
if (reply) {
|
|
78
|
+
state.inbox = {
|
|
79
|
+
version: (state.inbox?.version ?? 0) + 1,
|
|
80
|
+
conversations: state.inbox?.conversations ?? {},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
76
83
|
}
|
|
77
84
|
export function sessionToolCoordinator(store, sessionId) {
|
|
78
85
|
return {
|
package/server/page-wakes.d.ts
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module
|
|
3
|
-
* The ready-made decider for an app with no server of its own: the page open on the chat wakes it.
|
|
4
|
-
*/
|
|
5
|
-
import type { LateResultsDecider } from '@theoremjs/agents';
|
|
6
|
-
/**
|
|
7
|
-
* The page open on a chat wakes it when a background call ends, and a reply reads every result
|
|
8
|
-
* that waits. It keeps no count: each result is read once, by the first reply that runs.
|
|
9
|
-
*/
|
|
10
|
-
export declare const pageWakes: LateResultsDecider;
|
package/server/page-wakes.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The page open on a chat wakes it when a background call ends, and a reply reads every result
|
|
3
|
-
* that waits. It keeps no count: each result is read once, by the first reply that runs.
|
|
4
|
-
*/
|
|
5
|
-
export const pageWakes = {
|
|
6
|
-
give: ({ results }) => results.map((result) => result.operationId),
|
|
7
|
-
due: ({ results }) => results.length > 0,
|
|
8
|
-
};
|