@theoremjs/web 0.3.5-next.935.ga3dc485 → 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 +10 -6
- package/package.json +2 -2
- package/server/conversation-inbox.d.ts +45 -0
- package/server/conversation-inbox.js +240 -0
- package/server/conversation-store.d.ts +9 -0
- package/server/conversation-store.js +7 -0
- package/server/conversation.d.ts +7 -12
- package/server/conversation.js +77 -49
- package/server/handler.d.ts +9 -2
- package/server/handler.js +238 -147
- package/server/mod.d.ts +3 -3
- package/server/mod.js +2 -2
- package/server/session-authority.js +3 -1
- package/server/session-store.d.ts +33 -2
- package/server/session-store.js +37 -2
- package/server/tell-every-result.d.ts +11 -0
- package/server/tell-every-result.js +17 -0
- package/server/tool-operations.js +11 -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, and gives up a result two replies read without telling. 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
|
|
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.
|
|
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. 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
|
+
|
|
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.
|
|
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.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
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handler's conversation inbox: each chat's late results, kept in the session store. An item
|
|
3
|
+
* is a detached call that ended; the transcript says whether a saved reply told it, and the
|
|
4
|
+
* session keeps who holds the chat and which replies were handed what.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import { type LateResultItem, type Profile, type ToolOperationOutcome } from '@theoremjs/agents';
|
|
9
|
+
import type { ConversationInbox } from '@theoremjs/agents/conversation';
|
|
10
|
+
import type { StoredConversation } from './conversation-store.ts';
|
|
11
|
+
import type { MutableStore } from './session-authority.ts';
|
|
12
|
+
import type { SessionToolOperation, TheoremSessionState } from './session-store.ts';
|
|
13
|
+
/** A background call that ended, as the session keeps it. */
|
|
14
|
+
export type SettledOperation = Extract<SessionToolOperation, {
|
|
15
|
+
status: 'settled';
|
|
16
|
+
}>;
|
|
17
|
+
/** A detached call as its chat's transcript keeps it: what an end is told about. */
|
|
18
|
+
export type DetachedCall = {
|
|
19
|
+
operationId: string;
|
|
20
|
+
callId: string;
|
|
21
|
+
name: string;
|
|
22
|
+
at: number;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* What became of a detached call, as the model and the page read it: the end the session saved, or
|
|
26
|
+
* that it is unresolved when the session holds no end (the call was cut off, or its saved end was
|
|
27
|
+
* dropped). Undefined while it runs.
|
|
28
|
+
*/
|
|
29
|
+
export declare function detachedEnd(call: DetachedCall, operation: SessionToolOperation | undefined, labels: Profile['labels']): ToolOperationOutcome | undefined;
|
|
30
|
+
/** Options for {@link sessionConversationInbox}. */
|
|
31
|
+
export type SessionConversationInboxOptions = {
|
|
32
|
+
sessions: MutableStore<TheoremSessionState>;
|
|
33
|
+
sessionId: string;
|
|
34
|
+
/** How long a hold has a chat after it opens or renews, in milliseconds. */
|
|
35
|
+
leaseMs: number;
|
|
36
|
+
/** The chat as its last save left it, by its id; undefined when the store no longer has it. */
|
|
37
|
+
conversation: (key: string) => Promise<StoredConversation | undefined>;
|
|
38
|
+
/** Whether this request may read the call's result: the handler's `authorizeToolReplay`. */
|
|
39
|
+
readable: (operation: SettledOperation) => Promise<boolean>;
|
|
40
|
+
/** The profile's labels, for the words of an end the session does not hold. */
|
|
41
|
+
labels: Profile['labels'];
|
|
42
|
+
now?: () => number;
|
|
43
|
+
};
|
|
44
|
+
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
45
|
+
export declare function sessionConversationInbox(options: SessionConversationInboxOptions): ConversationInbox<LateResultItem>;
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handler's conversation inbox: each chat's late results, kept in the session store. An item
|
|
3
|
+
* is a detached call that ended; the transcript says whether a saved reply told it, and the
|
|
4
|
+
* session keeps who holds the chat and which replies were handed what.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import { labelText, } from '@theoremjs/agents';
|
|
9
|
+
/**
|
|
10
|
+
* What became of a detached call, as the model and the page read it: the end the session saved, or
|
|
11
|
+
* that it is unresolved when the session holds no end (the call was cut off, or its saved end was
|
|
12
|
+
* dropped). Undefined while it runs.
|
|
13
|
+
*/
|
|
14
|
+
export function detachedEnd(call, operation, labels) {
|
|
15
|
+
if (operation?.status === 'settled')
|
|
16
|
+
return operation.outcome;
|
|
17
|
+
if (operation !== undefined && operation.status !== 'uncertain')
|
|
18
|
+
return undefined;
|
|
19
|
+
const message = labelText('tool.execution_uncertain', {}, labels);
|
|
20
|
+
const failure = {
|
|
21
|
+
code: operation ? operation.reason : 'outcome_not_retained',
|
|
22
|
+
kind: 'internal',
|
|
23
|
+
message,
|
|
24
|
+
};
|
|
25
|
+
const { operationId, callId, name } = call;
|
|
26
|
+
const at = operation ? operation.detectedAt : call.at;
|
|
27
|
+
return {
|
|
28
|
+
event: {
|
|
29
|
+
type: 'tool',
|
|
30
|
+
tool: { name, callId, operationId, at, phase: 'error', failure, readBack: message },
|
|
31
|
+
},
|
|
32
|
+
effects: 'unknown',
|
|
33
|
+
replay: { failure },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** The operation ids a chat's saved replies told, those its paused reply holds, and its untold calls. */
|
|
37
|
+
function transcriptState(conversation) {
|
|
38
|
+
const told = new Set();
|
|
39
|
+
const detached = [];
|
|
40
|
+
for (const block of conversation?.transcript ?? []) {
|
|
41
|
+
if (block.kind === 'late-results')
|
|
42
|
+
for (const id of block.operationIds)
|
|
43
|
+
told.add(id);
|
|
44
|
+
const { tool } = block.kind === 'tool' ? block : { tool: undefined };
|
|
45
|
+
if (tool?.state?.phase === 'background' && tool.operationId) {
|
|
46
|
+
const { operationId, callId, name } = tool;
|
|
47
|
+
detached.push({ operationId, callId, name, at: tool.state.at });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const paused = new Set();
|
|
51
|
+
const draft = [];
|
|
52
|
+
for (const event of conversation?.paused?.events ?? []) {
|
|
53
|
+
if (event.type === 'late_results')
|
|
54
|
+
for (const id of event.operationIds)
|
|
55
|
+
paused.add(id);
|
|
56
|
+
const tool = event.type === 'tool' ? event.tool : undefined;
|
|
57
|
+
if (tool?.phase === 'background' && tool.operationId) {
|
|
58
|
+
const { operationId, callId, name, at } = tool;
|
|
59
|
+
draft.push({ operationId, callId, name, at });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
told,
|
|
64
|
+
paused,
|
|
65
|
+
pausedReply: conversation?.paused?.reply,
|
|
66
|
+
untold: detached.filter((call) => !told.has(call.operationId)),
|
|
67
|
+
/** The calls the paused reply read, wherever it detached them. */
|
|
68
|
+
kept: [...detached, ...draft].filter((call) => paused.has(call.operationId)),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function operationOf(state, id) {
|
|
72
|
+
return Object.hasOwn(state.operations, id) ? state.operations[id] : undefined;
|
|
73
|
+
}
|
|
74
|
+
/** Creates the {@link ConversationInbox} of one session's chats, keyed by `StoredConversation.id`. */
|
|
75
|
+
export function sessionConversationInbox(options) {
|
|
76
|
+
const { sessions, sessionId, leaseMs } = options;
|
|
77
|
+
const now = options.now ?? Date.now;
|
|
78
|
+
const inboxOf = (state, key) => {
|
|
79
|
+
state.inbox ??= { version: 0, conversations: {} };
|
|
80
|
+
const conversations = state.inbox.conversations;
|
|
81
|
+
if (!Object.hasOwn(conversations, key))
|
|
82
|
+
conversations[key] = { leasedUntil: 0, entries: {} };
|
|
83
|
+
return conversations[key];
|
|
84
|
+
};
|
|
85
|
+
const has = (inbox, hold, at) => inbox.hold === hold && inbox.leasedUntil > at;
|
|
86
|
+
/** Handed to a reply whose hold still has the chat. */
|
|
87
|
+
const heldLive = (inbox, entry, at) => entry.handed !== undefined && has(inbox, entry.handed.hold, at);
|
|
88
|
+
const entryOf = (inbox, id) => {
|
|
89
|
+
if (!Object.hasOwn(inbox.entries, id))
|
|
90
|
+
inbox.entries[id] = { handovers: [] };
|
|
91
|
+
return inbox.entries[id];
|
|
92
|
+
};
|
|
93
|
+
const item = (id, outcome, entry) => ({
|
|
94
|
+
id,
|
|
95
|
+
kind: 'late_result',
|
|
96
|
+
handovers: [...(entry?.handovers ?? [])],
|
|
97
|
+
outcome,
|
|
98
|
+
});
|
|
99
|
+
/** The call's end; undefined while it runs. */
|
|
100
|
+
const endOf = (state, call) => detachedEnd(call, operationOf(state, call.operationId), options.labels);
|
|
101
|
+
const handTo = (entry, hold, handover, at) => {
|
|
102
|
+
// invariant: A reply that lost its hold never gave its item back: what it was handed counts as a handover.
|
|
103
|
+
if (entry.handed)
|
|
104
|
+
entry.handovers.push(entry.handed);
|
|
105
|
+
entry.handed = { ...handover, hold, at };
|
|
106
|
+
};
|
|
107
|
+
/** The chat's untold calls that no paused reply keeps. */
|
|
108
|
+
const untoldCalls = async (key) => {
|
|
109
|
+
const conversation = await options.conversation(key);
|
|
110
|
+
const chat = transcriptState(conversation);
|
|
111
|
+
return { chat, calls: chat.untold.filter((call) => !chat.paused.has(call.operationId)) };
|
|
112
|
+
};
|
|
113
|
+
/** The call's end, while it waits for a reply: ended, not given up, and no live hold has it. */
|
|
114
|
+
const waiting = (inbox, state, call, at) => {
|
|
115
|
+
const id = call.operationId;
|
|
116
|
+
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
117
|
+
if (entry?.givenUp || (entry && heldLive(inbox, entry, at)))
|
|
118
|
+
return undefined;
|
|
119
|
+
return endOf(state, call);
|
|
120
|
+
};
|
|
121
|
+
/** Whether this request may read the end: a saved result only as the host allows; an unresolved end always. */
|
|
122
|
+
const readable = (state, id) => {
|
|
123
|
+
const operation = operationOf(state, id);
|
|
124
|
+
return operation?.status === 'settled' ? options.readable(operation) : Promise.resolve(true);
|
|
125
|
+
};
|
|
126
|
+
/** Changes one chat's lock and entries in one session write. */
|
|
127
|
+
const change = (key, apply) => sessions.mutate(sessionId, (state) => apply(inboxOf(state, key), state, now()));
|
|
128
|
+
/** Acts on each of `ids` that waits, only while `hold` has the chat; returns those it acted on. */
|
|
129
|
+
const actOnWaiting = async (key, hold, ids, act) => {
|
|
130
|
+
const { calls } = await untoldCalls(key);
|
|
131
|
+
const wanted = calls.filter((call) => ids.includes(call.operationId));
|
|
132
|
+
return change(key, (inbox, state, at) => {
|
|
133
|
+
if (!has(inbox, hold, at))
|
|
134
|
+
return [];
|
|
135
|
+
return wanted.flatMap((call) => {
|
|
136
|
+
const outcome = waiting(inbox, state, call, at);
|
|
137
|
+
if (!outcome)
|
|
138
|
+
return [];
|
|
139
|
+
const entry = entryOf(inbox, call.operationId);
|
|
140
|
+
act(entry, at);
|
|
141
|
+
return [item(call.operationId, outcome, entry)];
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
};
|
|
145
|
+
const lease = (inbox, hold, at) => {
|
|
146
|
+
inbox.hold = hold;
|
|
147
|
+
inbox.leasedUntil = at + leaseMs;
|
|
148
|
+
};
|
|
149
|
+
return {
|
|
150
|
+
open(key, hold) {
|
|
151
|
+
return change(key, (inbox, _state, at) => {
|
|
152
|
+
if (inbox.hold !== undefined && inbox.hold !== hold && inbox.leasedUntil > at) {
|
|
153
|
+
return { outcome: 'held', leasedUntil: inbox.leasedUntil };
|
|
154
|
+
}
|
|
155
|
+
lease(inbox, hold, at);
|
|
156
|
+
return { outcome: 'opened' };
|
|
157
|
+
});
|
|
158
|
+
},
|
|
159
|
+
takeOver(key, hold) {
|
|
160
|
+
return change(key, (inbox, _state, at) => lease(inbox, hold, at));
|
|
161
|
+
},
|
|
162
|
+
renew(key, hold) {
|
|
163
|
+
return change(key, (inbox, _state, at) => {
|
|
164
|
+
if (!has(inbox, hold, at))
|
|
165
|
+
return false;
|
|
166
|
+
lease(inbox, hold, at);
|
|
167
|
+
return true;
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
async read(key) {
|
|
171
|
+
const { calls } = await untoldCalls(key);
|
|
172
|
+
const state = await sessions.read(sessionId);
|
|
173
|
+
const inbox = state.inbox?.conversations[key] ?? { leasedUntil: 0, entries: {} };
|
|
174
|
+
const at = now();
|
|
175
|
+
const items = [];
|
|
176
|
+
for (const call of calls) {
|
|
177
|
+
const id = call.operationId;
|
|
178
|
+
const outcome = waiting(inbox, state, call, at);
|
|
179
|
+
if (outcome && (await readable(state, id)))
|
|
180
|
+
items.push(item(id, outcome, inbox.entries[id]));
|
|
181
|
+
}
|
|
182
|
+
return { items, version: String(state.inbox?.version ?? 0) };
|
|
183
|
+
},
|
|
184
|
+
hand(key, hold, handover, ids) {
|
|
185
|
+
return actOnWaiting(key, hold, ids, (entry, at) => handTo(entry, hold, handover, at));
|
|
186
|
+
},
|
|
187
|
+
async giveBack(key, hold, reply, ids) {
|
|
188
|
+
const { chat } = await untoldCalls(key);
|
|
189
|
+
await change(key, (inbox) => {
|
|
190
|
+
for (const id of ids) {
|
|
191
|
+
const entry = Object.hasOwn(inbox.entries, id) ? inbox.entries[id] : undefined;
|
|
192
|
+
if (entry?.handed?.hold !== hold || entry.handed.reply !== reply)
|
|
193
|
+
continue;
|
|
194
|
+
if (chat.told.has(id)) {
|
|
195
|
+
delete inbox.entries[id];
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
entry.handovers.push(entry.handed);
|
|
199
|
+
delete entry.handed;
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
},
|
|
203
|
+
async resume(key, hold, paused, handover) {
|
|
204
|
+
const { chat } = await untoldCalls(key);
|
|
205
|
+
if (chat.pausedReply !== paused)
|
|
206
|
+
return [];
|
|
207
|
+
return change(key, (inbox, state, at) => {
|
|
208
|
+
if (!has(inbox, hold, at))
|
|
209
|
+
return [];
|
|
210
|
+
return chat.kept.flatMap((call) => {
|
|
211
|
+
const outcome = endOf(state, call);
|
|
212
|
+
const entry = entryOf(inbox, call.operationId);
|
|
213
|
+
if (!outcome || heldLive(inbox, entry, at))
|
|
214
|
+
return [];
|
|
215
|
+
handTo(entry, hold, handover, at);
|
|
216
|
+
return [item(call.operationId, outcome, entry)];
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
},
|
|
220
|
+
giveUp(key, hold, ids) {
|
|
221
|
+
return actOnWaiting(key, hold, ids, (entry) => {
|
|
222
|
+
if (entry.handed)
|
|
223
|
+
entry.handovers.push(entry.handed);
|
|
224
|
+
delete entry.handed;
|
|
225
|
+
entry.givenUp = true;
|
|
226
|
+
});
|
|
227
|
+
},
|
|
228
|
+
release(key, hold, version) {
|
|
229
|
+
return change(key, (inbox, state) => {
|
|
230
|
+
if (inbox.hold !== hold)
|
|
231
|
+
return 'lost';
|
|
232
|
+
if (String(state.inbox?.version ?? 0) !== version)
|
|
233
|
+
return 'moved';
|
|
234
|
+
delete inbox.hold;
|
|
235
|
+
inbox.leasedUntil = 0;
|
|
236
|
+
return 'released';
|
|
237
|
+
});
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
@@ -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). */
|
|
@@ -28,6 +35,8 @@ export type PausedReply = {
|
|
|
28
35
|
model?: string;
|
|
29
36
|
effort?: string;
|
|
30
37
|
stated?: StatedTurn;
|
|
38
|
+
/** The reply's id under its chat's hold, so the reply that goes on after its gates resumes what it read. */
|
|
39
|
+
reply?: string;
|
|
31
40
|
};
|
|
32
41
|
/** One conversation as the host stores it. */
|
|
33
42
|
export type StoredConversation = {
|
|
@@ -18,11 +18,18 @@ const pausedReply = z.object({
|
|
|
18
18
|
events: z.array(turnEventSchema),
|
|
19
19
|
base: z.array(turnHistoryMessageSchema),
|
|
20
20
|
baseEvents: z.number().int().nonnegative(),
|
|
21
|
+
uncompacted: z
|
|
22
|
+
.object({
|
|
23
|
+
base: z.array(turnHistoryMessageSchema),
|
|
24
|
+
baseEvents: z.number().int().nonnegative(),
|
|
25
|
+
})
|
|
26
|
+
.optional(),
|
|
21
27
|
workedMs: z.number().nonnegative(),
|
|
22
28
|
endedAt: z.number(),
|
|
23
29
|
model: z.string().optional(),
|
|
24
30
|
effort: z.string().optional(),
|
|
25
31
|
stated: statedTurnSchema.optional(),
|
|
32
|
+
reply: z.string().min(1).optional(),
|
|
26
33
|
});
|
|
27
34
|
true;
|
|
28
35
|
const storedConversation = z.object({
|
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));
|
|
@@ -214,17 +189,32 @@ function pausedOn(conversation, reply, runner) {
|
|
|
214
189
|
events: reply.events,
|
|
215
190
|
base: reply.base,
|
|
216
191
|
baseEvents: reply.baseEvents,
|
|
192
|
+
...(reply.uncompacted ? { uncompacted: reply.uncompacted } : {}),
|
|
217
193
|
workedMs: reply.workedMs,
|
|
218
194
|
endedAt: Date.now(),
|
|
219
195
|
...(runner.model ? { model: runner.model } : {}),
|
|
220
196
|
...(runner.effort ? { effort: runner.effort } : {}),
|
|
221
197
|
...(runner.stated ? { stated: runner.stated } : {}),
|
|
198
|
+
...(runner.reply ? { reply: runner.reply } : {}),
|
|
222
199
|
};
|
|
223
200
|
return { ...conversation, ...metered(conversation, reply.events), paused };
|
|
224
201
|
}
|
|
225
|
-
/**
|
|
202
|
+
/**
|
|
203
|
+
* The reply failed: it commits as far as it got, closed by its error. The late results it read
|
|
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.
|
|
206
|
+
*/
|
|
226
207
|
function failed(host, conversation, reply, failure) {
|
|
227
|
-
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);
|
|
212
|
+
const next = committed(host, conversation, {
|
|
213
|
+
base: from.base,
|
|
214
|
+
events,
|
|
215
|
+
baseEvents: unread(reply.events.slice(0, from.baseEvents)).length,
|
|
216
|
+
workedMs: reply.workedMs,
|
|
217
|
+
});
|
|
228
218
|
if (next.transcript.slice(conversation.transcript.length).some((b) => b.kind === 'error')) {
|
|
229
219
|
return next;
|
|
230
220
|
}
|
|
@@ -252,8 +242,9 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
|
|
|
252
242
|
const { conversation } = opened;
|
|
253
243
|
const startedAt = Date.now();
|
|
254
244
|
const worked = () => ({ ...reply, workedMs: reply.workedMs + (Date.now() - startedAt) });
|
|
245
|
+
// invariant: A reply whose hold lost its chat saves nothing; the hold that has it tells what this one read.
|
|
246
|
+
const held = async () => !runner.held || (await runner.held());
|
|
255
247
|
let errorEvent;
|
|
256
|
-
let current = opened;
|
|
257
248
|
try {
|
|
258
249
|
const events = runner.run({
|
|
259
250
|
input,
|
|
@@ -263,8 +254,6 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
|
|
|
263
254
|
effort: runner.effort,
|
|
264
255
|
...(runner.stated ? { stated: runner.stated } : {}),
|
|
265
256
|
...(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
257
|
});
|
|
269
258
|
for await (const event of events) {
|
|
270
259
|
reply.events.push(event);
|
|
@@ -274,6 +263,10 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
|
|
|
274
263
|
continue;
|
|
275
264
|
}
|
|
276
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
|
+
}
|
|
277
270
|
reply.base = withMessage(event.history);
|
|
278
271
|
reply.baseEvents = reply.events.length;
|
|
279
272
|
}
|
|
@@ -281,37 +274,40 @@ async function* runReply(host, opened, reply, runner, input, withMessage) {
|
|
|
281
274
|
}
|
|
282
275
|
}
|
|
283
276
|
catch (err) {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
277
|
+
if (await held()) {
|
|
278
|
+
const written = await save(host, opened, runner.signal.aborted
|
|
279
|
+
? stopped(host, conversation, worked())
|
|
280
|
+
: failed(host, conversation, worked(), toErrorEvent(err)));
|
|
281
|
+
yield* refLine(written);
|
|
282
|
+
}
|
|
288
283
|
// why: A stopped reply is no failure; the browser draws what it left from the ref.
|
|
289
284
|
if (!runner.signal.aborted)
|
|
290
285
|
throw err;
|
|
291
286
|
return;
|
|
292
287
|
}
|
|
293
288
|
const settled = worked();
|
|
289
|
+
if (!(await held()))
|
|
290
|
+
return;
|
|
294
291
|
if (runner.signal.aborted) {
|
|
295
|
-
|
|
292
|
+
yield* refLine(await save(host, opened, stopped(host, conversation, settled)));
|
|
296
293
|
}
|
|
297
294
|
else if (errorEvent) {
|
|
298
|
-
|
|
295
|
+
yield* refLine(await save(host, opened, failed(host, conversation, settled, errorEvent)));
|
|
296
|
+
yield errorEvent;
|
|
299
297
|
}
|
|
300
298
|
else if (gatedToolsFromEvents(settled.events).length) {
|
|
301
|
-
|
|
299
|
+
yield* refLine(await save(host, opened, pausedOn(conversation, settled, runner)));
|
|
302
300
|
}
|
|
303
301
|
else {
|
|
304
|
-
current = await save(host,
|
|
302
|
+
const current = await save(host, opened, committed(host, conversation, settled));
|
|
305
303
|
yield* refLine(current);
|
|
306
304
|
// why: The reply is the browser's before compaction runs, so a failed compaction loses none of it.
|
|
305
|
+
if (!(await held()))
|
|
306
|
+
return;
|
|
307
307
|
const compacted = await compactedAfter(host, current, settled, runner, withMessage);
|
|
308
308
|
if (compacted)
|
|
309
309
|
yield* refLine(compacted);
|
|
310
|
-
return;
|
|
311
310
|
}
|
|
312
|
-
yield* refLine(current);
|
|
313
|
-
if (errorEvent)
|
|
314
|
-
yield errorEvent;
|
|
315
311
|
}
|
|
316
312
|
/**
|
|
317
313
|
* The profile compacts after a reply (`done.compaction.needed`): the history
|
|
@@ -422,6 +418,7 @@ function pausedReply(paused) {
|
|
|
422
418
|
base: paused.base,
|
|
423
419
|
events: [...paused.events],
|
|
424
420
|
baseEvents: paused.baseEvents,
|
|
421
|
+
...(paused.uncompacted ? { uncompacted: paused.uncompacted } : {}),
|
|
425
422
|
workedMs: paused.workedMs,
|
|
426
423
|
};
|
|
427
424
|
}
|
|
@@ -455,14 +452,27 @@ export async function* messageReply(args) {
|
|
|
455
452
|
}
|
|
456
453
|
opened = { ...opened, conversation: committed(host, opened.conversation, walked) };
|
|
457
454
|
}
|
|
458
|
-
const { conversation } = opened;
|
|
459
455
|
const withMessage = (history) => appendUserDraftToHistory(history, message.draft, message.media);
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
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;
|
|
466
476
|
yield* refLine(opened, 'posted');
|
|
467
477
|
const reply = {
|
|
468
478
|
base: withMessage(conversation.history),
|
|
@@ -472,6 +482,22 @@ export async function* messageReply(args) {
|
|
|
472
482
|
};
|
|
473
483
|
yield* runReply(host, opened, reply, runner, { ...message.input, ...historyInput(conversation) }, withMessage);
|
|
474
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
|
+
}
|
|
475
501
|
/** The conversation's history as a run reads it, with its meters. */
|
|
476
502
|
function historyInput(conversation) {
|
|
477
503
|
return {
|
|
@@ -526,6 +552,8 @@ export async function* answerReply(args) {
|
|
|
526
552
|
// why: An answer that failed before its call settled leaves the reply as it was, to answer again.
|
|
527
553
|
const settledCall = reply.events.some((event) => settlesToolCall(event, args.call.callId));
|
|
528
554
|
const events = error && !settledCall ? paused.events : reply.events;
|
|
555
|
+
if (runner.held && !(await runner.held()))
|
|
556
|
+
return;
|
|
529
557
|
opened = await save(host, opened, {
|
|
530
558
|
...opened.conversation,
|
|
531
559
|
paused: { ...paused, events, workedMs: reply.workedMs, endedAt: Date.now() },
|