@theoremjs/web 0.3.5-next.980.g83e419d → 0.3.5-next.982.g16b31de
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 +270 -6
- package/client/chat.js +136 -21
- package/client/index.d.ts +1 -1
- package/client/run-session.d.ts +12 -2
- package/client/run-session.js +3 -3
- package/client/transcript-schema.d.ts +4 -0
- package/client/transcript-schema.js +9 -1
- package/client/transport.d.ts +34 -6
- package/client/transport.js +17 -5
- package/client/turn-client.d.ts +5 -1
- package/client/turn-client.js +1 -0
- package/package.json +2 -2
- package/server/conversation-core.d.ts +264 -0
- package/server/conversation-core.js +780 -0
- package/server/conversation-store.d.ts +25 -1
- package/server/conversation-store.js +8 -2
- package/server/conversation.d.ts +61 -2
- package/server/conversation.js +225 -37
- package/server/create-conversation-core.d.ts +28 -0
- package/server/create-conversation-core.js +46 -0
- package/server/handler.d.ts +67 -20
- package/server/handler.js +203 -908
- package/server/mod.d.ts +8 -3
- package/server/mod.js +2 -0
- 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 +23 -0
- package/server/session-calls.d.ts +122 -0
- package/server/session-calls.js +512 -0
- package/server/steer-inbox.d.ts +3 -4
- package/server/steer-inbox.js +6 -5
- package/server/turn-wiring.d.ts +19 -4
- package/server/turn-wiring.js +8 -1
|
@@ -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
|
+
}
|
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
|
/**
|
package/server/steer-inbox.js
CHANGED
|
@@ -6,18 +6,19 @@
|
|
|
6
6
|
* @module
|
|
7
7
|
*/
|
|
8
8
|
import { TheoremError } from '@theoremjs/agents';
|
|
9
|
+
import { appendUserDraftToHistory } from '@theoremjs/agents/interface';
|
|
9
10
|
/** The stages a steer can land at. */
|
|
10
11
|
const STEER_STAGES = new Set(['pre_turn', 'post_tool', 'before_end']);
|
|
11
12
|
/**
|
|
12
|
-
* A steer as a client posts it (a checked `TheoremSteerRequest`): its user
|
|
13
|
-
*
|
|
14
|
-
* assistant or tool turns — and a steer with no user message is refused.
|
|
13
|
+
* A steer as a client posts it (a checked `TheoremSteerRequest`): its message as the one user
|
|
14
|
+
* message the model reads. A steer with no text and no file is refused.
|
|
15
15
|
*/
|
|
16
16
|
export function steerUnitOf(steer) {
|
|
17
|
-
const
|
|
17
|
+
const { text, attachments, voice } = steer.input;
|
|
18
|
+
const messages = appendUserDraftToHistory([], { ...(text === undefined ? {} : { text }) }, { ...(attachments ? { attachments } : {}), ...(voice ? { voice } : {}) });
|
|
18
19
|
// labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
|
|
19
20
|
if (!messages.length)
|
|
20
|
-
throw new TheoremError('request', '
|
|
21
|
+
throw new TheoremError('request', 'a steer needs text or a file');
|
|
21
22
|
return { id: steer.id, messages };
|
|
22
23
|
}
|
|
23
24
|
/** Lands the inbox's next steer, one per steerable stage, named by its id. */
|
package/server/turn-wiring.d.ts
CHANGED
|
@@ -6,8 +6,22 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
-
import type { NormalizedTurnRequest, StageHandler, TurnRequest
|
|
10
|
-
import { type ToolBackgroundService, type ToolCredentialSource } from '@theoremjs/agents/kernel';
|
|
9
|
+
import type { NormalizedTurnRequest, StageHandler, TurnRequest } from '@theoremjs/agents';
|
|
10
|
+
import { type JsonObject, type ToolBackgroundService, type ToolCredentialSource } from '@theoremjs/agents/kernel';
|
|
11
|
+
/**
|
|
12
|
+
* The app's refusal of a reply, in place of a turn: its own line is the reply, with no model run.
|
|
13
|
+
* `host` is the app's own values for the line's block.
|
|
14
|
+
*/
|
|
15
|
+
export type ReplyRefusal = {
|
|
16
|
+
refuse: {
|
|
17
|
+
text: string;
|
|
18
|
+
host?: JsonObject;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
/** The app's `prepare` for a turn the server runs: the turn, or its refusal of the reply. */
|
|
22
|
+
export type AppPrepare = (turn: NormalizedTurnRequest) => TurnRequest | ReplyRefusal | Promise<TurnRequest | ReplyRefusal>;
|
|
23
|
+
/** Whether `prepare` refused the reply. */
|
|
24
|
+
export declare function isRefusal(prepared: TurnRequest | ReplyRefusal): prepared is ReplyRefusal;
|
|
11
25
|
/** The fields a handler sets on every turn, which `prepare` cannot replace. */
|
|
12
26
|
export type HandlerOwned = Pick<TurnRequest, 'profile' | 'pageExecution' | 'providerState' | 'signal'>;
|
|
13
27
|
/**
|
|
@@ -25,9 +39,10 @@ export type HandlerTurnParts = {
|
|
|
25
39
|
/**
|
|
26
40
|
* The turn to run: `turn` through the application's `prepare`, with the handler's own fields
|
|
27
41
|
* kept, its credentials and steering after the application's, and the application's tool record
|
|
28
|
-
* and background service, when it gives them, joined with the session's.
|
|
42
|
+
* and background service, when it gives them, joined with the session's. The application's
|
|
43
|
+
* refusal is returned as it is.
|
|
29
44
|
*/
|
|
30
|
-
export declare function preparedTurn(prepare:
|
|
45
|
+
export declare function preparedTurn(prepare: AppPrepare | undefined, turn: NormalizedTurnRequest & HandlerOwned & HandlerTools, handler: HandlerTurnParts): Promise<TurnRequest | ReplyRefusal>;
|
|
31
46
|
/**
|
|
32
47
|
* The application's stage handler, then the handler's own when the application's asks for
|
|
33
48
|
* nothing. What the second one would have done waits for the next stage that allows it.
|
package/server/turn-wiring.js
CHANGED
|
@@ -8,13 +8,20 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { isSealedSource, } from '@theoremjs/agents/kernel';
|
|
10
10
|
import { layeredToolCoordinator } from "./tool-operations.js";
|
|
11
|
+
/** Whether `prepare` refused the reply. */
|
|
12
|
+
export function isRefusal(prepared) {
|
|
13
|
+
return 'refuse' in prepared;
|
|
14
|
+
}
|
|
11
15
|
/**
|
|
12
16
|
* The turn to run: `turn` through the application's `prepare`, with the handler's own fields
|
|
13
17
|
* kept, its credentials and steering after the application's, and the application's tool record
|
|
14
|
-
* and background service, when it gives them, joined with the session's.
|
|
18
|
+
* and background service, when it gives them, joined with the session's. The application's
|
|
19
|
+
* refusal is returned as it is.
|
|
15
20
|
*/
|
|
16
21
|
export async function preparedTurn(prepare, turn, handler) {
|
|
17
22
|
const app = prepare ? await prepare(turn) : turn;
|
|
23
|
+
if (isRefusal(app))
|
|
24
|
+
return app;
|
|
18
25
|
const owned = {
|
|
19
26
|
profile: turn.profile,
|
|
20
27
|
...(turn.pageExecution ? { pageExecution: turn.pageExecution } : {}),
|