@thready-web/dsh-bot-plugin 0.1.0-beta.2 → 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 +109 -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/desk.js +24 -2
- package/dist/http-plugin.js +8 -2
- package/dist/http.js +208 -76
- package/dist/inbox.js +21 -35
- package/dist/index.js +126 -9
- 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 +166 -6
- 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 +11 -1
- package/dist/work-tickets.js +212 -16
- package/dist/work-tools.js +2 -2
- package/dist/work-worker.js +788 -152
- 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-plugin.js
CHANGED
|
@@ -3,9 +3,12 @@ import { join } from 'node:path';
|
|
|
3
3
|
import { openStore } from "./store.js";
|
|
4
4
|
import { createEngine } from "./engine.js";
|
|
5
5
|
import { registerHttp } from "./http.js";
|
|
6
|
+
import { questionAnswererFor } from "./questions.js";
|
|
7
|
+
import { approvalAnswererFor } from "./approvals.js";
|
|
8
|
+
import { authorizationFor } from "./authorization.js";
|
|
6
9
|
import { runtimeFor, workRuntimeFor } from "./runtime-registry.js";
|
|
7
10
|
export const name = 'session-foundations-http';
|
|
8
|
-
export const inject = ['webServer', 'agents', 'sessionPersistence'];
|
|
11
|
+
export const inject = ['webServer', 'agents', 'sessionPersistence', 'sessionQuery'];
|
|
9
12
|
/**
|
|
10
13
|
* Local management routes for the same SQLite the main plugin uses.
|
|
11
14
|
* Loaded only on profiles that have a web server, so headless does not need it.
|
|
@@ -33,5 +36,8 @@ export function apply(ctx, config = {}) {
|
|
|
33
36
|
catch {
|
|
34
37
|
/* not created yet */
|
|
35
38
|
}
|
|
36
|
-
registerHttp(ctx, engine, () => runtimeFor(key) ?? runtimeFor(dataDir), () => workRuntimeFor(key) ?? workRuntimeFor(dataDir), dataDir)
|
|
39
|
+
registerHttp(ctx, engine, () => runtimeFor(key) ?? runtimeFor(dataDir), () => workRuntimeFor(key) ?? workRuntimeFor(dataDir), dataDir, () => questionAnswererFor(key) ?? questionAnswererFor(dataDir), {
|
|
40
|
+
getApprovals: () => approvalAnswererFor(key) ?? approvalAnswererFor(dataDir),
|
|
41
|
+
getAuthorization: () => authorizationFor(key) ?? authorizationFor(dataDir),
|
|
42
|
+
});
|
|
37
43
|
}
|
package/dist/http.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
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
|
-
import { createDesk } from "./desk.js";
|
|
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,17 +18,20 @@ 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({
|
|
25
32
|
ledgerFile: join(storeDir, 'desk-ledger.json'),
|
|
26
33
|
profileDir,
|
|
27
|
-
sessionCwd: (process.env
|
|
34
|
+
sessionCwd: defaultSessionCwd(process.env),
|
|
28
35
|
isBot: sessionId => engine.isBot(sessionId),
|
|
29
36
|
mark: sessionId => engine.markBot(sessionId),
|
|
30
37
|
hold: sessionId => {
|
|
@@ -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
|
}
|