dsh-hello 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +529 -3
  3. package/cordis.patch.yml +3 -0
  4. package/lib/catalogs.d.ts +100 -0
  5. package/lib/catalogs.d.ts.map +1 -0
  6. package/lib/catalogs.js +205 -0
  7. package/lib/catalogs.js.map +1 -0
  8. package/lib/client.js +605 -0
  9. package/lib/config.d.ts +111 -0
  10. package/lib/config.d.ts.map +1 -0
  11. package/lib/config.js +115 -0
  12. package/lib/config.js.map +1 -0
  13. package/lib/devices.d.ts +71 -0
  14. package/lib/devices.d.ts.map +1 -0
  15. package/lib/devices.js +219 -0
  16. package/lib/devices.js.map +1 -0
  17. package/lib/files.d.ts +43 -0
  18. package/lib/files.d.ts.map +1 -0
  19. package/lib/files.js +187 -0
  20. package/lib/files.js.map +1 -0
  21. package/lib/host.d.ts +350 -0
  22. package/lib/host.d.ts.map +1 -0
  23. package/lib/host.js +10 -0
  24. package/lib/host.js.map +1 -0
  25. package/lib/http.d.ts +85 -0
  26. package/lib/http.d.ts.map +1 -0
  27. package/lib/http.js +369 -0
  28. package/lib/http.js.map +1 -0
  29. package/lib/index.d.ts +20 -0
  30. package/lib/index.d.ts.map +1 -0
  31. package/lib/index.js +8364 -0
  32. package/lib/index.js.map +7 -0
  33. package/lib/interactions.d.ts +123 -0
  34. package/lib/interactions.d.ts.map +1 -0
  35. package/lib/interactions.js +621 -0
  36. package/lib/interactions.js.map +1 -0
  37. package/lib/pairing.d.ts +65 -0
  38. package/lib/pairing.d.ts.map +1 -0
  39. package/lib/pairing.js +150 -0
  40. package/lib/pairing.js.map +1 -0
  41. package/lib/protocol.d.ts +338 -0
  42. package/lib/protocol.d.ts.map +1 -0
  43. package/lib/protocol.js +7 -0
  44. package/lib/protocol.js.map +1 -0
  45. package/lib/push.d.ts +47 -0
  46. package/lib/push.d.ts.map +1 -0
  47. package/lib/push.js +339 -0
  48. package/lib/push.js.map +1 -0
  49. package/lib/read-state.d.ts +32 -0
  50. package/lib/read-state.d.ts.map +1 -0
  51. package/lib/read-state.js +39 -0
  52. package/lib/read-state.js.map +1 -0
  53. package/lib/routes.d.ts +38 -0
  54. package/lib/routes.d.ts.map +1 -0
  55. package/lib/routes.js +1337 -0
  56. package/lib/routes.js.map +1 -0
  57. package/lib/schedules.d.ts +31 -0
  58. package/lib/schedules.d.ts.map +1 -0
  59. package/lib/schedules.js +122 -0
  60. package/lib/schedules.js.map +1 -0
  61. package/lib/sessions.d.ts +60 -0
  62. package/lib/sessions.d.ts.map +1 -0
  63. package/lib/sessions.js +296 -0
  64. package/lib/sessions.js.map +1 -0
  65. package/lib/speech.d.ts +20 -0
  66. package/lib/speech.d.ts.map +1 -0
  67. package/lib/speech.js +47 -0
  68. package/lib/speech.js.map +1 -0
  69. package/lib/streams.d.ts +30 -0
  70. package/lib/streams.d.ts.map +1 -0
  71. package/lib/streams.js +106 -0
  72. package/lib/streams.js.map +1 -0
  73. package/lib/terminal.d.ts +55 -0
  74. package/lib/terminal.d.ts.map +1 -0
  75. package/lib/terminal.js +231 -0
  76. package/lib/terminal.js.map +1 -0
  77. package/lib/util.d.ts +18 -0
  78. package/lib/util.d.ts.map +1 -0
  79. package/lib/util.js +52 -0
  80. package/lib/util.js.map +1 -0
  81. package/lib/version.d.ts +15 -0
  82. package/lib/version.d.ts.map +1 -0
  83. package/lib/version.js +98 -0
  84. package/lib/version.js.map +1 -0
  85. package/package.json +82 -6
package/lib/routes.js ADDED
@@ -0,0 +1,1337 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { agentPresetsAvailable, createWorkspace, currentSessionModel, listAgentPresets, listWorkspaces, modelCatalog, modelsAvailable, renameWorkspace, selectSessionModel, setSessionArchived, setSessionPinned, uploadAttachment, uploadsAvailable, workspaceRenameAvailable, workspacesAvailable, } from './catalogs.js';
3
+ import { listWorkspaceFiles, listWorkspaceFilesByWorkspace, readWorkspaceFile, readWorkspaceFileByWorkspace, resolveWorkspaceBinary } from './files.js';
4
+ import { HttpError, markStreaming, sendJson, sendNoContent, startSse, writeSse } from './http.js';
5
+ import { parseReadState, tagReadService } from './read-state.js';
6
+ import { PROTOCOL_VERSION } from './protocol.js';
7
+ import { deleteSchedule, editSchedule, listSchedules, runSchedule, scheduleActionsAvailable, scheduleHistory, scheduleHistoryAvailable, schedulesAvailable, sessionScheduleMarks, viewSchedule, } from './schedules.js';
8
+ import { speechCatalog, transcribeSpeech } from './speech.js';
9
+ import { newId, shortError } from './util.js';
10
+ export function registerRoutes(router, deps) {
11
+ const { config } = deps;
12
+ router.add({
13
+ method: 'GET',
14
+ pattern: '/health',
15
+ auth: 'public',
16
+ handler: (rc) => {
17
+ const facts = serverFacts(deps, requestOrigin(deps, rc));
18
+ const response = {
19
+ ok: true,
20
+ ...facts,
21
+ pairingOpen: deps.pairing.status().pairingOpen,
22
+ pairingFixed: deps.pairing.status().fixed,
23
+ deviceCount: deps.devices.count(),
24
+ features: features(deps),
25
+ time: Date.now(),
26
+ };
27
+ sendJson(rc.res, 200, response);
28
+ },
29
+ });
30
+ router.add({
31
+ method: 'GET',
32
+ pattern: '/admin/data',
33
+ auth: 'public',
34
+ handler: async (rc) => {
35
+ if (!adminAuthorized(deps, rc))
36
+ throw new HttpError(401, 'admin-unauthorized', 'open this page from an authenticated dsh browser');
37
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
38
+ },
39
+ });
40
+ router.add({
41
+ method: 'POST',
42
+ pattern: '/admin/pair-code',
43
+ auth: 'public',
44
+ handler: async (rc) => {
45
+ if (!adminAuthorized(deps, rc))
46
+ throw new HttpError(401, 'admin-unauthorized', 'open this page from an authenticated dsh browser');
47
+ const body = (rc.body ?? {});
48
+ try {
49
+ if (body.action === 'fixed') {
50
+ if (typeof body.code !== 'string')
51
+ throw new HttpError(400, 'bad-code', 'code is required');
52
+ await deps.pairing.setFixedCode(body.code);
53
+ }
54
+ else if (body.action === 'auto' || body.action === 'rotate') {
55
+ if (body.action === 'auto')
56
+ await deps.pairing.setFixedCode(null);
57
+ else
58
+ deps.pairing.rotate();
59
+ }
60
+ else {
61
+ throw new HttpError(400, 'bad-action', 'action must be rotate, fixed, or auto');
62
+ }
63
+ }
64
+ catch (error) {
65
+ if (error instanceof HttpError)
66
+ throw error;
67
+ throw new HttpError(400, 'bad-code', error instanceof Error ? error.message : String(error));
68
+ }
69
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
70
+ },
71
+ });
72
+ router.add({
73
+ method: 'POST',
74
+ pattern: '/admin/lock',
75
+ auth: 'public',
76
+ handler: async (rc) => {
77
+ if (!adminAuthorized(deps, rc))
78
+ throw new HttpError(401, 'admin-unauthorized', 'open this page from an authenticated dsh browser');
79
+ const body = (rc.body ?? {});
80
+ if (typeof body.locked !== 'boolean')
81
+ throw new HttpError(400, 'bad-lock', 'locked must be true or false');
82
+ await deps.pairing.setLocked(body.locked);
83
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
84
+ },
85
+ });
86
+ router.add({
87
+ method: 'DELETE',
88
+ pattern: '/admin/devices/:id',
89
+ auth: 'public',
90
+ handler: async (rc) => {
91
+ if (!adminAuthorized(deps, rc))
92
+ throw new HttpError(401, 'admin-unauthorized', 'open this page from an authenticated dsh browser');
93
+ const removed = await deps.devices.revoke(rc.params.id);
94
+ if (!removed)
95
+ throw new HttpError(404, 'device-not-found', 'no such device');
96
+ deps.hub.closeDevice(rc.params.id);
97
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
98
+ },
99
+ });
100
+ router.add({
101
+ method: 'PUT',
102
+ pattern: '/admin/devices/:id',
103
+ auth: 'public',
104
+ handler: async (rc) => {
105
+ if (!adminAuthorized(deps, rc))
106
+ throw new HttpError(401, 'admin-unauthorized', 'open this page from an authenticated dsh browser');
107
+ const body = (rc.body ?? {});
108
+ const name = typeof body.name === 'string' ? body.name.trim().slice(0, 120) : '';
109
+ if (name.length === 0)
110
+ throw new HttpError(400, 'bad-device-name', 'a non-empty device name is required');
111
+ const renamed = await deps.devices.rename(rc.params.id, name);
112
+ if (!renamed)
113
+ throw new HttpError(404, 'device-not-found', 'no such device');
114
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
115
+ },
116
+ });
117
+ router.add({
118
+ method: 'GET',
119
+ pattern: '/web-url',
120
+ auth: 'device',
121
+ handler: (rc) => {
122
+ const url = deps.webUrl?.() ?? null;
123
+ if (url === null)
124
+ throw new HttpError(503, 'web-url-unavailable', 'this Host does not expose its Web UI URL');
125
+ sendJson(rc.res, 200, { url });
126
+ },
127
+ });
128
+ router.add({
129
+ method: 'GET',
130
+ pattern: '/pair',
131
+ auth: 'public',
132
+ handler: (rc) => {
133
+ const status = deps.pairing.status();
134
+ sendJson(rc.res, 200, {
135
+ server: serverFacts(deps, requestOrigin(deps, rc)),
136
+ features: features(deps),
137
+ pairing: { open: status.pairingOpen },
138
+ });
139
+ },
140
+ });
141
+ router.add({
142
+ method: 'GET',
143
+ pattern: '/pair/code',
144
+ auth: 'public',
145
+ handler: async (rc) => {
146
+ assertLoopback(rc);
147
+ const current = deps.pairing.current();
148
+ const origin = serverFacts(deps, requestOrigin(deps, rc)).origin ?? '';
149
+ const payload = JSON.stringify({
150
+ v: 1,
151
+ url: `${origin}${config.basePath}`,
152
+ code: current.code,
153
+ });
154
+ const qr = await renderQr(payload);
155
+ sendJson(rc.res, 200, {
156
+ code: current.code,
157
+ formatted: current.formatted,
158
+ expiresAt: current.expiresAt,
159
+ payload,
160
+ qr,
161
+ });
162
+ },
163
+ });
164
+ router.add({
165
+ method: 'POST',
166
+ pattern: '/pair/code',
167
+ auth: 'public',
168
+ handler: (rc) => {
169
+ assertLoopback(rc);
170
+ const rotated = deps.pairing.rotate();
171
+ sendJson(rc.res, 200, rotated);
172
+ },
173
+ });
174
+ router.add({
175
+ method: 'POST',
176
+ pattern: '/pair',
177
+ auth: 'public',
178
+ handler: async (rc) => {
179
+ const body = rc.body;
180
+ if (body === undefined || typeof body.code !== 'string') {
181
+ throw new HttpError(400, 'bad-pair-request', 'pairing requires a code');
182
+ }
183
+ const verification = deps.pairing.verify(body.code, rc.clientAddress);
184
+ if (!verification.ok) {
185
+ const message = verification.reason === 'locked'
186
+ ? 'this Host is not accepting new devices; unlock pairing in the dsh settings first'
187
+ : verification.reason === 'rate-limited'
188
+ ? 'too many pairing attempts from this address'
189
+ : verification.reason === 'expired'
190
+ ? 'the pairing code has expired; read the new code from the dsh terminal'
191
+ : 'the pairing code is invalid';
192
+ const status = verification.reason === 'locked'
193
+ ? 403
194
+ : verification.reason === 'rate-limited' ? 429 : 401;
195
+ throw new HttpError(status, `pair-${verification.reason}`, message);
196
+ }
197
+ const authority = rc.authority;
198
+ if (authority.length === 0)
199
+ throw new HttpError(400, 'missing-host', 'the Host header is required');
200
+ const token = randomPairingToken();
201
+ const device = await deps.devices.pair({
202
+ token,
203
+ deviceName: sanitizeName(body.deviceName),
204
+ devicePublicKey: typeof body.devicePublicKey === 'string' ? body.devicePublicKey : undefined,
205
+ platform: body.platform,
206
+ appVersion: body.appVersion,
207
+ authority,
208
+ });
209
+ const response = {
210
+ deviceId: device.deviceId,
211
+ token,
212
+ deviceName: device.deviceName,
213
+ pairedAt: device.pairedAt,
214
+ server: serverFacts(deps, requestOrigin(deps, rc)),
215
+ features: features(deps),
216
+ };
217
+ deps.logger.info(`[dsh-hello] paired device "${device.deviceName}" (${device.deviceId.slice(0, 12)}…) from ${rc.clientAddress}`);
218
+ sendJson(rc.res, 201, response);
219
+ },
220
+ });
221
+ router.add({
222
+ method: 'GET',
223
+ pattern: '/devices',
224
+ auth: 'device',
225
+ handler: (rc) => {
226
+ sendJson(rc.res, 200, {
227
+ current: rc.device?.deviceId,
228
+ items: deps.devices.list(),
229
+ });
230
+ },
231
+ });
232
+ router.add({
233
+ method: 'DELETE',
234
+ pattern: '/devices/:id',
235
+ auth: 'device',
236
+ handler: async (rc) => {
237
+ const removed = await deps.devices.revoke(rc.params.id);
238
+ if (!removed)
239
+ throw new HttpError(404, 'device-not-found', 'no such device');
240
+ deps.hub.closeDevice(rc.params.id);
241
+ sendNoContent(rc.res);
242
+ },
243
+ });
244
+ router.add({
245
+ method: 'POST',
246
+ pattern: '/push/register',
247
+ auth: 'device',
248
+ handler: async (rc) => {
249
+ const body = rc.body;
250
+ const provider = body?.provider;
251
+ const token = body?.token;
252
+ if (provider !== 'fcm' && provider !== 'apns') {
253
+ throw new HttpError(400, 'bad-push-provider', 'provider must be "fcm" or "apns"');
254
+ }
255
+ if (typeof token !== 'string' || token.length < 8 || token.length > 4096) {
256
+ throw new HttpError(400, 'bad-push-token', 'token must be a non-empty push token');
257
+ }
258
+ const updated = await deps.devices.setPush(rc.device.deviceId, { provider, token, updatedAt: Date.now() });
259
+ if (!updated)
260
+ throw new HttpError(404, 'device-not-found', 'no such device');
261
+ await deps.push.registerDevice(rc.device.deviceId, provider, token);
262
+ sendJson(rc.res, 200, { accepted: true, provider });
263
+ },
264
+ });
265
+ router.add({
266
+ method: 'PUT',
267
+ pattern: '/push/subscriptions',
268
+ auth: 'device',
269
+ handler: async (rc) => {
270
+ const body = rc.body;
271
+ if (typeof body?.approval !== 'boolean' || typeof body.question !== 'boolean' || typeof body.turnEnd !== 'boolean') {
272
+ throw new HttpError(400, 'bad-push-subscriptions', 'approval, question and turnEnd must be booleans');
273
+ }
274
+ const subscriptions = { approval: body.approval, question: body.question, turnEnd: body.turnEnd };
275
+ const updated = await deps.devices.setSubscriptions(rc.device.deviceId, subscriptions);
276
+ if (!updated)
277
+ throw new HttpError(404, 'device-not-found', 'no such device');
278
+ sendJson(rc.res, 200, { accepted: true, subscriptions });
279
+ },
280
+ });
281
+ router.add({
282
+ method: 'DELETE',
283
+ pattern: '/push',
284
+ auth: 'device',
285
+ handler: async (rc) => {
286
+ await deps.devices.clearPush(rc.device.deviceId);
287
+ await deps.push.unregisterDevice(rc.device.deviceId);
288
+ sendNoContent(rc.res);
289
+ },
290
+ });
291
+ router.add({
292
+ method: 'GET',
293
+ pattern: '/speech',
294
+ auth: 'device',
295
+ handler: (rc) => {
296
+ sendJson(rc.res, 200, speechCatalog(deps.ctx));
297
+ },
298
+ });
299
+ router.add({
300
+ method: 'POST',
301
+ pattern: '/speech/transcribe',
302
+ auth: 'device',
303
+ // 4 MiB WAV becomes roughly 5.33 MiB of canonical base64 plus JSON.
304
+ maxBodyBytes: 6 * 1024 * 1024,
305
+ handler: async (rc) => {
306
+ const body = rc.body;
307
+ if (body === undefined || typeof body.audioBase64 !== 'string') {
308
+ throw new HttpError(400, 'empty-audio', 'audioBase64 is required');
309
+ }
310
+ const result = await transcribeSpeech(deps.ctx, {
311
+ audioBase64: body.audioBase64,
312
+ ...(typeof body.providerId === 'string' && body.providerId.length > 0 ? { providerId: body.providerId } : {}),
313
+ ...(typeof body.language === 'string' && body.language.length > 0 ? { language: body.language } : {}),
314
+ }, rc.signal);
315
+ sendJson(rc.res, 200, result);
316
+ },
317
+ });
318
+ router.add({
319
+ method: 'GET',
320
+ pattern: '/schedules',
321
+ auth: 'device',
322
+ handler: async (rc) => {
323
+ const result = await listSchedules(deps.ctx, rc.signal);
324
+ sendJson(rc.res, 200, result);
325
+ },
326
+ });
327
+ router.add({
328
+ method: 'GET',
329
+ pattern: '/schedule-marks',
330
+ auth: 'device',
331
+ handler: async (rc) => {
332
+ sendJson(rc.res, 200, await sessionScheduleMarks(deps.ctx, rc.signal));
333
+ },
334
+ });
335
+ router.add({
336
+ method: 'GET',
337
+ pattern: '/schedules/:id',
338
+ auth: 'device',
339
+ handler: async (rc) => {
340
+ const result = await viewSchedule(deps.ctx, rc.params.id, rc.signal);
341
+ if (result === undefined)
342
+ throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
343
+ const code = scheduleCode(result);
344
+ if (code === 'schedule_not_found')
345
+ throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
346
+ sendJson(rc.res, 200, result);
347
+ },
348
+ });
349
+ router.add({
350
+ method: 'GET',
351
+ pattern: '/schedules/:id/history',
352
+ auth: 'device',
353
+ handler: async (rc) => {
354
+ const rawLimit = rc.query.get('limit');
355
+ const parsed = rawLimit === null ? 20 : Number(rawLimit);
356
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 100) {
357
+ throw new HttpError(400, 'bad-limit', 'limit must be an integer from 1 to 100');
358
+ }
359
+ const before = rc.query.get('before') ?? undefined;
360
+ const result = await scheduleHistory(deps.ctx, rc.params.id, parsed, before, rc.signal);
361
+ if (result === undefined)
362
+ throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
363
+ const code = scheduleCode(result);
364
+ if (code === 'schedule_not_found')
365
+ throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
366
+ if (code === 'delivery_cursor_not_found')
367
+ throw new HttpError(404, 'delivery-cursor-not-found', 'the history cursor is no longer valid');
368
+ sendJson(rc.res, 200, result);
369
+ },
370
+ });
371
+ router.add({
372
+ method: 'POST',
373
+ pattern: '/schedules/:id/run',
374
+ auth: 'device',
375
+ handler: async (rc) => {
376
+ const result = await runSchedule(deps.ctx, rc.params.id, rc.signal);
377
+ if (result === undefined)
378
+ throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
379
+ const code = scheduleCode(result);
380
+ if (code === 'schedule_not_found')
381
+ throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
382
+ if (code === 'schedule_execution_pending') {
383
+ throw new HttpError(409, 'schedule-execution-pending', 'the task is already running or cooling down');
384
+ }
385
+ sendJson(rc.res, 200, result);
386
+ },
387
+ });
388
+ router.add({
389
+ method: 'PUT',
390
+ pattern: '/schedules/:id',
391
+ auth: 'device',
392
+ handler: async (rc) => {
393
+ const body = (rc.body ?? {});
394
+ if (typeof body.active !== 'boolean') {
395
+ throw new HttpError(400, 'bad-schedule-patch', 'active must be a boolean');
396
+ }
397
+ const expectedUpdatedAt = typeof body.expectedUpdatedAt === 'string' || body.expectedUpdatedAt === null
398
+ ? body.expectedUpdatedAt
399
+ : undefined;
400
+ const result = await editSchedule(deps.ctx, rc.params.id, { active: body.active }, expectedUpdatedAt, rc.signal);
401
+ if (result === undefined)
402
+ throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
403
+ const code = scheduleCode(result);
404
+ if (code === 'schedule_not_found')
405
+ throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
406
+ if (code === 'schedule_conflict')
407
+ throw new HttpError(409, 'schedule-conflict', 'the task changed on the Host');
408
+ sendJson(rc.res, 200, result);
409
+ },
410
+ });
411
+ router.add({
412
+ method: 'DELETE',
413
+ pattern: '/schedules/:id',
414
+ auth: 'device',
415
+ handler: async (rc) => {
416
+ const body = (rc.body ?? {});
417
+ const fromBody = body.expectedUpdatedAt;
418
+ const fromQuery = rc.query.get('expectedUpdatedAt') ?? undefined;
419
+ const expectedUpdatedAt = typeof fromBody === 'string' || fromBody === null
420
+ ? fromBody
421
+ : fromQuery;
422
+ const result = await deleteSchedule(deps.ctx, rc.params.id, expectedUpdatedAt, rc.signal);
423
+ if (result === undefined)
424
+ throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
425
+ const code = scheduleCode(result);
426
+ if (code === 'schedule_not_found')
427
+ throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
428
+ if (code === 'schedule_conflict')
429
+ throw new HttpError(409, 'schedule-conflict', 'the task changed on the Host');
430
+ sendJson(rc.res, 200, result);
431
+ },
432
+ });
433
+ router.add({
434
+ method: 'GET',
435
+ pattern: '/sessions',
436
+ auth: 'device',
437
+ handler: async (rc) => {
438
+ const items = await deps.sessions.list(rc.signal);
439
+ const response = { items };
440
+ sendJson(rc.res, 200, response);
441
+ },
442
+ });
443
+ router.add({
444
+ method: 'POST',
445
+ pattern: '/sessions',
446
+ auth: 'device',
447
+ handler: async (rc) => {
448
+ const body = (rc.body ?? {});
449
+ const created = await deps.sessions.create({
450
+ ...(typeof body.cwd === 'string' && body.cwd.length > 0 ? { cwd: body.cwd } : {}),
451
+ ...(typeof body.workspaceId === 'string' && body.workspaceId.length > 0 ? { workspaceId: body.workspaceId } : {}),
452
+ ...(typeof body.agentPreset === 'string' && body.agentPreset.length > 0 ? { agentPreset: body.agentPreset } : {}),
453
+ });
454
+ sendJson(rc.res, 201, created);
455
+ },
456
+ });
457
+ router.add({
458
+ method: 'GET',
459
+ pattern: '/workspaces/:id/raw',
460
+ auth: 'device',
461
+ handler: async (rc) => {
462
+ const path = rc.query.get('path');
463
+ if (path === null || path.length === 0)
464
+ throw new HttpError(400, 'empty-path', 'path is required');
465
+ const file = await resolveWorkspaceBinary(deps.ctx, { workspaceId: rc.params.id }, path, rc.signal);
466
+ await sendBinary(rc, file);
467
+ },
468
+ });
469
+ router.add({
470
+ method: 'GET',
471
+ pattern: '/sessions/:id/raw',
472
+ auth: 'device',
473
+ handler: async (rc) => {
474
+ const path = rc.query.get('path');
475
+ if (path === null || path.length === 0)
476
+ throw new HttpError(400, 'empty-path', 'path is required');
477
+ const file = await resolveWorkspaceBinary(deps.ctx, { sessionId: rc.params.id }, path, rc.signal);
478
+ await sendBinary(rc, file);
479
+ },
480
+ });
481
+ router.add({
482
+ method: 'GET',
483
+ pattern: '/workspaces/:id/files',
484
+ auth: 'device',
485
+ handler: async (rc) => {
486
+ const response = await listWorkspaceFilesByWorkspace(deps.ctx, rc.params.id, rc.query.get('path') ?? '', rc.signal);
487
+ sendJson(rc.res, 200, response);
488
+ },
489
+ });
490
+ router.add({
491
+ method: 'GET',
492
+ pattern: '/workspaces/:id/file',
493
+ auth: 'device',
494
+ handler: async (rc) => {
495
+ const path = rc.query.get('path');
496
+ if (path === null || path.length === 0)
497
+ throw new HttpError(400, 'empty-path', 'path is required');
498
+ const offset = numberParam(rc.query.get('offset')) ?? 0;
499
+ const response = await readWorkspaceFileByWorkspace(deps.ctx, rc.params.id, path, rc.signal, offset);
500
+ sendJson(rc.res, 200, response);
501
+ },
502
+ });
503
+ router.add({
504
+ method: 'GET',
505
+ pattern: '/workspaces',
506
+ auth: 'device',
507
+ handler: (rc) => {
508
+ sendJson(rc.res, 200, { items: listWorkspaces(deps.ctx) });
509
+ },
510
+ });
511
+ router.add({
512
+ method: 'POST',
513
+ pattern: '/workspaces',
514
+ auth: 'device',
515
+ handler: async (rc) => {
516
+ const body = (rc.body ?? {});
517
+ if (typeof body.path !== 'string' || body.path.trim().length === 0) {
518
+ throw new HttpError(400, 'workspace-invalid-path', 'a non-empty absolute directory path is required');
519
+ }
520
+ const title = typeof body.title === 'string' && body.title.trim().length > 0
521
+ ? body.title.trim().slice(0, 120)
522
+ : undefined;
523
+ try {
524
+ const workspace = await createWorkspace(deps.ctx, body.path.trim(), title);
525
+ sendJson(rc.res, 201, { workspace });
526
+ }
527
+ catch (error) {
528
+ throw new HttpError(400, 'workspace-create-failed', shortError(error));
529
+ }
530
+ },
531
+ });
532
+ router.add({
533
+ method: 'PUT',
534
+ pattern: '/workspaces/:id',
535
+ auth: 'device',
536
+ handler: async (rc) => {
537
+ const body = (rc.body ?? {});
538
+ if (typeof body.title !== 'string' || body.title.trim().length === 0) {
539
+ throw new HttpError(400, 'workspace-invalid-title', 'a non-empty workspace title is required');
540
+ }
541
+ const result = await renameWorkspace(deps.ctx, rc.params.id, body.title.trim().slice(0, 120));
542
+ if ('code' in result) {
543
+ throw new HttpError(404, 'workspace-not-found', 'the workspace no longer exists');
544
+ }
545
+ sendJson(rc.res, 200, result);
546
+ },
547
+ });
548
+ router.add({
549
+ method: 'GET',
550
+ pattern: '/agent-presets',
551
+ auth: 'device',
552
+ handler: async (rc) => {
553
+ sendJson(rc.res, 200, await listAgentPresets(deps.ctx));
554
+ },
555
+ });
556
+ router.add({
557
+ method: 'GET',
558
+ pattern: '/models',
559
+ auth: 'device',
560
+ handler: async (rc) => {
561
+ sendJson(rc.res, 200, await modelCatalog(deps.ctx));
562
+ },
563
+ });
564
+ // Read watermarks are owned by dsh-tag (colour and weight share one layer);
565
+ // this authenticated route is the phone's way in. Without dsh-tag the
566
+ // feature is simply absent, which the app sees through `features.readState`.
567
+ router.add({
568
+ method: 'GET',
569
+ pattern: '/read-state',
570
+ auth: 'device',
571
+ handler: (rc) => {
572
+ const tag = tagReadService(deps.ctx);
573
+ if (tag === undefined)
574
+ throw new HttpError(404, 'read-state-unavailable', 'install dsh-tag to share read state');
575
+ sendJson(rc.res, 200, { sessions: tag.reads(), serverTime: Date.now() });
576
+ },
577
+ });
578
+ router.add({
579
+ method: 'POST',
580
+ pattern: '/read-state',
581
+ auth: 'device',
582
+ handler: async (rc) => {
583
+ const tag = tagReadService(deps.ctx);
584
+ if (tag === undefined)
585
+ throw new HttpError(404, 'read-state-unavailable', 'install dsh-tag to share read state');
586
+ const body = (rc.body ?? {});
587
+ const sessions = parseReadState(body.sessions);
588
+ if (sessions === undefined) {
589
+ throw new HttpError(400, 'bad-read-state', 'sessions must be an object of {readAt, unread, at}');
590
+ }
591
+ sendJson(rc.res, 200, { sessions: tag.mergeReads(sessions), serverTime: Date.now() });
592
+ },
593
+ });
594
+ router.add({
595
+ method: 'GET',
596
+ pattern: '/sessions/:id/model',
597
+ auth: 'device',
598
+ handler: async (rc) => {
599
+ const catalog = await modelCatalog(deps.ctx);
600
+ const resolved = await deps.ctx.sessionController.resolveAgent(rc.params.id);
601
+ if (!('agent' in resolved) || resolved.agent === undefined) {
602
+ throw new HttpError(404, 'agent-not-found', 'the session has no live agent');
603
+ }
604
+ const agent = resolved.agent;
605
+ sendJson(rc.res, 200, { selection: currentSessionModel(agent, catalog.default) });
606
+ },
607
+ });
608
+ router.add({
609
+ method: 'POST',
610
+ pattern: '/sessions/:id/model',
611
+ auth: 'device',
612
+ handler: async (rc) => {
613
+ const body = (rc.body ?? {});
614
+ if (typeof body.provider !== 'string' || body.provider.length === 0 || typeof body.model !== 'string' || body.model.length === 0) {
615
+ throw new HttpError(400, 'bad-model-selection', 'provider and model are required');
616
+ }
617
+ const selection = {
618
+ provider: body.provider,
619
+ model: body.model,
620
+ ...(typeof body.reasoningEffort === 'string' && body.reasoningEffort.length > 0 ? { reasoningEffort: body.reasoningEffort } : {}),
621
+ };
622
+ const resolved = await deps.ctx.sessionController.resolveAgent(rc.params.id);
623
+ if (!('agent' in resolved) || resolved.agent === undefined) {
624
+ throw new HttpError(404, 'agent-not-found', 'the session has no live agent');
625
+ }
626
+ try {
627
+ await selectSessionModel(deps.ctx, resolved.agent, selection);
628
+ }
629
+ catch (error) {
630
+ throw new HttpError(400, 'model-selection-rejected', error instanceof Error ? error.message : String(error));
631
+ }
632
+ sendJson(rc.res, 200, { selection });
633
+ },
634
+ });
635
+ router.add({
636
+ method: 'GET',
637
+ pattern: '/sessions/:id/transcript',
638
+ auth: 'device',
639
+ handler: async (rc) => {
640
+ const beforeSeq = numberParam(rc.query.get('beforeSeq'));
641
+ const maxMessages = numberParam(rc.query.get('maxMessages'));
642
+ const response = await deps.sessions.transcript(rc.params.id, {
643
+ ...(beforeSeq === undefined ? {} : { beforeSeq }),
644
+ ...(maxMessages === undefined ? {} : { maxMessages }),
645
+ }, rc.signal);
646
+ sendJson(rc.res, 200, response);
647
+ },
648
+ });
649
+ router.add({
650
+ method: 'GET',
651
+ pattern: '/sessions/:id/files',
652
+ auth: 'device',
653
+ handler: async (rc) => {
654
+ const response = await listWorkspaceFiles(deps.ctx, rc.params.id, rc.query.get('path') ?? '', rc.signal);
655
+ sendJson(rc.res, 200, response);
656
+ },
657
+ });
658
+ router.add({
659
+ method: 'GET',
660
+ pattern: '/sessions/:id/file',
661
+ auth: 'device',
662
+ handler: async (rc) => {
663
+ const path = rc.query.get('path');
664
+ if (path === null || path.length === 0)
665
+ throw new HttpError(400, 'empty-path', 'path is required');
666
+ const offset = numberParam(rc.query.get('offset')) ?? 0;
667
+ const response = await readWorkspaceFile(deps.ctx, rc.params.id, path, rc.signal, offset);
668
+ sendJson(rc.res, 200, response);
669
+ },
670
+ });
671
+ router.add({
672
+ method: 'GET',
673
+ pattern: '/sessions/:id/state',
674
+ auth: 'device',
675
+ handler: async (rc) => {
676
+ const response = await deps.sessions.state(rc.params.id, rc.signal);
677
+ sendJson(rc.res, 200, response);
678
+ },
679
+ });
680
+ router.add({
681
+ method: 'POST',
682
+ pattern: '/sessions/:id/prompt',
683
+ auth: 'device',
684
+ handler: async (rc) => {
685
+ const body = rc.body;
686
+ if (body === undefined || typeof body.text !== 'string') {
687
+ throw new HttpError(400, 'bad-prompt', 'text is required');
688
+ }
689
+ const attachments = Array.isArray(body.attachments)
690
+ ? body.attachments
691
+ .filter((item) => typeof item === 'object' && item !== null
692
+ && typeof item.receiptId === 'string'
693
+ && item.receiptId.length > 0)
694
+ .map(item => item.receiptId)
695
+ : [];
696
+ if (body.text.trim().length === 0 && attachments.length === 0) {
697
+ throw new HttpError(400, 'empty-prompt', 'text or at least one attachment is required');
698
+ }
699
+ const mode = body.mode === 'steer' ? 'steer' : 'queue';
700
+ const requestId = typeof body.requestId === 'string' && body.requestId.length > 0 ? body.requestId : newId();
701
+ const accepted = await deps.sessions.prompt(rc.params.id, {
702
+ requestId,
703
+ text: body.text,
704
+ mode,
705
+ ...(attachments.length > 0 ? { attachments } : {}),
706
+ ...(typeof body.clientTimeZone === 'string' ? { clientTimeZone: body.clientTimeZone } : {}),
707
+ }, rc.signal);
708
+ sendJson(rc.res, 202, accepted);
709
+ },
710
+ });
711
+ router.add({
712
+ method: 'POST',
713
+ pattern: '/sessions/:id/uploads',
714
+ auth: 'device',
715
+ rawBody: true,
716
+ // dsh enforces its own per-file and per-image budgets; this only bounds the wire read.
717
+ maxBodyBytes: 30 * 1024 * 1024,
718
+ handler: async (rc) => {
719
+ const bytes = rc.body;
720
+ if (!Buffer.isBuffer(bytes) || bytes.byteLength === 0) {
721
+ throw new HttpError(400, 'empty-upload', 'the request body must carry the file bytes');
722
+ }
723
+ const kind = rc.query.get('kind') === 'image' ? 'image' : 'file';
724
+ const name = rc.query.get('name') ?? undefined;
725
+ const mediaType = rc.query.get('mediaType') ?? undefined;
726
+ try {
727
+ const receipt = await uploadAttachment(deps.ctx, rc.params.id, { kind, ...(name === undefined ? {} : { name }), ...(mediaType === undefined ? {} : { mediaType }), bytes });
728
+ sendJson(rc.res, 201, receipt);
729
+ }
730
+ catch (error) {
731
+ throw new HttpError(400, 'upload-rejected', error instanceof Error ? error.message : String(error));
732
+ }
733
+ },
734
+ });
735
+ router.add({
736
+ method: 'POST',
737
+ pattern: '/sessions/:id/rename',
738
+ auth: 'device',
739
+ handler: async (rc) => {
740
+ const body = rc.body;
741
+ if (body === undefined || typeof body.title !== 'string' || body.title.trim().length === 0) {
742
+ throw new HttpError(400, 'empty-title', 'title must be non-empty');
743
+ }
744
+ const renamed = await deps.sessions.rename(rc.params.id, body.title);
745
+ sendJson(rc.res, 200, renamed);
746
+ },
747
+ });
748
+ router.add({
749
+ method: 'POST',
750
+ pattern: '/sessions/:id/fork',
751
+ auth: 'device',
752
+ handler: async (rc) => {
753
+ const body = (rc.body ?? {});
754
+ if (body.atSeq !== undefined && (!Number.isSafeInteger(body.atSeq) || body.atSeq < 0)) {
755
+ throw new HttpError(400, 'invalid-fork-seq', 'atSeq must be a non-negative safe integer');
756
+ }
757
+ if (typeof deps.ctx.sessionController.fork !== 'function') {
758
+ throw new HttpError(501, 'fork-unavailable', 'this dsh version does not expose session/fork');
759
+ }
760
+ const forked = await deps.sessions.fork(rc.params.id, typeof body.atSeq === 'number' ? body.atSeq : undefined);
761
+ sendJson(rc.res, 201, forked);
762
+ },
763
+ });
764
+ router.add({
765
+ method: 'POST',
766
+ pattern: '/sessions/:id/cancel',
767
+ auth: 'device',
768
+ handler: (rc) => {
769
+ const accepted = deps.sessions.cancel(rc.params.id);
770
+ sendJson(rc.res, 202, accepted);
771
+ },
772
+ });
773
+ router.add({
774
+ method: 'POST',
775
+ pattern: '/sessions/:id/pin',
776
+ auth: 'device',
777
+ handler: async (rc) => {
778
+ try {
779
+ await setSessionPinned(deps.ctx, rc.params.id, true);
780
+ sendJson(rc.res, 200, { ok: true });
781
+ }
782
+ catch (error) {
783
+ throw new HttpError(409, 'session-pin-failed', shortError(error));
784
+ }
785
+ },
786
+ });
787
+ router.add({
788
+ method: 'POST',
789
+ pattern: '/sessions/:id/unpin',
790
+ auth: 'device',
791
+ handler: async (rc) => {
792
+ try {
793
+ await setSessionPinned(deps.ctx, rc.params.id, false);
794
+ sendJson(rc.res, 200, { ok: true });
795
+ }
796
+ catch (error) {
797
+ throw new HttpError(409, 'session-pin-failed', shortError(error));
798
+ }
799
+ },
800
+ });
801
+ router.add({
802
+ method: 'POST',
803
+ pattern: '/sessions/:id/archive',
804
+ auth: 'device',
805
+ handler: async (rc) => {
806
+ const body = (rc.body ?? {});
807
+ try {
808
+ await setSessionArchived(deps.ctx, rc.params.id, true, body.stopActivity === true);
809
+ sendJson(rc.res, 200, { ok: true });
810
+ }
811
+ catch (error) {
812
+ throw new HttpError(409, 'session-archive-failed', shortError(error));
813
+ }
814
+ },
815
+ });
816
+ router.add({
817
+ method: 'POST',
818
+ pattern: '/sessions/:id/unarchive',
819
+ auth: 'device',
820
+ handler: async (rc) => {
821
+ try {
822
+ await setSessionArchived(deps.ctx, rc.params.id, false);
823
+ sendJson(rc.res, 200, { ok: true });
824
+ }
825
+ catch (error) {
826
+ throw new HttpError(409, 'session-archive-failed', shortError(error));
827
+ }
828
+ },
829
+ });
830
+ router.add({
831
+ method: 'POST',
832
+ pattern: '/sessions/:id/questions/:callId/answer',
833
+ auth: 'device',
834
+ handler: async (rc) => {
835
+ const body = rc.body;
836
+ const answers = normalizeAnswers(body?.answers);
837
+ const accepted = await deps.interactions.answerContinued(rc.params.id, rc.params.callId, { answers });
838
+ if (!accepted)
839
+ throw new HttpError(409, 'question-not-open', 'the question is not open in this session');
840
+ sendJson(rc.res, 200, { accepted: true });
841
+ },
842
+ });
843
+ router.add({
844
+ method: 'GET',
845
+ pattern: '/sessions/:id/events',
846
+ auth: 'device',
847
+ handler: async (rc) => {
848
+ markStreaming(rc.res);
849
+ startSse(rc.res);
850
+ writeSse(rc.res, 'ready', { sessionId: rc.params.id, time: Date.now() });
851
+ const heartbeat = setInterval(() => writeSse(rc.res, 'heartbeat', { time: Date.now() }), 15_000);
852
+ heartbeat.unref?.();
853
+ // A client disconnect and a device revoke both end this follow stream.
854
+ const abort = new AbortController();
855
+ const onClientAbort = () => abort.abort();
856
+ rc.signal.addEventListener('abort', onClientAbort);
857
+ const untrack = deps.hub.trackDevice(rc.device.deviceId, () => abort.abort());
858
+ try {
859
+ for await (const frame of deps.sessions.follow(rc.params.id, abort.signal)) {
860
+ if (abort.signal.aborted)
861
+ break;
862
+ writeSse(rc.res, 'frame', frame);
863
+ }
864
+ }
865
+ catch (error) {
866
+ if (!abort.signal.aborted) {
867
+ writeSse(rc.res, 'error', { code: 'stream-failed', message: shortError(error) });
868
+ }
869
+ }
870
+ finally {
871
+ untrack();
872
+ rc.signal.removeEventListener('abort', onClientAbort);
873
+ clearInterval(heartbeat);
874
+ if (!rc.res.writableEnded)
875
+ rc.res.end();
876
+ }
877
+ },
878
+ });
879
+ router.add({
880
+ method: 'GET',
881
+ pattern: '/sessions/:id/terminals',
882
+ auth: 'device',
883
+ handler: (rc) => {
884
+ sendJson(rc.res, 200, { items: deps.terminals.list(rc.params.id) });
885
+ },
886
+ });
887
+ router.add({
888
+ method: 'POST',
889
+ pattern: '/sessions/:id/terminals',
890
+ auth: 'device',
891
+ handler: async (rc) => {
892
+ const sessionId = rc.params.id;
893
+ const body = rc.body;
894
+ const state = await deps.sessions.state(sessionId, rc.signal);
895
+ const cwd = state.session.cwd;
896
+ if (typeof cwd !== 'string' || cwd.length === 0) {
897
+ throw new HttpError(409, 'session-cwd-unknown', 'the session has no working directory yet');
898
+ }
899
+ const created = await deps.terminals.create(sessionId, cwd, {
900
+ ...(typeof body?.cols === 'number' ? { cols: body.cols } : {}),
901
+ ...(typeof body?.rows === 'number' ? { rows: body.rows } : {}),
902
+ });
903
+ sendJson(rc.res, 201, created);
904
+ },
905
+ });
906
+ router.add({
907
+ method: 'GET',
908
+ pattern: '/sessions/:id/terminals/:terminalId/events',
909
+ auth: 'device',
910
+ handler: async (rc) => {
911
+ const sessionId = rc.params.id;
912
+ const terminalId = rc.params.terminalId;
913
+ // Resolve before headers so a missing terminal is a JSON 404.
914
+ const snapshot = deps.terminals.snapshot(sessionId, terminalId);
915
+ markStreaming(rc.res);
916
+ startSse(rc.res);
917
+ const heartbeat = setInterval(() => writeSse(rc.res, 'heartbeat', { time: Date.now() }), 15_000);
918
+ heartbeat.unref?.();
919
+ let ready = false;
920
+ const pending = [];
921
+ let release = () => undefined;
922
+ const stopped = new Promise(resolve => { release = resolve; });
923
+ const shutdown = () => {
924
+ if (!rc.res.writableEnded)
925
+ rc.res.end();
926
+ release();
927
+ };
928
+ // Subscribe before the snapshot is sent, then flush anything that raced
929
+ // in while the reconnect replay was being written.
930
+ const unsubscribe = deps.terminals.subscribe(sessionId, terminalId, event => {
931
+ if (!ready) {
932
+ pending.push(event);
933
+ return;
934
+ }
935
+ writeSse(rc.res, event.type, event);
936
+ });
937
+ rc.signal.addEventListener('abort', shutdown);
938
+ const untrack = deps.hub.trackDevice(rc.device.deviceId, shutdown);
939
+ writeSse(rc.res, 'ready', { ...snapshot, time: Date.now() });
940
+ ready = true;
941
+ for (const event of pending.splice(0))
942
+ writeSse(rc.res, event.type, event);
943
+ try {
944
+ await stopped;
945
+ }
946
+ finally {
947
+ untrack();
948
+ rc.signal.removeEventListener('abort', shutdown);
949
+ unsubscribe();
950
+ clearInterval(heartbeat);
951
+ if (!rc.res.writableEnded)
952
+ rc.res.end();
953
+ }
954
+ },
955
+ });
956
+ router.add({
957
+ method: 'POST',
958
+ pattern: '/sessions/:id/terminals/:terminalId/input',
959
+ auth: 'device',
960
+ handler: async (rc) => {
961
+ const body = rc.body;
962
+ const data = body?.data;
963
+ if (typeof data !== 'string' || data.length === 0) {
964
+ throw new HttpError(400, 'bad-input', 'data must be a non-empty string');
965
+ }
966
+ if (data.length > 65_536)
967
+ throw new HttpError(413, 'input-too-large', 'terminal input is limited to 64 KiB');
968
+ await deps.terminals.write(rc.params.id, rc.params.terminalId, data);
969
+ sendJson(rc.res, 200, { accepted: true });
970
+ },
971
+ });
972
+ router.add({
973
+ method: 'POST',
974
+ pattern: '/sessions/:id/terminals/:terminalId/resize',
975
+ auth: 'device',
976
+ handler: async (rc) => {
977
+ const body = rc.body;
978
+ if (typeof body?.cols !== 'number' || typeof body?.rows !== 'number') {
979
+ throw new HttpError(400, 'bad-size', 'cols and rows must be numbers');
980
+ }
981
+ const info = await deps.terminals.resize(rc.params.id, rc.params.terminalId, body.cols, body.rows);
982
+ sendJson(rc.res, 200, info);
983
+ },
984
+ });
985
+ router.add({
986
+ method: 'DELETE',
987
+ pattern: '/sessions/:id/terminals/:terminalId',
988
+ auth: 'device',
989
+ handler: async (rc) => {
990
+ const closed = await deps.terminals.close(rc.params.id, rc.params.terminalId);
991
+ if (!closed)
992
+ throw new HttpError(404, 'terminal-not-found', 'no such terminal in this session');
993
+ sendNoContent(rc.res);
994
+ },
995
+ });
996
+ router.add({
997
+ method: 'GET',
998
+ pattern: '/events',
999
+ auth: 'device',
1000
+ handler: (rc) => {
1001
+ markStreaming(rc.res);
1002
+ const clientId = newId();
1003
+ deps.hub.add(clientId, rc.device.deviceId, rc.res);
1004
+ writeSse(rc.res, 'hello', {
1005
+ server: serverFacts(deps, requestOrigin(deps, rc)),
1006
+ features: features(deps),
1007
+ pendingApprovals: deps.interactions.listApprovals(),
1008
+ pendingQuestions: deps.interactions.listQuestions(),
1009
+ time: Date.now(),
1010
+ });
1011
+ rc.req.on('close', () => {
1012
+ // `SseHub` removes the response on close; nothing else is owned here.
1013
+ });
1014
+ },
1015
+ });
1016
+ router.add({
1017
+ method: 'GET',
1018
+ pattern: '/approvals',
1019
+ auth: 'device',
1020
+ handler: (rc) => {
1021
+ sendJson(rc.res, 200, { items: deps.interactions.listApprovals() });
1022
+ },
1023
+ });
1024
+ router.add({
1025
+ method: 'POST',
1026
+ pattern: '/approvals/:id',
1027
+ auth: 'device',
1028
+ handler: (rc) => {
1029
+ const body = rc.body;
1030
+ const decision = body?.decision;
1031
+ if (decision !== 'allow' && decision !== 'deny' && decision !== 'always' && decision !== 'later') {
1032
+ throw new HttpError(400, 'bad-decision', 'decision must be allow, deny, always, or later');
1033
+ }
1034
+ const item = deps.interactions.decideApproval(rc.params.id, decision);
1035
+ if (item === undefined)
1036
+ throw new HttpError(404, 'approval-not-found', 'the approval is no longer pending');
1037
+ sendJson(rc.res, 200, { accepted: true, decision });
1038
+ },
1039
+ });
1040
+ router.add({
1041
+ method: 'POST',
1042
+ pattern: '/presence',
1043
+ auth: 'device',
1044
+ handler: (rc) => {
1045
+ const body = rc.body;
1046
+ if (typeof body?.foreground !== 'boolean') {
1047
+ throw new HttpError(400, 'bad-presence', 'foreground must be a boolean');
1048
+ }
1049
+ const device = rc.device;
1050
+ if (device === undefined)
1051
+ throw new HttpError(401, 'unauthenticated', 'a valid device token is required');
1052
+ deps.interactions.setPresence(device.deviceId, body.foreground);
1053
+ sendJson(rc.res, 200, { accepted: true });
1054
+ },
1055
+ });
1056
+ router.add({
1057
+ method: 'GET',
1058
+ pattern: '/questions',
1059
+ auth: 'device',
1060
+ handler: (rc) => {
1061
+ sendJson(rc.res, 200, { items: deps.interactions.listQuestions() });
1062
+ },
1063
+ });
1064
+ router.add({
1065
+ method: 'POST',
1066
+ pattern: '/questions/:id/answer',
1067
+ auth: 'device',
1068
+ handler: (rc) => {
1069
+ const body = rc.body;
1070
+ const answers = normalizeAnswers(body?.answers);
1071
+ const answered = deps.interactions.answerQuestion(rc.params.id, { answers });
1072
+ if (answered === undefined)
1073
+ throw new HttpError(404, 'question-not-found', 'the question is no longer pending');
1074
+ sendJson(rc.res, 200, { accepted: true });
1075
+ },
1076
+ });
1077
+ if (config.enableDebugRoutes) {
1078
+ router.add({
1079
+ method: 'POST',
1080
+ pattern: '/debug/approval',
1081
+ auth: 'device',
1082
+ handler: (rc) => {
1083
+ const body = (rc.body ?? {});
1084
+ const item = deps.interactions.createDebugApproval({
1085
+ ...(typeof body.sessionId === 'string' ? { sessionId: body.sessionId } : {}),
1086
+ ...(typeof body.toolName === 'string' ? { toolName: body.toolName } : {}),
1087
+ ...(typeof body.reason === 'string' ? { reason: body.reason } : {}),
1088
+ ...(typeof body.displayReason === 'object' && body.displayReason !== null
1089
+ ? { displayReason: body.displayReason }
1090
+ : {}),
1091
+ });
1092
+ sendJson(rc.res, 201, item);
1093
+ },
1094
+ });
1095
+ router.add({
1096
+ method: 'POST',
1097
+ pattern: '/debug/question',
1098
+ auth: 'device',
1099
+ handler: (rc) => {
1100
+ const body = (rc.body ?? {});
1101
+ const item = deps.interactions.createDebugQuestion({
1102
+ ...(typeof body.sessionId === 'string' ? { sessionId: body.sessionId } : {}),
1103
+ ...(Array.isArray(body.questions) ? { questions: body.questions } : {}),
1104
+ });
1105
+ sendJson(rc.res, 201, item);
1106
+ },
1107
+ });
1108
+ deps.logger.warn('[dsh-hello] debug interaction routes are enabled');
1109
+ }
1110
+ deps.logger.info(`[dsh-hello] routes mounted at ${config.basePath} (protocol ${PROTOCOL_VERSION}, push ${config.push.provider})`);
1111
+ }
1112
+ function serverFacts(deps, originOverride) {
1113
+ const web = deps.ctx.webServer;
1114
+ let fallback = null;
1115
+ try {
1116
+ fallback = typeof web.getOrigin === 'function' ? web.getOrigin() : null;
1117
+ }
1118
+ catch {
1119
+ fallback = null;
1120
+ }
1121
+ const origin = originOverride ?? fallback;
1122
+ return {
1123
+ name: 'dsh-hello',
1124
+ version: deps.pluginVersion,
1125
+ protocol: PROTOCOL_VERSION,
1126
+ dshVersion: deps.version.version,
1127
+ dshCompatible: deps.version.compatible,
1128
+ origin,
1129
+ protocolName: origin !== null && origin.startsWith('https://') ? 'https' : web.protocol === 'https:' ? 'https' : 'http',
1130
+ host: web.host ?? null,
1131
+ port: web.port ?? null,
1132
+ };
1133
+ }
1134
+ /** `scheme://authority` as the client reached this request, or null when unknown. */
1135
+ function requestOrigin(deps, rc) {
1136
+ if (rc.authority.length === 0)
1137
+ return null;
1138
+ const scheme = deps.ctx.webServer.protocol === 'https:' ? 'https' : 'http';
1139
+ return `${scheme}://${rc.authority}`;
1140
+ }
1141
+ function scheduleCode(result) {
1142
+ if (typeof result !== 'object' || result === null)
1143
+ return undefined;
1144
+ const code = result.code;
1145
+ return typeof code === 'string' ? code : undefined;
1146
+ }
1147
+ function features(deps) {
1148
+ return {
1149
+ approvals: deps.config.interactionTarget !== 'browser-only',
1150
+ questions: deps.config.interactionTarget !== 'browser-only',
1151
+ interactionTarget: deps.config.interactionTarget,
1152
+ presence: true,
1153
+ push: deps.push.isConfigured(),
1154
+ debugRoutes: deps.config.enableDebugRoutes,
1155
+ terminal: deps.terminals.available(),
1156
+ files: true,
1157
+ workspaces: workspacesAvailable(deps.ctx),
1158
+ workspaceRename: workspaceRenameAvailable(deps.ctx),
1159
+ archive: workspacesAvailable(deps.ctx),
1160
+ pin: workspacesAvailable(deps.ctx),
1161
+ agentPresets: agentPresetsAvailable(deps.ctx),
1162
+ models: modelsAvailable(deps.ctx),
1163
+ uploads: uploadsAvailable(deps.ctx),
1164
+ readState: tagReadService(deps.ctx) !== undefined,
1165
+ schedules: schedulesAvailable(deps.ctx),
1166
+ scheduleActions: scheduleActionsAvailable(deps.ctx),
1167
+ scheduleHistory: scheduleHistoryAvailable(deps.ctx),
1168
+ sessionEvents: 'sse',
1169
+ protocol: PROTOCOL_VERSION,
1170
+ };
1171
+ }
1172
+ function assertLoopback(rc) {
1173
+ const address = rc.clientAddress.replace(/^::ffff:/, '');
1174
+ if (address !== '127.0.0.1' && address !== '::1' && !address.startsWith('127.')) {
1175
+ throw new HttpError(403, 'loopback-only', 'this route is available only from the Host itself');
1176
+ }
1177
+ }
1178
+ function numberParam(value) {
1179
+ if (value === null || value === '')
1180
+ return undefined;
1181
+ const parsed = Number(value);
1182
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;
1183
+ }
1184
+ function sanitizeName(value) {
1185
+ if (typeof value !== 'string' || value.trim().length === 0)
1186
+ return 'Mobile device';
1187
+ return value.trim().slice(0, 80);
1188
+ }
1189
+ function randomPairingToken() {
1190
+ // 32 random bytes rendered base64url, prefixed for recognisability.
1191
+ const bytes = new Uint8Array(32);
1192
+ globalThis.crypto.getRandomValues(bytes);
1193
+ return `dshd_${Buffer.from(bytes).toString('base64url')}`;
1194
+ }
1195
+ function normalizeAnswers(value) {
1196
+ if (!Array.isArray(value) || value.length === 0) {
1197
+ throw new HttpError(400, 'bad-answers', 'answers must be a non-empty array');
1198
+ }
1199
+ return value.map((item) => {
1200
+ if (typeof item !== 'object' || item === null)
1201
+ throw new HttpError(400, 'bad-answers', 'each answer must be an object');
1202
+ const candidate = item;
1203
+ if (typeof candidate.id !== 'string' || !Array.isArray(candidate.selected) || !candidate.selected.every(label => typeof label === 'string')) {
1204
+ throw new HttpError(400, 'bad-answers', 'each answer needs an id and a selected string array');
1205
+ }
1206
+ return {
1207
+ id: candidate.id,
1208
+ selected: candidate.selected,
1209
+ ...(typeof candidate.custom === 'string' ? { custom: candidate.custom } : {}),
1210
+ };
1211
+ });
1212
+ }
1213
+ function adminAuthorized(deps, rc) {
1214
+ const connection = deps.ctx.get('connection');
1215
+ if (connection !== undefined && typeof connection.admit === 'function') {
1216
+ try {
1217
+ const admission = connection.admit({ headers: rc.req.headers });
1218
+ if (admission.peer !== undefined)
1219
+ return true;
1220
+ }
1221
+ catch {
1222
+ // Fall through to the loopback check.
1223
+ }
1224
+ }
1225
+ return rc.clientAddress === '127.0.0.1' || rc.clientAddress === '::1' || rc.clientAddress.startsWith('127.');
1226
+ }
1227
+ async function adminData(deps, originBase) {
1228
+ const view = deps.pairing.current();
1229
+ const origin = originBase;
1230
+ const payload = JSON.stringify({ v: 1, url: `${origin}${deps.config.basePath}`, code: view.code });
1231
+ const qr = await renderQr(payload);
1232
+ const qrSvg = await renderQrSvg(payload);
1233
+ return {
1234
+ code: view.code,
1235
+ formatted: view.formatted,
1236
+ fixed: view.fixed,
1237
+ locked: deps.pairing.isLocked(),
1238
+ expiresAt: view.fixed ? null : view.expiresAt,
1239
+ origin,
1240
+ basePath: deps.config.basePath,
1241
+ qr,
1242
+ qrSvg,
1243
+ time: Date.now(),
1244
+ devices: deps.devices.list().map(device => ({
1245
+ deviceId: device.deviceId,
1246
+ deviceName: device.deviceName,
1247
+ platform: device.platform,
1248
+ appVersion: device.appVersion,
1249
+ authorities: device.authorities,
1250
+ pairedAt: device.pairedAt,
1251
+ lastSeenAt: device.lastSeenAt,
1252
+ push: device.push !== undefined,
1253
+ })),
1254
+ };
1255
+ }
1256
+ /**
1257
+ * The admin page sends the base directory it was loaded from (`new URL('.',
1258
+ * location.href)`). It is the URL the user is actually using, so the Settings
1259
+ * QR follows the public URL without any Host-side public-URL configuration.
1260
+ * A loopback page yields a loopback QR; the phone can edit the address.
1261
+ */
1262
+ function requestBase(rc) {
1263
+ const value = rc.query.get('base');
1264
+ if (value === null || value.length === 0 || value.length > 2048)
1265
+ return null;
1266
+ try {
1267
+ const url = new URL(value);
1268
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
1269
+ return null;
1270
+ if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '')
1271
+ return null;
1272
+ return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
1273
+ }
1274
+ catch {
1275
+ return null;
1276
+ }
1277
+ }
1278
+ async function sendBinary(rc, file) {
1279
+ const offset = numberParam(rc.query.get('offset')) ?? 0;
1280
+ const limit = Math.min(Math.max(numberParam(rc.query.get('limit')) ?? 512 * 1024, 1), 2 * 1024 * 1024);
1281
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > file.size) {
1282
+ throw new HttpError(400, 'invalid-offset', 'offset must be a byte position inside the file');
1283
+ }
1284
+ const length = Math.min(limit, file.size - offset);
1285
+ const buffer = Buffer.alloc(length);
1286
+ const handle = await open(file.filename, 'r');
1287
+ let bytesRead = 0;
1288
+ try {
1289
+ if (length > 0)
1290
+ ({ bytesRead } = await handle.read(buffer, 0, length, offset));
1291
+ }
1292
+ finally {
1293
+ await handle.close();
1294
+ }
1295
+ const chunk = buffer.subarray(0, bytesRead);
1296
+ sendJson(rc.res, 200, {
1297
+ path: rc.query.get('path') ?? '',
1298
+ size: file.size,
1299
+ offset,
1300
+ bytes: bytesRead,
1301
+ contentType: file.contentType,
1302
+ nextOffset: offset + bytesRead < file.size ? offset + bytesRead : undefined,
1303
+ dataBase64: chunk.toString('base64'),
1304
+ });
1305
+ }
1306
+ async function renderQr(text) {
1307
+ try {
1308
+ const mod = await import('qrcode-terminal');
1309
+ const qrcode = mod.default ?? mod;
1310
+ return await new Promise((resolve) => {
1311
+ ;
1312
+ qrcode
1313
+ .generate(text, { small: true }, resolve);
1314
+ });
1315
+ }
1316
+ catch {
1317
+ return null;
1318
+ }
1319
+ }
1320
+ async function renderQrSvg(text) {
1321
+ try {
1322
+ const mod = await import('qrcode');
1323
+ const qrcode = mod.default ?? mod;
1324
+ return await qrcode.toString(text, {
1325
+ type: 'svg',
1326
+ margin: 1,
1327
+ width: 320,
1328
+ errorCorrectionLevel: 'M',
1329
+ color: { dark: '#0b0e14', light: '#ffffff' },
1330
+ });
1331
+ }
1332
+ catch (error) {
1333
+ console.warn('[dsh-hello] QR SVG generation failed:', error);
1334
+ return null;
1335
+ }
1336
+ }
1337
+ //# sourceMappingURL=routes.js.map