@theoremjs/web 0.3.4 → 0.3.5-next.1001.g68d8dcf
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +330 -13
- package/client/chat.d.ts +14 -2
- package/client/chat.js +302 -34
- package/client/composer-hints.d.ts +18 -10
- package/client/composer-hints.js +23 -6
- package/client/host-transport.d.ts +7 -2
- package/client/host-transport.js +9 -3
- package/client/index.d.ts +4 -4
- package/client/index.js +3 -3
- package/client/page-dispatch.js +5 -0
- package/client/run-session.d.ts +27 -2
- package/client/run-session.js +34 -4
- package/client/schema-fields.d.ts +28 -1
- package/client/schema-fields.js +172 -13
- package/client/tool-result.d.ts +9 -5
- package/client/tool-result.js +23 -42
- package/client/transcript-schema.d.ts +4 -0
- package/client/transcript-schema.js +25 -6
- package/client/transport.d.ts +90 -9
- package/client/transport.js +56 -11
- package/client/turn-client.d.ts +8 -2
- package/client/turn-client.js +9 -0
- package/package.json +2 -2
- package/server/conversation-core.d.ts +273 -0
- package/server/conversation-core.js +797 -0
- package/server/conversation-inbox.d.ts +45 -0
- package/server/conversation-inbox.js +240 -0
- package/server/conversation-store.d.ts +43 -2
- package/server/conversation-store.js +15 -2
- package/server/conversation.d.ts +82 -2
- package/server/conversation.js +357 -60
- package/server/create-conversation-core.d.ts +28 -0
- package/server/create-conversation-core.js +46 -0
- package/server/embedding-handler.js +2 -0
- package/server/handler.d.ts +84 -20
- package/server/handler.js +279 -659
- package/server/mcp-handler.js +25 -11
- package/server/mod.d.ts +11 -4
- package/server/mod.js +6 -2
- package/server/notifier.d.ts +3 -2
- package/server/notifier.js +3 -2
- package/server/session-authority.d.ts +3 -1
- package/server/session-authority.js +26 -1
- package/server/session-boundary.d.ts +5 -3
- package/server/session-boundary.js +2 -2
- package/server/session-calls.d.ts +122 -0
- package/server/session-calls.js +512 -0
- package/server/session-store.d.ts +33 -0
- package/server/session-store.js +37 -2
- package/server/steer-inbox.d.ts +3 -4
- package/server/steer-inbox.js +6 -5
- package/server/tell-every-result.d.ts +11 -0
- package/server/tell-every-result.js +17 -0
- package/server/tool-operations.d.ts +8 -0
- package/server/tool-operations.js +71 -0
- package/server/turn-input.d.ts +4 -2
- package/server/turn-input.js +5 -2
- package/server/turn-wiring.d.ts +31 -6
- package/server/turn-wiring.js +59 -5
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A session's tool calls, with no `Request`: each call recorded in the session, its gates saved
|
|
3
|
+
* as they pause, an answered call run on, and a background call announced as it ends. The HTTP
|
|
4
|
+
* handlers and the conversation core both run their calls through here.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import { authorizeToolReplay, defaultKernelScope, invokeTool, jsonObjectSchema, labelText, registerProfile, TheoremError, toolInvocationHash, } from '@theoremjs/agents';
|
|
9
|
+
import { withPublicLabels } from '@theoremjs/agents/guardrails';
|
|
10
|
+
import { gatedToolsFromEvents, promotedToolIdsFromEvents, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
|
|
11
|
+
import { answerGatedCall, isSealedSource, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
|
|
12
|
+
import { requiredOperationId, waitingCalls } from "./conversation.js";
|
|
13
|
+
import { detachedEnd } from "./conversation-inbox.js";
|
|
14
|
+
import { createMemoryCredentialStore, } from "./credential-store.js";
|
|
15
|
+
import { checkPageToolTimeout, createMemoryPageToolBroker, sessionPageDispatch, } from "./page-dispatch.js";
|
|
16
|
+
import { lockedStore, sessionStateStore, } from "./session-authority.js";
|
|
17
|
+
import { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, } from "./session-store.js";
|
|
18
|
+
import { sameAcceptedAnswer, sessionToolCoordinator } from "./tool-operations.js";
|
|
19
|
+
import { isRefusal, preparedTurn } from "./turn-wiring.js";
|
|
20
|
+
/**
|
|
21
|
+
* The profile, registered, and the session's stores as its calls read them. `name` is the
|
|
22
|
+
* function the app called, for the error a wrong option throws.
|
|
23
|
+
*/
|
|
24
|
+
export function sessionParts(name, profile, options) {
|
|
25
|
+
const gateTtlMs = resolveGateTtlMs(name, options.gateTtlMs);
|
|
26
|
+
const operationRetentionMs = options.operationRetentionMs ?? DEFAULT_OPERATION_RETENTION_MS;
|
|
27
|
+
if (!Number.isSafeInteger(operationRetentionMs) || operationRetentionMs <= 0) {
|
|
28
|
+
throw new TheoremError('config', labelText('error.config'), {
|
|
29
|
+
cause: { code: 'operation_retention' },
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
checkPageToolTimeout(options.pageToolTimeoutMs);
|
|
33
|
+
const retryMs = options.notifyRetryMs;
|
|
34
|
+
if (retryMs !== undefined && !(Number.isFinite(retryMs) && retryMs >= 0)) {
|
|
35
|
+
throw new TheoremError('config', labelText('error.config'), {
|
|
36
|
+
cause: { code: 'notify_retry' },
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
registerProfile(profile);
|
|
40
|
+
return {
|
|
41
|
+
profile,
|
|
42
|
+
pageToolBroker: options.pageToolBroker ?? createMemoryPageToolBroker(),
|
|
43
|
+
sessions: sessionStateStore(options.sessionStore ?? createMemorySessionStore(), gateTtlMs, operationRetentionMs),
|
|
44
|
+
credentials: lockedStore(options.credentialStore ?? createMemoryCredentialStore(), (saved = {}) => saved),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** The exact paused calls the user may now approve, when the stream stopped on gates. */
|
|
48
|
+
function pendingGatesFrom(events, context) {
|
|
49
|
+
return gatedToolsFromEvents(events).map((gated) => ({
|
|
50
|
+
callId: gated.callId,
|
|
51
|
+
gate: {
|
|
52
|
+
profileId: context.profileId,
|
|
53
|
+
operationId: requiredOperationId(gated),
|
|
54
|
+
callId: gated.callId,
|
|
55
|
+
name: gated.name,
|
|
56
|
+
arguments: gated.arguments,
|
|
57
|
+
gate: {
|
|
58
|
+
kind: gated.gateKind,
|
|
59
|
+
permission: gated.permission,
|
|
60
|
+
...(gated.auth ? { auth: gated.auth } : {}),
|
|
61
|
+
},
|
|
62
|
+
snapshot: toolSnapshotFromEvents(events),
|
|
63
|
+
promoted: [...new Set([...(context.promoted ?? []), ...promotedToolIdsFromEvents(events)])],
|
|
64
|
+
turnInput: context.turnInput,
|
|
65
|
+
model: context.model,
|
|
66
|
+
createdAt: Date.now(),
|
|
67
|
+
},
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
/** When the stream paused on gates, record the exact calls the user may now approve. */
|
|
71
|
+
async function recordOutcome(sessions, sessionId, events, context) {
|
|
72
|
+
const pending = pendingGatesFrom(events, context);
|
|
73
|
+
if (!pending.length)
|
|
74
|
+
return;
|
|
75
|
+
await sessions.mutate(sessionId, (state) => {
|
|
76
|
+
for (const { gate } of pending) {
|
|
77
|
+
const operation = state.operations[gate.operationId];
|
|
78
|
+
if (operation && operation.status !== 'ready')
|
|
79
|
+
throw new TheoremError('unavailable', `Tool operation ${gate.operationId} is ${operation.status}, not ready, so its gate was not saved`, // labels-exempt: internal diagnostic; the user reads session.busy
|
|
80
|
+
{ copy: { key: 'session.busy' } });
|
|
81
|
+
delete state.operations[gate.operationId];
|
|
82
|
+
Object.defineProperty(state.gates, gate.operationId, {
|
|
83
|
+
value: gate,
|
|
84
|
+
writable: true,
|
|
85
|
+
enumerable: true,
|
|
86
|
+
configurable: true,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
export async function* recorded(sessions, sessionId, events, context, seed = []) {
|
|
92
|
+
const seen = [...seed];
|
|
93
|
+
for await (const event of events) {
|
|
94
|
+
seen.push(event);
|
|
95
|
+
if (event.type === 'done' || event.type === 'provider_checkpoint')
|
|
96
|
+
await recordOutcome(sessions, sessionId, seen, context);
|
|
97
|
+
yield event;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Save one credential, leaving the session's others as they are. */
|
|
101
|
+
function saveCredential(ctx, sessionId, slot, credential) {
|
|
102
|
+
return ctx.credentials.mutate(sessionId, (saved) => {
|
|
103
|
+
saved[slot] = credential;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The session's credentials as a call reads them: one slot when a tool needs it,
|
|
108
|
+
* saved the moment the kernel sets one, so a rotated refresh token is never lost
|
|
109
|
+
* to a closed stream.
|
|
110
|
+
*/
|
|
111
|
+
export function sessionCredentials(ctx, sessionId) {
|
|
112
|
+
return {
|
|
113
|
+
get: async (slot) => (await ctx.credentials.read(sessionId))[slot],
|
|
114
|
+
set: (slot, credential) => saveCredential(ctx, sessionId, slot, credential),
|
|
115
|
+
delete: (slot) => ctx.credentials.mutate(sessionId, (saved) => {
|
|
116
|
+
delete saved[slot];
|
|
117
|
+
}),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** An OAuth gate given the host's sign-in URL. */
|
|
121
|
+
async function withAuthorizationUrl(ctx, at, event) {
|
|
122
|
+
if (event.type !== 'tool' || event.tool.phase !== 'gate')
|
|
123
|
+
return event;
|
|
124
|
+
const { tool } = event;
|
|
125
|
+
const gate = tool.gate.kind === 'auth' ? tool.gate : undefined;
|
|
126
|
+
if (gate?.authChallenge.authType !== 'oauth2' || !ctx.options.authorizationUrl)
|
|
127
|
+
return event;
|
|
128
|
+
const challenge = gate.authChallenge;
|
|
129
|
+
const authorizationUrl = await ctx.options.authorizationUrl(challenge, at);
|
|
130
|
+
return {
|
|
131
|
+
...event,
|
|
132
|
+
tool: { ...tool, gate: { ...gate, authChallenge: { ...challenge, authorizationUrl } } },
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Every OAuth gate in the stream, given the host's sign-in URL. */
|
|
136
|
+
export async function* withAuthorizationUrls(ctx, at, events) {
|
|
137
|
+
for await (const event of events)
|
|
138
|
+
yield await withAuthorizationUrl(ctx, at, event);
|
|
139
|
+
}
|
|
140
|
+
function answerPendingGate(state, request, profileId) {
|
|
141
|
+
const operation = Object.hasOwn(state.operations, request.operationId)
|
|
142
|
+
? state.operations[request.operationId]
|
|
143
|
+
: undefined;
|
|
144
|
+
if (operation?.status === 'ready' &&
|
|
145
|
+
operation.profileId === profileId &&
|
|
146
|
+
operation.pending.callId === request.callId) {
|
|
147
|
+
const accepted = answerGatedCall(request, {
|
|
148
|
+
name: operation.pending.name,
|
|
149
|
+
arguments: operation.pending.arguments,
|
|
150
|
+
permission: operation.pending.gate.permission,
|
|
151
|
+
gateKind: operation.pending.gate.kind,
|
|
152
|
+
...(operation.pending.gate.kind === 'auth' && operation.pending.gate.auth
|
|
153
|
+
? { auth: operation.pending.gate.auth }
|
|
154
|
+
: {}),
|
|
155
|
+
}, operation.answer.sessionPermissions);
|
|
156
|
+
const { typed: _typed, ...plain } = accepted;
|
|
157
|
+
if (!sameAcceptedAnswer(plain, operation.answer))
|
|
158
|
+
throw new TheoremError('request', labelText('error.request'));
|
|
159
|
+
return {
|
|
160
|
+
callId: request.callId,
|
|
161
|
+
pending: operation.pending,
|
|
162
|
+
answer: { ...operation.answer, ...(accepted.typed ? { typed: accepted.typed } : {}) },
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
const pending = Object.hasOwn(state.gates, request.operationId)
|
|
166
|
+
? state.gates[request.operationId]
|
|
167
|
+
: undefined;
|
|
168
|
+
if (!pending || pending.profileId !== profileId || pending.callId !== request.callId) {
|
|
169
|
+
throw new TheoremError('request', labelText('session.gate_expired'), {
|
|
170
|
+
copy: { key: 'session.gate_expired' },
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
// why: A refused answer (a refused secret, an edit without an approval) throws here and leaves the gate pending.
|
|
174
|
+
const answer = answerGatedCall(request, {
|
|
175
|
+
name: pending.name,
|
|
176
|
+
arguments: pending.arguments,
|
|
177
|
+
permission: pending.gate.permission,
|
|
178
|
+
gateKind: pending.gate.kind,
|
|
179
|
+
...(pending.gate.kind === 'auth' && pending.gate.auth ? { auth: pending.gate.auth } : {}),
|
|
180
|
+
}, state.permissions);
|
|
181
|
+
delete state.gates[request.operationId];
|
|
182
|
+
const { typed: _typed, ...accepted } = answer;
|
|
183
|
+
state.operations[request.operationId] = {
|
|
184
|
+
status: 'ready',
|
|
185
|
+
profileId,
|
|
186
|
+
pending,
|
|
187
|
+
answer: accepted,
|
|
188
|
+
readyAt: Date.now(),
|
|
189
|
+
};
|
|
190
|
+
state.permissions = answer.sessionPermissions;
|
|
191
|
+
return { callId: request.callId, pending, answer };
|
|
192
|
+
}
|
|
193
|
+
function walkedCallOf(state, reference, profileId, paused, cause = 'abandoned') {
|
|
194
|
+
const settled = Object.hasOwn(state.operations, reference.operationId)
|
|
195
|
+
? state.operations[reference.operationId]
|
|
196
|
+
: undefined;
|
|
197
|
+
// why: A wake that took the call and ended before the call settled left it refused and not run; the next wake runs it with the answer it has.
|
|
198
|
+
if (cause === 'expired' && settled && refusedAndNotRun(settled, reference, profileId)) {
|
|
199
|
+
return { callId: reference.callId, pending: settled.pending, answer: settled.answer };
|
|
200
|
+
}
|
|
201
|
+
// why: A gate that lapsed is gone from the session while the reply still waits on its call. The call is only ever cancelled here, so the next message is never refused for it.
|
|
202
|
+
if (!settled && !Object.hasOwn(state.gates, reference.operationId)) {
|
|
203
|
+
const lapsed = pendingGatesFrom(paused, { profileId, turnInput: {} }).find(({ callId }) => callId === reference.callId);
|
|
204
|
+
if (lapsed)
|
|
205
|
+
state.gates[reference.operationId] = lapsed.gate;
|
|
206
|
+
}
|
|
207
|
+
if (settled?.status === 'settled' &&
|
|
208
|
+
settled.callId === reference.callId &&
|
|
209
|
+
settled.profileId === profileId) {
|
|
210
|
+
return { callId: reference.callId, settled };
|
|
211
|
+
}
|
|
212
|
+
const answered = answerPendingGate(state, { ...reference, decision: 'abandon' }, profileId);
|
|
213
|
+
if (cause === 'abandoned')
|
|
214
|
+
return answered;
|
|
215
|
+
const answer = { ...answered.answer, resume: { ...answered.answer.resume, cause } };
|
|
216
|
+
const taken = state.operations[reference.operationId];
|
|
217
|
+
if (taken?.status === 'ready')
|
|
218
|
+
taken.answer = answer;
|
|
219
|
+
return { ...answered, answer };
|
|
220
|
+
}
|
|
221
|
+
/** Whether `operation` is this call, answered with a refusal and not yet run. */
|
|
222
|
+
function refusedAndNotRun(operation, reference, profileId) {
|
|
223
|
+
return (operation.status === 'ready' &&
|
|
224
|
+
operation.profileId === profileId &&
|
|
225
|
+
operation.pending.callId === reference.callId &&
|
|
226
|
+
operation.answer.resume.granted !== true);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* What a paused reply's calls still wait on, for a reply to no message. Defined while a call's
|
|
230
|
+
* gate can be answered, or its answer runs; `until` is when the last gate lapses, unset when one
|
|
231
|
+
* has no time limit or an answer runs. Undefined once every gate has lapsed, and for a
|
|
232
|
+
* conversation that is not paused.
|
|
233
|
+
*/
|
|
234
|
+
function stillWaits(state, calls, profileId) {
|
|
235
|
+
let waits = false;
|
|
236
|
+
let until = 0;
|
|
237
|
+
for (const reference of calls) {
|
|
238
|
+
const gate = Object.hasOwn(state.gates, reference.operationId)
|
|
239
|
+
? state.gates[reference.operationId]
|
|
240
|
+
: undefined;
|
|
241
|
+
const operation = Object.hasOwn(state.operations, reference.operationId)
|
|
242
|
+
? state.operations[reference.operationId]
|
|
243
|
+
: undefined;
|
|
244
|
+
const runs = operation !== undefined &&
|
|
245
|
+
operation.status !== 'settled' &&
|
|
246
|
+
!refusedAndNotRun(operation, reference, profileId);
|
|
247
|
+
if (!gate && !runs)
|
|
248
|
+
continue;
|
|
249
|
+
waits = true;
|
|
250
|
+
until =
|
|
251
|
+
gate?.expiresAt === undefined || until === undefined || runs
|
|
252
|
+
? undefined
|
|
253
|
+
: Math.max(until, gate.expiresAt);
|
|
254
|
+
}
|
|
255
|
+
return waits ? (until === undefined ? {} : { until }) : undefined;
|
|
256
|
+
}
|
|
257
|
+
/** {@link stillWaits} for `conversation`'s paused reply, read from the session. Writes nothing. */
|
|
258
|
+
export async function pausedWaits(ctx, at, conversation) {
|
|
259
|
+
const calls = waitingCalls(conversation);
|
|
260
|
+
if (!calls.length)
|
|
261
|
+
return undefined;
|
|
262
|
+
return stillWaits(await ctx.sessions.read(at.sessionId), calls, ctx.profile.id);
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Take the calls of a paused reply whose gates have all lapsed out of the session, each settled
|
|
266
|
+
* as `expired`. Undefined, with nothing taken, while one still waits ({@link stillWaits}).
|
|
267
|
+
*/
|
|
268
|
+
export async function takeLapsed(ctx, at, conversation) {
|
|
269
|
+
const references = waitingCalls(conversation);
|
|
270
|
+
const paused = conversation.paused?.events ?? [];
|
|
271
|
+
// why: One write decides and takes, so an answer that lands meanwhile is never walked away from.
|
|
272
|
+
const calls = await ctx.sessions.mutate(at.sessionId, (state) => stillWaits(state, references, ctx.profile.id)
|
|
273
|
+
? undefined
|
|
274
|
+
: references.map((reference) => ({
|
|
275
|
+
reference,
|
|
276
|
+
call: walkedCallOf(state, reference, ctx.profile.id, paused, 'expired'),
|
|
277
|
+
})));
|
|
278
|
+
return calls?.map((taken) => issuedWalkAway(ctx, at, taken));
|
|
279
|
+
}
|
|
280
|
+
/** A taken call with the run that settles it. */
|
|
281
|
+
function issuedWalkAway(ctx, at, { reference, call }) {
|
|
282
|
+
return {
|
|
283
|
+
...reference,
|
|
284
|
+
events: 'settled' in call ? replayOperation(ctx, at, call.settled) : settleAnswered(ctx, at, call),
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Take the calls a message or a rewind walks away from out of the session,
|
|
289
|
+
* answered `abandon`: every one of them, or none when one is neither waiting
|
|
290
|
+
* nor settled. Each comes back with the run that settles it.
|
|
291
|
+
*/
|
|
292
|
+
export async function takeWalkedAway(ctx, at, abandon, conversation) {
|
|
293
|
+
const paused = conversation.paused?.events ?? [];
|
|
294
|
+
// why: A throw leaves the session unsaved, so no call is taken unless all are.
|
|
295
|
+
const calls = await ctx.sessions.mutate(at.sessionId, (state) => abandon.map((reference) => ({
|
|
296
|
+
reference,
|
|
297
|
+
call: walkedCallOf(state, reference, ctx.profile.id, paused),
|
|
298
|
+
})));
|
|
299
|
+
return calls.map((taken) => issuedWalkAway(ctx, at, taken));
|
|
300
|
+
}
|
|
301
|
+
async function* settleAnswered(ctx, at, answered) {
|
|
302
|
+
yield* invokeAnswered(ctx, at, answered);
|
|
303
|
+
}
|
|
304
|
+
async function* invokeAnswered(ctx, at, { callId, pending, answer }) {
|
|
305
|
+
const host = await at.host;
|
|
306
|
+
// why: The held call goes on with what the application set for its turn: its context, stage handler and credentials.
|
|
307
|
+
const prepared = await preparedTurn(ctx.options.prepare, {
|
|
308
|
+
profile: ctx.profile.id,
|
|
309
|
+
execution: sessionToolCoordinator(ctx.sessions, at.sessionId),
|
|
310
|
+
...backgroundWiring(ctx, at),
|
|
311
|
+
input: pending.turnInput ?? {},
|
|
312
|
+
host,
|
|
313
|
+
signal: at.signal,
|
|
314
|
+
answersHeldCall: true,
|
|
315
|
+
}, {
|
|
316
|
+
credentials: sessionCredentials(ctx, at.sessionId),
|
|
317
|
+
...(ctx.options.onStage ? { onStage: ctx.options.onStage } : {}),
|
|
318
|
+
announce: (service) => announced(ctx, at, service),
|
|
319
|
+
});
|
|
320
|
+
if (isRefusal(prepared)) {
|
|
321
|
+
// labels-exempt: builder config error; the user reads error.config
|
|
322
|
+
throw new TheoremError('config', '`prepare` refused a turn that has `answersHeldCall`: an answered call has no reply to refuse');
|
|
323
|
+
}
|
|
324
|
+
if (answer.typed) {
|
|
325
|
+
// invariant: a sealed source keeps every key where the run cannot read it, so a key typed
|
|
326
|
+
// here would be saved and never sent; the person enters it where the keys are kept.
|
|
327
|
+
if (prepared.credentials && isSealedSource(prepared.credentials)) {
|
|
328
|
+
throw new TheoremError('request', `call ${callId} runs with a sealed credential source, which takes no typed secret`);
|
|
329
|
+
}
|
|
330
|
+
await saveCredential(ctx, at.sessionId, answer.typed.slot, answer.typed.credential);
|
|
331
|
+
}
|
|
332
|
+
yield* invokeTool({
|
|
333
|
+
profile: ctx.profile.id,
|
|
334
|
+
...(prepared.execution ? { execution: prepared.execution } : {}),
|
|
335
|
+
...(prepared.background ? { background: prepared.background } : {}),
|
|
336
|
+
pageExecution: sessionPageDispatch(ctx.sessions, at.sessionId, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
|
|
337
|
+
name: pending.name,
|
|
338
|
+
callId,
|
|
339
|
+
operationId: pending.operationId,
|
|
340
|
+
input: answer.input,
|
|
341
|
+
resume: answer.resume,
|
|
342
|
+
// why: An approval that names no answer is the page saying it has none, so the call is not held again.
|
|
343
|
+
...(pending.gate.kind === 'page' && answer.resume.granted
|
|
344
|
+
? { page: answer.page ?? { unanswered: true } }
|
|
345
|
+
: {}),
|
|
346
|
+
sessionPermissions: answer.sessionPermissions,
|
|
347
|
+
credentials: prepared.credentials,
|
|
348
|
+
...(prepared.onStage ? { onStage: prepared.onStage } : {}),
|
|
349
|
+
turnInput: pending.turnInput,
|
|
350
|
+
snapshot: pending.snapshot,
|
|
351
|
+
promoted: pending.promoted,
|
|
352
|
+
model: pending.model,
|
|
353
|
+
signal: at.signal,
|
|
354
|
+
host: prepared.host,
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
/** The host's service for a call in this session, for a request that runs a tool. */
|
|
358
|
+
export function backgroundWiring(ctx, at) {
|
|
359
|
+
const service = ctx.options.background?.(at);
|
|
360
|
+
return service ? { background: announced(ctx, at, service) } : {};
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* `service`, telling the session's open pages when each of its calls ends, and the decider's
|
|
364
|
+
* `ended`, with the wake and the notify it may use.
|
|
365
|
+
*/
|
|
366
|
+
export function announced(ctx, at, service) {
|
|
367
|
+
const { notifier, lateResultsDecider } = ctx.options;
|
|
368
|
+
const ended = lateResultsDecider?.ended?.bind(lateResultsDecider);
|
|
369
|
+
if (!notifier && !ended)
|
|
370
|
+
return service;
|
|
371
|
+
const notify = async () => {
|
|
372
|
+
await notifier?.publish(at.sessionId);
|
|
373
|
+
};
|
|
374
|
+
return {
|
|
375
|
+
detached(call) {
|
|
376
|
+
service.detached(call);
|
|
377
|
+
void call.done
|
|
378
|
+
.then(async () => {
|
|
379
|
+
await notify();
|
|
380
|
+
if (!ended)
|
|
381
|
+
return;
|
|
382
|
+
const { operations } = await ctx.sessions.read(at.sessionId);
|
|
383
|
+
const { operationId, callId, toolId } = call;
|
|
384
|
+
const operation = Object.hasOwn(operations, operationId)
|
|
385
|
+
? operations[operationId]
|
|
386
|
+
: undefined;
|
|
387
|
+
const outcome = detachedEnd({ operationId, callId, name: toolId, at: Date.now() }, operation, ctx.profile.labels);
|
|
388
|
+
if (!outcome)
|
|
389
|
+
return;
|
|
390
|
+
await ended({
|
|
391
|
+
host: await at.host,
|
|
392
|
+
result: { operationId, outcome },
|
|
393
|
+
wake: (conversation) => ctx.options.wake(at, conversation),
|
|
394
|
+
notify,
|
|
395
|
+
});
|
|
396
|
+
})
|
|
397
|
+
.catch((err) => ctx.options.onError?.(err, at));
|
|
398
|
+
},
|
|
399
|
+
event: (event, call) => service.event(event, call),
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
/** A settled call's answer, streamed again. */
|
|
403
|
+
async function* once(event, labels) {
|
|
404
|
+
yield withPublicLabels(event, labels);
|
|
405
|
+
}
|
|
406
|
+
/** Whether this request may read a settled call's result: the host's `authorizeToolReplay`. */
|
|
407
|
+
export async function replayAllowed(ctx, at, operation) {
|
|
408
|
+
const { authorizeToolReplay } = ctx.options;
|
|
409
|
+
return !authorizeToolReplay || (await authorizeToolReplay(at, operation));
|
|
410
|
+
}
|
|
411
|
+
async function* invokeEvents(ctx, at, answered) {
|
|
412
|
+
const events = settleAnswered(ctx, at, answered);
|
|
413
|
+
const { pending, answer } = answered;
|
|
414
|
+
yield* recorded(ctx.sessions, at.sessionId, withAuthorizationUrls(ctx, at, events), {
|
|
415
|
+
profileId: ctx.profile.id,
|
|
416
|
+
turnInput: pending.turnInput,
|
|
417
|
+
model: pending.model,
|
|
418
|
+
promoted: pending.promoted,
|
|
419
|
+
}, [
|
|
420
|
+
{
|
|
421
|
+
type: 'tool',
|
|
422
|
+
tool: {
|
|
423
|
+
name: pending.name,
|
|
424
|
+
callId: pending.callId,
|
|
425
|
+
operationId: pending.operationId,
|
|
426
|
+
arguments: jsonObjectSchema.parse(answer.input),
|
|
427
|
+
},
|
|
428
|
+
},
|
|
429
|
+
]);
|
|
430
|
+
}
|
|
431
|
+
/** One call of one of a host's tools, run as the page asked it; a gate it pauses on waits in the session. */
|
|
432
|
+
export async function* callEvents(ctx, at, body) {
|
|
433
|
+
const state = await ctx.sessions.read(at.sessionId);
|
|
434
|
+
const host = await at.host;
|
|
435
|
+
const events = invokeTool({
|
|
436
|
+
profile: ctx.profile.id,
|
|
437
|
+
execution: sessionToolCoordinator(ctx.sessions, at.sessionId),
|
|
438
|
+
...backgroundWiring(ctx, at),
|
|
439
|
+
pageExecution: sessionPageDispatch(ctx.sessions, at.sessionId, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
|
|
440
|
+
name: body.name,
|
|
441
|
+
input: body.input,
|
|
442
|
+
sessionPermissions: state.permissions,
|
|
443
|
+
credentials: sessionCredentials(ctx, at.sessionId),
|
|
444
|
+
...(ctx.options.onStage ? { onStage: ctx.options.onStage } : {}),
|
|
445
|
+
signal: at.signal,
|
|
446
|
+
host,
|
|
447
|
+
});
|
|
448
|
+
yield* recorded(ctx.sessions, at.sessionId, withAuthorizationUrls(ctx, at, events), {
|
|
449
|
+
profileId: ctx.profile.id,
|
|
450
|
+
turnInput: {},
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
function answerRequest(body) {
|
|
454
|
+
return {
|
|
455
|
+
callId: body.gateId,
|
|
456
|
+
operationId: body.operationId,
|
|
457
|
+
decision: body.decision,
|
|
458
|
+
input: body.input,
|
|
459
|
+
secret: body.secret,
|
|
460
|
+
page: body.page,
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
async function* replayOperation(ctx, at, operation) {
|
|
464
|
+
const tool = defaultKernelScope.tools.get(operation.toolId);
|
|
465
|
+
if (operation.profileId !== ctx.profile.id ||
|
|
466
|
+
!tool ||
|
|
467
|
+
tool.type === 'builtin' ||
|
|
468
|
+
!('tools' in ctx.profile) ||
|
|
469
|
+
!ctx.profile.tools?.allow.includes(operation.toolId) ||
|
|
470
|
+
(operation.status === 'settled' &&
|
|
471
|
+
ctx.options.authorizeToolReplay &&
|
|
472
|
+
!(await ctx.options.authorizeToolReplay(at, operation))))
|
|
473
|
+
throw new TheoremError('blocked', labelText('error.blocked'));
|
|
474
|
+
authorizeToolReplay({
|
|
475
|
+
tools: defaultKernelScope.tools,
|
|
476
|
+
profile: ctx.profile,
|
|
477
|
+
name: operation.toolId,
|
|
478
|
+
resume: undefined,
|
|
479
|
+
...(operation.status === 'settled' ? { outcome: operation.outcome } : {}),
|
|
480
|
+
});
|
|
481
|
+
yield* once(operation.status === 'settled' ? operation.outcome.event : operation.reply.event, ctx.profile.labels);
|
|
482
|
+
}
|
|
483
|
+
/** The answered call's events: its saved outcome again, or the call run as answered. */
|
|
484
|
+
export async function settlingOf(ctx, at, body) {
|
|
485
|
+
const saved = await ctx.sessions.read(at.sessionId);
|
|
486
|
+
const operation = Object.hasOwn(saved.operations, body.operationId)
|
|
487
|
+
? saved.operations[body.operationId]
|
|
488
|
+
: undefined;
|
|
489
|
+
if (operation &&
|
|
490
|
+
operation.status !== 'ready' &&
|
|
491
|
+
operation.callId === body.gateId &&
|
|
492
|
+
operation.profileId === ctx.profile.id &&
|
|
493
|
+
(operation.status === 'running' || operation.status === 'uncertain')) {
|
|
494
|
+
throw new TheoremError('conflict', `The tool operation is ${operation.status}, so it does not run again until the host settles it`, // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
|
|
495
|
+
{ copy: { key: 'tool.execution_uncertain' } });
|
|
496
|
+
}
|
|
497
|
+
if ((operation?.status === 'settled' || operation?.status === 'background') &&
|
|
498
|
+
operation.profileId === ctx.profile.id &&
|
|
499
|
+
operation.callId === body.gateId) {
|
|
500
|
+
if (body.input !== undefined &&
|
|
501
|
+
(!operation.invocation ||
|
|
502
|
+
(await toolInvocationHash(body.input)) !==
|
|
503
|
+
(await toolInvocationHash(operation.invocation.accepted.input))))
|
|
504
|
+
throw new TheoremError('request', labelText('error.request'), {
|
|
505
|
+
copy: { key: 'error.request' },
|
|
506
|
+
});
|
|
507
|
+
return () => replayOperation(ctx, at, operation);
|
|
508
|
+
}
|
|
509
|
+
// why: Take the answered call before streaming, so a stale answer is a reply status, not a stream error.
|
|
510
|
+
const answered = await ctx.sessions.mutate(at.sessionId, (state) => answerPendingGate(state, answerRequest(body), ctx.profile.id));
|
|
511
|
+
return () => invokeEvents(ctx, at, answered);
|
|
512
|
+
}
|
|
@@ -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';
|
|
@@ -72,6 +73,30 @@ export type SessionToolOperation = {
|
|
|
72
73
|
/** The reply the model read for a call that detached, whatever has happened to the call since. */
|
|
73
74
|
export declare function detachedReply(operation: SessionToolOperation): ToolOperationReply | undefined;
|
|
74
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
|
+
};
|
|
75
100
|
export type TheoremSessionState = {
|
|
76
101
|
version: 3;
|
|
77
102
|
operations: Record<string, SessionToolOperation>;
|
|
@@ -81,6 +106,8 @@ export type TheoremSessionState = {
|
|
|
81
106
|
gates: Record<string, PendingToolGate>;
|
|
82
107
|
/** Checkpoint identities this session produced, newest last. */
|
|
83
108
|
providerCheckpoints: string[];
|
|
109
|
+
/** Unset until a call first ends or a reply first holds a conversation. */
|
|
110
|
+
inbox?: SessionInbox;
|
|
84
111
|
};
|
|
85
112
|
/** Stored authority is checked before the handler reads or changes it. */
|
|
86
113
|
export declare const theoremSessionStateSchema: z.ZodType<TheoremSessionState>;
|
|
@@ -114,6 +141,12 @@ export declare function pruneGates<Gate extends {
|
|
|
114
141
|
createdAt: number;
|
|
115
142
|
expiresAt?: number;
|
|
116
143
|
}>(gates: Record<string, Gate>, now: number, ttlMs: number | undefined): Record<string, Gate>;
|
|
144
|
+
/**
|
|
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.
|
|
148
|
+
*/
|
|
149
|
+
export declare function pruneInbox(state: TheoremSessionState, now: number): void;
|
|
117
150
|
export type MemorySessionStoreOptions = {
|
|
118
151
|
/** What it holds for one session. Unset, it holds any size. */
|
|
119
152
|
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. */
|
|
@@ -44,7 +44,6 @@ const inputSchema = z.strictObject({
|
|
|
44
44
|
.optional(),
|
|
45
45
|
voice: z.array(blobSchema).optional(),
|
|
46
46
|
history: z.array(turnHistoryMessageSchema).optional(),
|
|
47
|
-
lateResults: z.array(toolOperationOutcomeSchema).optional(),
|
|
48
47
|
repair: z
|
|
49
48
|
.strictObject({ previousOutput: z.string(), rejection: z.string(), guidance: z.string() })
|
|
50
49
|
.optional(),
|
|
@@ -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,20 @@ export function pruneGates(gates, now, ttlMs) {
|
|
|
197
218
|
? now < gate.expiresAt
|
|
198
219
|
: !gateExpired(gate.createdAt, now, ttlMs)));
|
|
199
220
|
}
|
|
221
|
+
/**
|
|
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.
|
|
225
|
+
*/
|
|
226
|
+
export function pruneInbox(state, now) {
|
|
227
|
+
if (!state.inbox)
|
|
228
|
+
return;
|
|
229
|
+
for (const [key, conversation] of Object.entries(state.inbox.conversations)) {
|
|
230
|
+
if (conversation.leasedUntil <= now && Object.keys(conversation.entries).length === 0) {
|
|
231
|
+
delete state.inbox.conversations[key];
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
200
235
|
export function memoryStoreLimits(options) {
|
|
201
236
|
const { ttlMs, maxSessions } = options;
|
|
202
237
|
if ((ttlMs !== undefined && (!Number.isFinite(ttlMs) || ttlMs <= 0)) ||
|
package/server/steer-inbox.d.ts
CHANGED
|
@@ -13,11 +13,10 @@ export type SteerUnit = {
|
|
|
13
13
|
messages: TurnHistoryMessage[];
|
|
14
14
|
};
|
|
15
15
|
/**
|
|
16
|
-
* A steer as a client posts it (a checked `TheoremSteerRequest`): its user
|
|
17
|
-
*
|
|
18
|
-
* assistant or tool turns — and a steer with no user message is refused.
|
|
16
|
+
* A steer as a client posts it (a checked `TheoremSteerRequest`): its message as the one user
|
|
17
|
+
* message the model reads. A steer with no text and no file is refused.
|
|
19
18
|
*/
|
|
20
|
-
export declare function steerUnitOf(steer: Pick<TheoremSteerRequest, 'id' | '
|
|
19
|
+
export declare function steerUnitOf(steer: Pick<TheoremSteerRequest, 'id' | 'input'>): SteerUnit;
|
|
21
20
|
/** Lands the inbox's next steer, one per steerable stage, named by its id. */
|
|
22
21
|
export declare function steerStage(inbox: SteerInbox, key: string): StageHandler;
|
|
23
22
|
/**
|