@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 0.1.0-beta.11

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.
Files changed (160) hide show
  1. package/README.md +109 -1
  2. package/client.js +646 -621
  3. package/dist/approvals.js +160 -0
  4. package/dist/authorization.js +225 -0
  5. package/dist/canvas-http.js +248 -0
  6. package/dist/canvas-skills.js +56 -0
  7. package/dist/canvas-store.js +794 -0
  8. package/dist/canvas-tools.js +211 -0
  9. package/dist/cli.js +32 -12
  10. package/dist/context.js +60 -17
  11. package/dist/cron.js +1 -1
  12. package/dist/cua-access.js +79 -0
  13. package/dist/desk.js +314 -37
  14. package/dist/engine.js +178 -84
  15. package/dist/fs-safe.js +1 -1
  16. package/dist/host.js +1 -0
  17. package/dist/http-plugin.js +14 -4
  18. package/dist/http.js +402 -85
  19. package/dist/inbox.js +51 -40
  20. package/dist/index.js +201 -47
  21. package/dist/live-diff.js +3 -1
  22. package/dist/live-snapshot.js +2 -13
  23. package/dist/log/canonical.js +37 -0
  24. package/dist/log/plan.js +62 -0
  25. package/dist/log/routes.js +144 -0
  26. package/dist/log/snapshot-service.js +76 -0
  27. package/dist/log/source.js +173 -0
  28. package/dist/memory-catalog.js +798 -0
  29. package/dist/permissions.js +86 -0
  30. package/dist/provision.js +2 -0
  31. package/dist/questions.js +407 -0
  32. package/dist/runtime-registry.js +4 -4
  33. package/dist/session-files.js +2 -2
  34. package/dist/session-previews.js +5 -1
  35. package/dist/store.js +20 -5
  36. package/dist/tools.js +150 -32
  37. package/dist/triggers.js +83 -39
  38. package/dist/work-admit.js +222 -25
  39. package/dist/work-child.js +17 -9
  40. package/dist/work-http.js +52 -2
  41. package/dist/work-ledger.js +256 -16
  42. package/dist/work-mock-host.js +9 -6
  43. package/dist/work-mock.js +29 -19
  44. package/dist/work-tickets.js +423 -96
  45. package/dist/work-tools.js +43 -6
  46. package/dist/work-worker.js +1033 -207
  47. package/dist/workspace-files.js +319 -0
  48. package/dist/workspace-image.js +91 -0
  49. package/fixtures/mock-llm.mjs +17 -2
  50. package/package.json +16 -5
  51. package/public/assets/SourceEditor-CJwK846Z.css +1 -0
  52. package/public/assets/SourceEditor-uu0G7jsM.js +669 -0
  53. package/public/assets/abap-CRCWOmpq.js +1 -0
  54. package/public/assets/apex-DnsZk_dE.js +1 -0
  55. package/public/assets/azcli-1IWB1ccx.js +1 -0
  56. package/public/assets/bat-DPkNLes8.js +1 -0
  57. package/public/assets/bicep-Corcdgou.js +2 -0
  58. package/public/assets/cameligo-CGrWLZr3.js +1 -0
  59. package/public/assets/clojure-D9WOWImG.js +1 -0
  60. package/public/assets/codicon-DCmgc-ay.ttf +0 -0
  61. package/public/assets/coffee-B7EJu28W.js +1 -0
  62. package/public/assets/cpp-SEyurbux.js +1 -0
  63. package/public/assets/csharp-BoL64M5l.js +1 -0
  64. package/public/assets/csp-C46ZqvIl.js +1 -0
  65. package/public/assets/css-DQU6DXDx.js +3 -0
  66. package/public/assets/css.worker-DYpkewsP.js +79 -0
  67. package/public/assets/cssMode-C5DAFF5H.js +4 -0
  68. package/public/assets/cypher-D84EuPTj.js +1 -0
  69. package/public/assets/dart-D8lhlL1r.js +1 -0
  70. package/public/assets/dockerfile-DLk6rpji.js +1 -0
  71. package/public/assets/ecl-BO6FnfXk.js +1 -0
  72. package/public/assets/editor.worker-B4pQIWZD.js +12 -0
  73. package/public/assets/elixir-BRjLKONM.js +1 -0
  74. package/public/assets/flow9-Cac8vKd7.js +1 -0
  75. package/public/assets/freemarker2-DExNwSiZ.js +3 -0
  76. package/public/assets/fsharp-fd1GTHhf.js +1 -0
  77. package/public/assets/go-O9LJTZXk.js +1 -0
  78. package/public/assets/graphql-LQdxqEYJ.js +1 -0
  79. package/public/assets/handlebars-BK7YAvpQ.js +1 -0
  80. package/public/assets/hcl-DxDQ3s82.js +1 -0
  81. package/public/assets/html-CdDm_zae.js +1 -0
  82. package/public/assets/html.worker-tnXziJOq.js +456 -0
  83. package/public/assets/htmlMode-CLdn9oa1.js +4 -0
  84. package/public/assets/index-BB-QDSf2.css +1 -0
  85. package/public/assets/index-CsX-_qbo.js +62 -0
  86. package/public/assets/ini-BvajGCUy.js +1 -0
  87. package/public/assets/java-SYsfObOQ.js +1 -0
  88. package/public/assets/javascript-mLl83_3W.js +1 -0
  89. package/public/assets/json.worker-aFakAbRR.js +44 -0
  90. package/public/assets/jsonMode-B1-bihFd.js +10 -0
  91. package/public/assets/julia-DQXNmw_w.js +1 -0
  92. package/public/assets/kotlin-qQ0MG-9I.js +1 -0
  93. package/public/assets/less-GGFNNJHn.js +2 -0
  94. package/public/assets/lexon-Canl7DCW.js +1 -0
  95. package/public/assets/liquid-Cv8m0HUb.js +1 -0
  96. package/public/assets/lua-D28Ae8-K.js +1 -0
  97. package/public/assets/m3-DPitgjJI.js +1 -0
  98. package/public/assets/markdown-B811l8j2.js +1 -0
  99. package/public/assets/mdx-Q12b91rL.js +1 -0
  100. package/public/assets/mips-CdjsipkG.js +1 -0
  101. package/public/assets/msdax-CYqgjx_P.js +1 -0
  102. package/public/assets/mysql-BHd6q0vd.js +1 -0
  103. package/public/assets/objective-c-B1aVtJYH.js +1 -0
  104. package/public/assets/pascal-BhNW15KB.js +1 -0
  105. package/public/assets/pascaligo-5jv8CcQD.js +1 -0
  106. package/public/assets/perl-DlYyT36c.js +1 -0
  107. package/public/assets/pgsql-Dy0bjov7.js +1 -0
  108. package/public/assets/php-120yhfDK.js +1 -0
  109. package/public/assets/pla-CjnFlu4u.js +1 -0
  110. package/public/assets/postiats-CQpG440k.js +1 -0
  111. package/public/assets/powerquery-DdJtto1Z.js +1 -0
  112. package/public/assets/powershell-Bu_VLpJB.js +1 -0
  113. package/public/assets/protobuf-IBS6jZEB.js +2 -0
  114. package/public/assets/pug-kFxLfcjb.js +1 -0
  115. package/public/assets/python-Kda811W0.js +1 -0
  116. package/public/assets/qsharp-q7JyzKFN.js +1 -0
  117. package/public/assets/r-BIFz-_sK.js +1 -0
  118. package/public/assets/razor-CRuCpdOW.js +1 -0
  119. package/public/assets/redis-CHOsPHWR.js +1 -0
  120. package/public/assets/redshift-CBifECDb.js +1 -0
  121. package/public/assets/restructuredtext-CghPJEOS.js +1 -0
  122. package/public/assets/ruby-CYWGW-b1.js +1 -0
  123. package/public/assets/rust-DMDD0SHb.js +1 -0
  124. package/public/assets/sb-BYAiYHFx.js +1 -0
  125. package/public/assets/scala-Bqvq8jcR.js +1 -0
  126. package/public/assets/scheme-Dhb-2j9p.js +1 -0
  127. package/public/assets/scss-CTwUZ5N7.js +3 -0
  128. package/public/assets/shell-CsDZo4DB.js +1 -0
  129. package/public/assets/solidity-CME5AdoB.js +1 -0
  130. package/public/assets/sophia-RYC1BQQz.js +1 -0
  131. package/public/assets/sparql-KEyrF7De.js +1 -0
  132. package/public/assets/sql-BdTr02Mf.js +1 -0
  133. package/public/assets/st-C7iG7M4S.js +1 -0
  134. package/public/assets/swift-D7IUmUK8.js +1 -0
  135. package/public/assets/systemverilog-DgMryOEJ.js +1 -0
  136. package/public/assets/tcl-PloMZuKG.js +1 -0
  137. package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
  138. package/public/assets/tsMode-BGHcz-M3.js +11 -0
  139. package/public/assets/twig-BfRIq3la.js +1 -0
  140. package/public/assets/typescript-Db1e0DCT.js +1 -0
  141. package/public/assets/typespec-CzxlYoT_.js +1 -0
  142. package/public/assets/vb-BwAE3J76.js +1 -0
  143. package/public/assets/wgsl-B_1kOXbF.js +298 -0
  144. package/public/assets/xml-H3zzFmnd.js +1 -0
  145. package/public/assets/yaml-BQrKvmTF.js +1 -0
  146. package/public/index.html +2 -2
  147. package/skills/ui/baseline-ui/SKILL.md +85 -0
  148. package/skills/ui/bencium-innovative-ux-designer/SKILL.md +227 -0
  149. package/skills/ui/better-ui/SKILL.md +133 -0
  150. package/skills/ui/design-lab/SKILL.md +920 -0
  151. package/skills/ui/frontend-design/SKILL.md +71 -0
  152. package/skills/ui/impeccable/SKILL.md +93 -0
  153. package/skills/ui/interface-design/SKILL.md +320 -0
  154. package/skills/ui/sources.json +66 -0
  155. package/skills/ui/ui-design/SKILL.md +35 -0
  156. package/skills/ui/ui-skills-root/SKILL.md +59 -0
  157. package/skills/ui/visual-design-foundations/SKILL.md +318 -0
  158. package/skills/ui/web-design-guidelines/SKILL.md +39 -0
  159. package/public/assets/index-Be82iGwe.css +0 -1
  160. package/public/assets/index-ByU9a3Lh.js +0 -61
package/dist/http.js CHANGED
@@ -1,35 +1,61 @@
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 { sessionEvents } from "./inbox.js";
7
- import { createSessionSnapshots, eventsBefore, eventsWindow, followTailStart } from "./live-snapshot.js";
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";
17
+ import { handleCanvasApi, serveCanvasMedia } from "./canvas-http.js";
18
+ import { openCanvasStore } from "./canvas-store.js";
10
19
  /**
11
20
  * Local management routes. Model tools cannot confirm a persona or change revocation.
12
21
  * @param {import('@deepseek-ai/cordis').Context} ctx
13
22
  * @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]
23
+ * @param {() => import('./triggers.js').ReturnType<typeof import('./triggers.js').createTriggers> | null} [getRuntime]
24
+ * @param {() => import('./work-worker.js').ReturnType<typeof import('./work-worker.js').createWorkRuntime> | null} [getWork]
16
25
  */
17
- export function registerHttp(ctx, engine, getRuntime = () => null, getWork = () => null, dataDir = '') {
26
+ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = () => null, dataDir = '', getQuestions = () => null, extras = {}) {
27
+ const getApprovals = extras.getApprovals ?? (() => null);
28
+ const getAuthorization = extras.getAuthorization ?? (() => null);
18
29
  const webServer = ctx.webServer;
19
30
  const storeDir = dataDir || (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
20
31
  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
- });
32
+ const canvas = storeDir === '' ? null : openCanvasStore(join(storeDir, 'canvas.sqlite'));
33
+ const logService = createLogSnapshotService(createLogSource(ctx));
34
+ const logOnConnection = registerLogRoutes(ctx, logService);
35
+ const persistence = ctx.sessionPersistence;
36
+ const sessionsRoot = typeof persistence?.root === 'string' ? persistence.root : '';
37
+ const desk = profileDir === ''
38
+ ? null
39
+ : createDesk({
40
+ ledgerFile: join(storeDir, 'desk-ledger.json'),
41
+ profileDir,
42
+ ...(sessionsRoot !== '' ? { sessionsRoot, stateRoot: dirname(sessionsRoot) } : {}),
43
+ sessionCwd: defaultSessionCwd(process.env),
44
+ isBot: sessionId => engine.isBot(sessionId),
45
+ mark: sessionId => engine.markBot(sessionId),
46
+ hold: sessionId => {
47
+ getWork()?.holdNotices(sessionId);
48
+ },
49
+ release: sessionId => {
50
+ getWork()?.releaseHold(sessionId);
51
+ },
52
+ releaseLoaded: sessionId => releaseLoadedAgent(sessionId),
53
+ releaseAttached: sessionId => unloadAttachedSession(ctx, sessionId),
54
+ stillAttached: sessionId => attachedSession(ctx, sessionId),
55
+ rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
56
+ usage: req => hostUsage(req),
57
+ files: { home: homedir(), dshHome: process.env.DSH_HOME ?? '' },
58
+ });
33
59
  /**
34
60
  * @param {import('node:http').IncomingMessage} req
35
61
  */
@@ -50,21 +76,57 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
50
76
  bots: { ok: true, sessionIds: bots.map(bot => bot.sessionId), bots },
51
77
  };
52
78
  }
79
+ // Compact reads do not enumerate the static authorization provider catalog.
80
+ function interactionSnapshot(sessionId, compact) {
81
+ return {
82
+ ok: true,
83
+ sessionId,
84
+ questions: sessionId || !compact ? (getQuestions()?.snapshot(sessionId || undefined) ?? []) : [],
85
+ approvals: sessionId || !compact ? (getApprovals()?.snapshot(sessionId || undefined) ?? []) : [],
86
+ authorization: getAuthorization()?.snapshot({ catalog: !compact }) ?? {
87
+ available: false,
88
+ ...(compact ? { catalogRevision: 0, inFlight: [] } : { entries: [] }),
89
+ notices: [],
90
+ prompts: [],
91
+ },
92
+ };
93
+ }
53
94
  const handler = async (req, res) => {
95
+ const requestTarget = req.url ?? '/';
96
+ if ((requestTarget.split('?')[0] ?? '').startsWith('/dsh-bot/canvas-media/')) {
97
+ return serveCanvasMedia(req, res, requestTarget, canvas);
98
+ }
54
99
  const rejection = reject(ctx, req);
55
100
  if (rejection)
56
101
  return send(res, rejection, { ok: false, code: 'FORBIDDEN' });
57
102
  const url = new URL(req.url ?? '/', 'http://127.0.0.1');
58
103
  const rawPath = url.pathname.replace(/\/+$/, '') || '/';
104
+ if (!logOnConnection && rawPath.startsWith('/api/dsh-bot/log')) {
105
+ const response = await dispatchLogRequest(logService, await asFetchRequest(req));
106
+ if (response)
107
+ return sendFetchResponse(res, response);
108
+ }
59
109
  if (rawPath === '/dsh-bot' || (rawPath.startsWith('/dsh-bot/') && !rawPath.startsWith('/dsh-bot/api'))) {
60
110
  if (serveDesk(req, res, rawPath))
61
111
  return;
112
+ if (serveWorkspaceImage(req, res, rawPath, defaultSessionCwd(process.env, { mkdir: false })))
113
+ return;
62
114
  return send(res, 404, { ok: false, code: 'NOT_FOUND' });
63
115
  }
64
116
  const path = rawPath.startsWith('/dsh-bot/api')
65
117
  ? '/session-foundations/api' + rawPath.slice('/dsh-bot/api'.length)
66
118
  : rawPath;
67
119
  try {
120
+ if (desk && req.method === 'GET' && path === '/session-foundations/api/files/raw') {
121
+ return pipeDownload(res, await desk.openDownload(req, url), url.searchParams.get('inline') === '1');
122
+ }
123
+ if (desk && req.method === 'POST' && path === '/session-foundations/api/files') {
124
+ const outcome = await desk.saveUpload(req, url);
125
+ send(res, outcome.status, outcome.body);
126
+ if (outcome.status === 413)
127
+ res.on('finish', () => req.destroy());
128
+ return;
129
+ }
68
130
  if (desk && desk.owns(req.method ?? 'GET', path)) {
69
131
  const outcome = await desk.handle(req.method ?? 'GET', path, url, req);
70
132
  return send(res, outcome.status, outcome.body);
@@ -84,6 +146,129 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
84
146
  const bots = engine.listBots();
85
147
  return send(res, 200, { ok: true, sessionIds: bots.map(bot => bot.sessionId), bots });
86
148
  }
149
+ if (req.method === 'POST' && path === '/session-foundations/api/questions/answer') {
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
+ if (typeof body.sessionId !== 'string' || body.sessionId === '') {
155
+ return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
156
+ }
157
+ const result = questions.submit({
158
+ sessionId: body.sessionId,
159
+ callId: typeof body.callId === 'string' ? body.callId : undefined,
160
+ answers: body.answers,
161
+ });
162
+ if (result.ok === false) {
163
+ const status = result.code === 'NOT_FOUND'
164
+ ? 404
165
+ : result.code === 'CONFLICT'
166
+ ? 409
167
+ : result.code === 'FORBIDDEN'
168
+ ? 403
169
+ : result.code === 'UNAVAILABLE'
170
+ ? 503
171
+ : 400;
172
+ return send(res, status, result);
173
+ }
174
+ return send(res, 200, result);
175
+ }
176
+ if (req.method === 'POST' && path === '/session-foundations/api/questions/cancel') {
177
+ const questions = getQuestions();
178
+ if (!questions)
179
+ return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
180
+ const body = await readJson(req);
181
+ return sendTool(res, questions.cancel({
182
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
183
+ callId: typeof body.callId === 'string' ? body.callId : undefined,
184
+ answers: Array.isArray(body.answers) ? body.answers : undefined,
185
+ }));
186
+ }
187
+ if (req.method === 'POST' && path === '/session-foundations/api/questions/timeout') {
188
+ const questions = getQuestions();
189
+ if (!questions)
190
+ return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
191
+ const body = await readJson(req);
192
+ return sendTool(res, questions.timeout({
193
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
194
+ callId: typeof body.callId === 'string' ? body.callId : undefined,
195
+ }));
196
+ }
197
+ if (req.method === 'POST' && path === '/session-foundations/api/questions/take-time') {
198
+ const questions = getQuestions();
199
+ if (!questions)
200
+ return send(res, 503, toolError('UNAVAILABLE', 'The user-questions answerer is not attached to this host yet.'));
201
+ const body = await readJson(req);
202
+ return sendTool(res, questions.takeTime({
203
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
204
+ callId: typeof body.callId === 'string' ? body.callId : undefined,
205
+ }));
206
+ }
207
+ if (req.method === 'GET' && path === '/session-foundations/api/interactions') {
208
+ const sessionId = url.searchParams.get('sessionId') ?? '';
209
+ return send(res, 200, interactionSnapshot(sessionId, url.searchParams.get('compact') === '1'));
210
+ }
211
+ if (req.method === 'POST' && path === '/session-foundations/api/approvals/answer') {
212
+ const approvals = getApprovals();
213
+ if (!approvals)
214
+ return send(res, 503, toolError('UNAVAILABLE', 'The tool-approval answerer is not attached to this host yet.'));
215
+ const body = await readJson(req);
216
+ return sendTool(res, approvals.submit({
217
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
218
+ requestId: typeof body.requestId === 'string' ? body.requestId : '',
219
+ outcome: body.outcome,
220
+ }));
221
+ }
222
+ if (req.method === 'GET' && path === '/session-foundations/api/permissions') {
223
+ const sessionId = url.searchParams.get('sessionId') ?? '';
224
+ return send(res, 200, { ok: true, ...permissionView(ctx, sessionId) });
225
+ }
226
+ if (req.method === 'POST' && path === '/session-foundations/api/permissions') {
227
+ const body = await readJson(req);
228
+ return sendTool(res, setPermission(ctx, typeof body.sessionId === 'string' ? body.sessionId : '', typeof body.name === 'string' ? body.name : ''));
229
+ }
230
+ if (req.method === 'GET' && path === '/session-foundations/api/authorization') {
231
+ const authorization = getAuthorization();
232
+ if (!authorization)
233
+ return send(res, 200, { ok: true, available: false, entries: [], notices: [], prompts: [] });
234
+ return send(res, 200, { ok: true, ...authorization.snapshot() });
235
+ }
236
+ if (req.method === 'POST' && path === '/session-foundations/api/authorization/begin') {
237
+ const authorization = getAuthorization();
238
+ if (!authorization)
239
+ return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
240
+ const body = await readJson(req);
241
+ return sendTool(res, await authorization.begin({
242
+ key: body.key,
243
+ method: typeof body.method === 'string' ? body.method : undefined,
244
+ }));
245
+ }
246
+ if (req.method === 'POST' && path === '/session-foundations/api/authorization/answer') {
247
+ const authorization = getAuthorization();
248
+ if (!authorization)
249
+ return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
250
+ const body = await readJson(req);
251
+ return sendTool(res, authorization.answer({
252
+ promptId: typeof body.promptId === 'string' ? body.promptId : '',
253
+ value: typeof body.value === 'string' ? body.value : undefined,
254
+ declined: body.declined === true,
255
+ }));
256
+ }
257
+ if (req.method === 'POST' && path === '/session-foundations/api/authorization/cancel') {
258
+ const authorization = getAuthorization();
259
+ if (!authorization)
260
+ return send(res, 503, toolError('UNAVAILABLE', 'Official authorization is not attached to this host yet.'));
261
+ const body = await readJson(req);
262
+ return sendTool(res, authorization.cancel({ key: body.key }));
263
+ }
264
+ if (req.method === 'GET' && path === '/session-foundations/api/cua') {
265
+ const locale = url.searchParams.get('locale') ?? 'en';
266
+ return send(res, 200, { ok: true, ...(await cuaSnapshot(ctx, locale)) });
267
+ }
268
+ if (req.method === 'POST' && path === '/session-foundations/api/cua') {
269
+ const body = await readJson(req);
270
+ return sendTool(res, await cuaAction(ctx, body));
271
+ }
87
272
  if (req.method === 'POST' && path === '/session-foundations/api/sessions/open') {
88
273
  const body = await readJson(req);
89
274
  const opened = await provisionSession(engine, body);
@@ -112,6 +297,11 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
112
297
  return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
113
298
  return send(res, 200, { ok: true, ...memoryView(engine, sessionId) });
114
299
  }
300
+ if (req.method === 'GET' && path.startsWith('/session-foundations/api/memory/')) {
301
+ const memoryHit = handleMemoryRoute(engine, path, url);
302
+ if (memoryHit)
303
+ return send(res, memoryHit.status, memoryHit.body);
304
+ }
115
305
  if (req.method === 'POST' && path === '/session-foundations/api/skills/register') {
116
306
  const body = await readJson(req);
117
307
  if (!engine.isBot(body.sessionId))
@@ -217,47 +407,6 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
217
407
  const body = await readJson(req);
218
408
  return send(res, 200, runtime.revokeWebhook(body.id));
219
409
  }
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
410
  if (req.method === 'GET' && path === '/session-foundations/api/live') {
262
411
  const work = getWork();
263
412
  if (!work)
@@ -266,6 +415,8 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
266
415
  workStamp: () => work.liveStamp(),
267
416
  workBoard: () => work.liveBoardAll(),
268
417
  loadDesk: () => loadPageDesk(req),
418
+ interactions: () => interactionSnapshot(url.searchParams.get('sessionId') ?? '', true),
419
+ ...(canvas ? { canvas: () => canvas.live(url.searchParams.get('sessionId') ?? '') } : {}),
269
420
  });
270
421
  }
271
422
  if (req.method === 'GET' && path === '/session-foundations/api/work/live') {
@@ -274,6 +425,11 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
274
425
  return send(res, 503, toolError('UNAVAILABLE', 'The work host is not attached yet.'));
275
426
  return openWorkLive(req, res, url.searchParams.get('sessionId') ?? '', work);
276
427
  }
428
+ if (canvas &&
429
+ (path === '/session-foundations/api/canvas' || path.startsWith('/session-foundations/api/canvas/'))) {
430
+ const outcome = await handleCanvasApi(req, path, url, canvas);
431
+ return send(res, outcome.status, outcome.body);
432
+ }
277
433
  if (path.startsWith('/session-foundations/api/work')) {
278
434
  const workBody = req.method === 'GET' ? {} : await readJson(req);
279
435
  const workHit = await handleWorkApi(req.method ?? 'GET', path, url, workBody, getWork());
@@ -312,11 +468,26 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
312
468
  path: '/dsh-bot',
313
469
  handler,
314
470
  });
471
+ const disposeLog = logOnConnection
472
+ ? null
473
+ : webServer.register({
474
+ kind: 'prefix',
475
+ path: '/api/dsh-bot',
476
+ handler,
477
+ });
315
478
  return () => {
316
479
  if (typeof disposeFoundations === 'function')
317
480
  disposeFoundations();
318
481
  if (typeof disposeDesk === 'function')
319
482
  disposeDesk();
483
+ if (typeof disposeLog === 'function')
484
+ disposeLog();
485
+ try {
486
+ canvas?.close();
487
+ }
488
+ catch {
489
+ /* closed */
490
+ }
320
491
  };
321
492
  });
322
493
  }
@@ -339,7 +510,11 @@ export function status(engine, sessionId) {
339
510
  view,
340
511
  persona,
341
512
  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) : [],
513
+ skills: binding
514
+ ? engine.store.db
515
+ .prepare('SELECT skill_id, scope, version, enabled, revoked, content_hash FROM skill_bindings WHERE session_id = ?')
516
+ .all(sessionId)
517
+ : [],
343
518
  isolation: 'host-session-id',
344
519
  sandbox: false,
345
520
  };
@@ -360,34 +535,99 @@ function personaText(engine, persona) {
360
535
  */
361
536
  export function memoryView(engine, sessionId) {
362
537
  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),
538
+ facts: engine.store.db
539
+ .prepare('SELECT id, content, status, revision, priority FROM facts WHERE session_id = ? ORDER BY id')
540
+ .all(sessionId),
541
+ memories: engine.store.db
542
+ .prepare('SELECT id, title, content, status, revision FROM memories WHERE session_id = ? ORDER BY id')
543
+ .all(sessionId),
365
544
  state: engine.statePayload(sessionId),
366
545
  };
367
546
  }
368
547
  /**
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}
548
+ * A live store entry means some fiber still has the session open.
549
+ * The caller must inject `sessions`. Reading it without inject throws.
550
+ * @param {import('./host.ts').HostContext} ctx
551
+ * @param {string} sessionId
552
+ */
553
+ export function attachedSession(ctx, sessionId) {
554
+ const sessions = ctx.sessions;
555
+ return typeof sessions?.get === 'function' && sessions.get(sessionId) != null;
556
+ }
557
+ /**
558
+ * Drop an idle session another fiber still has open, then let the caller delete its log.
559
+ * The host has no delete RPC. The store entry's detach is the same disposer `enter` keeps,
560
+ * and it emits `session/disposed`, which closes the JSONL writer.
561
+ * @param {import('./host.ts').HostContext} ctx
562
+ * @param {string} sessionId
563
+ */
564
+ export async function unloadAttachedSession(ctx, sessionId) {
565
+ const agent = liveAgentOf(ctx, sessionId);
566
+ if (agent && typeof agent.cancel === 'function') {
567
+ try {
568
+ agent.cancel({ kind: 'hook', reason: 'session-delete' }, { keepInbox: false });
569
+ }
570
+ catch {
571
+ /* already idle */
572
+ }
573
+ }
574
+ if (agent && typeof agent.whenIdle === 'function')
575
+ await agent.whenIdle();
576
+ const writer = sessionWriter(ctx, sessionId);
577
+ if (writer && typeof writer.close === 'function')
578
+ await writer.close();
579
+ detachAgentEntry(ctx, sessionId);
580
+ detachSessionEntry(ctx, sessionId);
581
+ }
582
+ /**
583
+ * @param {import('./host.ts').HostContext} ctx
584
+ * @param {string} sessionId
373
585
  */
374
- function readCount(url, name) {
375
- const raw = url.searchParams.get(name);
376
- if (raw == null || raw === '')
586
+ function liveAgentOf(ctx, sessionId) {
587
+ try {
588
+ return ctx.agents?.get?.(sessionId) ?? null;
589
+ }
590
+ catch {
377
591
  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;
592
+ }
593
+ }
594
+ /**
595
+ * @param {import('./host.ts').HostContext} ctx
596
+ * @param {string} sessionId
597
+ */
598
+ function sessionWriter(ctx, sessionId) {
599
+ const writers = ctx.sessionPersistence?.tracker?.writers;
600
+ if (!writers || typeof writers.get !== 'function')
601
+ return null;
602
+ const writer = writers.get(sessionId);
603
+ return writer && typeof writer === 'object' ? writer : null;
604
+ }
605
+ /**
606
+ * @param {import('./host.ts').HostContext} ctx
607
+ * @param {string} sessionId
608
+ */
609
+ function detachAgentEntry(ctx, sessionId) {
610
+ const agents = ctx.agents;
611
+ const entry = agents?.store?.get?.(sessionId);
612
+ if (!entry || typeof agents.detachEntered !== 'function')
613
+ return;
614
+ agents.detachEntered(entry);
615
+ }
616
+ /**
617
+ * @param {import('./host.ts').HostContext} ctx
618
+ * @param {string} sessionId
619
+ */
620
+ function detachSessionEntry(ctx, sessionId) {
621
+ const entry = ctx.sessions?.store?.get?.(sessionId);
622
+ if (entry && typeof entry.detach === 'function')
623
+ entry.detach();
384
624
  }
385
625
  /**
386
626
  * @param {import('@deepseek-ai/cordis').Context} ctx
387
627
  * @param {import('node:http').IncomingMessage} req
388
628
  */
389
629
  function reject(ctx, req) {
390
- const connection = ctx.get?.('connection') ?? ctx.connection;
630
+ const connection = probeConnection(ctx);
391
631
  const rejection = connection?.requestRejection?.(req);
392
632
  if (rejection !== undefined)
393
633
  return rejection;
@@ -396,11 +636,35 @@ function reject(ctx, req) {
396
636
  return 403;
397
637
  return 0;
398
638
  }
399
- /**
400
- * @param {import('node:http').ServerResponse} res
401
- * @param {number} status
402
- * @param {unknown} body
403
- */
639
+ function imageMedia(name) {
640
+ const ext = name.split('.').pop()?.toLowerCase() ?? '';
641
+ if (ext === 'png')
642
+ return 'image/png';
643
+ if (ext === 'jpg' || ext === 'jpeg')
644
+ return 'image/jpeg';
645
+ if (ext === 'gif')
646
+ return 'image/gif';
647
+ if (ext === 'webp')
648
+ return 'image/webp';
649
+ return null;
650
+ }
651
+ function pipeDownload(res, opened, inline = false) {
652
+ if (!('stream' in opened))
653
+ return send(res, opened.status, opened.body);
654
+ const encoded = encodeURIComponent(opened.name);
655
+ const image = inline ? imageMedia(opened.name) : null;
656
+ res.writeHead(opened.status, {
657
+ 'content-type': image ?? 'application/octet-stream',
658
+ 'content-length': opened.size,
659
+ 'content-disposition': image ? `inline; filename*=UTF-8''${encoded}` : `attachment; filename*=UTF-8''${encoded}`,
660
+ 'x-content-type-options': 'nosniff',
661
+ 'cache-control': 'private, no-store',
662
+ 'content-security-policy': "default-src 'none'; sandbox",
663
+ });
664
+ opened.stream.on('error', () => res.destroy());
665
+ res.on('close', () => opened.stream.destroy());
666
+ opened.stream.pipe(res);
667
+ }
404
668
  function send(res, status, body) {
405
669
  if (status === 0)
406
670
  return;
@@ -412,6 +676,20 @@ function send(res, status, body) {
412
676
  });
413
677
  res.end(text);
414
678
  }
679
+ function sendTool(res, result) {
680
+ if (result.ok !== false)
681
+ return send(res, 200, result);
682
+ const status = result.code === 'NOT_FOUND'
683
+ ? 404
684
+ : result.code === 'CONFLICT' || result.code === 'ALREADY_IN_FLIGHT' || result.code === 'REPLY_QUEUED'
685
+ ? 409
686
+ : result.code === 'FORBIDDEN'
687
+ ? 403
688
+ : result.code === 'UNAVAILABLE'
689
+ ? 503
690
+ : 400;
691
+ return send(res, status, result);
692
+ }
415
693
  /**
416
694
  * @param {import('node:http').IncomingMessage} req
417
695
  */
@@ -431,7 +709,7 @@ function readRaw(req, max) {
431
709
  return new Promise((resolve, rejectPromise) => {
432
710
  const chunks = [];
433
711
  let size = 0;
434
- req.on('data', chunk => {
712
+ req.on('data', (chunk) => {
435
713
  size += chunk.length;
436
714
  if (size > max) {
437
715
  rejectPromise(Object.assign(new Error('The body is too long.'), { code: 'VALIDATION' }));
@@ -447,7 +725,7 @@ function readRaw(req, max) {
447
725
  function readJson(req) {
448
726
  return new Promise((resolve, rejectPromise) => {
449
727
  const chunks = [];
450
- req.on('data', chunk => chunks.push(chunk));
728
+ req.on('data', (chunk) => chunks.push(chunk));
451
729
  req.on('end', () => {
452
730
  try {
453
731
  resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
@@ -470,7 +748,15 @@ async function hostRpc(req, endpoint, args) {
470
748
  const origin = localOrigin(req);
471
749
  const cookie = header(req, 'cookie') ?? '';
472
750
  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.' } } } };
751
+ return {
752
+ status: 503,
753
+ body: {
754
+ result: {
755
+ ok: false,
756
+ error: { code: 'primary_unready', message: 'This process has not issued a session cookie yet.' },
757
+ },
758
+ },
759
+ };
474
760
  }
475
761
  const response = await fetch(`${origin}/api/${endpoint}`, {
476
762
  method: 'POST',
@@ -526,7 +812,12 @@ async function hostUsage(req) {
526
812
  if (response.status === 404)
527
813
  return { connected: false, code: 'usage_not_installed', error: 'The usage plugin is not installed.' };
528
814
  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.' };
815
+ return {
816
+ connected: false,
817
+ code: 'usage_unconfigured',
818
+ status: response.status,
819
+ error: typeof body?.error === 'string' ? body.error : 'The usage upstream is unavailable.',
820
+ };
530
821
  }
531
822
  return { connected: true, summary: body };
532
823
  }
@@ -549,9 +840,12 @@ const DESK_TYPES = new Map([
549
840
  ['.svg', 'image/svg+xml'],
550
841
  ['.json', 'application/json; charset=utf-8'],
551
842
  ['.map', 'application/json; charset=utf-8'],
843
+ ['.jpg', 'image/jpeg'],
844
+ ['.jpeg', 'image/jpeg'],
552
845
  ['.png', 'image/png'],
553
846
  ['.webp', 'image/webp'],
554
847
  ['.woff2', 'font/woff2'],
848
+ ['.ttf', 'font/ttf'],
555
849
  ]);
556
850
  /** Workbench files built into public/. API routes are handled before this. */
557
851
  function serveDesk(req, res, pathname) {
@@ -591,3 +885,26 @@ function serveDesk(req, res, pathname) {
591
885
  createReadStream(file).pipe(res);
592
886
  return true;
593
887
  }
888
+ async function asFetchRequest(req) {
889
+ const host = req.headers.host ?? '127.0.0.1';
890
+ const url = `http://${host}${req.url ?? '/'}`;
891
+ const headers = new Headers();
892
+ for (const [name, value] of Object.entries(req.headers)) {
893
+ if (typeof value === 'string')
894
+ headers.set(name, value);
895
+ else if (Array.isArray(value)) {
896
+ for (const item of value)
897
+ headers.append(name, item);
898
+ }
899
+ }
900
+ return new Request(url, { method: req.method ?? 'GET', headers });
901
+ }
902
+ async function sendFetchResponse(res, response) {
903
+ const headers = {};
904
+ response.headers.forEach((value, name) => {
905
+ headers[name] = value;
906
+ });
907
+ const body = response.body ? Buffer.from(await response.arrayBuffer()) : Buffer.alloc(0);
908
+ res.writeHead(response.status, headers);
909
+ res.end(body);
910
+ }