@theoremjs/web 0.3.5-next.936.ga984349 → 0.3.5-next.938.g3cbd0dd
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 +4 -4
- package/package.json +2 -2
- package/server/conversation-inbox.d.ts +16 -1
- package/server/conversation-inbox.js +83 -44
- package/server/conversation-store.d.ts +7 -0
- package/server/conversation-store.js +6 -0
- package/server/conversation.js +52 -12
- package/server/handler.js +13 -20
- package/server/mod.d.ts +1 -1
- package/server/session-store.d.ts +3 -2
- package/server/session-store.js +3 -6
- package/server/tell-every-result.d.ts +2 -1
- package/server/tell-every-result.js +12 -2
- package/server/tool-operations.js +11 -7
package/README.md
CHANGED
|
@@ -271,7 +271,7 @@ 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. `tellEveryResult` tells each result to the first reply that runs. See [the background section](#share-session-authority). |
|
|
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, and gives up a result two replies read without telling. See [the background section](#share-session-authority). |
|
|
275
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`. |
|
|
276
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). |
|
|
277
277
|
| `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
|
|
@@ -461,16 +461,16 @@ Browser dispatch uses a host-owned `PageToolExecution` service beside the execut
|
|
|
461
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`.
|
|
462
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.
|
|
463
463
|
|
|
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
|
|
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 ended and no saved reply told it. When the session holds no end for the call (it dropped the settled operation, or marked the call `uncertain`), the result waits as an error with the code `outcome_not_retained` or the uncertainty's reason, and the model reads that the action is unresolved. `ended` hears that end too. A call `authorizeToolReplay` withholds from the request does not wait.
|
|
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
467
|
|
|
468
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`.
|
|
469
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.
|
|
470
470
|
|
|
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.
|
|
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. A result that two replies read and did not tell (the model failed, or the reply lost the chat) is given up and reported once as `late_results_given_up`, so a model that keeps failing does not reply again and again. Write your own to keep a count, such as a cap or quiet hours, or to reply from the server.
|
|
472
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.
|
|
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. When the wake was already saving its reply as the message read the chat, the message posts after that reply. When that reply stopped on an approval, the message fails with `session.gate_pending`, and the approval waits.
|
|
474
474
|
|
|
475
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`).
|
|
476
476
|
|
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.938.g3cbd0dd",
|
|
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.938.g3cbd0dd"
|
|
29
29
|
}
|
|
30
30
|
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*
|
|
6
6
|
* @module
|
|
7
7
|
*/
|
|
8
|
-
import type
|
|
8
|
+
import { type LateResultItem, type Profile, type ToolOperationOutcome } from '@theoremjs/agents';
|
|
9
9
|
import type { ConversationInbox } from '@theoremjs/agents/conversation';
|
|
10
10
|
import type { StoredConversation } from './conversation-store.ts';
|
|
11
11
|
import type { MutableStore } from './session-authority.ts';
|
|
@@ -14,6 +14,19 @@ import type { SessionToolOperation, TheoremSessionState } from './session-store.
|
|
|
14
14
|
export type SettledOperation = Extract<SessionToolOperation, {
|
|
15
15
|
status: 'settled';
|
|
16
16
|
}>;
|
|
17
|
+
/** A detached call as its chat's transcript keeps it: what an end is told about. */
|
|
18
|
+
export type DetachedCall = {
|
|
19
|
+
operationId: string;
|
|
20
|
+
callId: string;
|
|
21
|
+
name: string;
|
|
22
|
+
at: number;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* What became of a detached call, as the model and the page read it: the end the session saved, or
|
|
26
|
+
* that it is unresolved when the session holds no end (the call was cut off, or its saved end was
|
|
27
|
+
* dropped). Undefined while it runs.
|
|
28
|
+
*/
|
|
29
|
+
export declare function detachedEnd(call: DetachedCall, operation: SessionToolOperation | undefined, labels: Profile['labels']): ToolOperationOutcome | undefined;
|
|
17
30
|
/** Options for {@link sessionConversationInbox}. */
|
|
18
31
|
export type SessionConversationInboxOptions = {
|
|
19
32
|
sessions: MutableStore<TheoremSessionState>;
|
|
@@ -24,6 +37,8 @@ export type SessionConversationInboxOptions = {
|
|
|
24
37
|
conversation: (key: string) => Promise<StoredConversation | undefined>;
|
|
25
38
|
/** Whether this request may read the call's result: the handler's `authorizeToolReplay`. */
|
|
26
39
|
readable: (operation: SettledOperation) => Promise<boolean>;
|
|
40
|
+
/** The profile's labels, for the words of an end the session does not hold. */
|
|
41
|
+
labels: Profile['labels'];
|
|
27
42
|
now?: () => number;
|
|
28
43
|
};
|
|
29
44
|
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
@@ -5,7 +5,35 @@
|
|
|
5
5
|
*
|
|
6
6
|
* @module
|
|
7
7
|
*/
|
|
8
|
-
|
|
8
|
+
import { labelText, } from '@theoremjs/agents';
|
|
9
|
+
/**
|
|
10
|
+
* What became of a detached call, as the model and the page read it: the end the session saved, or
|
|
11
|
+
* that it is unresolved when the session holds no end (the call was cut off, or its saved end was
|
|
12
|
+
* dropped). Undefined while it runs.
|
|
13
|
+
*/
|
|
14
|
+
export function detachedEnd(call, operation, labels) {
|
|
15
|
+
if (operation?.status === 'settled')
|
|
16
|
+
return operation.outcome;
|
|
17
|
+
if (operation !== undefined && operation.status !== 'uncertain')
|
|
18
|
+
return undefined;
|
|
19
|
+
const message = labelText('tool.execution_uncertain', {}, labels);
|
|
20
|
+
const failure = {
|
|
21
|
+
code: operation ? operation.reason : 'outcome_not_retained',
|
|
22
|
+
kind: 'internal',
|
|
23
|
+
message,
|
|
24
|
+
};
|
|
25
|
+
const { operationId, callId, name } = call;
|
|
26
|
+
const at = operation ? operation.detectedAt : call.at;
|
|
27
|
+
return {
|
|
28
|
+
event: {
|
|
29
|
+
type: 'tool',
|
|
30
|
+
tool: { name, callId, operationId, at, phase: 'error', failure, readBack: message },
|
|
31
|
+
},
|
|
32
|
+
effects: 'unknown',
|
|
33
|
+
replay: { failure },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** The operation ids a chat's saved replies told, those its paused reply holds, and its untold calls. */
|
|
9
37
|
function transcriptState(conversation) {
|
|
10
38
|
const told = new Set();
|
|
11
39
|
const detached = [];
|
|
@@ -13,25 +41,35 @@ function transcriptState(conversation) {
|
|
|
13
41
|
if (block.kind === 'late-results')
|
|
14
42
|
for (const id of block.operationIds)
|
|
15
43
|
told.add(id);
|
|
16
|
-
|
|
17
|
-
|
|
44
|
+
const { tool } = block.kind === 'tool' ? block : { tool: undefined };
|
|
45
|
+
if (tool?.state?.phase === 'background' && tool.operationId) {
|
|
46
|
+
const { operationId, callId, name } = tool;
|
|
47
|
+
detached.push({ operationId, callId, name, at: tool.state.at });
|
|
48
|
+
}
|
|
18
49
|
}
|
|
19
50
|
const paused = new Set();
|
|
51
|
+
const draft = [];
|
|
20
52
|
for (const event of conversation?.paused?.events ?? []) {
|
|
21
53
|
if (event.type === 'late_results')
|
|
22
54
|
for (const id of event.operationIds)
|
|
23
55
|
paused.add(id);
|
|
56
|
+
const tool = event.type === 'tool' ? event.tool : undefined;
|
|
57
|
+
if (tool?.phase === 'background' && tool.operationId) {
|
|
58
|
+
const { operationId, callId, name, at } = tool;
|
|
59
|
+
draft.push({ operationId, callId, name, at });
|
|
60
|
+
}
|
|
24
61
|
}
|
|
25
62
|
return {
|
|
26
63
|
told,
|
|
27
64
|
paused,
|
|
28
65
|
pausedReply: conversation?.paused?.reply,
|
|
29
|
-
untold: detached.filter((
|
|
66
|
+
untold: detached.filter((call) => !told.has(call.operationId)),
|
|
67
|
+
/** The calls the paused reply read, wherever it detached them. */
|
|
68
|
+
kept: [...detached, ...draft].filter((call) => paused.has(call.operationId)),
|
|
30
69
|
};
|
|
31
70
|
}
|
|
32
|
-
function
|
|
33
|
-
|
|
34
|
-
return operation?.status === 'settled' ? operation : undefined;
|
|
71
|
+
function operationOf(state, id) {
|
|
72
|
+
return Object.hasOwn(state.operations, id) ? state.operations[id] : undefined;
|
|
35
73
|
}
|
|
36
74
|
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
37
75
|
export function sessionConversationInbox(options) {
|
|
@@ -52,56 +90,55 @@ export function sessionConversationInbox(options) {
|
|
|
52
90
|
inbox.entries[id] = { handovers: [] };
|
|
53
91
|
return inbox.entries[id];
|
|
54
92
|
};
|
|
55
|
-
const item = (
|
|
56
|
-
id
|
|
93
|
+
const item = (id, outcome, entry) => ({
|
|
94
|
+
id,
|
|
57
95
|
kind: 'late_result',
|
|
58
96
|
handovers: [...(entry?.handovers ?? [])],
|
|
59
|
-
outcome
|
|
97
|
+
outcome,
|
|
60
98
|
});
|
|
99
|
+
/** The call's end; undefined while it runs. */
|
|
100
|
+
const endOf = (state, call) => detachedEnd(call, operationOf(state, call.operationId), options.labels);
|
|
61
101
|
const handTo = (entry, hold, handover, at) => {
|
|
62
102
|
// invariant: A reply that lost its hold never gave its item back: what it was handed counts as a handover.
|
|
63
103
|
if (entry.handed)
|
|
64
104
|
entry.handovers.push(entry.handed);
|
|
65
105
|
entry.handed = { ...handover, hold, at };
|
|
66
106
|
};
|
|
67
|
-
/** The untold
|
|
68
|
-
const
|
|
107
|
+
/** The chat's untold calls that no paused reply keeps. */
|
|
108
|
+
const untoldCalls = async (key) => {
|
|
69
109
|
const conversation = await options.conversation(key);
|
|
70
110
|
const chat = transcriptState(conversation);
|
|
71
|
-
return { chat,
|
|
111
|
+
return { chat, calls: chat.untold.filter((call) => !chat.paused.has(call.operationId)) };
|
|
72
112
|
};
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return undefined;
|
|
113
|
+
/** The call's end, while it waits for a reply: ended, not given up, and no live hold has it. */
|
|
114
|
+
const waiting = (inbox, state, call, at) => {
|
|
115
|
+
const id = call.operationId;
|
|
77
116
|
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
78
117
|
if (entry?.givenUp || (entry && heldLive(inbox, entry, at)))
|
|
79
118
|
return undefined;
|
|
80
|
-
return
|
|
119
|
+
return endOf(state, call);
|
|
81
120
|
};
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
kept.push(operation);
|
|
87
|
-
return kept;
|
|
121
|
+
/** Whether this request may read the end: a saved result only as the host allows; an unresolved end always. */
|
|
122
|
+
const readable = (state, id) => {
|
|
123
|
+
const operation = operationOf(state, id);
|
|
124
|
+
return operation?.status === 'settled' ? options.readable(operation) : Promise.resolve(true);
|
|
88
125
|
};
|
|
89
126
|
/** Changes one chat's lock and entries in one session write. */
|
|
90
127
|
const change = (key, apply) => sessions.mutate(sessionId, (state) => apply(inboxOf(state, key), state, now()));
|
|
91
128
|
/** Acts on each of `ids` that waits, only while `hold` has the chat; returns those it acted on. */
|
|
92
129
|
const actOnWaiting = async (key, hold, ids, act) => {
|
|
93
|
-
const {
|
|
94
|
-
const wanted =
|
|
130
|
+
const { calls } = await untoldCalls(key);
|
|
131
|
+
const wanted = calls.filter((call) => ids.includes(call.operationId));
|
|
95
132
|
return change(key, (inbox, state, at) => {
|
|
96
133
|
if (!has(inbox, hold, at))
|
|
97
134
|
return [];
|
|
98
|
-
return wanted.flatMap((
|
|
99
|
-
const
|
|
100
|
-
if (!
|
|
135
|
+
return wanted.flatMap((call) => {
|
|
136
|
+
const outcome = waiting(inbox, state, call, at);
|
|
137
|
+
if (!outcome)
|
|
101
138
|
return [];
|
|
102
|
-
const entry = entryOf(inbox,
|
|
139
|
+
const entry = entryOf(inbox, call.operationId);
|
|
103
140
|
act(entry, at);
|
|
104
|
-
return [item(
|
|
141
|
+
return [item(call.operationId, outcome, entry)];
|
|
105
142
|
});
|
|
106
143
|
});
|
|
107
144
|
};
|
|
@@ -131,22 +168,24 @@ export function sessionConversationInbox(options) {
|
|
|
131
168
|
});
|
|
132
169
|
},
|
|
133
170
|
async read(key) {
|
|
134
|
-
const {
|
|
171
|
+
const { calls } = await untoldCalls(key);
|
|
135
172
|
const state = await sessions.read(sessionId);
|
|
136
173
|
const inbox = state.inbox?.conversations[key] ?? { leasedUntil: 0, entries: {} };
|
|
137
174
|
const at = now();
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
175
|
+
const items = [];
|
|
176
|
+
for (const call of calls) {
|
|
177
|
+
const id = call.operationId;
|
|
178
|
+
const outcome = waiting(inbox, state, call, at);
|
|
179
|
+
if (outcome && (await readable(state, id)))
|
|
180
|
+
items.push(item(id, outcome, inbox.entries[id]));
|
|
181
|
+
}
|
|
143
182
|
return { items, version: String(state.inbox?.version ?? 0) };
|
|
144
183
|
},
|
|
145
184
|
hand(key, hold, handover, ids) {
|
|
146
185
|
return actOnWaiting(key, hold, ids, (entry, at) => handTo(entry, hold, handover, at));
|
|
147
186
|
},
|
|
148
187
|
async giveBack(key, hold, reply, ids) {
|
|
149
|
-
const { chat } = await
|
|
188
|
+
const { chat } = await untoldCalls(key);
|
|
150
189
|
await change(key, (inbox) => {
|
|
151
190
|
for (const id of ids) {
|
|
152
191
|
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
@@ -162,19 +201,19 @@ export function sessionConversationInbox(options) {
|
|
|
162
201
|
});
|
|
163
202
|
},
|
|
164
203
|
async resume(key, hold, paused, handover) {
|
|
165
|
-
const { chat } = await
|
|
204
|
+
const { chat } = await untoldCalls(key);
|
|
166
205
|
if (chat.pausedReply !== paused)
|
|
167
206
|
return [];
|
|
168
207
|
return change(key, (inbox, state, at) => {
|
|
169
208
|
if (!has(inbox, hold, at))
|
|
170
209
|
return [];
|
|
171
|
-
return
|
|
172
|
-
const
|
|
173
|
-
const entry = entryOf(inbox,
|
|
174
|
-
if (!
|
|
210
|
+
return chat.kept.flatMap((call) => {
|
|
211
|
+
const outcome = endOf(state, call);
|
|
212
|
+
const entry = entryOf(inbox, call.operationId);
|
|
213
|
+
if (!outcome || heldLive(inbox, entry, at))
|
|
175
214
|
return [];
|
|
176
215
|
handTo(entry, hold, handover, at);
|
|
177
|
-
return [item(
|
|
216
|
+
return [item(call.operationId, outcome, entry)];
|
|
178
217
|
});
|
|
179
218
|
});
|
|
180
219
|
},
|
|
@@ -13,6 +13,11 @@ import { type ProviderCheckpoint, TheoremError, type TurnEvent, type TurnHistory
|
|
|
13
13
|
import type { TranscriptBlock } from '@theoremjs/agents/interface';
|
|
14
14
|
import { type StatedTurn } from '../client/transport.ts';
|
|
15
15
|
import { type MemorySessionStoreOptions } from './session-store.ts';
|
|
16
|
+
/** A reply's base and the count of its events that base holds, as they stood before a compaction. */
|
|
17
|
+
export type UncompactedBase = {
|
|
18
|
+
base: TurnHistoryMessage[];
|
|
19
|
+
baseEvents: number;
|
|
20
|
+
};
|
|
16
21
|
/** A reply paused on gates: its events so far, and the history it was given. */
|
|
17
22
|
export type PausedReply = {
|
|
18
23
|
events: TurnEvent[];
|
|
@@ -20,6 +25,8 @@ export type PausedReply = {
|
|
|
20
25
|
base: TurnHistoryMessage[];
|
|
21
26
|
/** How many of `events` `base` already holds: a compaction mid-reply moves the base. */
|
|
22
27
|
baseEvents: number;
|
|
28
|
+
/** The base before a compaction folded in late results this reply read; a failure goes back to it. */
|
|
29
|
+
uncompacted?: UncompactedBase;
|
|
23
30
|
/** How long the reply worked before it paused (ms), approval waits excluded. */
|
|
24
31
|
workedMs: number;
|
|
25
32
|
/** When the reply last paused (epoch ms). */
|
|
@@ -18,6 +18,12 @@ const pausedReply = z.object({
|
|
|
18
18
|
events: z.array(turnEventSchema),
|
|
19
19
|
base: z.array(turnHistoryMessageSchema),
|
|
20
20
|
baseEvents: z.number().int().nonnegative(),
|
|
21
|
+
uncompacted: z
|
|
22
|
+
.object({
|
|
23
|
+
base: z.array(turnHistoryMessageSchema),
|
|
24
|
+
baseEvents: z.number().int().nonnegative(),
|
|
25
|
+
})
|
|
26
|
+
.optional(),
|
|
21
27
|
workedMs: z.number().nonnegative(),
|
|
22
28
|
endedAt: z.number(),
|
|
23
29
|
model: z.string().optional(),
|
package/server/conversation.js
CHANGED
|
@@ -189,6 +189,7 @@ function pausedOn(conversation, reply, runner) {
|
|
|
189
189
|
events: reply.events,
|
|
190
190
|
base: reply.base,
|
|
191
191
|
baseEvents: reply.baseEvents,
|
|
192
|
+
...(reply.uncompacted ? { uncompacted: reply.uncompacted } : {}),
|
|
192
193
|
workedMs: reply.workedMs,
|
|
193
194
|
endedAt: Date.now(),
|
|
194
195
|
...(runner.model ? { model: runner.model } : {}),
|
|
@@ -200,14 +201,19 @@ function pausedOn(conversation, reply, runner) {
|
|
|
200
201
|
}
|
|
201
202
|
/**
|
|
202
203
|
* 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
|
+
* leave with it, so a later reply tells them. A compaction that folded them in is undone too: the
|
|
205
|
+
* history goes back to its base before that compaction, and the next reply compacts again.
|
|
204
206
|
*/
|
|
205
207
|
function failed(host, conversation, reply, failure) {
|
|
206
|
-
const
|
|
208
|
+
const from = reply.uncompacted ?? reply;
|
|
209
|
+
const unread = (events) => events.filter((event, index) => event.type !== 'late_results' &&
|
|
210
|
+
!(reply.uncompacted && event.type === 'compaction' && index >= from.baseEvents));
|
|
211
|
+
const events = unread(reply.events);
|
|
207
212
|
const next = committed(host, conversation, {
|
|
208
|
-
|
|
209
|
-
events
|
|
210
|
-
baseEvents: unread(reply.events.slice(0,
|
|
213
|
+
base: from.base,
|
|
214
|
+
events,
|
|
215
|
+
baseEvents: unread(reply.events.slice(0, from.baseEvents)).length,
|
|
216
|
+
workedMs: reply.workedMs,
|
|
211
217
|
});
|
|
212
218
|
if (next.transcript.slice(conversation.transcript.length).some((b) => b.kind === 'error')) {
|
|
213
219
|
return next;
|
|
@@ -257,6 +263,10 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
|
|
|
257
263
|
continue;
|
|
258
264
|
}
|
|
259
265
|
if (event.type === 'compaction') {
|
|
266
|
+
// invariant: A failure must not leave in the history a late result it gives back.
|
|
267
|
+
if (!reply.uncompacted && reply.events.some((seen) => seen.type === 'late_results')) {
|
|
268
|
+
reply.uncompacted = { base: reply.base, baseEvents: reply.baseEvents };
|
|
269
|
+
}
|
|
260
270
|
reply.base = withMessage(event.history);
|
|
261
271
|
reply.baseEvents = reply.events.length;
|
|
262
272
|
}
|
|
@@ -408,6 +418,7 @@ function pausedReply(paused) {
|
|
|
408
418
|
base: paused.base,
|
|
409
419
|
events: [...paused.events],
|
|
410
420
|
baseEvents: paused.baseEvents,
|
|
421
|
+
...(paused.uncompacted ? { uncompacted: paused.uncompacted } : {}),
|
|
411
422
|
workedMs: paused.workedMs,
|
|
412
423
|
};
|
|
413
424
|
}
|
|
@@ -441,14 +452,27 @@ export async function* messageReply(args) {
|
|
|
441
452
|
}
|
|
442
453
|
opened = { ...opened, conversation: committed(host, opened.conversation, walked) };
|
|
443
454
|
}
|
|
444
|
-
const { conversation } = opened;
|
|
445
455
|
const withMessage = (history) => appendUserDraftToHistory(history, message.draft, message.media);
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
456
|
+
let base = opened;
|
|
457
|
+
for (;;) {
|
|
458
|
+
try {
|
|
459
|
+
// why: The message posts before the model runs, so a reply the browser stops still leaves it, in the transcript and the history.
|
|
460
|
+
opened = await save(host, base, {
|
|
461
|
+
...base.conversation,
|
|
462
|
+
transcript: [...base.conversation.transcript, ...message.blocks],
|
|
463
|
+
history: withMessage(base.conversation.history),
|
|
464
|
+
});
|
|
465
|
+
break;
|
|
466
|
+
}
|
|
467
|
+
catch (err) {
|
|
468
|
+
const moved = paused ? undefined : await savedSince(host, base, runner, err);
|
|
469
|
+
if (!moved)
|
|
470
|
+
throw err;
|
|
471
|
+
requireWalkAway(moved.conversation, undefined);
|
|
472
|
+
base = moved;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
const { conversation } = base;
|
|
452
476
|
yield* refLine(opened, 'posted');
|
|
453
477
|
const reply = {
|
|
454
478
|
base: withMessage(conversation.history),
|
|
@@ -458,6 +482,22 @@ export async function* messageReply(args) {
|
|
|
458
482
|
};
|
|
459
483
|
yield* runReply(host, opened, reply, runner, { ...message.input, ...historyInput(conversation) }, withMessage);
|
|
460
484
|
}
|
|
485
|
+
/**
|
|
486
|
+
* The conversation as a save that `err` lost to left it, while this reply's hold still has the chat.
|
|
487
|
+
* Undefined when `err` is no such loss, the hold lost the chat, or no newer save is there to read.
|
|
488
|
+
*
|
|
489
|
+
* why: The hold a message took the chat from may land the one save it began first; no save of it follows.
|
|
490
|
+
*/
|
|
491
|
+
async function savedSince(host, opened, runner, err) {
|
|
492
|
+
if (!(err instanceof TheoremError && err.cause === CONFLICT) || opened.ref === null)
|
|
493
|
+
return undefined;
|
|
494
|
+
if (runner.held && !(await runner.held()))
|
|
495
|
+
return undefined;
|
|
496
|
+
const snapshot = await host.store.read(host.sessionId, opened.ref);
|
|
497
|
+
if (!snapshot || snapshot.revision === opened.revision)
|
|
498
|
+
return undefined;
|
|
499
|
+
return { ref: opened.ref, revision: snapshot.revision, conversation: snapshot.conversation };
|
|
500
|
+
}
|
|
461
501
|
/** The conversation's history as a run reads it, with its meters. */
|
|
462
502
|
function historyInput(conversation) {
|
|
463
503
|
return {
|
package/server/handler.js
CHANGED
|
@@ -47,7 +47,7 @@ import { answerGatedCall, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
|
|
|
47
47
|
import { hostInterface, theoremHostCallRequestSchema, } from "../client/host-transport.js";
|
|
48
48
|
import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
49
49
|
import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
|
|
50
|
-
import { sessionConversationInbox } from "./conversation-inbox.js";
|
|
50
|
+
import { detachedEnd, sessionConversationInbox } from "./conversation-inbox.js";
|
|
51
51
|
import { unknownConversation, } from "./conversation-store.js";
|
|
52
52
|
import { createMemoryCredentialStore, } from "./credential-store.js";
|
|
53
53
|
import { sessionStateStore, } from "./session-authority.js";
|
|
@@ -442,14 +442,16 @@ function announced(ctx, request, sessionId, service) {
|
|
|
442
442
|
if (!ended)
|
|
443
443
|
return;
|
|
444
444
|
const { operations } = await ctx.sessions.read(sessionId);
|
|
445
|
-
const
|
|
446
|
-
|
|
445
|
+
const { operationId, callId, toolId } = call;
|
|
446
|
+
const operation = Object.hasOwn(operations, operationId)
|
|
447
|
+
? operations[operationId]
|
|
447
448
|
: undefined;
|
|
448
|
-
|
|
449
|
+
const outcome = detachedEnd({ operationId, callId, name: toolId, at: Date.now() }, operation, ctx.profile.labels);
|
|
450
|
+
if (!outcome)
|
|
449
451
|
return;
|
|
450
452
|
await ended({
|
|
451
453
|
host: await ctx.options.host?.(request),
|
|
452
|
-
result: { operationId
|
|
454
|
+
result: { operationId, outcome },
|
|
453
455
|
wake: (conversation) => serverWake(ctx, request, sessionId, conversation),
|
|
454
456
|
notify,
|
|
455
457
|
});
|
|
@@ -510,6 +512,7 @@ function chatInbox(ctx, request, session, host, opened) {
|
|
|
510
512
|
return conversation?.id === key ? conversation : undefined;
|
|
511
513
|
},
|
|
512
514
|
readable: (operation) => replayAllowed(ctx, request, operation),
|
|
515
|
+
labels: ctx.profile.labels,
|
|
513
516
|
});
|
|
514
517
|
return {
|
|
515
518
|
inbox,
|
|
@@ -912,22 +915,12 @@ async function lateBlock(ctx, request, block, operations, host) {
|
|
|
912
915
|
return block;
|
|
913
916
|
return { ...block, tool: { ...tool, state, endedAt: operation.settledAt } };
|
|
914
917
|
}
|
|
915
|
-
const message = labelText('tool.execution_uncertain', {}, labels);
|
|
916
|
-
const failure = {
|
|
917
|
-
code: operation?.status === 'uncertain' ? operation.reason : 'outcome_not_retained',
|
|
918
|
-
kind: 'internal',
|
|
919
|
-
message,
|
|
920
|
-
};
|
|
921
918
|
const { name, callId } = tool;
|
|
922
|
-
const
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
state: { name, callId, at, phase: 'error', failure, readBack: message },
|
|
928
|
-
endedAt: at,
|
|
929
|
-
},
|
|
930
|
-
};
|
|
919
|
+
const unresolved = detachedEnd({ operationId: id ?? '', callId, name, at: tool.state?.at ?? Date.now() }, operation, labels);
|
|
920
|
+
if (!unresolved)
|
|
921
|
+
return block;
|
|
922
|
+
const { operationId: _id, ...state } = unresolved.event.tool;
|
|
923
|
+
return { ...block, tool: { ...tool, state, endedAt: state.at } };
|
|
931
924
|
}
|
|
932
925
|
/** The conversation cut after one block; a reply that waits on gates is walked away from first. */
|
|
933
926
|
async function rewind(ctx, request, session) {
|
package/server/mod.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ 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
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
|
-
export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, unknownConversation, } from './conversation-store.ts';
|
|
12
|
+
export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, type UncompactedBase, 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';
|
|
15
15
|
export { createTheoremEmbeddingHandler, embedBodySchema, embedRequest, type TheoremEmbeddingHandlerOptions, } from './embedding-handler.ts';
|
|
@@ -142,8 +142,9 @@ export declare function pruneGates<Gate extends {
|
|
|
142
142
|
expiresAt?: number;
|
|
143
143
|
}>(gates: Record<string, Gate>, now: number, ttlMs: number | undefined): Record<string, Gate>;
|
|
144
144
|
/**
|
|
145
|
-
* Drops
|
|
146
|
-
*
|
|
145
|
+
* Drops the conversations no hold has with nothing kept.
|
|
146
|
+
*
|
|
147
|
+
* invariant: An entry outlives its result: a result the session dropped is still told, as unresolved.
|
|
147
148
|
*/
|
|
148
149
|
export declare function pruneInbox(state: TheoremSessionState, now: number): void;
|
|
149
150
|
export type MemorySessionStoreOptions = {
|
package/server/session-store.js
CHANGED
|
@@ -219,17 +219,14 @@ export function pruneGates(gates, now, ttlMs) {
|
|
|
219
219
|
: !gateExpired(gate.createdAt, now, ttlMs)));
|
|
220
220
|
}
|
|
221
221
|
/**
|
|
222
|
-
* Drops
|
|
223
|
-
*
|
|
222
|
+
* Drops the conversations no hold has with nothing kept.
|
|
223
|
+
*
|
|
224
|
+
* invariant: An entry outlives its result: a result the session dropped is still told, as unresolved.
|
|
224
225
|
*/
|
|
225
226
|
export function pruneInbox(state, now) {
|
|
226
227
|
if (!state.inbox)
|
|
227
228
|
return;
|
|
228
229
|
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
230
|
if (conversation.leasedUntil <= now && Object.keys(conversation.entries).length === 0) {
|
|
234
231
|
delete state.inbox.conversations[key];
|
|
235
232
|
}
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import type { LateResultsDecider } from '@theoremjs/agents';
|
|
6
6
|
/**
|
|
7
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.
|
|
8
|
+
* when one waits. A result two replies read without telling is given up, and reported once as
|
|
9
|
+
* `late_results_given_up`, so a model that keeps failing does not reply again and again.
|
|
9
10
|
*/
|
|
10
11
|
export declare const tellEveryResult: LateResultsDecider;
|
|
@@ -1,7 +1,17 @@
|
|
|
1
|
+
/** Replies that may read one result: the first, and one more after a reply that failed or lost the chat. */
|
|
2
|
+
const READS_PER_RESULT_COUNT = 2;
|
|
1
3
|
/**
|
|
2
4
|
* Each late result is told to the first reply that runs, and the page open on the chat wakes it
|
|
3
|
-
* when one waits.
|
|
5
|
+
* when one waits. A result two replies read without telling is given up, and reported once as
|
|
6
|
+
* `late_results_given_up`, so a model that keeps failing does not reply again and again.
|
|
4
7
|
*/
|
|
5
8
|
export const tellEveryResult = {
|
|
6
|
-
policy: (items) => ({
|
|
9
|
+
policy: (items) => ({
|
|
10
|
+
tell: items
|
|
11
|
+
.filter((item) => item.handovers.length < READS_PER_RESULT_COUNT)
|
|
12
|
+
.map((item) => item.id),
|
|
13
|
+
giveUp: items
|
|
14
|
+
.filter((item) => item.handovers.length >= READS_PER_RESULT_COUNT)
|
|
15
|
+
.map((item) => item.id),
|
|
16
|
+
}),
|
|
7
17
|
};
|
|
@@ -73,13 +73,15 @@ function saveOutcome(state, identity, outcome) {
|
|
|
73
73
|
outcome,
|
|
74
74
|
settledAt,
|
|
75
75
|
};
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
76
|
+
if (reply)
|
|
77
|
+
movedInbox(state);
|
|
78
|
+
}
|
|
79
|
+
/** why: A detached call's end is an item in its conversation's inbox; a hold reads again before it lets go. */
|
|
80
|
+
function movedInbox(state) {
|
|
81
|
+
state.inbox = {
|
|
82
|
+
version: (state.inbox?.version ?? 0) + 1,
|
|
83
|
+
conversations: state.inbox?.conversations ?? {},
|
|
84
|
+
};
|
|
83
85
|
}
|
|
84
86
|
export function sessionToolCoordinator(store, sessionId) {
|
|
85
87
|
return {
|
|
@@ -157,6 +159,8 @@ export function sessionToolCoordinator(store, sessionId) {
|
|
|
157
159
|
reason,
|
|
158
160
|
detectedAt: Date.now(),
|
|
159
161
|
};
|
|
162
|
+
if (reply)
|
|
163
|
+
movedInbox(state);
|
|
160
164
|
});
|
|
161
165
|
},
|
|
162
166
|
};
|