@thready-web/dsh-bot-plugin 0.0.0-stage → 0.1.0-beta.1
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/LICENSE +21 -0
- package/README.md +45 -2
- package/client.js +646 -0
- package/dist/cdc.js +73 -0
- package/dist/cli.js +352 -0
- package/dist/context.js +262 -0
- package/dist/cron.js +98 -0
- package/dist/desk-ledger.js +91 -0
- package/dist/desk.js +518 -0
- package/dist/engine.js +733 -0
- package/dist/errors.js +46 -0
- package/dist/fs-safe.js +100 -0
- package/dist/http-plugin.js +33 -0
- package/dist/http.js +593 -0
- package/dist/inbox.js +194 -0
- package/dist/index.js +411 -0
- package/dist/live-diff.js +188 -0
- package/dist/live-snapshot.js +152 -0
- package/dist/provision.js +44 -0
- package/dist/router-plugin.js +14 -0
- package/dist/runtime-registry.js +36 -0
- package/dist/session-files.js +111 -0
- package/dist/session-previews.js +111 -0
- package/dist/store.js +598 -0
- package/dist/tools.js +357 -0
- package/dist/triggers.js +874 -0
- package/dist/work-admit.js +128 -0
- package/dist/work-child.js +73 -0
- package/dist/work-durable.js +53 -0
- package/dist/work-http.js +287 -0
- package/dist/work-ledger.js +217 -0
- package/dist/work-mock-host.js +187 -0
- package/dist/work-mock.js +131 -0
- package/dist/work-tickets.js +1042 -0
- package/dist/work-tools.js +150 -0
- package/dist/work-worker.js +1108 -0
- package/fixtures/mock-llm.mjs +267 -0
- package/package.json +54 -4
- package/public/assets/index-Be82iGwe.css +1 -0
- package/public/assets/index-ByU9a3Lh.js +61 -0
- package/public/index.html +14 -0
package/dist/http.js
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { createReadStream, statSync } from 'node:fs';
|
|
2
|
+
import { dirname, extname, join, resolve, sep } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { createDesk } from "./desk.js";
|
|
5
|
+
import { toolError } from "./errors.js";
|
|
6
|
+
import { sessionEvents } from "./inbox.js";
|
|
7
|
+
import { createSessionSnapshots, eventsBefore, eventsWindow, followTailStart } from "./live-snapshot.js";
|
|
8
|
+
import { provisionSession } from "./provision.js";
|
|
9
|
+
import { handleWorkApi, openPageLive, openWorkLive } from "./work-http.js";
|
|
10
|
+
/**
|
|
11
|
+
* Local management routes. Model tools cannot confirm a persona or change revocation.
|
|
12
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
13
|
+
* @param {import('./engine.js').Engine} engine
|
|
14
|
+
* @param {() => import('./triggers.js').ReturnType<import('./triggers.js').createTriggers> | null} [getRuntime]
|
|
15
|
+
* @param {() => import('./work-worker.js').ReturnType<import('./work-worker.js').createWorkRuntime> | null} [getWork]
|
|
16
|
+
*/
|
|
17
|
+
export function registerHttp(ctx, engine, getRuntime = () => null, getWork = () => null, dataDir = '') {
|
|
18
|
+
const webServer = ctx.webServer;
|
|
19
|
+
const storeDir = dataDir || (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
|
|
20
|
+
const profileDir = ctx.profileContext?.dir || (storeDir !== '' ? dirname(storeDir) : '');
|
|
21
|
+
const sessionSnapshots = createSessionSnapshots();
|
|
22
|
+
const desk = profileDir === '' ? null : createDesk({
|
|
23
|
+
ledgerFile: join(storeDir, 'desk-ledger.json'),
|
|
24
|
+
profileDir,
|
|
25
|
+
sessionCwd: (process.env.THREADY_SESSION_CWD ?? '').trim(),
|
|
26
|
+
isBot: (sessionId) => engine.isBot(sessionId),
|
|
27
|
+
mark: (sessionId) => engine.markBot(sessionId),
|
|
28
|
+
hold: (sessionId) => { getWork()?.holdNotices(sessionId); },
|
|
29
|
+
release: (sessionId) => { getWork()?.releaseHold(sessionId); },
|
|
30
|
+
rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
|
|
31
|
+
usage: (req) => hostUsage(req),
|
|
32
|
+
});
|
|
33
|
+
/**
|
|
34
|
+
* @param {import('node:http').IncomingMessage} req
|
|
35
|
+
*/
|
|
36
|
+
async function loadPageDesk(req) {
|
|
37
|
+
if (!desk)
|
|
38
|
+
return null;
|
|
39
|
+
const base = 'http://127.0.0.1';
|
|
40
|
+
const [sessions, health, usage] = await Promise.all([
|
|
41
|
+
desk.handle('GET', '/session-foundations/api/sessions', new URL('/session-foundations/api/sessions', base), req),
|
|
42
|
+
desk.handle('GET', '/session-foundations/api/health', new URL('/session-foundations/api/health', base), req),
|
|
43
|
+
desk.handle('GET', '/session-foundations/api/usage', new URL('/session-foundations/api/usage', base), req),
|
|
44
|
+
]);
|
|
45
|
+
const bots = engine.listBots();
|
|
46
|
+
return {
|
|
47
|
+
sessions: sessions.body,
|
|
48
|
+
health: health.status === 200 ? health.body : null,
|
|
49
|
+
usage: usage.status === 200 ? usage.body : null,
|
|
50
|
+
bots: { ok: true, sessionIds: bots.map(bot => bot.sessionId), bots },
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
const handler = async (req, res) => {
|
|
54
|
+
const rejection = reject(ctx, req);
|
|
55
|
+
if (rejection)
|
|
56
|
+
return send(res, rejection, { ok: false, code: 'FORBIDDEN' });
|
|
57
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
58
|
+
const rawPath = url.pathname.replace(/\/+$/, '') || '/';
|
|
59
|
+
if (rawPath === '/dsh-bot' || (rawPath.startsWith('/dsh-bot/') && !rawPath.startsWith('/dsh-bot/api'))) {
|
|
60
|
+
if (serveDesk(req, res, rawPath))
|
|
61
|
+
return;
|
|
62
|
+
return send(res, 404, { ok: false, code: 'NOT_FOUND' });
|
|
63
|
+
}
|
|
64
|
+
const path = rawPath.startsWith('/dsh-bot/api')
|
|
65
|
+
? '/session-foundations/api' + rawPath.slice('/dsh-bot/api'.length)
|
|
66
|
+
: rawPath;
|
|
67
|
+
try {
|
|
68
|
+
if (desk && desk.owns(req.method ?? 'GET', path)) {
|
|
69
|
+
const outcome = await desk.handle(req.method ?? 'GET', path, url, req);
|
|
70
|
+
return send(res, outcome.status, outcome.body);
|
|
71
|
+
}
|
|
72
|
+
if (req.method === 'GET' && path === '/session-foundations/api/status') {
|
|
73
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
74
|
+
return send(res, 200, status(engine, sessionId));
|
|
75
|
+
}
|
|
76
|
+
if (req.method === 'POST' && path === '/session-foundations/api/sessions/mark') {
|
|
77
|
+
const body = await readJson(req);
|
|
78
|
+
if (typeof body.sessionId !== 'string' || body.sessionId.trim() === '')
|
|
79
|
+
return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
|
|
80
|
+
const binding = engine.markBot(body.sessionId.trim());
|
|
81
|
+
return send(res, 200, { ok: true, kind: 'bot', sessionId: binding.session_id });
|
|
82
|
+
}
|
|
83
|
+
if (req.method === 'GET' && path === '/session-foundations/api/sessions/bots') {
|
|
84
|
+
const bots = engine.listBots();
|
|
85
|
+
return send(res, 200, { ok: true, sessionIds: bots.map(bot => bot.sessionId), bots });
|
|
86
|
+
}
|
|
87
|
+
if (req.method === 'POST' && path === '/session-foundations/api/sessions/open') {
|
|
88
|
+
const body = await readJson(req);
|
|
89
|
+
const opened = await provisionSession(engine, body);
|
|
90
|
+
if (opened.ok === false)
|
|
91
|
+
return send(res, 400, opened);
|
|
92
|
+
return send(res, 200, {
|
|
93
|
+
...status(engine, opened.sessionId),
|
|
94
|
+
fact: opened.fact,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
if (req.method === 'POST' && path === '/session-foundations/api/persona/confirm') {
|
|
98
|
+
const body = await readJson(req);
|
|
99
|
+
if (typeof body.text !== 'string' || body.text.trim() === '')
|
|
100
|
+
return send(res, 400, toolError('VALIDATION', 'text is required.'));
|
|
101
|
+
const persona = engine.confirmPersona(body.text, typeof body.note === 'string' ? body.note : undefined);
|
|
102
|
+
if (typeof body.sessionId === 'string' && body.sessionId !== '') {
|
|
103
|
+
if (!engine.isBot(body.sessionId))
|
|
104
|
+
return send(res, 400, toolError('FORBIDDEN', 'Only a bot session can bind a persona.'));
|
|
105
|
+
engine.bindPersona(body.sessionId, persona.id);
|
|
106
|
+
}
|
|
107
|
+
return send(res, 200, { ok: true, persona });
|
|
108
|
+
}
|
|
109
|
+
if (req.method === 'GET' && path === '/session-foundations/api/memory') {
|
|
110
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
111
|
+
if (sessionId === '')
|
|
112
|
+
return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
|
|
113
|
+
return send(res, 200, { ok: true, ...memoryView(engine, sessionId) });
|
|
114
|
+
}
|
|
115
|
+
if (req.method === 'POST' && path === '/session-foundations/api/skills/register') {
|
|
116
|
+
const body = await readJson(req);
|
|
117
|
+
if (!engine.isBot(body.sessionId))
|
|
118
|
+
return send(res, 400, toolError('FORBIDDEN', 'Only a bot session can register a skill.'));
|
|
119
|
+
const row = engine.registerSkillFromDisk(body.sessionId, body.scope === 'private' ? 'private' : 'public', body.skillId);
|
|
120
|
+
return send(res, 200, { ok: true, skill: row });
|
|
121
|
+
}
|
|
122
|
+
const hookMatch = /^\/session-foundations\/hooks\/([^/]+)$/.exec(path);
|
|
123
|
+
if (req.method === 'POST' && hookMatch) {
|
|
124
|
+
const runtime = getRuntime();
|
|
125
|
+
if (!runtime)
|
|
126
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
127
|
+
const raw = await readRaw(req, 65536);
|
|
128
|
+
const result = await runtime.acceptWebhook(hookMatch[1], raw, {
|
|
129
|
+
timestamp: header(req, 'x-foundations-timestamp'),
|
|
130
|
+
signature: header(req, 'x-foundations-signature'),
|
|
131
|
+
eventId: header(req, 'x-foundations-event-id'),
|
|
132
|
+
});
|
|
133
|
+
return send(res, result.http, result.body);
|
|
134
|
+
}
|
|
135
|
+
if (req.method === 'POST' && path === '/session-foundations/api/messages/allow') {
|
|
136
|
+
const runtime = getRuntime();
|
|
137
|
+
if (!runtime)
|
|
138
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
139
|
+
const body = await readJson(req);
|
|
140
|
+
return send(res, 200, runtime.allow(body.targetSessionId, body.senderSessionId));
|
|
141
|
+
}
|
|
142
|
+
if (req.method === 'POST' && path === '/session-foundations/api/messages/deny') {
|
|
143
|
+
const runtime = getRuntime();
|
|
144
|
+
if (!runtime)
|
|
145
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
146
|
+
const body = await readJson(req);
|
|
147
|
+
return send(res, 200, runtime.deny(body.targetSessionId, body.senderSessionId));
|
|
148
|
+
}
|
|
149
|
+
if (req.method === 'POST' && path === '/session-foundations/api/messages/send') {
|
|
150
|
+
const runtime = getRuntime();
|
|
151
|
+
if (!runtime)
|
|
152
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
153
|
+
const body = await readJson(req);
|
|
154
|
+
if (typeof body.senderSessionId !== 'string')
|
|
155
|
+
return send(res, 400, toolError('VALIDATION', 'senderSessionId is required.'));
|
|
156
|
+
const result = await runtime.send(body.senderSessionId, body);
|
|
157
|
+
return send(res, result.ok ? 202 : 400, result);
|
|
158
|
+
}
|
|
159
|
+
if (req.method === 'GET' && path === '/session-foundations/api/deliveries') {
|
|
160
|
+
const runtime = getRuntime();
|
|
161
|
+
if (!runtime)
|
|
162
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
163
|
+
return send(res, 200, {
|
|
164
|
+
ok: true,
|
|
165
|
+
deliveries: runtime.listDeliveries(url.searchParams.get('sessionId') ?? '', url.searchParams.get('correlationId') ?? ''),
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
if (req.method === 'POST' && path === '/session-foundations/api/timers') {
|
|
169
|
+
const runtime = getRuntime();
|
|
170
|
+
if (!runtime)
|
|
171
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
172
|
+
const body = await readJson(req);
|
|
173
|
+
return send(res, 200, runtime.addSchedule({
|
|
174
|
+
sessionId: body.sessionId,
|
|
175
|
+
kind: body.kind,
|
|
176
|
+
cron: body.cron,
|
|
177
|
+
runAt: body.runAt,
|
|
178
|
+
timezone: body.timezone,
|
|
179
|
+
note: body.note,
|
|
180
|
+
}));
|
|
181
|
+
}
|
|
182
|
+
if (req.method === 'GET' && path === '/session-foundations/api/timers') {
|
|
183
|
+
const runtime = getRuntime();
|
|
184
|
+
if (!runtime)
|
|
185
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
186
|
+
return send(res, 200, { ok: true, timers: runtime.listSchedules() });
|
|
187
|
+
}
|
|
188
|
+
if (req.method === 'POST' && path === '/session-foundations/api/timers/flags') {
|
|
189
|
+
const runtime = getRuntime();
|
|
190
|
+
if (!runtime)
|
|
191
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
192
|
+
const body = await readJson(req);
|
|
193
|
+
if (body.deleted === true)
|
|
194
|
+
return send(res, 200, runtime.deleteSchedule(body.id));
|
|
195
|
+
return send(res, 200, runtime.setScheduleEnabled(body.id, body.enabled !== false));
|
|
196
|
+
}
|
|
197
|
+
if (req.method === 'POST' && path === '/session-foundations/api/webhooks') {
|
|
198
|
+
const runtime = getRuntime();
|
|
199
|
+
if (!runtime)
|
|
200
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
201
|
+
const body = await readJson(req);
|
|
202
|
+
const created = runtime.registerWebhook(body.targetSessionId);
|
|
203
|
+
if (created.ok === false)
|
|
204
|
+
return send(res, 400, created);
|
|
205
|
+
return send(res, 200, { ok: true, hook: created.hook });
|
|
206
|
+
}
|
|
207
|
+
if (req.method === 'GET' && path === '/session-foundations/api/webhooks') {
|
|
208
|
+
const runtime = getRuntime();
|
|
209
|
+
if (!runtime)
|
|
210
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
211
|
+
return send(res, 200, { ok: true, webhooks: runtime.listWebhooks() });
|
|
212
|
+
}
|
|
213
|
+
if (req.method === 'POST' && path === '/session-foundations/api/webhooks/revoke') {
|
|
214
|
+
const runtime = getRuntime();
|
|
215
|
+
if (!runtime)
|
|
216
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Triggers are not attached to this host yet.'));
|
|
217
|
+
const body = await readJson(req);
|
|
218
|
+
return send(res, 200, runtime.revokeWebhook(body.id));
|
|
219
|
+
}
|
|
220
|
+
if (req.method === 'GET' && (path === '/session-foundations/api/snapshot' || path === '/session-foundations/api/snapshot/chunks' || path === '/session-foundations/api/snapshot/range')) {
|
|
221
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
222
|
+
if (sessionId === '')
|
|
223
|
+
return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
|
|
224
|
+
if (path === '/session-foundations/api/snapshot/chunks') {
|
|
225
|
+
const hashes = url.searchParams.getAll('hash').filter(hash => hash !== '');
|
|
226
|
+
const taken = sessionSnapshots.take(sessionId, hashes);
|
|
227
|
+
if (!taken)
|
|
228
|
+
return send(res, 409, toolError('STALE', 'Ask for the snapshot manifest again.'));
|
|
229
|
+
return send(res, 200, taken);
|
|
230
|
+
}
|
|
231
|
+
const beforeSeq = readCount(url, 'beforeSeq');
|
|
232
|
+
const fromSeq = readCount(url, 'fromSeq');
|
|
233
|
+
const tailMessages = readCount(url, 'tailMessages');
|
|
234
|
+
if (beforeSeq === false || fromSeq === false || tailMessages === false)
|
|
235
|
+
return send(res, 400, toolError('VALIDATION', 'Sequence bounds must be non-negative integers.'));
|
|
236
|
+
/** @type {unknown[]} */
|
|
237
|
+
let events = [];
|
|
238
|
+
try {
|
|
239
|
+
events = await sessionEvents(ctx, sessionId);
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
return send(res, 503, toolError('UNAVAILABLE', error instanceof Error ? error.message : 'The session log is not readable.'));
|
|
243
|
+
}
|
|
244
|
+
if (path === '/session-foundations/api/snapshot/range') {
|
|
245
|
+
if (typeof fromSeq !== 'number')
|
|
246
|
+
return send(res, 400, toolError('VALIDATION', 'fromSeq is required.'));
|
|
247
|
+
return send(res, 200, { ok: true, sessionId, events: eventsWindow(events, fromSeq, beforeSeq) });
|
|
248
|
+
}
|
|
249
|
+
const tail = typeof tailMessages === 'number' && tailMessages > 0 ? Math.min(tailMessages, 80) : null;
|
|
250
|
+
const cut = typeof beforeSeq === 'number' ? beforeSeq : tail == null ? null : followTailStart(events, tail);
|
|
251
|
+
const source = cut == null ? events : eventsBefore(events, cut);
|
|
252
|
+
if (source.length === 0) {
|
|
253
|
+
return send(res, 200, { ok: true, sessionId, epoch: '', totalSize: 0, hashes: [], count: 0, ...(cut == null ? {} : { beforeSeq: cut }) });
|
|
254
|
+
}
|
|
255
|
+
sessionSnapshots.publish(sessionId, source);
|
|
256
|
+
const listed = sessionSnapshots.manifest(sessionId);
|
|
257
|
+
if (listed.ok !== true)
|
|
258
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The session snapshot is not ready.'));
|
|
259
|
+
return send(res, 200, cut == null ? listed : { ...listed, beforeSeq: cut });
|
|
260
|
+
}
|
|
261
|
+
if (req.method === 'GET' && path === '/session-foundations/api/live') {
|
|
262
|
+
const work = getWork();
|
|
263
|
+
if (!work)
|
|
264
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The work host is not attached yet.'));
|
|
265
|
+
return openPageLive(req, res, {
|
|
266
|
+
workStamp: () => work.liveStamp(),
|
|
267
|
+
workBoard: () => work.liveBoardAll(),
|
|
268
|
+
loadDesk: () => loadPageDesk(req),
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
if (req.method === 'GET' && path === '/session-foundations/api/work/live') {
|
|
272
|
+
const work = getWork();
|
|
273
|
+
if (!work)
|
|
274
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The work host is not attached yet.'));
|
|
275
|
+
return openWorkLive(req, res, url.searchParams.get('sessionId') ?? '', work);
|
|
276
|
+
}
|
|
277
|
+
if (path.startsWith('/session-foundations/api/work')) {
|
|
278
|
+
const workBody = req.method === 'GET' ? {} : await readJson(req);
|
|
279
|
+
const workHit = await handleWorkApi(req.method ?? 'GET', path, url, workBody, getWork());
|
|
280
|
+
if (workHit)
|
|
281
|
+
return send(res, workHit.status, workHit.body);
|
|
282
|
+
}
|
|
283
|
+
if (req.method === 'POST' && path === '/session-foundations/api/skills/flags') {
|
|
284
|
+
const body = await readJson(req);
|
|
285
|
+
if (!engine.isBot(body.sessionId))
|
|
286
|
+
return send(res, 400, toolError('FORBIDDEN', 'Only a bot session can change a skill.'));
|
|
287
|
+
const row = engine.setSkillFlags(body.sessionId, body.skillId, {
|
|
288
|
+
enabled: body.enabled,
|
|
289
|
+
revoked: body.revoked,
|
|
290
|
+
});
|
|
291
|
+
return send(res, 200, { ok: true, skill: row });
|
|
292
|
+
}
|
|
293
|
+
return send(res, 404, { ok: false, code: 'NOT_FOUND' });
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : 'STORE_FAILURE';
|
|
297
|
+
return send(res, code === 'VALIDATION' || code === 'NOT_FOUND' || code === 'FORBIDDEN' ? 400 : 500, {
|
|
298
|
+
ok: false,
|
|
299
|
+
code,
|
|
300
|
+
message: error instanceof Error ? error.message : String(error),
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
ctx.effect(() => {
|
|
305
|
+
const disposeFoundations = webServer.register({
|
|
306
|
+
kind: 'prefix',
|
|
307
|
+
path: '/session-foundations',
|
|
308
|
+
handler,
|
|
309
|
+
});
|
|
310
|
+
const disposeDesk = webServer.register({
|
|
311
|
+
kind: 'prefix',
|
|
312
|
+
path: '/dsh-bot',
|
|
313
|
+
handler,
|
|
314
|
+
});
|
|
315
|
+
return () => {
|
|
316
|
+
if (typeof disposeFoundations === 'function')
|
|
317
|
+
disposeFoundations();
|
|
318
|
+
if (typeof disposeDesk === 'function')
|
|
319
|
+
disposeDesk();
|
|
320
|
+
};
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* @param {import('./engine.js').Engine} engine
|
|
325
|
+
* @param {string} sessionId
|
|
326
|
+
*/
|
|
327
|
+
export function status(engine, sessionId) {
|
|
328
|
+
if (sessionId === '') {
|
|
329
|
+
const persona = engine.latestPersona();
|
|
330
|
+
return { ok: true, persona, personaText: personaText(engine, persona) };
|
|
331
|
+
}
|
|
332
|
+
const binding = engine.binding(sessionId);
|
|
333
|
+
const view = binding ? engine.currentView(sessionId) : null;
|
|
334
|
+
const persona = binding?.persona_version_id ? engine.persona(binding.persona_version_id) : null;
|
|
335
|
+
return {
|
|
336
|
+
ok: true,
|
|
337
|
+
kind: binding?.kind === 'bot' ? 'bot' : 'session',
|
|
338
|
+
binding,
|
|
339
|
+
view,
|
|
340
|
+
persona,
|
|
341
|
+
personaText: personaText(engine, persona),
|
|
342
|
+
skills: binding ? engine.store.db.prepare('SELECT skill_id, scope, version, enabled, revoked, content_hash FROM skill_bindings WHERE session_id = ?').all(sessionId) : [],
|
|
343
|
+
isolation: 'host-session-id',
|
|
344
|
+
sandbox: false,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* @param {import('./engine.js').Engine} engine
|
|
349
|
+
* @param {{ content_hash: string } | null} persona
|
|
350
|
+
*/
|
|
351
|
+
function personaText(engine, persona) {
|
|
352
|
+
if (!persona)
|
|
353
|
+
return '';
|
|
354
|
+
const bytes = engine.store.readBlob('persona', persona.content_hash);
|
|
355
|
+
return bytes ? bytes.toString('utf8') : '';
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* @param {import('./engine.js').Engine} engine
|
|
359
|
+
* @param {string} sessionId
|
|
360
|
+
*/
|
|
361
|
+
export function memoryView(engine, sessionId) {
|
|
362
|
+
return {
|
|
363
|
+
facts: engine.store.db.prepare('SELECT id, content, status, revision, priority FROM facts WHERE session_id = ? ORDER BY id').all(sessionId),
|
|
364
|
+
memories: engine.store.db.prepare('SELECT id, title, content, status, revision FROM memories WHERE session_id = ? ORDER BY id').all(sessionId),
|
|
365
|
+
state: engine.statePayload(sessionId),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* A non-negative integer query, or null when the parameter is absent.
|
|
370
|
+
* @param {URL} url
|
|
371
|
+
* @param {string} name
|
|
372
|
+
* @returns {number | null | false}
|
|
373
|
+
*/
|
|
374
|
+
function readCount(url, name) {
|
|
375
|
+
const raw = url.searchParams.get(name);
|
|
376
|
+
if (raw == null || raw === '')
|
|
377
|
+
return null;
|
|
378
|
+
if (!/^\d+$/.test(raw))
|
|
379
|
+
return false;
|
|
380
|
+
const value = Number(raw);
|
|
381
|
+
if (!Number.isSafeInteger(value))
|
|
382
|
+
return false;
|
|
383
|
+
return value;
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
387
|
+
* @param {import('node:http').IncomingMessage} req
|
|
388
|
+
*/
|
|
389
|
+
function reject(ctx, req) {
|
|
390
|
+
const connection = ctx.get?.('connection') ?? ctx.connection;
|
|
391
|
+
const rejection = connection?.requestRejection?.(req);
|
|
392
|
+
if (rejection !== undefined)
|
|
393
|
+
return rejection;
|
|
394
|
+
const remote = req.socket?.remoteAddress ?? '';
|
|
395
|
+
if (remote !== '127.0.0.1' && remote !== '::1' && remote !== '::ffff:127.0.0.1')
|
|
396
|
+
return 403;
|
|
397
|
+
return 0;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* @param {import('node:http').ServerResponse} res
|
|
401
|
+
* @param {number} status
|
|
402
|
+
* @param {unknown} body
|
|
403
|
+
*/
|
|
404
|
+
function send(res, status, body) {
|
|
405
|
+
if (status === 0)
|
|
406
|
+
return;
|
|
407
|
+
const text = JSON.stringify(body);
|
|
408
|
+
res.writeHead(status, {
|
|
409
|
+
'content-type': 'application/json; charset=utf-8',
|
|
410
|
+
'content-length': Buffer.byteLength(text),
|
|
411
|
+
'cache-control': 'no-store',
|
|
412
|
+
});
|
|
413
|
+
res.end(text);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* @param {import('node:http').IncomingMessage} req
|
|
417
|
+
*/
|
|
418
|
+
/**
|
|
419
|
+
* @param {import('node:http').IncomingMessage} req
|
|
420
|
+
* @param {string} name
|
|
421
|
+
*/
|
|
422
|
+
function header(req, name) {
|
|
423
|
+
const value = req.headers[name];
|
|
424
|
+
return Array.isArray(value) ? value[0] : value;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* @param {import('node:http').IncomingMessage} req
|
|
428
|
+
* @param {number} max
|
|
429
|
+
*/
|
|
430
|
+
function readRaw(req, max) {
|
|
431
|
+
return new Promise((resolve, rejectPromise) => {
|
|
432
|
+
const chunks = [];
|
|
433
|
+
let size = 0;
|
|
434
|
+
req.on('data', chunk => {
|
|
435
|
+
size += chunk.length;
|
|
436
|
+
if (size > max) {
|
|
437
|
+
rejectPromise(Object.assign(new Error('The body is too long.'), { code: 'VALIDATION' }));
|
|
438
|
+
req.destroy();
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
chunks.push(chunk);
|
|
442
|
+
});
|
|
443
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
444
|
+
req.on('error', rejectPromise);
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
function readJson(req) {
|
|
448
|
+
return new Promise((resolve, rejectPromise) => {
|
|
449
|
+
const chunks = [];
|
|
450
|
+
req.on('data', chunk => chunks.push(chunk));
|
|
451
|
+
req.on('end', () => {
|
|
452
|
+
try {
|
|
453
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
|
|
454
|
+
}
|
|
455
|
+
catch (error) {
|
|
456
|
+
rejectPromise(Object.assign(new Error('invalid json'), { code: 'VALIDATION', cause: error }));
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
req.on('error', rejectPromise);
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Call the host RPC on this same DSH process. The cookie is the browser session cookie.
|
|
464
|
+
* This process does not read the launch token.
|
|
465
|
+
* @param {import('node:http').IncomingMessage} req
|
|
466
|
+
* @param {string} endpoint
|
|
467
|
+
* @param {Record<string, unknown>} args
|
|
468
|
+
*/
|
|
469
|
+
async function hostRpc(req, endpoint, args) {
|
|
470
|
+
const origin = localOrigin(req);
|
|
471
|
+
const cookie = header(req, 'cookie') ?? '';
|
|
472
|
+
if (origin === '' || cookie === '') {
|
|
473
|
+
return { status: 503, body: { result: { ok: false, error: { code: 'primary_unready', message: 'This process has not issued a session cookie yet.' } } } };
|
|
474
|
+
}
|
|
475
|
+
const response = await fetch(`${origin}/api/${endpoint}`, {
|
|
476
|
+
method: 'POST',
|
|
477
|
+
headers: {
|
|
478
|
+
'content-type': 'application/json',
|
|
479
|
+
accept: 'application/json',
|
|
480
|
+
cookie,
|
|
481
|
+
origin,
|
|
482
|
+
},
|
|
483
|
+
body: JSON.stringify({
|
|
484
|
+
type: 'client-request',
|
|
485
|
+
rpcId: crypto.randomUUID(),
|
|
486
|
+
method: endpoint,
|
|
487
|
+
payload: { args },
|
|
488
|
+
}),
|
|
489
|
+
});
|
|
490
|
+
const text = await response.text();
|
|
491
|
+
let parsed = null;
|
|
492
|
+
try {
|
|
493
|
+
parsed = JSON.parse(text);
|
|
494
|
+
}
|
|
495
|
+
catch {
|
|
496
|
+
parsed = null;
|
|
497
|
+
}
|
|
498
|
+
const result = parsed?.result ?? { ok: false, error: { code: 'bad-response', message: `HTTP ${response.status}` } };
|
|
499
|
+
return { status: response.status, body: { result } };
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* @param {import('node:http').IncomingMessage} req
|
|
503
|
+
*/
|
|
504
|
+
async function hostUsage(req) {
|
|
505
|
+
const origin = localOrigin(req);
|
|
506
|
+
const cookie = header(req, 'cookie') ?? '';
|
|
507
|
+
if (origin === '' || cookie === '')
|
|
508
|
+
return { connected: false, code: 'primary_unready', error: 'This process has not issued a session cookie yet.' };
|
|
509
|
+
let response;
|
|
510
|
+
try {
|
|
511
|
+
response = await fetch(`${origin}/ollama-usage/api/summary`, {
|
|
512
|
+
headers: { accept: 'application/json', cookie, origin },
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
catch {
|
|
516
|
+
return { connected: false, code: 'primary_down', error: 'The runtime could not be reached.' };
|
|
517
|
+
}
|
|
518
|
+
const text = await response.text();
|
|
519
|
+
let body = null;
|
|
520
|
+
try {
|
|
521
|
+
body = JSON.parse(text);
|
|
522
|
+
}
|
|
523
|
+
catch {
|
|
524
|
+
body = null;
|
|
525
|
+
}
|
|
526
|
+
if (response.status === 404)
|
|
527
|
+
return { connected: false, code: 'usage_not_installed', error: 'The usage plugin is not installed.' };
|
|
528
|
+
if (!body || body.ok !== true) {
|
|
529
|
+
return { connected: false, code: 'usage_unconfigured', status: response.status, error: typeof body?.error === 'string' ? body.error : 'The usage upstream is unavailable.' };
|
|
530
|
+
}
|
|
531
|
+
return { connected: true, summary: body };
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* @param {import('node:http').IncomingMessage} req
|
|
535
|
+
*/
|
|
536
|
+
function localOrigin(req) {
|
|
537
|
+
const port = req.socket?.localPort;
|
|
538
|
+
if (!port)
|
|
539
|
+
return '';
|
|
540
|
+
const address = req.socket?.localAddress ?? '';
|
|
541
|
+
const host = address === '::1' ? '[::1]' : '127.0.0.1';
|
|
542
|
+
return `http://${host}:${port}`;
|
|
543
|
+
}
|
|
544
|
+
const DESK_DIR = fileURLToPath(new URL('../public/', import.meta.url));
|
|
545
|
+
const DESK_TYPES = new Map([
|
|
546
|
+
['.html', 'text/html; charset=utf-8'],
|
|
547
|
+
['.js', 'text/javascript; charset=utf-8'],
|
|
548
|
+
['.css', 'text/css; charset=utf-8'],
|
|
549
|
+
['.svg', 'image/svg+xml'],
|
|
550
|
+
['.json', 'application/json; charset=utf-8'],
|
|
551
|
+
['.map', 'application/json; charset=utf-8'],
|
|
552
|
+
['.png', 'image/png'],
|
|
553
|
+
['.webp', 'image/webp'],
|
|
554
|
+
['.woff2', 'font/woff2'],
|
|
555
|
+
]);
|
|
556
|
+
/** Workbench files built into public/. API routes are handled before this. */
|
|
557
|
+
function serveDesk(req, res, pathname) {
|
|
558
|
+
if (req.method !== 'GET' && req.method !== 'HEAD')
|
|
559
|
+
return false;
|
|
560
|
+
const rel = pathname === '/dsh-bot' ? 'index.html' : pathname.slice('/dsh-bot/'.length);
|
|
561
|
+
let decoded = rel;
|
|
562
|
+
try {
|
|
563
|
+
decoded = decodeURIComponent(rel);
|
|
564
|
+
}
|
|
565
|
+
catch {
|
|
566
|
+
return false;
|
|
567
|
+
}
|
|
568
|
+
if (decoded === '' || decoded.includes('\0') || decoded.includes('..'))
|
|
569
|
+
return false;
|
|
570
|
+
const root = resolve(DESK_DIR);
|
|
571
|
+
const file = resolve(root, decoded);
|
|
572
|
+
if (file !== root && !file.startsWith(root + sep))
|
|
573
|
+
return false;
|
|
574
|
+
let stat;
|
|
575
|
+
try {
|
|
576
|
+
stat = statSync(file);
|
|
577
|
+
}
|
|
578
|
+
catch {
|
|
579
|
+
return false;
|
|
580
|
+
}
|
|
581
|
+
if (!stat.isFile())
|
|
582
|
+
return false;
|
|
583
|
+
res.writeHead(200, {
|
|
584
|
+
'content-type': DESK_TYPES.get(extname(file)) ?? 'application/octet-stream',
|
|
585
|
+
'content-length': stat.size,
|
|
586
|
+
'cache-control': extname(file) === '.html' ? 'no-store' : 'public, max-age=31536000, immutable',
|
|
587
|
+
});
|
|
588
|
+
if (req.method === 'HEAD')
|
|
589
|
+
res.end();
|
|
590
|
+
else
|
|
591
|
+
createReadStream(file).pipe(res);
|
|
592
|
+
return true;
|
|
593
|
+
}
|