@thready-web/dsh-bot-plugin 0.1.0-beta.3 → 0.1.0-beta.4
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 +78 -1
- package/dist/approvals.js +160 -0
- package/dist/authorization.js +225 -0
- package/dist/context.js +11 -1
- package/dist/cua-access.js +79 -0
- package/dist/http-plugin.js +8 -2
- package/dist/http.js +206 -74
- package/dist/inbox.js +21 -35
- package/dist/index.js +53 -8
- package/dist/live-snapshot.js +2 -15
- package/dist/log/canonical.js +37 -0
- package/dist/log/plan.js +62 -0
- package/dist/log/routes.js +144 -0
- package/dist/log/snapshot-service.js +76 -0
- package/dist/log/source.js +173 -0
- package/dist/permissions.js +86 -0
- package/dist/questions.js +407 -0
- package/dist/work-admit.js +65 -15
- package/dist/work-child.js +8 -3
- package/dist/work-http.js +29 -0
- package/dist/work-ledger.js +7 -0
- package/dist/work-mock-host.js +1 -0
- package/dist/work-mock.js +6 -0
- package/dist/work-tickets.js +212 -16
- package/dist/work-tools.js +2 -2
- package/dist/work-worker.js +693 -134
- package/dist/workspace-image.js +91 -0
- package/fixtures/mock-llm.mjs +17 -2
- package/package.json +9 -3
- package/public/assets/index-Dczis232.css +1 -0
- package/public/assets/index-oExHCCsZ.js +63 -0
- package/public/index.html +2 -2
- package/public/assets/index-D0tTt7E4.js +0 -61
- package/public/assets/index-PyqSrdBb.css +0 -1
package/dist/http.js
CHANGED
|
@@ -2,11 +2,15 @@ import { createReadStream, statSync } from 'node:fs';
|
|
|
2
2
|
import { dirname, extname, join, resolve, sep } from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { createDesk, defaultSessionCwd } from "./desk.js";
|
|
5
|
+
import { serveWorkspaceImage } from "./workspace-image.js";
|
|
5
6
|
import { toolError } from "./errors.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
7
|
+
import { permissionView, setPermission } from "./permissions.js";
|
|
8
|
+
import { cuaAction, cuaSnapshot } from "./cua-access.js";
|
|
8
9
|
import { provisionSession } from "./provision.js";
|
|
9
10
|
import { handleWorkApi, openPageLive, openWorkLive } from "./work-http.js";
|
|
11
|
+
import { createLogSource } from "./log/source.js";
|
|
12
|
+
import { createLogSnapshotService } from "./log/snapshot-service.js";
|
|
13
|
+
import { dispatchLogRequest, probeConnection, registerLogRoutes } from "./log/routes.js";
|
|
10
14
|
/**
|
|
11
15
|
* Local management routes. Model tools cannot confirm a persona or change revocation.
|
|
12
16
|
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
@@ -14,11 +18,14 @@ import { handleWorkApi, openPageLive, openWorkLive } from "./work-http.js";
|
|
|
14
18
|
* @param {() => import('./triggers.js').ReturnType<typeof import('./triggers.js').createTriggers> | null} [getRuntime]
|
|
15
19
|
* @param {() => import('./work-worker.js').ReturnType<typeof import('./work-worker.js').createWorkRuntime> | null} [getWork]
|
|
16
20
|
*/
|
|
17
|
-
export function registerHttp(ctx, engine, getRuntime = () => null, getWork = () => null, dataDir = '') {
|
|
21
|
+
export function registerHttp(ctx, engine, getRuntime = () => null, getWork = () => null, dataDir = '', getQuestions = () => null, extras = {}) {
|
|
22
|
+
const getApprovals = extras.getApprovals ?? (() => null);
|
|
23
|
+
const getAuthorization = extras.getAuthorization ?? (() => null);
|
|
18
24
|
const webServer = ctx.webServer;
|
|
19
25
|
const storeDir = dataDir || (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
|
|
20
26
|
const profileDir = ctx.profileContext?.dir || (storeDir !== '' ? dirname(storeDir) : '');
|
|
21
|
-
const
|
|
27
|
+
const logService = createLogSnapshotService(createLogSource(ctx));
|
|
28
|
+
const logOnConnection = registerLogRoutes(ctx, logService);
|
|
22
29
|
const desk = profileDir === ''
|
|
23
30
|
? null
|
|
24
31
|
: createDesk({
|
|
@@ -56,15 +63,37 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
56
63
|
bots: { ok: true, sessionIds: bots.map(bot => bot.sessionId), bots },
|
|
57
64
|
};
|
|
58
65
|
}
|
|
66
|
+
// Compact reads do not enumerate the static authorization provider catalog.
|
|
67
|
+
function interactionSnapshot(sessionId, compact) {
|
|
68
|
+
return {
|
|
69
|
+
ok: true,
|
|
70
|
+
sessionId,
|
|
71
|
+
questions: sessionId || !compact ? (getQuestions()?.snapshot(sessionId || undefined) ?? []) : [],
|
|
72
|
+
approvals: sessionId || !compact ? (getApprovals()?.snapshot(sessionId || undefined) ?? []) : [],
|
|
73
|
+
authorization: getAuthorization()?.snapshot({ catalog: !compact }) ?? {
|
|
74
|
+
available: false,
|
|
75
|
+
...(compact ? { catalogRevision: 0, inFlight: [] } : { entries: [] }),
|
|
76
|
+
notices: [],
|
|
77
|
+
prompts: [],
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
59
81
|
const handler = async (req, res) => {
|
|
60
82
|
const rejection = reject(ctx, req);
|
|
61
83
|
if (rejection)
|
|
62
84
|
return send(res, rejection, { ok: false, code: 'FORBIDDEN' });
|
|
63
85
|
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
64
86
|
const rawPath = url.pathname.replace(/\/+$/, '') || '/';
|
|
87
|
+
if (!logOnConnection && rawPath.startsWith('/api/dsh-bot/log')) {
|
|
88
|
+
const response = await dispatchLogRequest(logService, await asFetchRequest(req));
|
|
89
|
+
if (response)
|
|
90
|
+
return sendFetchResponse(res, response);
|
|
91
|
+
}
|
|
65
92
|
if (rawPath === '/dsh-bot' || (rawPath.startsWith('/dsh-bot/') && !rawPath.startsWith('/dsh-bot/api'))) {
|
|
66
93
|
if (serveDesk(req, res, rawPath))
|
|
67
94
|
return;
|
|
95
|
+
if (serveWorkspaceImage(req, res, rawPath, defaultSessionCwd(process.env, { mkdir: false })))
|
|
96
|
+
return;
|
|
68
97
|
return send(res, 404, { ok: false, code: 'NOT_FOUND' });
|
|
69
98
|
}
|
|
70
99
|
const path = rawPath.startsWith('/dsh-bot/api')
|
|
@@ -90,6 +119,129 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
90
119
|
const bots = engine.listBots();
|
|
91
120
|
return send(res, 200, { ok: true, sessionIds: bots.map(bot => bot.sessionId), bots });
|
|
92
121
|
}
|
|
122
|
+
if (req.method === 'POST' && path === '/session-foundations/api/questions/answer') {
|
|
123
|
+
const questions = getQuestions();
|
|
124
|
+
if (!questions)
|
|
125
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
|
|
126
|
+
const body = await readJson(req);
|
|
127
|
+
if (typeof body.sessionId !== 'string' || body.sessionId === '') {
|
|
128
|
+
return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
|
|
129
|
+
}
|
|
130
|
+
const result = questions.submit({
|
|
131
|
+
sessionId: body.sessionId,
|
|
132
|
+
callId: typeof body.callId === 'string' ? body.callId : undefined,
|
|
133
|
+
answers: body.answers,
|
|
134
|
+
});
|
|
135
|
+
if (result.ok === false) {
|
|
136
|
+
const status = result.code === 'NOT_FOUND'
|
|
137
|
+
? 404
|
|
138
|
+
: result.code === 'CONFLICT'
|
|
139
|
+
? 409
|
|
140
|
+
: result.code === 'FORBIDDEN'
|
|
141
|
+
? 403
|
|
142
|
+
: result.code === 'UNAVAILABLE'
|
|
143
|
+
? 503
|
|
144
|
+
: 400;
|
|
145
|
+
return send(res, status, result);
|
|
146
|
+
}
|
|
147
|
+
return send(res, 200, result);
|
|
148
|
+
}
|
|
149
|
+
if (req.method === 'POST' && path === '/session-foundations/api/questions/cancel') {
|
|
150
|
+
const questions = getQuestions();
|
|
151
|
+
if (!questions)
|
|
152
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
|
|
153
|
+
const body = await readJson(req);
|
|
154
|
+
return sendTool(res, questions.cancel({
|
|
155
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
|
|
156
|
+
callId: typeof body.callId === 'string' ? body.callId : undefined,
|
|
157
|
+
answers: Array.isArray(body.answers) ? body.answers : undefined,
|
|
158
|
+
}));
|
|
159
|
+
}
|
|
160
|
+
if (req.method === 'POST' && path === '/session-foundations/api/questions/timeout') {
|
|
161
|
+
const questions = getQuestions();
|
|
162
|
+
if (!questions)
|
|
163
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
|
|
164
|
+
const body = await readJson(req);
|
|
165
|
+
return sendTool(res, questions.timeout({
|
|
166
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
|
|
167
|
+
callId: typeof body.callId === 'string' ? body.callId : undefined,
|
|
168
|
+
}));
|
|
169
|
+
}
|
|
170
|
+
if (req.method === 'POST' && path === '/session-foundations/api/questions/take-time') {
|
|
171
|
+
const questions = getQuestions();
|
|
172
|
+
if (!questions)
|
|
173
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
|
|
174
|
+
const body = await readJson(req);
|
|
175
|
+
return sendTool(res, questions.takeTime({
|
|
176
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
|
|
177
|
+
callId: typeof body.callId === 'string' ? body.callId : undefined,
|
|
178
|
+
}));
|
|
179
|
+
}
|
|
180
|
+
if (req.method === 'GET' && path === '/session-foundations/api/interactions') {
|
|
181
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
182
|
+
return send(res, 200, interactionSnapshot(sessionId, url.searchParams.get('compact') === '1'));
|
|
183
|
+
}
|
|
184
|
+
if (req.method === 'POST' && path === '/session-foundations/api/approvals/answer') {
|
|
185
|
+
const approvals = getApprovals();
|
|
186
|
+
if (!approvals)
|
|
187
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The tool-approval answerer is not attached to this host yet.'));
|
|
188
|
+
const body = await readJson(req);
|
|
189
|
+
return sendTool(res, approvals.submit({
|
|
190
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
|
|
191
|
+
requestId: typeof body.requestId === 'string' ? body.requestId : '',
|
|
192
|
+
outcome: body.outcome,
|
|
193
|
+
}));
|
|
194
|
+
}
|
|
195
|
+
if (req.method === 'GET' && path === '/session-foundations/api/permissions') {
|
|
196
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
197
|
+
return send(res, 200, { ok: true, ...permissionView(ctx, sessionId) });
|
|
198
|
+
}
|
|
199
|
+
if (req.method === 'POST' && path === '/session-foundations/api/permissions') {
|
|
200
|
+
const body = await readJson(req);
|
|
201
|
+
return sendTool(res, setPermission(ctx, typeof body.sessionId === 'string' ? body.sessionId : '', typeof body.name === 'string' ? body.name : ''));
|
|
202
|
+
}
|
|
203
|
+
if (req.method === 'GET' && path === '/session-foundations/api/authorization') {
|
|
204
|
+
const authorization = getAuthorization();
|
|
205
|
+
if (!authorization)
|
|
206
|
+
return send(res, 200, { ok: true, available: false, entries: [], notices: [], prompts: [] });
|
|
207
|
+
return send(res, 200, { ok: true, ...authorization.snapshot() });
|
|
208
|
+
}
|
|
209
|
+
if (req.method === 'POST' && path === '/session-foundations/api/authorization/begin') {
|
|
210
|
+
const authorization = getAuthorization();
|
|
211
|
+
if (!authorization)
|
|
212
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
|
|
213
|
+
const body = await readJson(req);
|
|
214
|
+
return sendTool(res, await authorization.begin({
|
|
215
|
+
key: body.key,
|
|
216
|
+
method: typeof body.method === 'string' ? body.method : undefined,
|
|
217
|
+
}));
|
|
218
|
+
}
|
|
219
|
+
if (req.method === 'POST' && path === '/session-foundations/api/authorization/answer') {
|
|
220
|
+
const authorization = getAuthorization();
|
|
221
|
+
if (!authorization)
|
|
222
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
|
|
223
|
+
const body = await readJson(req);
|
|
224
|
+
return sendTool(res, authorization.answer({
|
|
225
|
+
promptId: typeof body.promptId === 'string' ? body.promptId : '',
|
|
226
|
+
value: typeof body.value === 'string' ? body.value : undefined,
|
|
227
|
+
declined: body.declined === true,
|
|
228
|
+
}));
|
|
229
|
+
}
|
|
230
|
+
if (req.method === 'POST' && path === '/session-foundations/api/authorization/cancel') {
|
|
231
|
+
const authorization = getAuthorization();
|
|
232
|
+
if (!authorization)
|
|
233
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
|
|
234
|
+
const body = await readJson(req);
|
|
235
|
+
return sendTool(res, authorization.cancel({ key: body.key }));
|
|
236
|
+
}
|
|
237
|
+
if (req.method === 'GET' && path === '/session-foundations/api/cua') {
|
|
238
|
+
const locale = url.searchParams.get('locale') ?? 'en';
|
|
239
|
+
return send(res, 200, { ok: true, ...(await cuaSnapshot(ctx, locale)) });
|
|
240
|
+
}
|
|
241
|
+
if (req.method === 'POST' && path === '/session-foundations/api/cua') {
|
|
242
|
+
const body = await readJson(req);
|
|
243
|
+
return sendTool(res, await cuaAction(ctx, body));
|
|
244
|
+
}
|
|
93
245
|
if (req.method === 'POST' && path === '/session-foundations/api/sessions/open') {
|
|
94
246
|
const body = await readJson(req);
|
|
95
247
|
const opened = await provisionSession(engine, body);
|
|
@@ -223,58 +375,6 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
223
375
|
const body = await readJson(req);
|
|
224
376
|
return send(res, 200, runtime.revokeWebhook(body.id));
|
|
225
377
|
}
|
|
226
|
-
if (req.method === 'GET' &&
|
|
227
|
-
(path === '/session-foundations/api/snapshot' ||
|
|
228
|
-
path === '/session-foundations/api/snapshot/chunks' ||
|
|
229
|
-
path === '/session-foundations/api/snapshot/range')) {
|
|
230
|
-
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
231
|
-
if (sessionId === '')
|
|
232
|
-
return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
|
|
233
|
-
if (path === '/session-foundations/api/snapshot/chunks') {
|
|
234
|
-
const hashes = url.searchParams.getAll('hash').filter(hash => hash !== '');
|
|
235
|
-
const taken = sessionSnapshots.take(sessionId, hashes);
|
|
236
|
-
if (!taken)
|
|
237
|
-
return send(res, 409, toolError('STALE', 'Ask for the snapshot manifest again.'));
|
|
238
|
-
return send(res, 200, taken);
|
|
239
|
-
}
|
|
240
|
-
const beforeSeq = readCount(url, 'beforeSeq');
|
|
241
|
-
const fromSeq = readCount(url, 'fromSeq');
|
|
242
|
-
const tailMessages = readCount(url, 'tailMessages');
|
|
243
|
-
if (beforeSeq === false || fromSeq === false || tailMessages === false)
|
|
244
|
-
return send(res, 400, toolError('VALIDATION', 'Sequence bounds must be non-negative integers.'));
|
|
245
|
-
/** @type {unknown[]} */
|
|
246
|
-
let events = [];
|
|
247
|
-
try {
|
|
248
|
-
events = await sessionEvents(ctx, sessionId);
|
|
249
|
-
}
|
|
250
|
-
catch (error) {
|
|
251
|
-
return send(res, 503, toolError('UNAVAILABLE', error instanceof Error ? error.message : 'The session log is not readable.'));
|
|
252
|
-
}
|
|
253
|
-
if (path === '/session-foundations/api/snapshot/range') {
|
|
254
|
-
if (typeof fromSeq !== 'number')
|
|
255
|
-
return send(res, 400, toolError('VALIDATION', 'fromSeq is required.'));
|
|
256
|
-
return send(res, 200, { ok: true, sessionId, events: eventsWindow(events, fromSeq, beforeSeq) });
|
|
257
|
-
}
|
|
258
|
-
const tail = typeof tailMessages === 'number' && tailMessages > 0 ? Math.min(tailMessages, 80) : null;
|
|
259
|
-
const cut = typeof beforeSeq === 'number' ? beforeSeq : tail == null ? null : followTailStart(events, tail);
|
|
260
|
-
const source = cut == null ? events : eventsBefore(events, cut);
|
|
261
|
-
if (source.length === 0) {
|
|
262
|
-
return send(res, 200, {
|
|
263
|
-
ok: true,
|
|
264
|
-
sessionId,
|
|
265
|
-
epoch: '',
|
|
266
|
-
totalSize: 0,
|
|
267
|
-
hashes: [],
|
|
268
|
-
count: 0,
|
|
269
|
-
...(cut == null ? {} : { beforeSeq: cut }),
|
|
270
|
-
});
|
|
271
|
-
}
|
|
272
|
-
sessionSnapshots.publish(sessionId, source);
|
|
273
|
-
const listed = sessionSnapshots.manifest(sessionId);
|
|
274
|
-
if (listed.ok !== true)
|
|
275
|
-
return send(res, 503, toolError('UNAVAILABLE', 'The session snapshot is not ready.'));
|
|
276
|
-
return send(res, 200, cut == null ? listed : { ...listed, beforeSeq: cut });
|
|
277
|
-
}
|
|
278
378
|
if (req.method === 'GET' && path === '/session-foundations/api/live') {
|
|
279
379
|
const work = getWork();
|
|
280
380
|
if (!work)
|
|
@@ -283,6 +383,7 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
283
383
|
workStamp: () => work.liveStamp(),
|
|
284
384
|
workBoard: () => work.liveBoardAll(),
|
|
285
385
|
loadDesk: () => loadPageDesk(req),
|
|
386
|
+
interactions: () => interactionSnapshot(url.searchParams.get('sessionId') ?? '', true),
|
|
286
387
|
});
|
|
287
388
|
}
|
|
288
389
|
if (req.method === 'GET' && path === '/session-foundations/api/work/live') {
|
|
@@ -329,11 +430,20 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
329
430
|
path: '/dsh-bot',
|
|
330
431
|
handler,
|
|
331
432
|
});
|
|
433
|
+
const disposeLog = logOnConnection
|
|
434
|
+
? null
|
|
435
|
+
: webServer.register({
|
|
436
|
+
kind: 'prefix',
|
|
437
|
+
path: '/api/dsh-bot',
|
|
438
|
+
handler,
|
|
439
|
+
});
|
|
332
440
|
return () => {
|
|
333
441
|
if (typeof disposeFoundations === 'function')
|
|
334
442
|
disposeFoundations();
|
|
335
443
|
if (typeof disposeDesk === 'function')
|
|
336
444
|
disposeDesk();
|
|
445
|
+
if (typeof disposeLog === 'function')
|
|
446
|
+
disposeLog();
|
|
337
447
|
};
|
|
338
448
|
});
|
|
339
449
|
}
|
|
@@ -390,29 +500,12 @@ export function memoryView(engine, sessionId) {
|
|
|
390
500
|
state: engine.statePayload(sessionId),
|
|
391
501
|
};
|
|
392
502
|
}
|
|
393
|
-
/**
|
|
394
|
-
* A non-negative integer query, or null when the parameter is absent.
|
|
395
|
-
* @param {URL} url
|
|
396
|
-
* @param {string} name
|
|
397
|
-
* @returns {number | null | false}
|
|
398
|
-
*/
|
|
399
|
-
function readCount(url, name) {
|
|
400
|
-
const raw = url.searchParams.get(name);
|
|
401
|
-
if (raw == null || raw === '')
|
|
402
|
-
return null;
|
|
403
|
-
if (!/^\d+$/.test(raw))
|
|
404
|
-
return false;
|
|
405
|
-
const value = Number(raw);
|
|
406
|
-
if (!Number.isSafeInteger(value))
|
|
407
|
-
return false;
|
|
408
|
-
return value;
|
|
409
|
-
}
|
|
410
503
|
/**
|
|
411
504
|
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
412
505
|
* @param {import('node:http').IncomingMessage} req
|
|
413
506
|
*/
|
|
414
507
|
function reject(ctx, req) {
|
|
415
|
-
const connection = ctx
|
|
508
|
+
const connection = probeConnection(ctx);
|
|
416
509
|
const rejection = connection?.requestRejection?.(req);
|
|
417
510
|
if (rejection !== undefined)
|
|
418
511
|
return rejection;
|
|
@@ -437,6 +530,20 @@ function send(res, status, body) {
|
|
|
437
530
|
});
|
|
438
531
|
res.end(text);
|
|
439
532
|
}
|
|
533
|
+
function sendTool(res, result) {
|
|
534
|
+
if (result.ok !== false)
|
|
535
|
+
return send(res, 200, result);
|
|
536
|
+
const status = result.code === 'NOT_FOUND'
|
|
537
|
+
? 404
|
|
538
|
+
: result.code === 'CONFLICT' || result.code === 'ALREADY_IN_FLIGHT' || result.code === 'REPLY_QUEUED'
|
|
539
|
+
? 409
|
|
540
|
+
: result.code === 'FORBIDDEN'
|
|
541
|
+
? 403
|
|
542
|
+
: result.code === 'UNAVAILABLE'
|
|
543
|
+
? 503
|
|
544
|
+
: 400;
|
|
545
|
+
return send(res, status, result);
|
|
546
|
+
}
|
|
440
547
|
/**
|
|
441
548
|
* @param {import('node:http').IncomingMessage} req
|
|
442
549
|
*/
|
|
@@ -587,6 +694,8 @@ const DESK_TYPES = new Map([
|
|
|
587
694
|
['.svg', 'image/svg+xml'],
|
|
588
695
|
['.json', 'application/json; charset=utf-8'],
|
|
589
696
|
['.map', 'application/json; charset=utf-8'],
|
|
697
|
+
['.jpg', 'image/jpeg'],
|
|
698
|
+
['.jpeg', 'image/jpeg'],
|
|
590
699
|
['.png', 'image/png'],
|
|
591
700
|
['.webp', 'image/webp'],
|
|
592
701
|
['.woff2', 'font/woff2'],
|
|
@@ -629,3 +738,26 @@ function serveDesk(req, res, pathname) {
|
|
|
629
738
|
createReadStream(file).pipe(res);
|
|
630
739
|
return true;
|
|
631
740
|
}
|
|
741
|
+
async function asFetchRequest(req) {
|
|
742
|
+
const host = req.headers.host ?? '127.0.0.1';
|
|
743
|
+
const url = `http://${host}${req.url ?? '/'}`;
|
|
744
|
+
const headers = new Headers();
|
|
745
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
746
|
+
if (typeof value === 'string')
|
|
747
|
+
headers.set(name, value);
|
|
748
|
+
else if (Array.isArray(value)) {
|
|
749
|
+
for (const item of value)
|
|
750
|
+
headers.append(name, item);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
return new Request(url, { method: req.method ?? 'GET', headers });
|
|
754
|
+
}
|
|
755
|
+
async function sendFetchResponse(res, response) {
|
|
756
|
+
const headers = {};
|
|
757
|
+
response.headers.forEach((value, name) => {
|
|
758
|
+
headers[name] = value;
|
|
759
|
+
});
|
|
760
|
+
const body = response.body ? Buffer.from(await response.arrayBuffer()) : Buffer.alloc(0);
|
|
761
|
+
res.writeHead(response.status, headers);
|
|
762
|
+
res.end(body);
|
|
763
|
+
}
|
package/dist/inbox.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* agent.followup(), which appends agent/inbox/spliced and wakes a later turn.
|
|
4
4
|
* This module does not keep a second execution queue.
|
|
5
5
|
*/
|
|
6
|
+
import { createLogSource, logHasMessage as eventsHaveMessage, spliceSeq as seqOfSplice, } from "./log/source.js";
|
|
6
7
|
import { workerFileSetup } from "./work-child.js";
|
|
7
8
|
const handles = new Map();
|
|
8
9
|
const loading = new Map();
|
|
@@ -79,7 +80,13 @@ export async function followupDurable(ctx, sessionId, messageId, text) {
|
|
|
79
80
|
if (!message.includes('already pending'))
|
|
80
81
|
throw error;
|
|
81
82
|
}
|
|
82
|
-
|
|
83
|
+
let seq = null;
|
|
84
|
+
try {
|
|
85
|
+
seq = seqOfSplice((await createLogSource(ctx).read(sessionId, -1)).events, messageId);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
seq = spliceSeq(agent.session, messageId);
|
|
89
|
+
}
|
|
83
90
|
let flushed = false;
|
|
84
91
|
let flushError = '';
|
|
85
92
|
try {
|
|
@@ -102,9 +109,12 @@ export async function followupDurable(ctx, sessionId, messageId, text) {
|
|
|
102
109
|
* @param {string} messageId
|
|
103
110
|
*/
|
|
104
111
|
export function logHasMessage(session, messageId) {
|
|
105
|
-
const events =
|
|
106
|
-
|
|
107
|
-
|
|
112
|
+
const events = Array.isArray(session)
|
|
113
|
+
? session
|
|
114
|
+
: 'snapshotEvents' in session
|
|
115
|
+
? (session.snapshotEvents?.() ?? [])
|
|
116
|
+
: [];
|
|
117
|
+
return eventsHaveMessage(events, messageId);
|
|
108
118
|
}
|
|
109
119
|
/**
|
|
110
120
|
* Live snapshot when the agent is already entered. Otherwise a read-only
|
|
@@ -114,34 +124,8 @@ export function logHasMessage(session, messageId) {
|
|
|
114
124
|
* @returns {Promise<Array<{ type?: string, seq?: number, data?: { id?: string, message?: { id?: string }, inserted?: Array<{ id?: string }> } }>>}
|
|
115
125
|
*/
|
|
116
126
|
export async function sessionEvents(ctx, sessionId) {
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
return agent.session.snapshotEvents();
|
|
120
|
-
const persistence = ctx.sessionPersistence;
|
|
121
|
-
if (!persistence?.open)
|
|
122
|
-
throw new Error('session log is not readable');
|
|
123
|
-
/** @type {{ read?: () => Promise<{ events?: unknown[] }>, close?: () => Promise<void> } | undefined} */
|
|
124
|
-
let handle;
|
|
125
|
-
try {
|
|
126
|
-
handle = await persistence.open(sessionId, 'read');
|
|
127
|
-
const page = typeof handle?.read === 'function' ? await handle.read() : { events: [] };
|
|
128
|
-
return Array.isArray(page?.events) ? page.events : [];
|
|
129
|
-
}
|
|
130
|
-
catch (error) {
|
|
131
|
-
if (missingSession(error))
|
|
132
|
-
return [];
|
|
133
|
-
throw error;
|
|
134
|
-
}
|
|
135
|
-
finally {
|
|
136
|
-
await handle?.close?.().catch(() => { });
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* @param {unknown} error
|
|
141
|
-
*/
|
|
142
|
-
function missingSession(error) {
|
|
143
|
-
const name = error instanceof Error ? error.name : '';
|
|
144
|
-
return name === 'SessionPersistenceNotFoundError' || name === 'SessionNotFoundError';
|
|
127
|
+
const { events } = await createLogSource(ctx).read(sessionId, -1);
|
|
128
|
+
return events;
|
|
145
129
|
}
|
|
146
130
|
/**
|
|
147
131
|
* @param {{ snapshotEvents?: () => Array<{ type?: string, seq?: number, data?: { inserted?: Array<{ id?: string }> } }> }} session
|
|
@@ -184,14 +168,16 @@ export function userMessage(messageId, text) {
|
|
|
184
168
|
* @param {{ data?: { inserted?: Array<{ id?: string }> } }} event
|
|
185
169
|
*/
|
|
186
170
|
function insertedIds(event) {
|
|
187
|
-
const
|
|
171
|
+
const data = event.data && typeof event.data === 'object' ? event.data : null;
|
|
172
|
+
const inserted = data?.inserted;
|
|
188
173
|
if (!Array.isArray(inserted))
|
|
189
174
|
return [];
|
|
190
|
-
return inserted.map(message => message?.id).filter(id => typeof id === 'string');
|
|
175
|
+
return inserted.map(message => message?.id).filter((id) => typeof id === 'string');
|
|
191
176
|
}
|
|
192
177
|
/**
|
|
193
178
|
* @param {{ data?: { id?: string, message?: { id?: string } } }} event
|
|
194
179
|
*/
|
|
195
180
|
function messageIdOf(event) {
|
|
196
|
-
|
|
181
|
+
const data = event.data && typeof event.data === 'object' ? event.data : null;
|
|
182
|
+
return data?.id ?? data?.message?.id ?? '';
|
|
197
183
|
}
|
package/dist/index.js
CHANGED
|
@@ -5,16 +5,29 @@ import { createEngine } from "./engine.js";
|
|
|
5
5
|
import { renderPeers, renderSession, renderTickets } from "./context.js";
|
|
6
6
|
import { toolDefinitions } from "./tools.js";
|
|
7
7
|
import { createTriggers } from "./triggers.js";
|
|
8
|
-
import { followupDurable, liveAgent, logHasMessage, removePending
|
|
8
|
+
import { followupDurable, liveAgent, logHasMessage, removePending } from "./inbox.js";
|
|
9
|
+
import { createLogSource } from "./log/source.js";
|
|
9
10
|
import { toolError } from "./errors.js";
|
|
11
|
+
import { createQuestionAnswerer, publishQuestionAnswerer, questionAnswererFor } from "./questions.js";
|
|
12
|
+
import { createApprovalAnswerer, publishApprovalAnswerer, approvalAnswererFor } from "./approvals.js";
|
|
13
|
+
import { createAuthorizationController, publishAuthorization, authorizationFor } from "./authorization.js";
|
|
10
14
|
import { publishRuntime, publishWorkRuntime, runtimeFor } from "./runtime-registry.js";
|
|
11
|
-
import { childCreateOptions, resolveWorkBudget, WORK_BUDGET_ENV } from "./work-admit.js";
|
|
15
|
+
import { childCreateOptions, effectiveWorkLimits, resolveWorkBudget, WORK_BUDGET_ENV, } from "./work-admit.js";
|
|
12
16
|
import { ensureWorkerFilePreset, WORKER_FILE_PRESET, workerFileSetup } from "./work-child.js";
|
|
13
17
|
import { BUDGET_NOTICE_PREFIX, createWorkRuntime } from "./work-worker.js";
|
|
14
18
|
import { workToolDefinitions } from "./work-tools.js";
|
|
15
19
|
export const name = 'session-foundations';
|
|
16
20
|
// Cordis throws if a plugin reads a service it did not inject. Crash recovery reads the session log through this one.
|
|
17
|
-
export const inject = [
|
|
21
|
+
export const inject = [
|
|
22
|
+
'systemPrompt',
|
|
23
|
+
'tools',
|
|
24
|
+
'sessions',
|
|
25
|
+
'agents',
|
|
26
|
+
'agentPresets',
|
|
27
|
+
'sessionPersistence',
|
|
28
|
+
'sessionQuery',
|
|
29
|
+
'userQuestions',
|
|
30
|
+
];
|
|
18
31
|
/**
|
|
19
32
|
* @param {import('./host.ts').PluginHost} ctx
|
|
20
33
|
* @param {{ dataDir?: string, contextWindow?: number, traceEvents?: boolean, timerTickMs?: number }} [config]
|
|
@@ -200,10 +213,12 @@ export function apply(ctx, config = {}) {
|
|
|
200
213
|
const gate = work;
|
|
201
214
|
// Main-session step budget: refuse the next step instead of cancelling a
|
|
202
215
|
// step that already ended. A refused step ends the turn as `blocked`.
|
|
203
|
-
ctx.on('agent/pre-step', (payload, next) => {
|
|
216
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
204
217
|
const sessionId = payload?.agent?.id;
|
|
205
218
|
if (typeof sessionId !== 'string' || sessionId === '')
|
|
206
219
|
return next();
|
|
220
|
+
if (!(await gate.waitForBudget(sessionId, payload?.signal)))
|
|
221
|
+
return { kind: 'reject' };
|
|
207
222
|
const decision = gate.gateStep(sessionId, {
|
|
208
223
|
turn: payload?.turn,
|
|
209
224
|
step: payload?.step,
|
|
@@ -224,6 +239,27 @@ export function apply(ctx, config = {}) {
|
|
|
224
239
|
triggers?.tick().catch(() => { });
|
|
225
240
|
work?.tick().catch(() => { });
|
|
226
241
|
}
|
|
242
|
+
const questions = createQuestionAnswerer();
|
|
243
|
+
publishQuestionAnswerer(store.root, questions);
|
|
244
|
+
ctx.effect(() => questions.listen(ctx));
|
|
245
|
+
ctx.effect(() => () => {
|
|
246
|
+
if (questionAnswererFor(store.root) === questions)
|
|
247
|
+
publishQuestionAnswerer(store.root, null);
|
|
248
|
+
});
|
|
249
|
+
const approvals = createApprovalAnswerer();
|
|
250
|
+
publishApprovalAnswerer(store.root, approvals);
|
|
251
|
+
ctx.effect(() => approvals.listen(ctx));
|
|
252
|
+
ctx.effect(() => () => {
|
|
253
|
+
if (approvalAnswererFor(store.root) === approvals)
|
|
254
|
+
publishApprovalAnswerer(store.root, null);
|
|
255
|
+
});
|
|
256
|
+
const authorization = createAuthorizationController();
|
|
257
|
+
publishAuthorization(store.root, authorization);
|
|
258
|
+
ctx.effect(() => authorization.bind(ctx));
|
|
259
|
+
ctx.effect(() => () => {
|
|
260
|
+
if (authorizationFor(store.root) === authorization)
|
|
261
|
+
publishAuthorization(store.root, null);
|
|
262
|
+
});
|
|
227
263
|
ctx.logger?.info?.('session-foundations: ready dir=%s bindings=%s promoted=%s', dataDir, recovery.bindings, recovery.promoted.length);
|
|
228
264
|
}
|
|
229
265
|
/**
|
|
@@ -277,8 +313,16 @@ function startWork(ctx, store, engine, config) {
|
|
|
277
313
|
if (resolved.ignored.length > 0) {
|
|
278
314
|
ctx.logger?.warn?.('session-foundations: ignored work budget keys %s', resolved.ignored.join(','));
|
|
279
315
|
}
|
|
280
|
-
|
|
316
|
+
if (resolved.clamped.length > 0) {
|
|
317
|
+
ctx.logger?.warn?.('session-foundations: clamped work budget keys %s', resolved.clamped.join(','));
|
|
318
|
+
}
|
|
319
|
+
const slots = effectiveWorkLimits(resolved.budget);
|
|
320
|
+
ctx.logger?.info?.('session-foundations: main budget chat=%s steps/%sms main=%s steps/%sms slots perBot=%s global=%s queue perBot=%s global=%s', resolved.budget.chatMaxSteps, resolved.budget.chatWallMs, resolved.budget.mainMaxSteps, resolved.budget.mainWallMs, slots.perBot, slots.global, slots.perBotQueue, slots.globalQueue);
|
|
321
|
+
if (resolved.budget.perBot > resolved.budget.global || resolved.budget.perBotQueue > resolved.budget.globalQueue) {
|
|
322
|
+
ctx.logger?.info?.('session-foundations: per-bot cap reduced to the global cap (perBot=%s global=%s perBotQueue=%s globalQueue=%s)', resolved.budget.perBot, resolved.budget.global, resolved.budget.perBotQueue, resolved.budget.globalQueue);
|
|
323
|
+
}
|
|
281
324
|
const work = createWorkRuntime(store, engine, {
|
|
325
|
+
resumePaused: true,
|
|
282
326
|
budget: resolved.budget,
|
|
283
327
|
log: (level, message) => {
|
|
284
328
|
const sink = level === 'warn' ? (ctx.logger?.warn ?? ctx.logger?.info) : ctx.logger?.info;
|
|
@@ -348,12 +392,13 @@ function startWork(ctx, store, engine, config) {
|
|
|
348
392
|
},
|
|
349
393
|
snapshot: async (sessionId) => {
|
|
350
394
|
try {
|
|
351
|
-
return await
|
|
395
|
+
return (await createLogSource(ctx).read(sessionId, -1)).events;
|
|
352
396
|
}
|
|
353
397
|
catch {
|
|
354
398
|
return [];
|
|
355
399
|
}
|
|
356
400
|
},
|
|
401
|
+
childPresent: sessionId => liveAgent(ctx, sessionId) != null,
|
|
357
402
|
});
|
|
358
403
|
publishWorkRuntime(store.root, work);
|
|
359
404
|
ctx.effect(() => () => {
|
|
@@ -480,8 +525,8 @@ function triggerTool(name, description, parameters, run, isBot) {
|
|
|
480
525
|
* @param {string} messageId
|
|
481
526
|
*/
|
|
482
527
|
async function logHasDurable(ctx, sessionId, messageId) {
|
|
483
|
-
const events = await
|
|
484
|
-
return logHasMessage(
|
|
528
|
+
const { events } = await createLogSource(ctx).read(sessionId, -1);
|
|
529
|
+
return logHasMessage(events, messageId);
|
|
485
530
|
}
|
|
486
531
|
/**
|
|
487
532
|
* @param {{ data?: { message?: { content?: Array<{ type?: string, text?: string }> }, content?: Array<{ type?: string, text?: string }> } }} event
|
package/dist/live-snapshot.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { planChunks } from "./cdc.js";
|
|
2
|
+
import { stableStringify } from "./log/canonical.js";
|
|
2
3
|
/**
|
|
3
4
|
* Session history is one canonical JSON array of the host event log.
|
|
4
5
|
* FastCDC is only for that blob, and only when a session is opened.
|
|
@@ -9,21 +10,7 @@ const PLAN_LIMIT = 8;
|
|
|
9
10
|
* Sorted-key JSON, so the same log cuts into the same chunks.
|
|
10
11
|
* Array order is the host order.
|
|
11
12
|
*/
|
|
12
|
-
export
|
|
13
|
-
if (value === undefined)
|
|
14
|
-
return 'null';
|
|
15
|
-
if (value instanceof Date)
|
|
16
|
-
return JSON.stringify(value);
|
|
17
|
-
if (value === null || typeof value !== 'object')
|
|
18
|
-
return JSON.stringify(value) ?? 'null';
|
|
19
|
-
if (Array.isArray(value))
|
|
20
|
-
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
|
21
|
-
const record = value;
|
|
22
|
-
const keys = Object.keys(record)
|
|
23
|
-
.filter(key => record[key] !== undefined)
|
|
24
|
-
.sort();
|
|
25
|
-
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
|
|
26
|
-
}
|
|
13
|
+
export { stableStringify } from "./log/canonical.js";
|
|
27
14
|
export function canonicalBytes(value) {
|
|
28
15
|
return Buffer.from(stableStringify(value), 'utf8');
|
|
29
16
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sorted-key JSON used as the event-log canonical form.
|
|
3
|
+
* NDJSON is one event per line, so an append only changes the tail.
|
|
4
|
+
*/
|
|
5
|
+
export function stableStringify(value) {
|
|
6
|
+
if (value === undefined)
|
|
7
|
+
return 'null';
|
|
8
|
+
if (value instanceof Date)
|
|
9
|
+
return JSON.stringify(value);
|
|
10
|
+
if (value === null || typeof value !== 'object')
|
|
11
|
+
return JSON.stringify(value) ?? 'null';
|
|
12
|
+
if (Array.isArray(value))
|
|
13
|
+
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
|
14
|
+
const record = value;
|
|
15
|
+
const keys = Object.keys(record)
|
|
16
|
+
.filter(key => record[key] !== undefined)
|
|
17
|
+
.sort();
|
|
18
|
+
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
|
|
19
|
+
}
|
|
20
|
+
export function canonicalBytes(value) {
|
|
21
|
+
return Buffer.from(stableStringify(value), 'utf8');
|
|
22
|
+
}
|
|
23
|
+
export function eventNdjson(events) {
|
|
24
|
+
const parts = [];
|
|
25
|
+
const lines = [];
|
|
26
|
+
let offset = 0;
|
|
27
|
+
for (const event of events) {
|
|
28
|
+
const seq = event && typeof event === 'object' && typeof event.seq === 'number'
|
|
29
|
+
? event.seq
|
|
30
|
+
: lines.length;
|
|
31
|
+
const line = Buffer.from(`${stableStringify(event)}\n`, 'utf8');
|
|
32
|
+
lines.push({ seq, start: offset, end: offset + line.length });
|
|
33
|
+
parts.push(line);
|
|
34
|
+
offset += line.length;
|
|
35
|
+
}
|
|
36
|
+
return { bytes: parts.length ? Buffer.concat(parts) : Buffer.alloc(0), lines };
|
|
37
|
+
}
|