@theoremjs/web 0.3.4 → 0.3.5-next.1000.g569f044
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
package/server/handler.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema, sessionPageDispatch, } from "./page-dispatch.js";
|
|
1
|
+
import { pageToolResultSchema, sessionPageDispatch } from "./page-dispatch.js";
|
|
3
2
|
/**
|
|
4
3
|
* One Web-standard handler that serves a Theorem chat UI for a single profile.
|
|
5
4
|
*
|
|
@@ -14,9 +13,12 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
|
|
|
14
13
|
* - `POST <base>/stop` → stop a running turn where it stands
|
|
15
14
|
* - `POST <base>/page-result` → the page's result for a tool the turn ran in the page
|
|
16
15
|
* - `POST <base>/conversation` → the transcript and the paused reply, to draw
|
|
17
|
-
* - `POST <base>/notify` → NDJSON that stays open: one line now, and one each
|
|
18
|
-
*
|
|
16
|
+
* - `POST <base>/notify` → NDJSON that stays open: one line now, and one for each `publish` under
|
|
17
|
+
* this session: a background call ended, or the app saved a reply.
|
|
18
|
+
* Set `notifier` to serve it
|
|
19
19
|
* - `POST <base>/rewind` → `{ conversation, view }` the conversation cut after one block, and its new ref
|
|
20
|
+
* - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
|
|
21
|
+
* background calls that ended since it last ran. Empty when none waits
|
|
20
22
|
*
|
|
21
23
|
* `createTheoremHostHandler` serves a host profile the same way, with no model:
|
|
22
24
|
*
|
|
@@ -37,25 +39,21 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
|
|
|
37
39
|
*
|
|
38
40
|
* @module
|
|
39
41
|
*/
|
|
40
|
-
import {
|
|
42
|
+
import { defaultKernelScope, defineProfile, labelText, TheoremError, } from '@theoremjs/agents';
|
|
41
43
|
import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremjs/agents/host';
|
|
42
|
-
import {
|
|
43
|
-
import {
|
|
44
|
-
import {
|
|
45
|
-
import {
|
|
46
|
-
import {
|
|
47
|
-
import {
|
|
48
|
-
import { createMemoryCredentialStore, } from "./credential-store.js";
|
|
49
|
-
import { sessionStateStore, } from "./session-authority.js";
|
|
44
|
+
import { blockWithoutToolData, clientProfileInterface, eventWithoutToolData, profileShowsToolData, } from '@theoremjs/agents/interface';
|
|
45
|
+
import { hostInterface, theoremHostCallRequestSchema } from "../client/host-transport.js";
|
|
46
|
+
import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
47
|
+
import { statelessRefusal } from "./conversation.js";
|
|
48
|
+
import { chatOf, createConversationCore, followedUp, oneInbox, replyUnreachable, unconversedAnswer, } from "./conversation-core.js";
|
|
49
|
+
import { callEvents, sessionParts } from "./session-calls.js";
|
|
50
50
|
import { theoremSession } from "./session-identity.js";
|
|
51
|
+
import { kernelTurnInput } from "./turn-input.js";
|
|
51
52
|
export { theoremSession, theoremSessionId } from "./session-identity.js";
|
|
52
53
|
import { jsonResponse } from "./json-response.js";
|
|
53
54
|
import { boundedRequestJson, requestByteLimit } from "./request-body.js";
|
|
54
55
|
import { checkRequest } from "./request-check.js";
|
|
55
|
-
import {
|
|
56
|
-
import { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
|
|
57
|
-
import { sameAcceptedAnswer, sessionToolCoordinator } from "./tool-operations.js";
|
|
58
|
-
import { preparedTurn, stagesInOrder } from "./turn-wiring.js";
|
|
56
|
+
import { createMemorySteerInbox } from "./steer-inbox.js";
|
|
59
57
|
const NDJSON_HEADERS = {
|
|
60
58
|
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
61
59
|
'cache-control': 'no-store',
|
|
@@ -98,37 +96,12 @@ function routeOf(request) {
|
|
|
98
96
|
last === 'conversation' ||
|
|
99
97
|
last === 'notify' ||
|
|
100
98
|
last === 'rewind' ||
|
|
99
|
+
last === 'wake' ||
|
|
101
100
|
last === 'call' ||
|
|
102
101
|
last === 'page-result'
|
|
103
102
|
? last
|
|
104
103
|
: '';
|
|
105
104
|
}
|
|
106
|
-
function lockedStore(store, loaded) {
|
|
107
|
-
const locks = new Map();
|
|
108
|
-
const read = async (sessionId) => loaded(await store.load(sessionId));
|
|
109
|
-
return {
|
|
110
|
-
read,
|
|
111
|
-
mutate(sessionId, change) {
|
|
112
|
-
const next = (locks.get(sessionId) ?? Promise.resolve()).then(async () => {
|
|
113
|
-
const value = await read(sessionId);
|
|
114
|
-
const result = change(value);
|
|
115
|
-
await store.save(sessionId, value);
|
|
116
|
-
return result;
|
|
117
|
-
});
|
|
118
|
-
const settled = next.catch(() => { });
|
|
119
|
-
locks.set(sessionId, settled);
|
|
120
|
-
void settled.then(() => {
|
|
121
|
-
if (locks.get(sessionId) === settled)
|
|
122
|
-
locks.delete(sessionId);
|
|
123
|
-
});
|
|
124
|
-
return next;
|
|
125
|
-
},
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
/** The profile as the server reads a message against it, its tools as registered now. */
|
|
129
|
-
function chatInterface(chat) {
|
|
130
|
-
return interfaceFromProfile(chat.profile, defaultKernelScope.tools);
|
|
131
|
-
}
|
|
132
105
|
async function sessionOf(ctx, request) {
|
|
133
106
|
if (!ctx.options.session)
|
|
134
107
|
return theoremSession(request);
|
|
@@ -146,6 +119,33 @@ function caughtError(ctx, err, request) {
|
|
|
146
119
|
ctx.options.onError?.(err, { request });
|
|
147
120
|
return clientError(err, ctx.profile.labels, ctx.options.clientEvents);
|
|
148
121
|
}
|
|
122
|
+
/** A line as the page may have it: under `tools.showData: false`, none of a tool call's data. */
|
|
123
|
+
function shownLine(ctx, line) {
|
|
124
|
+
if (line.type === 'conversation')
|
|
125
|
+
return line;
|
|
126
|
+
const event = forClient(line, ctx.options.clientEvents);
|
|
127
|
+
return profileShowsToolData(ctx.profile) ? event : eventWithoutToolData(event);
|
|
128
|
+
}
|
|
129
|
+
/** The conversation as the page may have it, by `shownLine`'s rule. */
|
|
130
|
+
function shownView(ctx, view) {
|
|
131
|
+
if (profileShowsToolData(ctx.profile))
|
|
132
|
+
return view;
|
|
133
|
+
const blocks = (list) => list.flatMap((block) => blockWithoutToolData(block) ?? []);
|
|
134
|
+
const { paused, running, ...rest } = view;
|
|
135
|
+
return {
|
|
136
|
+
...rest,
|
|
137
|
+
transcript: blocks(view.transcript),
|
|
138
|
+
...(running ? { running: { ...running, prompt: blocks(running.prompt) } } : {}),
|
|
139
|
+
...(paused
|
|
140
|
+
? {
|
|
141
|
+
paused: {
|
|
142
|
+
events: paused.events.flatMap((event) => eventWithoutToolData(event) ?? []),
|
|
143
|
+
blocks: blocks(paused.blocks),
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
: {}),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
149
|
function eventStream(ctx, request, source) {
|
|
150
150
|
const encoder = new TextEncoder();
|
|
151
151
|
const line = (value) => encoder.encode(`${JSON.stringify(value)}\n`);
|
|
@@ -158,8 +158,10 @@ function eventStream(ctx, request, source) {
|
|
|
158
158
|
controller.enqueue(line(value));
|
|
159
159
|
};
|
|
160
160
|
try {
|
|
161
|
-
for await (const
|
|
162
|
-
|
|
161
|
+
for await (const line of source()) {
|
|
162
|
+
const shown = shownLine(ctx, line);
|
|
163
|
+
if (shown)
|
|
164
|
+
send(shown);
|
|
163
165
|
}
|
|
164
166
|
}
|
|
165
167
|
catch (err) {
|
|
@@ -184,371 +186,190 @@ function providerFor(ctx, request, model) {
|
|
|
184
186
|
return provider({ request, model });
|
|
185
187
|
return provider;
|
|
186
188
|
}
|
|
187
|
-
/**
|
|
188
|
-
function
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
callId: gated.callId,
|
|
199
|
-
name: gated.name,
|
|
200
|
-
arguments: gated.arguments,
|
|
201
|
-
gate: {
|
|
202
|
-
kind: gated.gateKind,
|
|
203
|
-
permission: gated.permission,
|
|
204
|
-
...(gated.auth ? { auth: gated.auth } : {}),
|
|
205
|
-
},
|
|
206
|
-
snapshot: toolSnapshotFromEvents(events),
|
|
207
|
-
promoted: [...new Set([...(context.promoted ?? []), ...promotedToolIdsFromEvents(events)])],
|
|
208
|
-
turnInput: context.turnInput,
|
|
209
|
-
model: context.model,
|
|
210
|
-
createdAt: Date.now(),
|
|
189
|
+
/** What a run reads in place of `request`. */
|
|
190
|
+
function contextOf(ctx, request, sessionId) {
|
|
191
|
+
let asked;
|
|
192
|
+
return {
|
|
193
|
+
sessionId,
|
|
194
|
+
signal: request.signal,
|
|
195
|
+
// why: The app's `host` is asked when a run first reads it, so a route that reads none asks
|
|
196
|
+
// none, and a reply and the app's steps around its save read the same value.
|
|
197
|
+
get host() {
|
|
198
|
+
asked ??= { host: ctx.options.host?.(request) };
|
|
199
|
+
return asked.host;
|
|
211
200
|
},
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
/** When the stream paused on gates, record the exact calls the user may now approve. */
|
|
215
|
-
async function recordOutcome(sessions, sessionId, events, context) {
|
|
216
|
-
const pending = pendingGatesFrom(events, context);
|
|
217
|
-
if (!pending.length)
|
|
218
|
-
return;
|
|
219
|
-
await sessions.mutate(sessionId, (state) => {
|
|
220
|
-
for (const { gate } of pending) {
|
|
221
|
-
const operation = state.operations[gate.operationId];
|
|
222
|
-
if (operation && operation.status !== 'ready')
|
|
223
|
-
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
|
|
224
|
-
{ copy: { key: 'session.busy' } });
|
|
225
|
-
delete state.operations[gate.operationId];
|
|
226
|
-
Object.defineProperty(state.gates, gate.operationId, {
|
|
227
|
-
value: gate,
|
|
228
|
-
writable: true,
|
|
229
|
-
enumerable: true,
|
|
230
|
-
configurable: true,
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
});
|
|
201
|
+
};
|
|
234
202
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
203
|
+
/** The session's calls as `request` runs them: each of the app's callbacks is given `request`. */
|
|
204
|
+
function callsOf(ctx, request) {
|
|
205
|
+
const { options } = ctx;
|
|
206
|
+
const { background, authorizeToolReplay, authorizationUrl } = options;
|
|
207
|
+
return {
|
|
208
|
+
profile: ctx.profile,
|
|
209
|
+
sessions: ctx.sessions,
|
|
210
|
+
credentials: ctx.credentials,
|
|
211
|
+
pageToolBroker: ctx.pageToolBroker,
|
|
212
|
+
options: {
|
|
213
|
+
prepare: options.prepare,
|
|
214
|
+
onStage: options.onStage,
|
|
215
|
+
pageToolTimeoutMs: options.pageToolTimeoutMs,
|
|
216
|
+
notifier: options.notifier,
|
|
217
|
+
lateResultsDecider: options.lateResultsDecider,
|
|
218
|
+
...(background
|
|
219
|
+
? { background: (at) => background({ request, sessionId: at.sessionId }) }
|
|
220
|
+
: {}),
|
|
221
|
+
...(authorizeToolReplay
|
|
222
|
+
? { authorizeToolReplay: (_at, operation) => authorizeToolReplay({ request, operation }) }
|
|
223
|
+
: {}),
|
|
224
|
+
...(authorizationUrl
|
|
225
|
+
? {
|
|
226
|
+
authorizationUrl: (challenge, at) => authorizationUrl(challenge, { request, sessionId: at.sessionId }),
|
|
227
|
+
}
|
|
228
|
+
: {}),
|
|
229
|
+
onError: (err) => options.onError?.(err, { request }),
|
|
230
|
+
wake: (at, ref) => serverWake(ctx, request, at.sessionId, ref),
|
|
231
|
+
},
|
|
232
|
+
};
|
|
243
233
|
}
|
|
244
|
-
/**
|
|
245
|
-
function
|
|
246
|
-
|
|
247
|
-
|
|
234
|
+
/** The chat's conversation core as `request` runs it. */
|
|
235
|
+
function coreOf(ctx, chat, request) {
|
|
236
|
+
const calls = callsOf(ctx, request);
|
|
237
|
+
return ctx.wire({
|
|
238
|
+
...calls,
|
|
239
|
+
chat,
|
|
240
|
+
steer: ctx.inbox,
|
|
241
|
+
options: {
|
|
242
|
+
...calls.options,
|
|
243
|
+
provider: (_at, model) => providerFor(ctx, request, model),
|
|
244
|
+
conversationLeaseMs: ctx.options.conversationLeaseMs,
|
|
245
|
+
notifyRetryMs: ctx.options.notifyRetryMs,
|
|
246
|
+
clientEvents: ctx.options.clientEvents,
|
|
247
|
+
},
|
|
248
248
|
});
|
|
249
249
|
}
|
|
250
250
|
/**
|
|
251
|
-
*
|
|
252
|
-
*
|
|
253
|
-
* to a closed stream.
|
|
251
|
+
* A page's run: when it ends with items that wait, `onContinue` says who runs the next reply.
|
|
252
|
+
* Unset, the chat is let go, and the page wakes it.
|
|
254
253
|
*/
|
|
255
|
-
function
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
set: (slot, credential) => saveCredential(ctx, sessionId, slot, credential),
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
/** An OAuth gate given the host's sign-in URL. */
|
|
262
|
-
async function withAuthorizationUrl(ctx, request, sessionId, event) {
|
|
263
|
-
if (event.type !== 'tool' || event.tool.phase !== 'gate')
|
|
264
|
-
return event;
|
|
265
|
-
const { tool } = event;
|
|
266
|
-
const gate = tool.gate.kind === 'auth' ? tool.gate : undefined;
|
|
267
|
-
if (gate?.authChallenge.authType !== 'oauth2' || !ctx.options.authorizationUrl)
|
|
268
|
-
return event;
|
|
269
|
-
const challenge = gate.authChallenge;
|
|
270
|
-
const authorizationUrl = await ctx.options.authorizationUrl(challenge, { request, sessionId });
|
|
271
|
-
return {
|
|
272
|
-
...event,
|
|
273
|
-
tool: { ...tool, gate: { ...gate, authChallenge: { ...challenge, authorizationUrl } } },
|
|
274
|
-
};
|
|
254
|
+
function pageRun(ctx, request, core, at, reply) {
|
|
255
|
+
const { onContinue } = ctx.options;
|
|
256
|
+
return followedUp(core, at, reply, (run) => onContinue ? onContinue(run, { request, sessionId: at.sessionId }) : 'let_go');
|
|
275
257
|
}
|
|
276
|
-
/**
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
function
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
258
|
+
/**
|
|
259
|
+
* The decider's wake, with no page: the reply runs on a request of its own, with the headers of
|
|
260
|
+
* the one that started the call and no signal, because that request has ended. When another reply
|
|
261
|
+
* holds the chat, it tries again as that hold's lease runs out.
|
|
262
|
+
*/
|
|
263
|
+
async function serverWake(ctx, started, sessionId, ref) {
|
|
264
|
+
const request = new Request(started.url, { headers: started.headers });
|
|
265
|
+
if (!ctx.chat)
|
|
266
|
+
throw statelessRefusal('wake');
|
|
267
|
+
const core = coreOf(ctx, ctx.chat, request);
|
|
268
|
+
const at = contextOf(ctx, request, sessionId);
|
|
269
|
+
// why: no page is open to wake the chat, so this wake runs each next reply itself
|
|
270
|
+
const lines = followedUp(core, at, await core.wake(at, { ref }), () => 'here');
|
|
271
|
+
// why: the run lets the chat go as it ends, so its lines are read to the end before a failure is thrown
|
|
272
|
+
let failed;
|
|
273
|
+
for (;;) {
|
|
274
|
+
const next = await lines.next();
|
|
275
|
+
if (next.done) {
|
|
276
|
+
if (failed)
|
|
277
|
+
throw failed;
|
|
278
|
+
if (next.value.outcome !== 'held')
|
|
279
|
+
return;
|
|
280
|
+
setTimeout(() => {
|
|
281
|
+
serverWake(ctx, started, sessionId, ref).catch((err) => ctx.options.onError?.(err, { request }));
|
|
282
|
+
}, Math.max(0, next.value.leasedUntil - Date.now()));
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (next.value.type === 'error') {
|
|
286
|
+
// labels-exempt: internal diagnostic for the decider's wake; no page reads it
|
|
287
|
+
failed ??= new TheoremError(next.value.errorKind, next.value.errorInternal ?? next.value.error ?? 'the wake failed');
|
|
288
|
+
}
|
|
305
289
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
});
|
|
290
|
+
}
|
|
291
|
+
/** The person's message: a new reply, run against the conversation the host keeps. */
|
|
292
|
+
async function turn(ctx, chat, request, session) {
|
|
293
|
+
const body = await readBody(request, theoremTurnRequestSchema, ctx.options.maxRequestBytes);
|
|
294
|
+
if (body.stated && !ctx.options.pageStatesTurn) {
|
|
295
|
+
throw new TheoremError('request', labelText('error.request'));
|
|
313
296
|
}
|
|
314
|
-
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
...(
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
const { typed: _typed, ...accepted } = answer;
|
|
324
|
-
state.operations[request.operationId] = {
|
|
325
|
-
status: 'ready',
|
|
326
|
-
profileId,
|
|
327
|
-
pending,
|
|
328
|
-
answer: accepted,
|
|
329
|
-
readyAt: Date.now(),
|
|
297
|
+
const context = await ctx.options.context?.(request);
|
|
298
|
+
const core = coreOf(ctx, chat, request);
|
|
299
|
+
const at = contextOf(ctx, request, session.id);
|
|
300
|
+
const message = {
|
|
301
|
+
ref: body.conversation,
|
|
302
|
+
input: body.input,
|
|
303
|
+
...(context === undefined ? {} : { context }),
|
|
304
|
+
generation: body,
|
|
305
|
+
...(body.abandon ? { abandon: body.abandon } : {}),
|
|
330
306
|
};
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const lapsed = pendingGatesFrom(paused, { profileId, turnInput: {} }).find(({ callId }) => callId === reference.callId);
|
|
341
|
-
if (lapsed)
|
|
342
|
-
state.gates[reference.operationId] = lapsed.gate;
|
|
307
|
+
if (ctx.options.intake) {
|
|
308
|
+
if (body.id === undefined) {
|
|
309
|
+
// labels-exempt: internal diagnostic; the user reads error.request
|
|
310
|
+
throw new TheoremError('request', 'a message needs an `id` where the host saves it itself');
|
|
311
|
+
}
|
|
312
|
+
const taken = await savedMessage(ctx.options.intake, core, at, { id: body.id, message });
|
|
313
|
+
return eventStream(ctx, request, () => taken.outcome === 'saved'
|
|
314
|
+
? lines([savedLine(taken)])
|
|
315
|
+
: openedRun(ctx, request, core, at, taken, message));
|
|
343
316
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
settled.profileId === profileId
|
|
347
|
-
? { callId: reference.callId, settled }
|
|
348
|
-
: answerPendingGate(state, { ...reference, decision: 'abandon' }, profileId);
|
|
317
|
+
const reply = await core.message(at, message);
|
|
318
|
+
return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
|
|
349
319
|
}
|
|
350
320
|
/**
|
|
351
|
-
*
|
|
352
|
-
*
|
|
353
|
-
* nor settled. Each comes back with the run that settles it.
|
|
321
|
+
* The app's save of a message, after the checks that can refuse it.
|
|
322
|
+
* invariant: Nothing refuses a message the app has saved, so the page never takes a saved message back.
|
|
354
323
|
*/
|
|
355
|
-
async function
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
reference,
|
|
360
|
-
call: walkedCallOf(state, reference, ctx.profile.id, paused),
|
|
361
|
-
})));
|
|
362
|
-
return calls.map(({ reference, call }) => ({
|
|
363
|
-
...reference,
|
|
364
|
-
events: 'settled' in call
|
|
365
|
-
? replayOperation(ctx, request, call.settled)
|
|
366
|
-
: settleAnswered(ctx, request, session, call),
|
|
367
|
-
}));
|
|
368
|
-
}
|
|
369
|
-
async function* settleAnswered(ctx, request, session, answered) {
|
|
370
|
-
yield* invokeAnswered(ctx, request, session.id, answered);
|
|
371
|
-
}
|
|
372
|
-
async function* invokeAnswered(ctx, request, sessionId, { callId, pending, answer }) {
|
|
373
|
-
const host = await ctx.options.host?.(request);
|
|
374
|
-
// why: The held call goes on with what the application set for its turn: its context, stage handler and credentials.
|
|
375
|
-
const prepared = await preparedTurn(ctx.options.prepare, {
|
|
376
|
-
profile: ctx.profile.id,
|
|
377
|
-
input: pending.turnInput ?? {},
|
|
378
|
-
host,
|
|
379
|
-
signal: request.signal,
|
|
380
|
-
answersHeldCall: true,
|
|
381
|
-
}, {
|
|
382
|
-
credentials: sessionCredentials(ctx, sessionId),
|
|
383
|
-
...(ctx.options.onStage ? { onStage: ctx.options.onStage } : {}),
|
|
384
|
-
});
|
|
385
|
-
yield* invokeTool({
|
|
386
|
-
profile: ctx.profile.id,
|
|
387
|
-
execution: sessionToolCoordinator(ctx.sessions, sessionId),
|
|
388
|
-
...backgroundWiring(ctx, request, sessionId),
|
|
389
|
-
pageExecution: sessionPageDispatch(ctx.sessions, sessionId, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
|
|
390
|
-
name: pending.name,
|
|
391
|
-
callId,
|
|
392
|
-
operationId: pending.operationId,
|
|
393
|
-
input: answer.input,
|
|
394
|
-
resume: answer.resume,
|
|
395
|
-
// why: An approval that names no answer is the page saying it has none, so the call is not held again.
|
|
396
|
-
...(pending.gate.kind === 'page' && answer.resume.granted
|
|
397
|
-
? { page: answer.page ?? { unanswered: true } }
|
|
398
|
-
: {}),
|
|
399
|
-
sessionPermissions: answer.sessionPermissions,
|
|
400
|
-
credentials: prepared.credentials,
|
|
401
|
-
...(prepared.onStage ? { onStage: prepared.onStage } : {}),
|
|
402
|
-
turnInput: pending.turnInput,
|
|
403
|
-
snapshot: pending.snapshot,
|
|
404
|
-
promoted: pending.promoted,
|
|
405
|
-
model: pending.model,
|
|
406
|
-
signal: request.signal,
|
|
407
|
-
host: prepared.host,
|
|
408
|
-
});
|
|
409
|
-
}
|
|
410
|
-
/** The host's service for a call in this session, for a request that runs a tool. */
|
|
411
|
-
function backgroundWiring(ctx, request, sessionId) {
|
|
412
|
-
const service = ctx.options.background?.({ request, sessionId });
|
|
413
|
-
if (!service)
|
|
414
|
-
return {};
|
|
415
|
-
const { notifier } = ctx.options;
|
|
416
|
-
if (!notifier)
|
|
417
|
-
return { background: service };
|
|
418
|
-
return {
|
|
419
|
-
background: {
|
|
420
|
-
detached(call) {
|
|
421
|
-
service.detached(call);
|
|
422
|
-
void call.done
|
|
423
|
-
.then(() => notifier.publish(sessionId))
|
|
424
|
-
.catch((err) => ctx.options.onError?.(err, { request }));
|
|
425
|
-
},
|
|
426
|
-
event: (event, call) => service.event(event, call),
|
|
427
|
-
},
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
/** A settled call's answer, streamed again. */
|
|
431
|
-
async function* once(event, labels) {
|
|
432
|
-
yield withPublicLabels(event, labels);
|
|
433
|
-
}
|
|
434
|
-
/** One model run of a chat's reply, its gates recorded in the session as they pause. */
|
|
435
|
-
async function* chatTurn(ctx, request, session, turn, key, stop) {
|
|
436
|
-
const state = await ctx.sessions.read(session.id);
|
|
437
|
-
const provider = await providerFor(ctx, request, turn.model);
|
|
438
|
-
const host = await ctx.options.host?.(request);
|
|
439
|
-
if (key) {
|
|
440
|
-
await ctx.inbox.open(key);
|
|
441
|
-
stopOnRequest(ctx.inbox, key, stop);
|
|
442
|
-
}
|
|
443
|
-
try {
|
|
444
|
-
const onStage = stagesInOrder(ctx.options.onStage, key ? steerStage(ctx.inbox, key) : undefined);
|
|
445
|
-
const prepared = await preparedTurn(ctx.options.prepare, {
|
|
446
|
-
profile: ctx.profile.id,
|
|
447
|
-
execution: sessionToolCoordinator(ctx.sessions, session.id),
|
|
448
|
-
...backgroundWiring(ctx, request, session.id),
|
|
449
|
-
pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
|
|
450
|
-
input: turn.input,
|
|
451
|
-
...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
|
|
452
|
-
...(turn.providerState ? { providerState: turn.providerState } : {}),
|
|
453
|
-
sessionPermissions: state.permissions,
|
|
454
|
-
signal: AbortSignal.any([request.signal, stop.signal]),
|
|
455
|
-
host,
|
|
456
|
-
...(turn.model ? { model: turn.model } : {}),
|
|
457
|
-
...(turn.effort ? { effort: turn.effort } : {}),
|
|
458
|
-
...turn.carried,
|
|
459
|
-
...turn.stated,
|
|
460
|
-
}, {
|
|
461
|
-
credentials: sessionCredentials(ctx, session.id),
|
|
462
|
-
...(onStage ? { onStage } : {}),
|
|
463
|
-
});
|
|
464
|
-
const events = runTurn(prepared, provider);
|
|
465
|
-
yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
|
|
466
|
-
profileId: ctx.profile.id,
|
|
467
|
-
turnInput: turn.input,
|
|
468
|
-
model: turn.model,
|
|
469
|
-
});
|
|
470
|
-
}
|
|
471
|
-
finally {
|
|
472
|
-
if (key)
|
|
473
|
-
await ctx.inbox.close(key);
|
|
474
|
-
}
|
|
324
|
+
async function savedMessage(intake, core, at, sent) {
|
|
325
|
+
await core.checkMessage(at, sent.message);
|
|
326
|
+
const { ref, input } = sent.message;
|
|
327
|
+
return intake(at, { id: sent.id, ...(ref === undefined ? {} : { ref }), message: input });
|
|
475
328
|
}
|
|
476
|
-
/**
|
|
477
|
-
function
|
|
478
|
-
|
|
479
|
-
const stop = new AbortController();
|
|
480
|
-
const signal = AbortSignal.any([request.signal, stop.signal]);
|
|
481
|
-
return {
|
|
482
|
-
run: (turn) => chatTurn(ctx, request, session, turn, key, stop),
|
|
483
|
-
async compact(history, tokens, model) {
|
|
484
|
-
const provider = await providerFor(ctx, request, model);
|
|
485
|
-
const compacted = await compactHistory({
|
|
486
|
-
profile: ctx.profile.id,
|
|
487
|
-
history,
|
|
488
|
-
tokens,
|
|
489
|
-
signal,
|
|
490
|
-
...(model ? { model } : {}),
|
|
491
|
-
}, provider);
|
|
492
|
-
return compacted?.history;
|
|
493
|
-
},
|
|
494
|
-
...(generation.model ? { model: generation.model } : {}),
|
|
495
|
-
...(generation.effort ? { effort: generation.effort } : {}),
|
|
496
|
-
...(generation.stated ? { stated: generation.stated } : {}),
|
|
497
|
-
signal,
|
|
498
|
-
};
|
|
329
|
+
/** The line that tells the page the app saved its message, and how a reply names it. */
|
|
330
|
+
function savedLine(taken) {
|
|
331
|
+
return { type: 'conversation', ref: taken.ref, posted: true, landsAs: [...taken.landsAs] };
|
|
499
332
|
}
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
const store = ctx.chat?.conversations;
|
|
503
|
-
if (!ctx.chat || !store)
|
|
504
|
-
return undefined;
|
|
505
|
-
return readerConversationHost({
|
|
506
|
-
sessionId: session.id,
|
|
507
|
-
store,
|
|
508
|
-
profile: { outputs: ctx.chat.profile.outputs, labels: ctx.profile.labels },
|
|
509
|
-
clientEvents: ctx.options.clientEvents,
|
|
510
|
-
});
|
|
333
|
+
async function* lines(values) {
|
|
334
|
+
yield* values;
|
|
511
335
|
}
|
|
512
|
-
/**
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
336
|
+
/**
|
|
337
|
+
* The reply to a message whose save took the conversation. The saved line goes first: whatever
|
|
338
|
+
* the reply does after it, the message stays saved.
|
|
339
|
+
*/
|
|
340
|
+
async function* openedRun(ctx, request, core, at, taken, message) {
|
|
341
|
+
const { ref, hold, blocks } = taken;
|
|
342
|
+
yield savedLine(taken);
|
|
343
|
+
let reply;
|
|
344
|
+
try {
|
|
345
|
+
reply = await core.message(at, { ...message, ref, saved: { hold, blocks } });
|
|
517
346
|
}
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
if (body.conversation !== undefined)
|
|
523
|
-
throw statelessRefusal('continue');
|
|
524
|
-
// labels-exempt: internal diagnostic; the user reads error.request
|
|
525
|
-
if (body.abandon)
|
|
526
|
-
throw statelessRefusal('walk away from');
|
|
527
|
-
return eventStream(ctx, request, () => runner.run({
|
|
528
|
-
input: message.input,
|
|
529
|
-
model: body.model,
|
|
530
|
-
effort: body.effort,
|
|
531
|
-
...(body.stated ? { stated: body.stated } : {}),
|
|
532
|
-
}));
|
|
347
|
+
catch (err) {
|
|
348
|
+
// why: No reply took the hold, so the handler lets the conversation go for the next one.
|
|
349
|
+
await core.release(at, { ref, hold });
|
|
350
|
+
throw err;
|
|
533
351
|
}
|
|
534
|
-
|
|
535
|
-
kind: 'message',
|
|
536
|
-
...(body.abandon ? { abandon: body.abandon } : {}),
|
|
537
|
-
});
|
|
538
|
-
// why: Take the walked-away calls before streaming, so a stale one is a reply status, not a stream error.
|
|
539
|
-
const walkAway = body.abandon
|
|
540
|
-
? await takeWalkedAway(ctx, request, session, body.abandon, opened.conversation)
|
|
541
|
-
: undefined;
|
|
542
|
-
return eventStream(ctx, request, () => messageReply({ host, opened, message, ...(walkAway ? { walkAway } : {}), runner }));
|
|
352
|
+
yield* pageRun(ctx, request, core, at, reply);
|
|
543
353
|
}
|
|
544
354
|
/** The conversation as the browser draws it. */
|
|
545
|
-
async function conversation(ctx, request, session) {
|
|
355
|
+
async function conversation(ctx, chat, request, session) {
|
|
546
356
|
const body = await readBody(request, theoremConversationRequestSchema, ctx.options.maxRequestBytes);
|
|
547
|
-
const
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
357
|
+
const view = await coreOf(ctx, chat, request).read(contextOf(ctx, request, session.id), {
|
|
358
|
+
ref: body.conversation,
|
|
359
|
+
});
|
|
360
|
+
return jsonResponse(200, shownView(ctx, view));
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* A reply to no message, for results that ended since the model last ran. It runs under a hold of
|
|
364
|
+
* the chat, so two pages that wake at once run it once, and reads what the decider's policy tells.
|
|
365
|
+
*/
|
|
366
|
+
async function wake(ctx, chat, request, session) {
|
|
367
|
+
const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
|
|
368
|
+
const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
|
|
369
|
+
const core = coreOf(ctx, chat, request);
|
|
370
|
+
const at = contextOf(ctx, request, session.id);
|
|
371
|
+
const reply = await core.wake(at, { ref: body.conversation, generation: body, input });
|
|
372
|
+
return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
|
|
552
373
|
}
|
|
553
374
|
const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
|
|
554
375
|
/**
|
|
@@ -590,178 +411,63 @@ async function notify(ctx, request, session, notifier) {
|
|
|
590
411
|
});
|
|
591
412
|
return new Response(stream, { headers: NDJSON_HEADERS });
|
|
592
413
|
}
|
|
593
|
-
/**
|
|
594
|
-
* why: The transcript keeps a detached call as the turn left it. The session holds what became of
|
|
595
|
-
* it, so a call that has ended does not read as running.
|
|
596
|
-
*/
|
|
597
|
-
async function currentView(ctx, request, session, host, conversation) {
|
|
598
|
-
const view = conversationView(host, conversation);
|
|
599
|
-
if (!view.transcript.some(isDetachedBlock))
|
|
600
|
-
return view;
|
|
601
|
-
const { operations } = await ctx.sessions.read(session.id);
|
|
602
|
-
const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, request, block, operations, host) : block));
|
|
603
|
-
const { notifier, notifyRetryMs } = ctx.options;
|
|
604
|
-
return {
|
|
605
|
-
...view,
|
|
606
|
-
transcript,
|
|
607
|
-
...(notifier && transcript.some(isDetachedBlock)
|
|
608
|
-
? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
|
|
609
|
-
: {}),
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
function isDetachedBlock(block) {
|
|
613
|
-
return block.kind === 'tool' && block.tool.state?.phase === 'background';
|
|
614
|
-
}
|
|
615
|
-
/** A detached call's block as its operation stands. One the session no longer holds has no known end. */
|
|
616
|
-
async function lateBlock(ctx, request, block, operations, host) {
|
|
617
|
-
const { tool } = block;
|
|
618
|
-
const id = tool.operationId;
|
|
619
|
-
const operation = id && Object.hasOwn(operations, id) ? operations[id] : undefined;
|
|
620
|
-
if (operation?.status === 'running' || operation?.status === 'background')
|
|
621
|
-
return block;
|
|
622
|
-
const { labels } = ctx.profile;
|
|
623
|
-
if (operation?.status === 'settled' &&
|
|
624
|
-
ctx.options.authorizeToolReplay &&
|
|
625
|
-
!(await ctx.options.authorizeToolReplay({ request, operation }))) {
|
|
626
|
-
const message = labelText('error.blocked', {}, labels);
|
|
627
|
-
const failure = { code: 'outcome_withheld', kind: 'blocked', message };
|
|
628
|
-
const { name, callId } = tool;
|
|
629
|
-
const at = operation.settledAt;
|
|
630
|
-
return {
|
|
631
|
-
...block,
|
|
632
|
-
tool: {
|
|
633
|
-
...tool,
|
|
634
|
-
state: { name, callId, at, phase: 'error', failure, readBack: message },
|
|
635
|
-
endedAt: at,
|
|
636
|
-
},
|
|
637
|
-
};
|
|
638
|
-
}
|
|
639
|
-
if (operation?.status === 'settled') {
|
|
640
|
-
const settled = host.forReader(operation.outcome.event);
|
|
641
|
-
if (settled.type !== 'tool')
|
|
642
|
-
return block;
|
|
643
|
-
const { tool: state } = settled;
|
|
644
|
-
if (!('phase' in state) || (state.phase !== 'complete' && state.phase !== 'error'))
|
|
645
|
-
return block;
|
|
646
|
-
return { ...block, tool: { ...tool, state, endedAt: operation.settledAt } };
|
|
647
|
-
}
|
|
648
|
-
const message = labelText('tool.execution_uncertain', {}, labels);
|
|
649
|
-
const failure = {
|
|
650
|
-
code: operation?.status === 'uncertain' ? operation.reason : 'outcome_not_retained',
|
|
651
|
-
kind: 'internal',
|
|
652
|
-
message,
|
|
653
|
-
};
|
|
654
|
-
const { name, callId } = tool;
|
|
655
|
-
const at = operation?.status === 'uncertain' ? operation.detectedAt : (tool.state?.at ?? Date.now());
|
|
656
|
-
return {
|
|
657
|
-
...block,
|
|
658
|
-
tool: {
|
|
659
|
-
...tool,
|
|
660
|
-
state: { name, callId, at, phase: 'error', failure, readBack: message },
|
|
661
|
-
endedAt: at,
|
|
662
|
-
},
|
|
663
|
-
};
|
|
664
|
-
}
|
|
665
414
|
/** The conversation cut after one block; a reply that waits on gates is walked away from first. */
|
|
666
|
-
async function rewind(ctx, request, session) {
|
|
415
|
+
async function rewind(ctx, chat, request, session) {
|
|
667
416
|
const body = await readBody(request, theoremRewindRequestSchema, ctx.options.maxRequestBytes);
|
|
668
|
-
const
|
|
669
|
-
|
|
670
|
-
throw statelessRefusal('rewind');
|
|
671
|
-
const opened = await openConversation(host, body.conversation, { kind: 'rewind', at: body.at });
|
|
672
|
-
const waiting = waitingCalls(opened.conversation);
|
|
673
|
-
const walkAway = waiting.length
|
|
674
|
-
? await takeWalkedAway(ctx, request, session, waiting, opened.conversation)
|
|
675
|
-
: undefined;
|
|
676
|
-
const next = await rewindConversation({
|
|
677
|
-
host,
|
|
678
|
-
opened,
|
|
417
|
+
const rewound = await coreOf(ctx, chat, request).rewind(contextOf(ctx, request, session.id), {
|
|
418
|
+
ref: body.conversation,
|
|
679
419
|
at: body.at,
|
|
680
|
-
...(walkAway ? { walkAway } : {}),
|
|
681
420
|
});
|
|
682
|
-
|
|
683
|
-
throw new TheoremError('internal', labelText('error.internal'));
|
|
684
|
-
const rewound = {
|
|
685
|
-
conversation: next.ref,
|
|
686
|
-
view: await currentView(ctx, request, session, host, next.conversation),
|
|
687
|
-
};
|
|
688
|
-
return jsonResponse(200, rewound);
|
|
689
|
-
}
|
|
690
|
-
async function* invokeEvents(ctx, request, session, answered) {
|
|
691
|
-
const { pending, answer } = answered;
|
|
692
|
-
if (answer.typed)
|
|
693
|
-
await saveCredential(ctx, session.id, answer.typed.slot, answer.typed.credential);
|
|
694
|
-
const events = settleAnswered(ctx, request, session, answered);
|
|
695
|
-
yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
|
|
696
|
-
profileId: ctx.profile.id,
|
|
697
|
-
turnInput: pending.turnInput,
|
|
698
|
-
model: pending.model,
|
|
699
|
-
promoted: pending.promoted,
|
|
700
|
-
}, [
|
|
701
|
-
{
|
|
702
|
-
type: 'tool',
|
|
703
|
-
tool: {
|
|
704
|
-
name: pending.name,
|
|
705
|
-
callId: pending.callId,
|
|
706
|
-
operationId: pending.operationId,
|
|
707
|
-
arguments: jsonObjectSchema.parse(answer.input),
|
|
708
|
-
},
|
|
709
|
-
},
|
|
710
|
-
]);
|
|
421
|
+
return jsonResponse(200, { ...rewound, view: shownView(ctx, rewound.view) });
|
|
711
422
|
}
|
|
712
|
-
async function steer(ctx, request, session) {
|
|
423
|
+
async function steer(ctx, chat, request, session) {
|
|
713
424
|
const body = await readBody(request, theoremSteerRequestSchema, ctx.options.maxRequestBytes);
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
425
|
+
const core = coreOf(ctx, chat, request);
|
|
426
|
+
const at = contextOf(ctx, request, session.id);
|
|
427
|
+
if (ctx.options.intake) {
|
|
428
|
+
const message = {
|
|
429
|
+
...(body.conversation === undefined ? {} : { ref: body.conversation }),
|
|
430
|
+
input: body.input,
|
|
431
|
+
};
|
|
432
|
+
const taken = await savedMessage(ctx.options.intake, core, at, { id: body.id, message });
|
|
433
|
+
if (taken.outcome === 'opened') {
|
|
434
|
+
const run = { ref: taken.ref, hold: taken.hold };
|
|
435
|
+
const { onContinue } = ctx.options;
|
|
436
|
+
const who = onContinue
|
|
437
|
+
? await onContinue(run, { request, sessionId: at.sessionId })
|
|
438
|
+
: 'let_go';
|
|
439
|
+
// why: A steer has no stream for a reply, so `here` is the page's own wake.
|
|
440
|
+
if (who !== 'taken')
|
|
441
|
+
await core.release(at, run);
|
|
442
|
+
}
|
|
443
|
+
const saved = { conversation: taken.ref, landsAs: [...taken.landsAs] };
|
|
444
|
+
return jsonResponse(200, { ok: true, saved });
|
|
719
445
|
}
|
|
446
|
+
// why: without `intake`, a steer reaches only a turn this server runs, by its id
|
|
447
|
+
if (!('turnId' in body))
|
|
448
|
+
throw replyUnreachable();
|
|
449
|
+
const steered = await core.steer(at, { turnId: body.turnId, id: body.id, input: body.input });
|
|
450
|
+
if (!steered)
|
|
451
|
+
throw replyNotRunning(body);
|
|
720
452
|
return jsonResponse(200, { ok: true });
|
|
721
453
|
}
|
|
454
|
+
/** The refusal of a steer or stop for a reply that is not running. */
|
|
455
|
+
function replyNotRunning(target) {
|
|
456
|
+
// labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
|
|
457
|
+
const what = 'turnId' in target ? `turn ${target.turnId}` : 'a reply on the conversation';
|
|
458
|
+
// labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
|
|
459
|
+
return new TheoremError('request', `${what} is not running`, {
|
|
460
|
+
copy: { key: 'session.turn_ended' },
|
|
461
|
+
});
|
|
462
|
+
}
|
|
722
463
|
/** Stops a running turn where it stands; its stream goes on to save and send what the reply left. */
|
|
723
|
-
async function stop(ctx, request, session) {
|
|
464
|
+
async function stop(ctx, chat, request, session) {
|
|
724
465
|
const body = await readBody(request, theoremStopRequestSchema, ctx.options.maxRequestBytes);
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
throw
|
|
728
|
-
copy: { key: 'session.turn_ended' },
|
|
729
|
-
});
|
|
730
|
-
}
|
|
466
|
+
const core = coreOf(ctx, chat, request);
|
|
467
|
+
if (!(await core.stop(contextOf(ctx, request, session.id), body)))
|
|
468
|
+
throw replyNotRunning(body);
|
|
731
469
|
return jsonResponse(200, { ok: true });
|
|
732
470
|
}
|
|
733
|
-
/** One call of one of a host's tools, run as the page asked it; a gate it pauses on waits in the session. */
|
|
734
|
-
async function* callEvents(ctx, request, session, body) {
|
|
735
|
-
const state = await ctx.sessions.read(session.id);
|
|
736
|
-
const host = await ctx.options.host?.(request);
|
|
737
|
-
const events = invokeTool({
|
|
738
|
-
profile: ctx.profile.id,
|
|
739
|
-
execution: sessionToolCoordinator(ctx.sessions, session.id),
|
|
740
|
-
...backgroundWiring(ctx, request, session.id),
|
|
741
|
-
pageExecution: sessionPageDispatch(ctx.sessions, session.id, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
|
|
742
|
-
name: body.name,
|
|
743
|
-
input: body.input,
|
|
744
|
-
sessionPermissions: state.permissions,
|
|
745
|
-
credentials: sessionCredentials(ctx, session.id),
|
|
746
|
-
...(ctx.options.onStage ? { onStage: ctx.options.onStage } : {}),
|
|
747
|
-
signal: request.signal,
|
|
748
|
-
host,
|
|
749
|
-
});
|
|
750
|
-
yield* recorded(ctx.sessions, session.id, withAuthorizationUrls(ctx, request, session.id, events), {
|
|
751
|
-
profileId: ctx.profile.id,
|
|
752
|
-
turnInput: {},
|
|
753
|
-
});
|
|
754
|
-
}
|
|
755
|
-
function answerRequest(body) {
|
|
756
|
-
return {
|
|
757
|
-
callId: body.gateId,
|
|
758
|
-
operationId: body.operationId,
|
|
759
|
-
decision: body.decision,
|
|
760
|
-
input: body.input,
|
|
761
|
-
secret: body.secret,
|
|
762
|
-
page: body.page,
|
|
763
|
-
};
|
|
764
|
-
}
|
|
765
471
|
/** A route this profile doesn't serve. */
|
|
766
472
|
function refused(ctx) {
|
|
767
473
|
return jsonResponse(HTTP_NOT_FOUND, {
|
|
@@ -769,26 +475,6 @@ function refused(ctx) {
|
|
|
769
475
|
errorKind: 'not_found',
|
|
770
476
|
});
|
|
771
477
|
}
|
|
772
|
-
async function* replayOperation(ctx, request, operation) {
|
|
773
|
-
const tool = defaultKernelScope.tools.get(operation.toolId);
|
|
774
|
-
if (operation.profileId !== ctx.profile.id ||
|
|
775
|
-
!tool ||
|
|
776
|
-
tool.type === 'builtin' ||
|
|
777
|
-
!('tools' in ctx.profile) ||
|
|
778
|
-
!ctx.profile.tools?.allow.includes(operation.toolId) ||
|
|
779
|
-
(operation.status === 'settled' &&
|
|
780
|
-
ctx.options.authorizeToolReplay &&
|
|
781
|
-
!(await ctx.options.authorizeToolReplay({ request, operation }))))
|
|
782
|
-
throw new TheoremError('blocked', labelText('error.blocked'));
|
|
783
|
-
authorizeToolReplay({
|
|
784
|
-
tools: defaultKernelScope.tools,
|
|
785
|
-
profile: ctx.profile,
|
|
786
|
-
name: operation.toolId,
|
|
787
|
-
resume: undefined,
|
|
788
|
-
...(operation.status === 'settled' ? { outcome: operation.outcome } : {}),
|
|
789
|
-
});
|
|
790
|
-
yield* once(operation.status === 'settled' ? operation.outcome.event : operation.reply.event, ctx.profile.labels);
|
|
791
|
-
}
|
|
792
478
|
/**
|
|
793
479
|
* The user's answer to a paused call. In a kept conversation the reply goes on
|
|
794
480
|
* in the same stream once no call waits; otherwise the stream is the call's.
|
|
@@ -797,49 +483,14 @@ async function invoke(ctx, request, session) {
|
|
|
797
483
|
const body = await readBody(request, theoremInvokeRequestSchema, ctx.options.maxRequestBytes);
|
|
798
484
|
if (body.page && 'output' in body.page)
|
|
799
485
|
throw new TheoremError('request', labelText('error.request'));
|
|
800
|
-
const
|
|
801
|
-
if (!
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
return eventStream(ctx, request, await settlingOf(ctx, request, session, body));
|
|
805
|
-
}
|
|
806
|
-
if (body.conversation === undefined)
|
|
807
|
-
throw unknownConversation();
|
|
808
|
-
const call = { callId: body.gateId, operationId: body.operationId };
|
|
809
|
-
const opened = await openConversation(host, body.conversation, { kind: 'answer', call });
|
|
810
|
-
const settling = await settlingOf(ctx, request, session, body);
|
|
811
|
-
const runner = chatRunner(ctx, request, session, body);
|
|
812
|
-
return eventStream(ctx, request, () => answerReply({ host, opened, call, settling: settling(), runner }));
|
|
813
|
-
}
|
|
814
|
-
/** The answered call's events: its saved outcome again, or the call run as answered. */
|
|
815
|
-
async function settlingOf(ctx, request, session, body) {
|
|
816
|
-
const saved = await ctx.sessions.read(session.id);
|
|
817
|
-
const operation = Object.hasOwn(saved.operations, body.operationId)
|
|
818
|
-
? saved.operations[body.operationId]
|
|
819
|
-
: undefined;
|
|
820
|
-
if (operation &&
|
|
821
|
-
operation.status !== 'ready' &&
|
|
822
|
-
operation.callId === body.gateId &&
|
|
823
|
-
operation.profileId === ctx.profile.id &&
|
|
824
|
-
(operation.status === 'running' || operation.status === 'uncertain')) {
|
|
825
|
-
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)
|
|
826
|
-
{ copy: { key: 'tool.execution_uncertain' } });
|
|
486
|
+
const at = contextOf(ctx, request, session.id);
|
|
487
|
+
if (!ctx.chat) {
|
|
488
|
+
const lines = await unconversedAnswer(callsOf(ctx, request), at, body);
|
|
489
|
+
return eventStream(ctx, request, () => lines);
|
|
827
490
|
}
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
if (body.input !== undefined &&
|
|
832
|
-
(!operation.invocation ||
|
|
833
|
-
(await toolInvocationHash(body.input)) !==
|
|
834
|
-
(await toolInvocationHash(operation.invocation.accepted.input))))
|
|
835
|
-
throw new TheoremError('request', labelText('error.request'), {
|
|
836
|
-
copy: { key: 'error.request' },
|
|
837
|
-
});
|
|
838
|
-
return () => replayOperation(ctx, request, operation);
|
|
839
|
-
}
|
|
840
|
-
// why: Take the answered call before streaming, so a stale answer is a reply status, not a stream error.
|
|
841
|
-
const answered = await ctx.sessions.mutate(session.id, (state) => answerPendingGate(state, answerRequest(body), ctx.profile.id));
|
|
842
|
-
return () => invokeEvents(ctx, request, session, answered);
|
|
491
|
+
const core = coreOf(ctx, ctx.chat, request);
|
|
492
|
+
const reply = await core.answer(at, body);
|
|
493
|
+
return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
|
|
843
494
|
}
|
|
844
495
|
async function hostRoute(ctx, request, session) {
|
|
845
496
|
const target = routeOf(request);
|
|
@@ -847,7 +498,7 @@ async function hostRoute(ctx, request, session) {
|
|
|
847
498
|
return jsonResponse(200, { interface: hostInterface(ctx.profile, hostTool) });
|
|
848
499
|
if (request.method === 'POST' && target === 'call') {
|
|
849
500
|
const body = await readBody(request, theoremHostCallRequestSchema, ctx.options.maxRequestBytes);
|
|
850
|
-
return eventStream(ctx, request, () => callEvents(ctx, request, session, body));
|
|
501
|
+
return eventStream(ctx, request, () => callEvents(callsOf(ctx, request), contextOf(ctx, request, session.id), body));
|
|
851
502
|
}
|
|
852
503
|
if (request.method === 'POST' && target === 'invoke')
|
|
853
504
|
return invoke(ctx, request, session);
|
|
@@ -876,7 +527,7 @@ async function route(ctx, request, session) {
|
|
|
876
527
|
if (target === 'invoke')
|
|
877
528
|
return invoke(ctx, request, session);
|
|
878
529
|
if (target === 'conversation')
|
|
879
|
-
return conversation(ctx, request, session);
|
|
530
|
+
return conversation(ctx, chat, request, session);
|
|
880
531
|
if (target === 'notify') {
|
|
881
532
|
const { notifier } = ctx.options;
|
|
882
533
|
if (!notifier || !chat.conversations)
|
|
@@ -884,40 +535,28 @@ async function route(ctx, request, session) {
|
|
|
884
535
|
return notify(ctx, request, session, notifier);
|
|
885
536
|
}
|
|
886
537
|
if (target === 'rewind')
|
|
887
|
-
return rewind(ctx, request, session);
|
|
538
|
+
return rewind(ctx, chat, request, session);
|
|
539
|
+
if (target === 'wake')
|
|
540
|
+
return wake(ctx, chat, request, session);
|
|
888
541
|
if (target === 'stop')
|
|
889
|
-
return stop(ctx, request, session);
|
|
890
|
-
return steer(ctx, request, session);
|
|
542
|
+
return stop(ctx, chat, request, session);
|
|
543
|
+
return steer(ctx, chat, request, session);
|
|
891
544
|
}
|
|
892
545
|
export function createTheoremHandler(options) {
|
|
893
|
-
const
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
throw new Error("createTheoremHandler serves turn-based profiles; serve type 'decision' with createTheoremDecisionHandler.");
|
|
897
|
-
}
|
|
898
|
-
if (profile.type === 'host') {
|
|
899
|
-
// labels-exempt: builder config error at setup; no user sees it
|
|
900
|
-
throw new Error("createTheoremHandler serves turn-based profiles; serve type 'host' with createTheoremHostHandler.");
|
|
901
|
-
}
|
|
902
|
-
if (profile.type === 'live' || profile.type === 'embedding') {
|
|
546
|
+
const chat = chatOf('createTheoremHandler', options.profile, options.conversationStore);
|
|
547
|
+
oneInbox(options);
|
|
548
|
+
if (options.intake && !options.inbox) {
|
|
903
549
|
// labels-exempt: builder config error at setup; no user sees it
|
|
904
|
-
throw new
|
|
905
|
-
}
|
|
906
|
-
const stateless = profile.providerContinuation?.history === 'stateless';
|
|
907
|
-
if (stateless === (options.conversationStore !== undefined)) {
|
|
908
|
-
throw new TheoremError('config', labelText('error.config'), {
|
|
909
|
-
cause: {
|
|
910
|
-
code: stateless ? 'conversation_store_stateless' : 'conversation_store_missing',
|
|
911
|
-
profile: profile.id,
|
|
912
|
-
},
|
|
913
|
-
});
|
|
550
|
+
throw new TheoremError('config', 'createTheoremHandler needs `inbox` with `intake`');
|
|
914
551
|
}
|
|
915
|
-
|
|
552
|
+
const { prepare, inbox, beforeSave, afterSave, compact } = options;
|
|
553
|
+
return serve('createTheoremHandler', chat.profile, options, {
|
|
916
554
|
steerInbox: options.steerInbox,
|
|
917
|
-
chat
|
|
918
|
-
|
|
919
|
-
...
|
|
920
|
-
|
|
555
|
+
chat,
|
|
556
|
+
wire: (state) => createConversationCore({
|
|
557
|
+
...state,
|
|
558
|
+
options: { ...state.options, prepare, inbox, beforeSave, afterSave, compact },
|
|
559
|
+
}),
|
|
921
560
|
});
|
|
922
561
|
}
|
|
923
562
|
/**
|
|
@@ -941,33 +580,14 @@ export function hostTool(name) {
|
|
|
941
580
|
const registered = defaultKernelScope.tools.get(name);
|
|
942
581
|
return registered?.type === 'builtin' ? undefined : registered;
|
|
943
582
|
}
|
|
944
|
-
function checkNotifyRetry(ms) {
|
|
945
|
-
if (ms === undefined || (Number.isFinite(ms) && ms >= 0))
|
|
946
|
-
return;
|
|
947
|
-
throw new TheoremError('config', labelText('error.config'), {
|
|
948
|
-
cause: { code: 'notify_retry' },
|
|
949
|
-
});
|
|
950
|
-
}
|
|
951
583
|
function serve(name, profile, options, chatOptions = {}) {
|
|
952
|
-
const gateTtlMs = resolveGateTtlMs(name, options.gateTtlMs);
|
|
953
|
-
const operationRetentionMs = options.operationRetentionMs ?? DEFAULT_OPERATION_RETENTION_MS;
|
|
954
|
-
if (!Number.isSafeInteger(operationRetentionMs) || operationRetentionMs <= 0) {
|
|
955
|
-
throw new TheoremError('config', labelText('error.config'), {
|
|
956
|
-
cause: { code: 'operation_retention' },
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
584
|
requestByteLimit(options.maxRequestBytes);
|
|
960
|
-
checkPageToolTimeout(options.pageToolTimeoutMs);
|
|
961
|
-
checkNotifyRetry(options.notifyRetryMs);
|
|
962
|
-
registerProfile(profile);
|
|
963
585
|
const ctx = {
|
|
964
586
|
options,
|
|
965
|
-
|
|
966
|
-
profile,
|
|
587
|
+
...sessionParts(name, profile, options),
|
|
967
588
|
...(chatOptions.chat ? { chat: chatOptions.chat } : {}),
|
|
968
589
|
inbox: chatOptions.steerInbox ?? createMemorySteerInbox(),
|
|
969
|
-
|
|
970
|
-
credentials: lockedStore(options.credentialStore ?? createMemoryCredentialStore(), (saved = {}) => saved),
|
|
590
|
+
wire: chatOptions.wire ?? createConversationCore,
|
|
971
591
|
};
|
|
972
592
|
return async (request) => {
|
|
973
593
|
let session;
|