@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/desk.js CHANGED
@@ -1,9 +1,34 @@
1
1
  /** Workbench routes inside the DSH process. The browser calls /dsh-bot/api. */
2
- import { readFileSync } from 'node:fs';
3
- import { dirname, join } from 'node:path';
2
+ import { mkdirSync, readFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { Readable } from 'node:stream';
4
6
  import { openLedger, validIdempotencyKey } from "./desk-ledger.js";
5
7
  import { openSessionPreviews } from "./session-previews.js";
6
8
  import { purgeSessionFiles, sessionDirectory, writeBotMarker } from "./session-files.js";
9
+ import { MAX_UPLOAD_BYTES, listDirectory, openDownload, readFileText, resolveFileRoots, saveUploadFile, } from "./workspace-files.js";
10
+ /**
11
+ * Working directory for workbench-created sessions. THREADY_SESSION_CWD wins;
12
+ * otherwise <DSH_HOME>/workspace, so the model does not start inside DSH_HOME
13
+ * (owner-token, profiles/, persona.sqlite). Empty only when neither is set,
14
+ * which keeps DSH's own default (the server process cwd).
15
+ * @param {Record<string, string | undefined>} env
16
+ * @param {{ mkdir?: boolean }} [options]
17
+ */
18
+ export function defaultSessionCwd(env, options = {}) {
19
+ const explicit = (env.THREADY_SESSION_CWD ?? '').trim();
20
+ const home = (env.DSH_HOME ?? '').trim();
21
+ const cwd = explicit !== '' ? resolve(explicit) : home !== '' ? join(resolve(home), 'workspace') : '';
22
+ if (cwd !== '' && options.mkdir !== false) {
23
+ try {
24
+ mkdirSync(cwd, { recursive: true, mode: 0o700 });
25
+ }
26
+ catch {
27
+ /* session/create reports a bad cwd */
28
+ }
29
+ }
30
+ return cwd;
31
+ }
7
32
  const API = '/session-foundations/api';
8
33
  const PREVIEW_SESSION = /^(?:session|worker)-[A-Za-z0-9-]+$/;
9
34
  const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;
@@ -11,20 +36,29 @@ const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;
11
36
  * @param {object} options
12
37
  * @param {string} options.ledgerFile
13
38
  * @param {string} options.profileDir
39
+ * @param {string} [options.sessionsRoot] JSONL persistence root. Defaults to <profileDir>/sessions.
40
+ * @param {string} [options.stateRoot] Directory that holds storages/. Defaults to profileDir.
14
41
  * @param {string} options.sessionCwd
15
42
  * @param {(sessionId: string) => boolean} options.isBot
16
43
  * @param {(sessionId: string) => { kind?: string } | null | undefined} options.mark
17
44
  * @param {(sessionId: string) => void | Promise<void>} options.hold
18
45
  * @param {(sessionId: string) => void | Promise<void>} options.release
19
- * @param {(endpoint: string, args: Record<string, unknown>, req: import('node:http').IncomingMessage) => Promise<{ status: number, body: RpcEnvelope }>} options.rpc
20
- * @param {(req: import('node:http').IncomingMessage) => Promise<Record<string, unknown>>} options.usage
46
+ * @param {(sessionId: string) => void | Promise<void>} [options.releaseLoaded]
47
+ * @param {(sessionId: string) => void | Promise<void>} [options.releaseAttached]
48
+ * @param {(sessionId: string) => boolean} [options.stillAttached]
49
+ * @param {(endpoint: string, args: Record<string, unknown>, req: DeskRequest) => Promise<{ status: number, body: RpcEnvelope }>} options.rpc
50
+ * @param {(req: DeskRequest) => Promise<Record<string, unknown>>} options.usage
51
+ * @param {{ home: string, dshHome: string }} [options.files] Browser roots. Defaults to the process home and DSH_HOME.
21
52
  */
22
53
  export function createDesk(options) {
23
54
  const ledger = openLedger(options.ledgerFile);
24
55
  const sessionPreviews = openSessionPreviews(join(dirname(options.ledgerFile), 'session-previews.json'));
25
56
  /** @type {Map<string, Promise<void>>} */
26
57
  const promptLocks = new Map();
27
- const sessionsRoot = join(options.profileDir, 'sessions');
58
+ const sessionsRoot = options.sessionsRoot !== undefined && options.sessionsRoot !== ''
59
+ ? options.sessionsRoot
60
+ : join(options.profileDir, 'sessions');
61
+ const stateRoot = options.stateRoot !== undefined && options.stateRoot !== '' ? options.stateRoot : options.profileDir;
28
62
  return {
29
63
  /**
30
64
  * @param {string} method
@@ -34,11 +68,19 @@ export function createDesk(options) {
34
68
  const sub = subpath(path);
35
69
  if (sub === null)
36
70
  return false;
37
- if (method === 'GET' && (sub === '/health' || sub === '/sessions' || sub === '/tasks' || sub === '/usage' || sub === '/file'))
71
+ if (method === 'GET' &&
72
+ (sub === '/health' ||
73
+ sub === '/sessions' ||
74
+ sub === '/tasks' ||
75
+ sub === '/usage' ||
76
+ sub === '/file' ||
77
+ sub === '/files' ||
78
+ sub === '/files/roots' ||
79
+ sub === '/files/text'))
38
80
  return true;
39
81
  if (method === 'POST' && (sub === '/sessions' || sub === '/sessions/previews' || sub === '/tasks'))
40
82
  return true;
41
- if (method === 'POST' && /^\/sessions\/session-[A-Za-z0-9-]+\/(?:archive|purge)$/.test(sub))
83
+ if (method === 'POST' && /^\/sessions\/session-[A-Za-z0-9-]+\/(?:archive|purge|delete)$/.test(sub))
42
84
  return true;
43
85
  if (method === 'POST' && /^\/tasks\/[0-9a-f-]{36}\/cancel$/.test(sub))
44
86
  return true;
@@ -48,7 +90,7 @@ export function createDesk(options) {
48
90
  * @param {string} method
49
91
  * @param {string} path
50
92
  * @param {URL} url
51
- * @param {import('node:http').IncomingMessage} req
93
+ * @param {DeskRequest} req
52
94
  */
53
95
  async handle(method, path, url, req) {
54
96
  const sub = subpath(path) ?? '';
@@ -69,6 +111,9 @@ export function createDesk(options) {
69
111
  const purge = sub.match(/^\/sessions\/(session-[A-Za-z0-9-]+)\/purge$/);
70
112
  if (method === 'POST' && purge)
71
113
  return purgeBlank(req, purge[1]);
114
+ const remove = sub.match(/^\/sessions\/(session-[A-Za-z0-9-]+)\/delete$/);
115
+ if (method === 'POST' && remove)
116
+ return deleteSession(req, remove[1]);
72
117
  if (method === 'GET' && sub === '/tasks')
73
118
  return { status: 200, body: { items: ledger.tasks() } };
74
119
  if (method === 'POST' && sub === '/tasks')
@@ -80,11 +125,23 @@ export function createDesk(options) {
80
125
  return { status: 200, body: redactSecrets(await options.usage(req)) };
81
126
  if (method === 'GET' && sub === '/file')
82
127
  return filePreview(req, url);
128
+ if (method === 'GET' && sub === '/files/roots')
129
+ return fileRoots(req, url.searchParams.get('sessionId') ?? '');
130
+ if (method === 'GET' && sub === '/files')
131
+ return fileList(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('path') ?? '');
132
+ if (method === 'GET' && sub === '/files/text')
133
+ return fileText(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('path') ?? '');
83
134
  return { status: 404, body: { error: 'not_found' } };
84
135
  },
136
+ openDownload(req, url) {
137
+ return downloadFile(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('path') ?? '');
138
+ },
139
+ saveUpload(req, url) {
140
+ return uploadFile(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('dir') ?? '', url.searchParams.get('name') ?? '', url.searchParams.get('overwrite') === '1');
141
+ },
85
142
  };
86
143
  /**
87
- * @param {import('node:http').IncomingMessage} req
144
+ * @param {DeskRequest} req
88
145
  */
89
146
  async function health(req) {
90
147
  const execution = await executionState(req);
@@ -94,7 +151,7 @@ export function createDesk(options) {
94
151
  };
95
152
  }
96
153
  /**
97
- * @param {import('node:http').IncomingMessage} req
154
+ * @param {DeskRequest} req
98
155
  */
99
156
  async function executionState(req) {
100
157
  const catalog = await options.rpc('session/modelCatalog', {}, req);
@@ -105,12 +162,12 @@ export function createDesk(options) {
105
162
  const failure = catalog.body?.result?.error?.message;
106
163
  return {
107
164
  ready: false,
108
- reason: catalog.body?.result?.ok === true ? 'no_provider' : (failure ? String(failure) : 'catalog_unreadable'),
165
+ reason: catalog.body?.result?.ok === true ? 'no_provider' : failure ? String(failure) : 'catalog_unreadable',
109
166
  reachable: catalog.status > 0 && catalog.status < 500,
110
167
  };
111
168
  }
112
169
  /**
113
- * @param {import('node:http').IncomingMessage} req
170
+ * @param {DeskRequest} req
114
171
  * @param {Record<string, unknown>} body
115
172
  */
116
173
  async function createSession(req, body) {
@@ -126,7 +183,10 @@ export function createDesk(options) {
126
183
  : [];
127
184
  const reusable = options.sessionCwd === ''
128
185
  ? undefined
129
- : known.find(item => item?.blank === true && item?.running !== true && item?.cwd === options.sessionCwd && typeof item.sessionId === 'string');
186
+ : known.find((item) => item?.blank === true &&
187
+ item?.running !== true &&
188
+ item?.cwd === options.sessionCwd &&
189
+ typeof item.sessionId === 'string');
130
190
  const request = options.sessionCwd === ''
131
191
  ? {}
132
192
  : reusable
@@ -156,10 +216,13 @@ export function createDesk(options) {
156
216
  }
157
217
  }
158
218
  ledger.rememberSession(key, sessionId);
159
- return { status: 201, body: { sessionId, kind: 'bot', marker, reused: Boolean(reusable) && sessionId === reusable.sessionId } };
219
+ return {
220
+ status: 201,
221
+ body: { sessionId, kind: 'bot', marker, reused: Boolean(reusable) && sessionId === reusable.sessionId },
222
+ };
160
223
  }
161
224
  /**
162
- * @param {import('node:http').IncomingMessage} req
225
+ * @param {DeskRequest} req
163
226
  * @param {string} sessionId
164
227
  */
165
228
  async function archiveBlank(req, sessionId) {
@@ -181,35 +244,98 @@ export function createDesk(options) {
181
244
  return { status: 200, body: { sessionId, archivedSessionIds } };
182
245
  }
183
246
  /**
184
- * @param {import('node:http').IncomingMessage} req
247
+ * @param {DeskRequest} req
185
248
  * @param {string} sessionId
186
249
  */
187
250
  async function purgeBlank(req, sessionId) {
251
+ const found = await findListedSession(req, sessionId);
252
+ if (found.error)
253
+ return found.error;
254
+ const item = found.item;
255
+ if (item.blank !== true || item.running === true || typeof item.cwd !== 'string' || item.cwd === '') {
256
+ return { status: 409, body: { error: 'not_blank' } };
257
+ }
258
+ const erased = await eraseSession(sessionId, item.cwd);
259
+ if (erased)
260
+ return erased;
261
+ return { status: 200, body: { sessionId, purged: true } };
262
+ }
263
+ /**
264
+ * Hard-delete any listed session, including one that already has messages.
265
+ * An idle session still open in this process is detached first, then its log
266
+ * is removed. A running turn is refused so its writer cannot recreate the log.
267
+ * @param {DeskRequest} req
268
+ * @param {string} sessionId
269
+ */
270
+ async function deleteSession(req, sessionId) {
271
+ const found = await findListedSession(req, sessionId);
272
+ if (found.error)
273
+ return found.error;
274
+ const item = found.item;
275
+ if (item.running === true)
276
+ return { status: 409, body: { error: 'running' } };
277
+ if (typeof item.cwd !== 'string' || item.cwd === '')
278
+ return { status: 409, body: { error: 'no_cwd' } };
279
+ try {
280
+ await options.releaseLoaded?.(sessionId);
281
+ if (options.stillAttached?.(sessionId) === true)
282
+ await options.releaseAttached?.(sessionId);
283
+ }
284
+ catch (error) {
285
+ return {
286
+ status: 500,
287
+ body: { error: 'delete_failed', message: error instanceof Error ? error.message : 'delete failed' },
288
+ };
289
+ }
290
+ if (options.stillAttached?.(sessionId) === true)
291
+ return { status: 409, body: { error: 'attached' } };
292
+ const erased = await eraseSession(sessionId, item.cwd);
293
+ if (erased)
294
+ return erased;
295
+ return { status: 200, body: { sessionId, deleted: true } };
296
+ }
297
+ /**
298
+ * @param {DeskRequest} req
299
+ * @param {string} sessionId
300
+ */
301
+ async function findListedSession(req, sessionId) {
188
302
  const listed = await options.rpc('session/list', { _request: {} }, req);
189
303
  const items = listed.body?.result?.value?.items;
190
304
  if (listed.body?.result?.ok !== true || !Array.isArray(items)) {
191
- return { status: 502, body: { error: 'session_list_failed', upstream: listed.body?.result?.error ?? null } };
305
+ return {
306
+ error: {
307
+ status: 502,
308
+ body: { error: 'session_list_failed', upstream: listed.body?.result?.error ?? null },
309
+ },
310
+ };
192
311
  }
193
312
  const item = items.find(entry => entry?.sessionId === sessionId);
194
313
  if (!item)
195
- return { status: 404, body: { error: 'session_not_found' } };
196
- if (item.blank !== true || item.running === true || typeof item.cwd !== 'string' || item.cwd === '') {
197
- return { status: 409, body: { error: 'not_blank' } };
198
- }
314
+ return { error: { status: 404, body: { error: 'session_not_found' } } };
315
+ return { item, error: undefined };
316
+ }
317
+ /**
318
+ * @param {string} sessionId
319
+ * @param {string} cwd
320
+ */
321
+ async function eraseSession(sessionId, cwd) {
199
322
  try {
200
323
  purgeSessionFiles({
201
324
  sessionsRoot,
202
- cacheFile: join(options.profileDir, 'storages', 'session_projcache', 'sessions', `${sessionId}.json`),
203
- workspaceFile: join(options.profileDir, 'storages', 'workspace.json'),
325
+ cacheFile: join(stateRoot, 'storages', 'session_projcache', 'sessions', `${sessionId}.json`),
326
+ workspaceFile: join(stateRoot, 'storages', 'workspace.json'),
204
327
  sessionId,
205
- cwd: item.cwd,
328
+ cwd,
206
329
  });
207
330
  }
208
331
  catch (error) {
209
- return { status: 500, body: { error: 'purge_failed', message: error instanceof Error ? error.message : 'purge failed' } };
332
+ return {
333
+ status: 500,
334
+ body: { error: 'purge_failed', message: error instanceof Error ? error.message : 'purge failed' },
335
+ };
210
336
  }
211
337
  sessionPreviews.forget(sessionId);
212
- return { status: 200, body: { sessionId, purged: true } };
338
+ return null;
213
339
  }
214
340
  /**
215
341
  * @param {unknown} body
@@ -233,7 +359,7 @@ export function createDesk(options) {
233
359
  return { status: 200, body: { ok: true, preview: saved.preview } };
234
360
  }
235
361
  /**
236
- * @param {import('node:http').IncomingMessage} req
362
+ * @param {DeskRequest} req
237
363
  * @param {Record<string, unknown>} body
238
364
  */
239
365
  async function createTask(req, body) {
@@ -254,7 +380,14 @@ export function createDesk(options) {
254
380
  if (!remembered.created)
255
381
  return { status: 200, body: { task: remembered.record, reused: true } };
256
382
  if (!execution.ready) {
257
- return { status: 409, body: { error: 'model_unconfigured', task: remembered.record, execution: { ready: false, reason: execution.reason } } };
383
+ return {
384
+ status: 409,
385
+ body: {
386
+ error: 'model_unconfigured',
387
+ task: remembered.record,
388
+ execution: { ready: false, reason: execution.reason },
389
+ },
390
+ };
258
391
  }
259
392
  const delivered = await withPromptLock(sessionId, () => deliverPrompt(req, sessionId, text, remembered.record.id));
260
393
  if (!delivered.ok) {
@@ -263,12 +396,16 @@ export function createDesk(options) {
263
396
  reason: delivered.reason,
264
397
  upstreamCode: delivered.upstreamCode,
265
398
  });
266
- return { status: delivered.status, body: { error: delivered.error, task: updated } };
399
+ const failStatus = delivered.status;
400
+ return {
401
+ status: typeof failStatus === 'number' ? failStatus : 502,
402
+ body: { error: delivered.error, task: updated },
403
+ };
267
404
  }
268
405
  return { status: 202, body: { task: remembered.record, reused: false, interrupted: delivered.interrupted } };
269
406
  }
270
407
  /**
271
- * @param {import('node:http').IncomingMessage} req
408
+ * @param {DeskRequest} req
272
409
  * @param {string} id
273
410
  */
274
411
  async function cancelTask(req, id) {
@@ -286,7 +423,119 @@ export function createDesk(options) {
286
423
  return { status: result.body?.result?.ok === true ? 200 : 502, body: { task: updated } };
287
424
  }
288
425
  /**
289
- * @param {import('node:http').IncomingMessage} req
426
+ * @param {DeskRequest} req
427
+ * @param {string} sessionId
428
+ */
429
+ async function fileRoots(req, sessionId) {
430
+ const ready = await browserAccess(req, sessionId);
431
+ if ('error' in ready)
432
+ return fileFailure(ready.error);
433
+ return { status: 200, body: ready.access.roots };
434
+ }
435
+ /**
436
+ * @param {DeskRequest} req
437
+ * @param {string} sessionId
438
+ * @param {string} filePath
439
+ */
440
+ async function fileList(req, sessionId, filePath) {
441
+ const ready = await browserAccess(req, sessionId);
442
+ if ('error' in ready)
443
+ return fileFailure(ready.error);
444
+ const listed = listDirectory(filePath, ready.access);
445
+ if (!listed.ok)
446
+ return fileFailure(listed.error);
447
+ return { status: 200, body: listed.value };
448
+ }
449
+ /**
450
+ * @param {DeskRequest} req
451
+ * @param {string} sessionId
452
+ * @param {string} filePath
453
+ */
454
+ async function fileText(req, sessionId, filePath) {
455
+ const ready = await browserAccess(req, sessionId);
456
+ if ('error' in ready)
457
+ return fileFailure(ready.error);
458
+ const text = readFileText(filePath, ready.access);
459
+ if (!text.ok)
460
+ return fileFailure(text.error);
461
+ return { status: 200, body: text.value };
462
+ }
463
+ /**
464
+ * @param {DeskRequest} req
465
+ * @param {string} sessionId
466
+ * @param {string} filePath
467
+ */
468
+ async function downloadFile(req, sessionId, filePath) {
469
+ const ready = await browserAccess(req, sessionId);
470
+ if ('error' in ready)
471
+ return fileFailure(ready.error);
472
+ const opened = openDownload(filePath, ready.access);
473
+ if (!opened.ok)
474
+ return fileFailure(opened.error);
475
+ return { status: 200, ...opened.value };
476
+ }
477
+ /**
478
+ * @param {DeskRequest} req
479
+ * @param {string} sessionId
480
+ * @param {string} dir
481
+ * @param {string} name
482
+ * @param {boolean} overwrite
483
+ */
484
+ async function uploadFile(req, sessionId, dir, name, overwrite) {
485
+ const declared = Number(headerValue(req, 'content-length'));
486
+ if (Number.isFinite(declared) && declared > MAX_UPLOAD_BYTES)
487
+ return fileFailure('too_large');
488
+ if (!(req instanceof Readable))
489
+ return fileFailure('bad_path');
490
+ const ready = await browserAccess(req, sessionId);
491
+ if ('error' in ready) {
492
+ req.resume();
493
+ return fileFailure(ready.error);
494
+ }
495
+ const saved = await saveUploadFile(dir, name, req, ready.access, { overwrite, maxBytes: MAX_UPLOAD_BYTES });
496
+ if (!saved.ok) {
497
+ if (saved.error !== 'too_large')
498
+ req.resume();
499
+ return fileFailure(saved.error);
500
+ }
501
+ return { status: 201, body: saved.value };
502
+ }
503
+ /**
504
+ * @param {DeskRequest} req
505
+ * @param {string} sessionId
506
+ */
507
+ async function browserAccess(req, sessionId) {
508
+ const cwd = await workspaceCwd(req, sessionId);
509
+ if (typeof cwd !== 'string')
510
+ return cwd;
511
+ const files = options.files ?? { home: homedir(), dshHome: process.env.DSH_HOME ?? '' };
512
+ return { access: resolveFileRoots({ workspace: cwd, home: files.home, dshHome: files.dshHome }) };
513
+ }
514
+ /**
515
+ * @param {DeskRequest} req
516
+ * @param {string} sessionId
517
+ * @returns {Promise<string | { error: 'invalid_session' }>}
518
+ */
519
+ async function workspaceCwd(req, sessionId) {
520
+ if (!PREVIEW_SESSION.test(sessionId))
521
+ return { error: 'invalid_session' };
522
+ let cwd = options.sessionCwd;
523
+ try {
524
+ const listed = await options.rpc('session/list', { _request: {} }, req);
525
+ const items = listed.body?.result?.value?.items;
526
+ if (Array.isArray(items)) {
527
+ const item = items.find(entry => entry?.sessionId === sessionId);
528
+ if (typeof item?.cwd === 'string' && item.cwd !== '')
529
+ cwd = item.cwd;
530
+ }
531
+ }
532
+ catch {
533
+ /* the configured workspace remains */
534
+ }
535
+ return cwd;
536
+ }
537
+ /**
538
+ * @param {DeskRequest} req
290
539
  * @param {URL} url
291
540
  */
292
541
  async function filePreview(req, url) {
@@ -357,7 +606,7 @@ export function createDesk(options) {
357
606
  }
358
607
  }
359
608
  /**
360
- * @param {import('node:http').IncomingMessage} req
609
+ * @param {DeskRequest} req
361
610
  * @param {string} sessionId
362
611
  * @returns {Promise<boolean | null>}
363
612
  */
@@ -365,13 +614,13 @@ export function createDesk(options) {
365
614
  const listed = await options.rpc('session/list', { _request: {} }, req);
366
615
  if (listed.body?.result?.ok !== true || !Array.isArray(listed.body.result.value?.items))
367
616
  return null;
368
- const item = listed.body.result.value.items.find(entry => entry?.sessionId === sessionId);
617
+ const item = listed.body.result.value.items.find((entry) => entry?.sessionId === sessionId);
369
618
  return item?.running === true;
370
619
  }
371
620
  /**
372
621
  * Idle sessions queue. A live bot turn is cancelled, then the new text is a new turn.
373
622
  * The cancel is only the main session. Worker sessions are not addressed here.
374
- * @param {import('node:http').IncomingMessage} req
623
+ * @param {DeskRequest} req
375
624
  * @param {string} sessionId
376
625
  * @param {string} text
377
626
  * @param {string} requestId
@@ -379,7 +628,13 @@ export function createDesk(options) {
379
628
  async function deliverPrompt(req, sessionId, text, requestId) {
380
629
  const running = await sessionRunning(req, sessionId);
381
630
  if (running === null) {
382
- return { ok: false, status: 502, error: 'session_unreadable', reason: 'Could not tell whether the session is still running.', upstreamCode: '' };
631
+ return {
632
+ ok: false,
633
+ status: 502,
634
+ error: 'session_unreadable',
635
+ reason: 'Could not tell whether the session is still running.',
636
+ upstreamCode: '',
637
+ };
383
638
  }
384
639
  let interrupted = false;
385
640
  if (running && (options.isBot(sessionId) || botMarked(sessionId))) {
@@ -430,7 +685,7 @@ function subpath(path) {
430
685
  return path.slice(API.length);
431
686
  }
432
687
  /**
433
- * @param {import('node:http').IncomingMessage} req
688
+ * @param {DeskRequest} req
434
689
  * @param {Record<string, unknown>} body
435
690
  */
436
691
  function idempotencyOf(req, body) {
@@ -440,6 +695,28 @@ function idempotencyOf(req, body) {
440
695
  return header;
441
696
  return typeof body.idempotencyKey === 'string' ? body.idempotencyKey : '';
442
697
  }
698
+ function fileFailure(error) {
699
+ const status = error === 'denied'
700
+ ? 403
701
+ : error === 'missing'
702
+ ? 404
703
+ : error === 'binary'
704
+ ? 415
705
+ : error === 'too_large'
706
+ ? 413
707
+ : error === 'exists'
708
+ ? 409
709
+ : 400;
710
+ return { status, body: { error } };
711
+ }
712
+ /**
713
+ * @param {DeskRequest} req
714
+ * @param {string} name
715
+ */
716
+ function headerValue(req, name) {
717
+ const value = req.headers[name];
718
+ return Array.isArray(value) ? (value[0] ?? '') : (value ?? '');
719
+ }
443
720
  /**
444
721
  * Keep a preview path inside a session workspace: relative, no parent segments.
445
722
  * @param {string} value
@@ -480,7 +757,7 @@ function redactSecrets(value) {
480
757
  return value;
481
758
  }
482
759
  /**
483
- * @param {import('node:http').IncomingMessage} req
760
+ * @param {DeskRequest} req
484
761
  * @returns {Promise<Record<string, unknown>>}
485
762
  */
486
763
  function readJson(req) {