@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 0.1.0-beta.10
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/client.js +646 -621
- package/dist/approvals.js +160 -0
- package/dist/authorization.js +225 -0
- package/dist/cli.js +32 -12
- package/dist/context.js +59 -17
- package/dist/cron.js +1 -1
- package/dist/cua-access.js +79 -0
- package/dist/desk.js +314 -37
- package/dist/engine.js +178 -84
- package/dist/fs-safe.js +1 -1
- package/dist/host.js +1 -0
- package/dist/http-plugin.js +14 -4
- package/dist/http.js +383 -85
- package/dist/inbox.js +51 -40
- package/dist/index.js +190 -47
- package/dist/live-diff.js +3 -1
- package/dist/live-snapshot.js +2 -13
- 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/memory-catalog.js +798 -0
- package/dist/permissions.js +86 -0
- package/dist/provision.js +2 -0
- package/dist/questions.js +407 -0
- package/dist/runtime-registry.js +4 -4
- package/dist/session-files.js +2 -2
- package/dist/session-previews.js +5 -1
- package/dist/store.js +20 -5
- package/dist/tools.js +150 -32
- package/dist/triggers.js +83 -39
- package/dist/work-admit.js +222 -25
- package/dist/work-child.js +17 -9
- package/dist/work-http.js +33 -2
- package/dist/work-ledger.js +256 -16
- package/dist/work-mock-host.js +9 -6
- package/dist/work-mock.js +29 -19
- package/dist/work-tickets.js +423 -96
- package/dist/work-tools.js +43 -6
- package/dist/work-worker.js +1028 -207
- package/dist/workspace-files.js +319 -0
- package/dist/workspace-image.js +91 -0
- package/fixtures/mock-llm.mjs +17 -2
- package/package.json +15 -5
- package/public/assets/SourceEditor-BEQaScgR.js +669 -0
- package/public/assets/SourceEditor-CJwK846Z.css +1 -0
- package/public/assets/abap-CRCWOmpq.js +1 -0
- package/public/assets/apex-DnsZk_dE.js +1 -0
- package/public/assets/azcli-1IWB1ccx.js +1 -0
- package/public/assets/bat-DPkNLes8.js +1 -0
- package/public/assets/bicep-Corcdgou.js +2 -0
- package/public/assets/cameligo-CGrWLZr3.js +1 -0
- package/public/assets/clojure-D9WOWImG.js +1 -0
- package/public/assets/codicon-DCmgc-ay.ttf +0 -0
- package/public/assets/coffee-B7EJu28W.js +1 -0
- package/public/assets/cpp-SEyurbux.js +1 -0
- package/public/assets/csharp-BoL64M5l.js +1 -0
- package/public/assets/csp-C46ZqvIl.js +1 -0
- package/public/assets/css-DQU6DXDx.js +3 -0
- package/public/assets/css.worker-DYpkewsP.js +79 -0
- package/public/assets/cssMode-gpcjCFFS.js +4 -0
- package/public/assets/cypher-D84EuPTj.js +1 -0
- package/public/assets/dart-D8lhlL1r.js +1 -0
- package/public/assets/dockerfile-DLk6rpji.js +1 -0
- package/public/assets/ecl-BO6FnfXk.js +1 -0
- package/public/assets/editor.worker-B4pQIWZD.js +12 -0
- package/public/assets/elixir-BRjLKONM.js +1 -0
- package/public/assets/flow9-Cac8vKd7.js +1 -0
- package/public/assets/freemarker2-C1qemGIt.js +3 -0
- package/public/assets/fsharp-fd1GTHhf.js +1 -0
- package/public/assets/go-O9LJTZXk.js +1 -0
- package/public/assets/graphql-LQdxqEYJ.js +1 -0
- package/public/assets/handlebars-sZqIfAlP.js +1 -0
- package/public/assets/hcl-DxDQ3s82.js +1 -0
- package/public/assets/html-Bn1WXB8L.js +1 -0
- package/public/assets/html.worker-tnXziJOq.js +456 -0
- package/public/assets/htmlMode-CvQyXnaW.js +4 -0
- package/public/assets/index-DRNkUrer.css +1 -0
- package/public/assets/index-DhL5Kdlz.js +63 -0
- package/public/assets/ini-BvajGCUy.js +1 -0
- package/public/assets/java-SYsfObOQ.js +1 -0
- package/public/assets/javascript-Ox4Jg12j.js +1 -0
- package/public/assets/json.worker-aFakAbRR.js +44 -0
- package/public/assets/jsonMode-DMR7R2dQ.js +10 -0
- package/public/assets/julia-DQXNmw_w.js +1 -0
- package/public/assets/kotlin-qQ0MG-9I.js +1 -0
- package/public/assets/less-GGFNNJHn.js +2 -0
- package/public/assets/lexon-Canl7DCW.js +1 -0
- package/public/assets/liquid-B6HxtpBd.js +1 -0
- package/public/assets/lua-D28Ae8-K.js +1 -0
- package/public/assets/m3-DPitgjJI.js +1 -0
- package/public/assets/markdown-B811l8j2.js +1 -0
- package/public/assets/mdx--jDhmrXq.js +1 -0
- package/public/assets/mips-CdjsipkG.js +1 -0
- package/public/assets/msdax-CYqgjx_P.js +1 -0
- package/public/assets/mysql-BHd6q0vd.js +1 -0
- package/public/assets/objective-c-B1aVtJYH.js +1 -0
- package/public/assets/pascal-BhNW15KB.js +1 -0
- package/public/assets/pascaligo-5jv8CcQD.js +1 -0
- package/public/assets/perl-DlYyT36c.js +1 -0
- package/public/assets/pgsql-Dy0bjov7.js +1 -0
- package/public/assets/php-120yhfDK.js +1 -0
- package/public/assets/pla-CjnFlu4u.js +1 -0
- package/public/assets/postiats-CQpG440k.js +1 -0
- package/public/assets/powerquery-DdJtto1Z.js +1 -0
- package/public/assets/powershell-Bu_VLpJB.js +1 -0
- package/public/assets/protobuf-IBS6jZEB.js +2 -0
- package/public/assets/pug-kFxLfcjb.js +1 -0
- package/public/assets/python-YjG50skX.js +1 -0
- package/public/assets/qsharp-q7JyzKFN.js +1 -0
- package/public/assets/r-BIFz-_sK.js +1 -0
- package/public/assets/razor-CEcFE3UK.js +1 -0
- package/public/assets/redis-CHOsPHWR.js +1 -0
- package/public/assets/redshift-CBifECDb.js +1 -0
- package/public/assets/restructuredtext-CghPJEOS.js +1 -0
- package/public/assets/ruby-CYWGW-b1.js +1 -0
- package/public/assets/rust-DMDD0SHb.js +1 -0
- package/public/assets/sb-BYAiYHFx.js +1 -0
- package/public/assets/scala-Bqvq8jcR.js +1 -0
- package/public/assets/scheme-Dhb-2j9p.js +1 -0
- package/public/assets/scss-CTwUZ5N7.js +3 -0
- package/public/assets/shell-CsDZo4DB.js +1 -0
- package/public/assets/solidity-CME5AdoB.js +1 -0
- package/public/assets/sophia-RYC1BQQz.js +1 -0
- package/public/assets/sparql-KEyrF7De.js +1 -0
- package/public/assets/sql-BdTr02Mf.js +1 -0
- package/public/assets/st-C7iG7M4S.js +1 -0
- package/public/assets/swift-D7IUmUK8.js +1 -0
- package/public/assets/systemverilog-DgMryOEJ.js +1 -0
- package/public/assets/tcl-PloMZuKG.js +1 -0
- package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
- package/public/assets/tsMode-g4kTQl09.js +11 -0
- package/public/assets/twig-BfRIq3la.js +1 -0
- package/public/assets/typescript-CnHeFmPW.js +1 -0
- package/public/assets/typespec-CzxlYoT_.js +1 -0
- package/public/assets/vb-BwAE3J76.js +1 -0
- package/public/assets/wgsl-B_1kOXbF.js +298 -0
- package/public/assets/xml-BFXMY9nb.js +1 -0
- package/public/assets/yaml-DNm87nSf.js +1 -0
- package/public/index.html +2 -2
- package/public/assets/index-Be82iGwe.css +0 -1
- package/public/assets/index-ByU9a3Lh.js +0 -61
package/dist/http.js
CHANGED
|
@@ -1,35 +1,58 @@
|
|
|
1
1
|
import { createReadStream, statSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
2
3
|
import { dirname, extname, join, resolve, sep } from 'node:path';
|
|
3
4
|
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import { createDesk } from "./desk.js";
|
|
5
|
+
import { createDesk, defaultSessionCwd } from "./desk.js";
|
|
6
|
+
import { serveWorkspaceImage } from "./workspace-image.js";
|
|
5
7
|
import { toolError } from "./errors.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
+
import { permissionView, setPermission } from "./permissions.js";
|
|
9
|
+
import { cuaAction, cuaSnapshot } from "./cua-access.js";
|
|
8
10
|
import { provisionSession } from "./provision.js";
|
|
9
11
|
import { handleWorkApi, openPageLive, openWorkLive } from "./work-http.js";
|
|
12
|
+
import { releaseLoadedAgent } from "./inbox.js";
|
|
13
|
+
import { createLogSource } from "./log/source.js";
|
|
14
|
+
import { createLogSnapshotService } from "./log/snapshot-service.js";
|
|
15
|
+
import { dispatchLogRequest, probeConnection, registerLogRoutes } from "./log/routes.js";
|
|
16
|
+
import { handleMemoryRoute } from "./memory-catalog.js";
|
|
10
17
|
/**
|
|
11
18
|
* Local management routes. Model tools cannot confirm a persona or change revocation.
|
|
12
19
|
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
13
20
|
* @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]
|
|
21
|
+
* @param {() => import('./triggers.js').ReturnType<typeof import('./triggers.js').createTriggers> | null} [getRuntime]
|
|
22
|
+
* @param {() => import('./work-worker.js').ReturnType<typeof import('./work-worker.js').createWorkRuntime> | null} [getWork]
|
|
16
23
|
*/
|
|
17
|
-
export function registerHttp(ctx, engine, getRuntime = () => null, getWork = () => null, dataDir = '') {
|
|
24
|
+
export function registerHttp(ctx, engine, getRuntime = () => null, getWork = () => null, dataDir = '', getQuestions = () => null, extras = {}) {
|
|
25
|
+
const getApprovals = extras.getApprovals ?? (() => null);
|
|
26
|
+
const getAuthorization = extras.getAuthorization ?? (() => null);
|
|
18
27
|
const webServer = ctx.webServer;
|
|
19
28
|
const storeDir = dataDir || (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
|
|
20
29
|
const profileDir = ctx.profileContext?.dir || (storeDir !== '' ? dirname(storeDir) : '');
|
|
21
|
-
const
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
const logService = createLogSnapshotService(createLogSource(ctx));
|
|
31
|
+
const logOnConnection = registerLogRoutes(ctx, logService);
|
|
32
|
+
const persistence = ctx.sessionPersistence;
|
|
33
|
+
const sessionsRoot = typeof persistence?.root === 'string' ? persistence.root : '';
|
|
34
|
+
const desk = profileDir === ''
|
|
35
|
+
? null
|
|
36
|
+
: createDesk({
|
|
37
|
+
ledgerFile: join(storeDir, 'desk-ledger.json'),
|
|
38
|
+
profileDir,
|
|
39
|
+
...(sessionsRoot !== '' ? { sessionsRoot, stateRoot: dirname(sessionsRoot) } : {}),
|
|
40
|
+
sessionCwd: defaultSessionCwd(process.env),
|
|
41
|
+
isBot: sessionId => engine.isBot(sessionId),
|
|
42
|
+
mark: sessionId => engine.markBot(sessionId),
|
|
43
|
+
hold: sessionId => {
|
|
44
|
+
getWork()?.holdNotices(sessionId);
|
|
45
|
+
},
|
|
46
|
+
release: sessionId => {
|
|
47
|
+
getWork()?.releaseHold(sessionId);
|
|
48
|
+
},
|
|
49
|
+
releaseLoaded: sessionId => releaseLoadedAgent(sessionId),
|
|
50
|
+
releaseAttached: sessionId => unloadAttachedSession(ctx, sessionId),
|
|
51
|
+
stillAttached: sessionId => attachedSession(ctx, sessionId),
|
|
52
|
+
rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
|
|
53
|
+
usage: req => hostUsage(req),
|
|
54
|
+
files: { home: homedir(), dshHome: process.env.DSH_HOME ?? '' },
|
|
55
|
+
});
|
|
33
56
|
/**
|
|
34
57
|
* @param {import('node:http').IncomingMessage} req
|
|
35
58
|
*/
|
|
@@ -50,21 +73,53 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
50
73
|
bots: { ok: true, sessionIds: bots.map(bot => bot.sessionId), bots },
|
|
51
74
|
};
|
|
52
75
|
}
|
|
76
|
+
// Compact reads do not enumerate the static authorization provider catalog.
|
|
77
|
+
function interactionSnapshot(sessionId, compact) {
|
|
78
|
+
return {
|
|
79
|
+
ok: true,
|
|
80
|
+
sessionId,
|
|
81
|
+
questions: sessionId || !compact ? (getQuestions()?.snapshot(sessionId || undefined) ?? []) : [],
|
|
82
|
+
approvals: sessionId || !compact ? (getApprovals()?.snapshot(sessionId || undefined) ?? []) : [],
|
|
83
|
+
authorization: getAuthorization()?.snapshot({ catalog: !compact }) ?? {
|
|
84
|
+
available: false,
|
|
85
|
+
...(compact ? { catalogRevision: 0, inFlight: [] } : { entries: [] }),
|
|
86
|
+
notices: [],
|
|
87
|
+
prompts: [],
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
53
91
|
const handler = async (req, res) => {
|
|
54
92
|
const rejection = reject(ctx, req);
|
|
55
93
|
if (rejection)
|
|
56
94
|
return send(res, rejection, { ok: false, code: 'FORBIDDEN' });
|
|
57
95
|
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
58
96
|
const rawPath = url.pathname.replace(/\/+$/, '') || '/';
|
|
97
|
+
if (!logOnConnection && rawPath.startsWith('/api/dsh-bot/log')) {
|
|
98
|
+
const response = await dispatchLogRequest(logService, await asFetchRequest(req));
|
|
99
|
+
if (response)
|
|
100
|
+
return sendFetchResponse(res, response);
|
|
101
|
+
}
|
|
59
102
|
if (rawPath === '/dsh-bot' || (rawPath.startsWith('/dsh-bot/') && !rawPath.startsWith('/dsh-bot/api'))) {
|
|
60
103
|
if (serveDesk(req, res, rawPath))
|
|
61
104
|
return;
|
|
105
|
+
if (serveWorkspaceImage(req, res, rawPath, defaultSessionCwd(process.env, { mkdir: false })))
|
|
106
|
+
return;
|
|
62
107
|
return send(res, 404, { ok: false, code: 'NOT_FOUND' });
|
|
63
108
|
}
|
|
64
109
|
const path = rawPath.startsWith('/dsh-bot/api')
|
|
65
110
|
? '/session-foundations/api' + rawPath.slice('/dsh-bot/api'.length)
|
|
66
111
|
: rawPath;
|
|
67
112
|
try {
|
|
113
|
+
if (desk && req.method === 'GET' && path === '/session-foundations/api/files/raw') {
|
|
114
|
+
return pipeDownload(res, await desk.openDownload(req, url), url.searchParams.get('inline') === '1');
|
|
115
|
+
}
|
|
116
|
+
if (desk && req.method === 'POST' && path === '/session-foundations/api/files') {
|
|
117
|
+
const outcome = await desk.saveUpload(req, url);
|
|
118
|
+
send(res, outcome.status, outcome.body);
|
|
119
|
+
if (outcome.status === 413)
|
|
120
|
+
res.on('finish', () => req.destroy());
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
68
123
|
if (desk && desk.owns(req.method ?? 'GET', path)) {
|
|
69
124
|
const outcome = await desk.handle(req.method ?? 'GET', path, url, req);
|
|
70
125
|
return send(res, outcome.status, outcome.body);
|
|
@@ -84,6 +139,129 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
84
139
|
const bots = engine.listBots();
|
|
85
140
|
return send(res, 200, { ok: true, sessionIds: bots.map(bot => bot.sessionId), bots });
|
|
86
141
|
}
|
|
142
|
+
if (req.method === 'POST' && path === '/session-foundations/api/questions/answer') {
|
|
143
|
+
const questions = getQuestions();
|
|
144
|
+
if (!questions)
|
|
145
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
|
|
146
|
+
const body = await readJson(req);
|
|
147
|
+
if (typeof body.sessionId !== 'string' || body.sessionId === '') {
|
|
148
|
+
return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
|
|
149
|
+
}
|
|
150
|
+
const result = questions.submit({
|
|
151
|
+
sessionId: body.sessionId,
|
|
152
|
+
callId: typeof body.callId === 'string' ? body.callId : undefined,
|
|
153
|
+
answers: body.answers,
|
|
154
|
+
});
|
|
155
|
+
if (result.ok === false) {
|
|
156
|
+
const status = result.code === 'NOT_FOUND'
|
|
157
|
+
? 404
|
|
158
|
+
: result.code === 'CONFLICT'
|
|
159
|
+
? 409
|
|
160
|
+
: result.code === 'FORBIDDEN'
|
|
161
|
+
? 403
|
|
162
|
+
: result.code === 'UNAVAILABLE'
|
|
163
|
+
? 503
|
|
164
|
+
: 400;
|
|
165
|
+
return send(res, status, result);
|
|
166
|
+
}
|
|
167
|
+
return send(res, 200, result);
|
|
168
|
+
}
|
|
169
|
+
if (req.method === 'POST' && path === '/session-foundations/api/questions/cancel') {
|
|
170
|
+
const questions = getQuestions();
|
|
171
|
+
if (!questions)
|
|
172
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
|
|
173
|
+
const body = await readJson(req);
|
|
174
|
+
return sendTool(res, questions.cancel({
|
|
175
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
|
|
176
|
+
callId: typeof body.callId === 'string' ? body.callId : undefined,
|
|
177
|
+
answers: Array.isArray(body.answers) ? body.answers : undefined,
|
|
178
|
+
}));
|
|
179
|
+
}
|
|
180
|
+
if (req.method === 'POST' && path === '/session-foundations/api/questions/timeout') {
|
|
181
|
+
const questions = getQuestions();
|
|
182
|
+
if (!questions)
|
|
183
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
|
|
184
|
+
const body = await readJson(req);
|
|
185
|
+
return sendTool(res, questions.timeout({
|
|
186
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
|
|
187
|
+
callId: typeof body.callId === 'string' ? body.callId : undefined,
|
|
188
|
+
}));
|
|
189
|
+
}
|
|
190
|
+
if (req.method === 'POST' && path === '/session-foundations/api/questions/take-time') {
|
|
191
|
+
const questions = getQuestions();
|
|
192
|
+
if (!questions)
|
|
193
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
|
|
194
|
+
const body = await readJson(req);
|
|
195
|
+
return sendTool(res, questions.takeTime({
|
|
196
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
|
|
197
|
+
callId: typeof body.callId === 'string' ? body.callId : undefined,
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
if (req.method === 'GET' && path === '/session-foundations/api/interactions') {
|
|
201
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
202
|
+
return send(res, 200, interactionSnapshot(sessionId, url.searchParams.get('compact') === '1'));
|
|
203
|
+
}
|
|
204
|
+
if (req.method === 'POST' && path === '/session-foundations/api/approvals/answer') {
|
|
205
|
+
const approvals = getApprovals();
|
|
206
|
+
if (!approvals)
|
|
207
|
+
return send(res, 503, toolError('UNAVAILABLE', 'The tool-approval answerer is not attached to this host yet.'));
|
|
208
|
+
const body = await readJson(req);
|
|
209
|
+
return sendTool(res, approvals.submit({
|
|
210
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
|
|
211
|
+
requestId: typeof body.requestId === 'string' ? body.requestId : '',
|
|
212
|
+
outcome: body.outcome,
|
|
213
|
+
}));
|
|
214
|
+
}
|
|
215
|
+
if (req.method === 'GET' && path === '/session-foundations/api/permissions') {
|
|
216
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
217
|
+
return send(res, 200, { ok: true, ...permissionView(ctx, sessionId) });
|
|
218
|
+
}
|
|
219
|
+
if (req.method === 'POST' && path === '/session-foundations/api/permissions') {
|
|
220
|
+
const body = await readJson(req);
|
|
221
|
+
return sendTool(res, setPermission(ctx, typeof body.sessionId === 'string' ? body.sessionId : '', typeof body.name === 'string' ? body.name : ''));
|
|
222
|
+
}
|
|
223
|
+
if (req.method === 'GET' && path === '/session-foundations/api/authorization') {
|
|
224
|
+
const authorization = getAuthorization();
|
|
225
|
+
if (!authorization)
|
|
226
|
+
return send(res, 200, { ok: true, available: false, entries: [], notices: [], prompts: [] });
|
|
227
|
+
return send(res, 200, { ok: true, ...authorization.snapshot() });
|
|
228
|
+
}
|
|
229
|
+
if (req.method === 'POST' && path === '/session-foundations/api/authorization/begin') {
|
|
230
|
+
const authorization = getAuthorization();
|
|
231
|
+
if (!authorization)
|
|
232
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
|
|
233
|
+
const body = await readJson(req);
|
|
234
|
+
return sendTool(res, await authorization.begin({
|
|
235
|
+
key: body.key,
|
|
236
|
+
method: typeof body.method === 'string' ? body.method : undefined,
|
|
237
|
+
}));
|
|
238
|
+
}
|
|
239
|
+
if (req.method === 'POST' && path === '/session-foundations/api/authorization/answer') {
|
|
240
|
+
const authorization = getAuthorization();
|
|
241
|
+
if (!authorization)
|
|
242
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
|
|
243
|
+
const body = await readJson(req);
|
|
244
|
+
return sendTool(res, authorization.answer({
|
|
245
|
+
promptId: typeof body.promptId === 'string' ? body.promptId : '',
|
|
246
|
+
value: typeof body.value === 'string' ? body.value : undefined,
|
|
247
|
+
declined: body.declined === true,
|
|
248
|
+
}));
|
|
249
|
+
}
|
|
250
|
+
if (req.method === 'POST' && path === '/session-foundations/api/authorization/cancel') {
|
|
251
|
+
const authorization = getAuthorization();
|
|
252
|
+
if (!authorization)
|
|
253
|
+
return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
|
|
254
|
+
const body = await readJson(req);
|
|
255
|
+
return sendTool(res, authorization.cancel({ key: body.key }));
|
|
256
|
+
}
|
|
257
|
+
if (req.method === 'GET' && path === '/session-foundations/api/cua') {
|
|
258
|
+
const locale = url.searchParams.get('locale') ?? 'en';
|
|
259
|
+
return send(res, 200, { ok: true, ...(await cuaSnapshot(ctx, locale)) });
|
|
260
|
+
}
|
|
261
|
+
if (req.method === 'POST' && path === '/session-foundations/api/cua') {
|
|
262
|
+
const body = await readJson(req);
|
|
263
|
+
return sendTool(res, await cuaAction(ctx, body));
|
|
264
|
+
}
|
|
87
265
|
if (req.method === 'POST' && path === '/session-foundations/api/sessions/open') {
|
|
88
266
|
const body = await readJson(req);
|
|
89
267
|
const opened = await provisionSession(engine, body);
|
|
@@ -112,6 +290,11 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
112
290
|
return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
|
|
113
291
|
return send(res, 200, { ok: true, ...memoryView(engine, sessionId) });
|
|
114
292
|
}
|
|
293
|
+
if (req.method === 'GET' && path.startsWith('/session-foundations/api/memory/')) {
|
|
294
|
+
const memoryHit = handleMemoryRoute(engine, path, url);
|
|
295
|
+
if (memoryHit)
|
|
296
|
+
return send(res, memoryHit.status, memoryHit.body);
|
|
297
|
+
}
|
|
115
298
|
if (req.method === 'POST' && path === '/session-foundations/api/skills/register') {
|
|
116
299
|
const body = await readJson(req);
|
|
117
300
|
if (!engine.isBot(body.sessionId))
|
|
@@ -217,47 +400,6 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
217
400
|
const body = await readJson(req);
|
|
218
401
|
return send(res, 200, runtime.revokeWebhook(body.id));
|
|
219
402
|
}
|
|
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
403
|
if (req.method === 'GET' && path === '/session-foundations/api/live') {
|
|
262
404
|
const work = getWork();
|
|
263
405
|
if (!work)
|
|
@@ -266,6 +408,7 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
266
408
|
workStamp: () => work.liveStamp(),
|
|
267
409
|
workBoard: () => work.liveBoardAll(),
|
|
268
410
|
loadDesk: () => loadPageDesk(req),
|
|
411
|
+
interactions: () => interactionSnapshot(url.searchParams.get('sessionId') ?? '', true),
|
|
269
412
|
});
|
|
270
413
|
}
|
|
271
414
|
if (req.method === 'GET' && path === '/session-foundations/api/work/live') {
|
|
@@ -312,11 +455,20 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
|
|
|
312
455
|
path: '/dsh-bot',
|
|
313
456
|
handler,
|
|
314
457
|
});
|
|
458
|
+
const disposeLog = logOnConnection
|
|
459
|
+
? null
|
|
460
|
+
: webServer.register({
|
|
461
|
+
kind: 'prefix',
|
|
462
|
+
path: '/api/dsh-bot',
|
|
463
|
+
handler,
|
|
464
|
+
});
|
|
315
465
|
return () => {
|
|
316
466
|
if (typeof disposeFoundations === 'function')
|
|
317
467
|
disposeFoundations();
|
|
318
468
|
if (typeof disposeDesk === 'function')
|
|
319
469
|
disposeDesk();
|
|
470
|
+
if (typeof disposeLog === 'function')
|
|
471
|
+
disposeLog();
|
|
320
472
|
};
|
|
321
473
|
});
|
|
322
474
|
}
|
|
@@ -339,7 +491,11 @@ export function status(engine, sessionId) {
|
|
|
339
491
|
view,
|
|
340
492
|
persona,
|
|
341
493
|
personaText: personaText(engine, persona),
|
|
342
|
-
skills: binding
|
|
494
|
+
skills: binding
|
|
495
|
+
? engine.store.db
|
|
496
|
+
.prepare('SELECT skill_id, scope, version, enabled, revoked, content_hash FROM skill_bindings WHERE session_id = ?')
|
|
497
|
+
.all(sessionId)
|
|
498
|
+
: [],
|
|
343
499
|
isolation: 'host-session-id',
|
|
344
500
|
sandbox: false,
|
|
345
501
|
};
|
|
@@ -360,34 +516,99 @@ function personaText(engine, persona) {
|
|
|
360
516
|
*/
|
|
361
517
|
export function memoryView(engine, sessionId) {
|
|
362
518
|
return {
|
|
363
|
-
facts: engine.store.db
|
|
364
|
-
|
|
519
|
+
facts: engine.store.db
|
|
520
|
+
.prepare('SELECT id, content, status, revision, priority FROM facts WHERE session_id = ? ORDER BY id')
|
|
521
|
+
.all(sessionId),
|
|
522
|
+
memories: engine.store.db
|
|
523
|
+
.prepare('SELECT id, title, content, status, revision FROM memories WHERE session_id = ? ORDER BY id')
|
|
524
|
+
.all(sessionId),
|
|
365
525
|
state: engine.statePayload(sessionId),
|
|
366
526
|
};
|
|
367
527
|
}
|
|
368
528
|
/**
|
|
369
|
-
* A
|
|
370
|
-
*
|
|
371
|
-
* @param {
|
|
372
|
-
* @
|
|
529
|
+
* A live store entry means some fiber still has the session open.
|
|
530
|
+
* The caller must inject `sessions`. Reading it without inject throws.
|
|
531
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
532
|
+
* @param {string} sessionId
|
|
533
|
+
*/
|
|
534
|
+
export function attachedSession(ctx, sessionId) {
|
|
535
|
+
const sessions = ctx.sessions;
|
|
536
|
+
return typeof sessions?.get === 'function' && sessions.get(sessionId) != null;
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Drop an idle session another fiber still has open, then let the caller delete its log.
|
|
540
|
+
* The host has no delete RPC. The store entry's detach is the same disposer `enter` keeps,
|
|
541
|
+
* and it emits `session/disposed`, which closes the JSONL writer.
|
|
542
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
543
|
+
* @param {string} sessionId
|
|
373
544
|
*/
|
|
374
|
-
function
|
|
375
|
-
const
|
|
376
|
-
if (
|
|
545
|
+
export async function unloadAttachedSession(ctx, sessionId) {
|
|
546
|
+
const agent = liveAgentOf(ctx, sessionId);
|
|
547
|
+
if (agent && typeof agent.cancel === 'function') {
|
|
548
|
+
try {
|
|
549
|
+
agent.cancel({ kind: 'hook', reason: 'session-delete' }, { keepInbox: false });
|
|
550
|
+
}
|
|
551
|
+
catch {
|
|
552
|
+
/* already idle */
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (agent && typeof agent.whenIdle === 'function')
|
|
556
|
+
await agent.whenIdle();
|
|
557
|
+
const writer = sessionWriter(ctx, sessionId);
|
|
558
|
+
if (writer && typeof writer.close === 'function')
|
|
559
|
+
await writer.close();
|
|
560
|
+
detachAgentEntry(ctx, sessionId);
|
|
561
|
+
detachSessionEntry(ctx, sessionId);
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
565
|
+
* @param {string} sessionId
|
|
566
|
+
*/
|
|
567
|
+
function liveAgentOf(ctx, sessionId) {
|
|
568
|
+
try {
|
|
569
|
+
return ctx.agents?.get?.(sessionId) ?? null;
|
|
570
|
+
}
|
|
571
|
+
catch {
|
|
377
572
|
return null;
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
577
|
+
* @param {string} sessionId
|
|
578
|
+
*/
|
|
579
|
+
function sessionWriter(ctx, sessionId) {
|
|
580
|
+
const writers = ctx.sessionPersistence?.tracker?.writers;
|
|
581
|
+
if (!writers || typeof writers.get !== 'function')
|
|
582
|
+
return null;
|
|
583
|
+
const writer = writers.get(sessionId);
|
|
584
|
+
return writer && typeof writer === 'object' ? writer : null;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
588
|
+
* @param {string} sessionId
|
|
589
|
+
*/
|
|
590
|
+
function detachAgentEntry(ctx, sessionId) {
|
|
591
|
+
const agents = ctx.agents;
|
|
592
|
+
const entry = agents?.store?.get?.(sessionId);
|
|
593
|
+
if (!entry || typeof agents.detachEntered !== 'function')
|
|
594
|
+
return;
|
|
595
|
+
agents.detachEntered(entry);
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
599
|
+
* @param {string} sessionId
|
|
600
|
+
*/
|
|
601
|
+
function detachSessionEntry(ctx, sessionId) {
|
|
602
|
+
const entry = ctx.sessions?.store?.get?.(sessionId);
|
|
603
|
+
if (entry && typeof entry.detach === 'function')
|
|
604
|
+
entry.detach();
|
|
384
605
|
}
|
|
385
606
|
/**
|
|
386
607
|
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
387
608
|
* @param {import('node:http').IncomingMessage} req
|
|
388
609
|
*/
|
|
389
610
|
function reject(ctx, req) {
|
|
390
|
-
const connection = ctx
|
|
611
|
+
const connection = probeConnection(ctx);
|
|
391
612
|
const rejection = connection?.requestRejection?.(req);
|
|
392
613
|
if (rejection !== undefined)
|
|
393
614
|
return rejection;
|
|
@@ -396,11 +617,35 @@ function reject(ctx, req) {
|
|
|
396
617
|
return 403;
|
|
397
618
|
return 0;
|
|
398
619
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
620
|
+
function imageMedia(name) {
|
|
621
|
+
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
|
622
|
+
if (ext === 'png')
|
|
623
|
+
return 'image/png';
|
|
624
|
+
if (ext === 'jpg' || ext === 'jpeg')
|
|
625
|
+
return 'image/jpeg';
|
|
626
|
+
if (ext === 'gif')
|
|
627
|
+
return 'image/gif';
|
|
628
|
+
if (ext === 'webp')
|
|
629
|
+
return 'image/webp';
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
function pipeDownload(res, opened, inline = false) {
|
|
633
|
+
if (!('stream' in opened))
|
|
634
|
+
return send(res, opened.status, opened.body);
|
|
635
|
+
const encoded = encodeURIComponent(opened.name);
|
|
636
|
+
const image = inline ? imageMedia(opened.name) : null;
|
|
637
|
+
res.writeHead(opened.status, {
|
|
638
|
+
'content-type': image ?? 'application/octet-stream',
|
|
639
|
+
'content-length': opened.size,
|
|
640
|
+
'content-disposition': image ? `inline; filename*=UTF-8''${encoded}` : `attachment; filename*=UTF-8''${encoded}`,
|
|
641
|
+
'x-content-type-options': 'nosniff',
|
|
642
|
+
'cache-control': 'private, no-store',
|
|
643
|
+
'content-security-policy': "default-src 'none'; sandbox",
|
|
644
|
+
});
|
|
645
|
+
opened.stream.on('error', () => res.destroy());
|
|
646
|
+
res.on('close', () => opened.stream.destroy());
|
|
647
|
+
opened.stream.pipe(res);
|
|
648
|
+
}
|
|
404
649
|
function send(res, status, body) {
|
|
405
650
|
if (status === 0)
|
|
406
651
|
return;
|
|
@@ -412,6 +657,20 @@ function send(res, status, body) {
|
|
|
412
657
|
});
|
|
413
658
|
res.end(text);
|
|
414
659
|
}
|
|
660
|
+
function sendTool(res, result) {
|
|
661
|
+
if (result.ok !== false)
|
|
662
|
+
return send(res, 200, result);
|
|
663
|
+
const status = result.code === 'NOT_FOUND'
|
|
664
|
+
? 404
|
|
665
|
+
: result.code === 'CONFLICT' || result.code === 'ALREADY_IN_FLIGHT' || result.code === 'REPLY_QUEUED'
|
|
666
|
+
? 409
|
|
667
|
+
: result.code === 'FORBIDDEN'
|
|
668
|
+
? 403
|
|
669
|
+
: result.code === 'UNAVAILABLE'
|
|
670
|
+
? 503
|
|
671
|
+
: 400;
|
|
672
|
+
return send(res, status, result);
|
|
673
|
+
}
|
|
415
674
|
/**
|
|
416
675
|
* @param {import('node:http').IncomingMessage} req
|
|
417
676
|
*/
|
|
@@ -431,7 +690,7 @@ function readRaw(req, max) {
|
|
|
431
690
|
return new Promise((resolve, rejectPromise) => {
|
|
432
691
|
const chunks = [];
|
|
433
692
|
let size = 0;
|
|
434
|
-
req.on('data', chunk => {
|
|
693
|
+
req.on('data', (chunk) => {
|
|
435
694
|
size += chunk.length;
|
|
436
695
|
if (size > max) {
|
|
437
696
|
rejectPromise(Object.assign(new Error('The body is too long.'), { code: 'VALIDATION' }));
|
|
@@ -447,7 +706,7 @@ function readRaw(req, max) {
|
|
|
447
706
|
function readJson(req) {
|
|
448
707
|
return new Promise((resolve, rejectPromise) => {
|
|
449
708
|
const chunks = [];
|
|
450
|
-
req.on('data', chunk => chunks.push(chunk));
|
|
709
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
451
710
|
req.on('end', () => {
|
|
452
711
|
try {
|
|
453
712
|
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
|
|
@@ -470,7 +729,15 @@ async function hostRpc(req, endpoint, args) {
|
|
|
470
729
|
const origin = localOrigin(req);
|
|
471
730
|
const cookie = header(req, 'cookie') ?? '';
|
|
472
731
|
if (origin === '' || cookie === '') {
|
|
473
|
-
return {
|
|
732
|
+
return {
|
|
733
|
+
status: 503,
|
|
734
|
+
body: {
|
|
735
|
+
result: {
|
|
736
|
+
ok: false,
|
|
737
|
+
error: { code: 'primary_unready', message: 'This process has not issued a session cookie yet.' },
|
|
738
|
+
},
|
|
739
|
+
},
|
|
740
|
+
};
|
|
474
741
|
}
|
|
475
742
|
const response = await fetch(`${origin}/api/${endpoint}`, {
|
|
476
743
|
method: 'POST',
|
|
@@ -526,7 +793,12 @@ async function hostUsage(req) {
|
|
|
526
793
|
if (response.status === 404)
|
|
527
794
|
return { connected: false, code: 'usage_not_installed', error: 'The usage plugin is not installed.' };
|
|
528
795
|
if (!body || body.ok !== true) {
|
|
529
|
-
return {
|
|
796
|
+
return {
|
|
797
|
+
connected: false,
|
|
798
|
+
code: 'usage_unconfigured',
|
|
799
|
+
status: response.status,
|
|
800
|
+
error: typeof body?.error === 'string' ? body.error : 'The usage upstream is unavailable.',
|
|
801
|
+
};
|
|
530
802
|
}
|
|
531
803
|
return { connected: true, summary: body };
|
|
532
804
|
}
|
|
@@ -549,9 +821,12 @@ const DESK_TYPES = new Map([
|
|
|
549
821
|
['.svg', 'image/svg+xml'],
|
|
550
822
|
['.json', 'application/json; charset=utf-8'],
|
|
551
823
|
['.map', 'application/json; charset=utf-8'],
|
|
824
|
+
['.jpg', 'image/jpeg'],
|
|
825
|
+
['.jpeg', 'image/jpeg'],
|
|
552
826
|
['.png', 'image/png'],
|
|
553
827
|
['.webp', 'image/webp'],
|
|
554
828
|
['.woff2', 'font/woff2'],
|
|
829
|
+
['.ttf', 'font/ttf'],
|
|
555
830
|
]);
|
|
556
831
|
/** Workbench files built into public/. API routes are handled before this. */
|
|
557
832
|
function serveDesk(req, res, pathname) {
|
|
@@ -591,3 +866,26 @@ function serveDesk(req, res, pathname) {
|
|
|
591
866
|
createReadStream(file).pipe(res);
|
|
592
867
|
return true;
|
|
593
868
|
}
|
|
869
|
+
async function asFetchRequest(req) {
|
|
870
|
+
const host = req.headers.host ?? '127.0.0.1';
|
|
871
|
+
const url = `http://${host}${req.url ?? '/'}`;
|
|
872
|
+
const headers = new Headers();
|
|
873
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
874
|
+
if (typeof value === 'string')
|
|
875
|
+
headers.set(name, value);
|
|
876
|
+
else if (Array.isArray(value)) {
|
|
877
|
+
for (const item of value)
|
|
878
|
+
headers.append(name, item);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return new Request(url, { method: req.method ?? 'GET', headers });
|
|
882
|
+
}
|
|
883
|
+
async function sendFetchResponse(res, response) {
|
|
884
|
+
const headers = {};
|
|
885
|
+
response.headers.forEach((value, name) => {
|
|
886
|
+
headers[name] = value;
|
|
887
|
+
});
|
|
888
|
+
const body = response.body ? Buffer.from(await response.arrayBuffer()) : Buffer.alloc(0);
|
|
889
|
+
res.writeHead(response.status, headers);
|
|
890
|
+
res.end(body);
|
|
891
|
+
}
|