dsh-hello 0.1.4 → 0.1.5

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 (75) hide show
  1. package/README.md +72 -54
  2. package/lib/admin.d.ts +25 -0
  3. package/lib/admin.d.ts.map +1 -0
  4. package/lib/admin.js +179 -0
  5. package/lib/admin.js.map +1 -0
  6. package/lib/client.js +313 -10
  7. package/lib/config.d.ts.map +1 -1
  8. package/lib/config.js +3 -6
  9. package/lib/config.js.map +1 -1
  10. package/lib/devices.d.ts +2 -5
  11. package/lib/devices.d.ts.map +1 -1
  12. package/lib/devices.js +1 -16
  13. package/lib/devices.js.map +1 -1
  14. package/lib/files.d.ts +2 -2
  15. package/lib/files.d.ts.map +1 -1
  16. package/lib/files.js +5 -5
  17. package/lib/files.js.map +1 -1
  18. package/lib/host.d.ts +5 -10
  19. package/lib/host.d.ts.map +1 -1
  20. package/lib/http.d.ts +1 -2
  21. package/lib/http.d.ts.map +1 -1
  22. package/lib/http.js +0 -3
  23. package/lib/http.js.map +1 -1
  24. package/lib/index.d.ts +0 -2
  25. package/lib/index.d.ts.map +1 -1
  26. package/lib/index.js +5904 -8557
  27. package/lib/index.js.map +4 -4
  28. package/lib/interaction-routes.d.ts +8 -0
  29. package/lib/interaction-routes.d.ts.map +1 -0
  30. package/lib/interaction-routes.js +126 -0
  31. package/lib/interaction-routes.js.map +1 -0
  32. package/lib/pairing.d.ts +0 -1
  33. package/lib/pairing.d.ts.map +1 -1
  34. package/lib/pairing.js +0 -3
  35. package/lib/pairing.js.map +1 -1
  36. package/lib/protocol.d.ts +4 -2
  37. package/lib/protocol.d.ts.map +1 -1
  38. package/lib/protocol.js +4 -2
  39. package/lib/protocol.js.map +1 -1
  40. package/lib/qr.d.ts +13 -0
  41. package/lib/qr.d.ts.map +1 -0
  42. package/lib/qr.js +34 -0
  43. package/lib/qr.js.map +1 -0
  44. package/lib/route-deps.d.ts +41 -0
  45. package/lib/route-deps.d.ts.map +1 -0
  46. package/lib/route-deps.js +2 -0
  47. package/lib/route-deps.js.map +1 -0
  48. package/lib/route-util.d.ts +7 -0
  49. package/lib/route-util.d.ts.map +1 -0
  50. package/lib/route-util.js +21 -0
  51. package/lib/route-util.js.map +1 -0
  52. package/lib/routes.d.ts +1 -39
  53. package/lib/routes.d.ts.map +1 -1
  54. package/lib/routes.js +45 -761
  55. package/lib/routes.js.map +1 -1
  56. package/lib/schedule-routes.d.ts +9 -0
  57. package/lib/schedule-routes.d.ts.map +1 -0
  58. package/lib/schedule-routes.js +131 -0
  59. package/lib/schedule-routes.js.map +1 -0
  60. package/lib/schedules.d.ts +2 -2
  61. package/lib/schedules.d.ts.map +1 -1
  62. package/lib/schedules.js +2 -2
  63. package/lib/schedules.js.map +1 -1
  64. package/lib/server-facts.d.ts +8 -0
  65. package/lib/server-facts.d.ts.map +1 -0
  66. package/lib/server-facts.js +60 -0
  67. package/lib/server-facts.js.map +1 -0
  68. package/lib/sessions.d.ts.map +1 -1
  69. package/lib/sessions.js +2 -24
  70. package/lib/sessions.js.map +1 -1
  71. package/lib/terminal-routes.d.ts +5 -0
  72. package/lib/terminal-routes.d.ts.map +1 -0
  73. package/lib/terminal-routes.js +122 -0
  74. package/lib/terminal-routes.js.map +1 -0
  75. package/package.json +2 -2
package/lib/routes.js CHANGED
@@ -1,14 +1,23 @@
1
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';
2
+ import { createWorkspace, currentSessionModel, listAgentPresets, listWorkspaces, modelCatalog, renameWorkspace, selectSessionModel, setSessionArchived, setSessionPinned, uploadAttachment, } from './catalogs.js';
3
+ import { registerAdminRoutes } from './admin.js';
4
+ import { registerInteractionRoutes } from './interaction-routes.js';
5
+ import { registerScheduleRoutes } from './schedule-routes.js';
6
+ import { registerTerminalRoutes } from './terminal-routes.js';
7
+ import { features, requestOrigin, serverFacts } from './server-facts.js';
3
8
  import { listWorkspaceFiles, listWorkspaceFilesByWorkspace, readWorkspaceFile, readWorkspaceFileByWorkspace, resolveWorkspaceBinary } from './files.js';
4
9
  import { HttpError, markStreaming, sendJson, sendNoContent, startSse, writeSse } from './http.js';
5
10
  import { parseReadState, tagReadService } from './read-state.js';
6
11
  import { PROTOCOL_VERSION } from './protocol.js';
7
- import { deleteSchedule, editSchedule, listSchedules, runSchedule, scheduleActionsAvailable, scheduleHistory, scheduleHistoryAvailable, schedulesAvailable, sessionScheduleMarks, viewSchedule, } from './schedules.js';
12
+ import { normalizeAnswers } from './route-util.js';
8
13
  import { speechCatalog, transcribeSpeech } from './speech.js';
9
14
  import { newId, shortError } from './util.js';
10
15
  export function registerRoutes(router, deps) {
11
16
  const { config } = deps;
17
+ registerAdminRoutes(router, { ...deps, requestOrigin: rc => requestOrigin(deps, rc) });
18
+ registerInteractionRoutes(router, deps);
19
+ registerScheduleRoutes(router, deps);
20
+ registerTerminalRoutes(router, deps);
12
21
  router.add({
13
22
  method: 'GET',
14
23
  pattern: '/health',
@@ -27,111 +36,6 @@ export function registerRoutes(router, deps) {
27
36
  sendJson(rc.res, 200, response);
28
37
  },
29
38
  });
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/interaction',
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
- const target = body.target;
81
- if (target !== 'phone-first' && target !== 'browser-first' && target !== 'browser-only') {
82
- throw new HttpError(400, 'bad-target', 'target must be phone-first, browser-first, or browser-only');
83
- }
84
- if (deps.saveInteractionTarget === undefined)
85
- throw new HttpError(503, 'interaction-unavailable', 'this Host cannot change the interaction policy');
86
- await deps.saveInteractionTarget(target);
87
- sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
88
- },
89
- });
90
- router.add({
91
- method: 'POST',
92
- pattern: '/admin/lock',
93
- auth: 'public',
94
- handler: async (rc) => {
95
- if (!adminAuthorized(deps, rc))
96
- throw new HttpError(401, 'admin-unauthorized', 'open this page from an authenticated dsh browser');
97
- const body = (rc.body ?? {});
98
- if (typeof body.locked !== 'boolean')
99
- throw new HttpError(400, 'bad-lock', 'locked must be true or false');
100
- await deps.pairing.setLocked(body.locked);
101
- sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
102
- },
103
- });
104
- router.add({
105
- method: 'DELETE',
106
- pattern: '/admin/devices/:id',
107
- auth: 'public',
108
- handler: async (rc) => {
109
- if (!adminAuthorized(deps, rc))
110
- throw new HttpError(401, 'admin-unauthorized', 'open this page from an authenticated dsh browser');
111
- const removed = await deps.devices.revoke(rc.params.id);
112
- if (!removed)
113
- throw new HttpError(404, 'device-not-found', 'no such device');
114
- deps.hub.closeDevice(rc.params.id);
115
- sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
116
- },
117
- });
118
- router.add({
119
- method: 'PUT',
120
- pattern: '/admin/devices/:id',
121
- auth: 'public',
122
- handler: async (rc) => {
123
- if (!adminAuthorized(deps, rc))
124
- throw new HttpError(401, 'admin-unauthorized', 'open this page from an authenticated dsh browser');
125
- const body = (rc.body ?? {});
126
- const name = typeof body.name === 'string' ? body.name.trim().slice(0, 120) : '';
127
- if (name.length === 0)
128
- throw new HttpError(400, 'bad-device-name', 'a non-empty device name is required');
129
- const renamed = await deps.devices.rename(rc.params.id, name);
130
- if (!renamed)
131
- throw new HttpError(404, 'device-not-found', 'no such device');
132
- sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ''));
133
- },
134
- });
135
39
  router.add({
136
40
  method: 'GET',
137
41
  pattern: '/web-url',
@@ -143,19 +47,6 @@ export function registerRoutes(router, deps) {
143
47
  sendJson(rc.res, 200, { url });
144
48
  },
145
49
  });
146
- router.add({
147
- method: 'GET',
148
- pattern: '/pair',
149
- auth: 'public',
150
- handler: (rc) => {
151
- const status = deps.pairing.status();
152
- sendJson(rc.res, 200, {
153
- server: serverFacts(deps, requestOrigin(deps, rc)),
154
- features: features(deps),
155
- pairing: { open: status.pairingOpen },
156
- });
157
- },
158
- });
159
50
  router.add({
160
51
  method: 'GET',
161
52
  pattern: '/pair/code',
@@ -169,13 +60,11 @@ export function registerRoutes(router, deps) {
169
60
  url: `${origin}${config.basePath}`,
170
61
  code: current.code,
171
62
  });
172
- const qr = await renderQr(payload);
173
63
  sendJson(rc.res, 200, {
174
64
  code: current.code,
175
65
  formatted: current.formatted,
176
66
  expiresAt: current.expiresAt,
177
67
  payload,
178
- qr,
179
68
  });
180
69
  },
181
70
  });
@@ -238,30 +127,31 @@ export function registerRoutes(router, deps) {
238
127
  });
239
128
  router.add({
240
129
  method: 'GET',
241
- pattern: '/devices',
130
+ pattern: '/devices/me',
242
131
  auth: 'device',
243
132
  handler: (rc) => {
244
- sendJson(rc.res, 200, {
245
- current: rc.device?.deviceId,
246
- items: deps.devices.list(),
247
- });
133
+ const device = deps.devices.list().find(item => item.deviceId === rc.device?.deviceId);
134
+ if (device === undefined)
135
+ throw new HttpError(404, 'device-not-found', 'this device is no longer paired');
136
+ sendJson(rc.res, 200, { device });
248
137
  },
249
138
  });
250
139
  router.add({
251
140
  method: 'DELETE',
252
- pattern: '/devices/:id',
141
+ pattern: '/devices/me',
253
142
  auth: 'device',
254
143
  handler: async (rc) => {
255
- const removed = await deps.devices.revoke(rc.params.id);
144
+ const deviceId = rc.device.deviceId;
145
+ const removed = await deps.devices.revoke(deviceId);
256
146
  if (!removed)
257
- throw new HttpError(404, 'device-not-found', 'no such device');
258
- deps.hub.closeDevice(rc.params.id);
147
+ throw new HttpError(404, 'device-not-found', 'this device is no longer paired');
148
+ deps.hub.closeDevice(deviceId);
259
149
  sendNoContent(rc.res);
260
150
  },
261
151
  });
262
152
  router.add({
263
- method: 'POST',
264
- pattern: '/push/register',
153
+ method: 'PUT',
154
+ pattern: '/devices/me/push',
265
155
  auth: 'device',
266
156
  handler: async (rc) => {
267
157
  const body = rc.body;
@@ -282,7 +172,7 @@ export function registerRoutes(router, deps) {
282
172
  });
283
173
  router.add({
284
174
  method: 'PUT',
285
- pattern: '/push/subscriptions',
175
+ pattern: '/devices/me/push/subscriptions',
286
176
  auth: 'device',
287
177
  handler: async (rc) => {
288
178
  const body = rc.body;
@@ -298,7 +188,7 @@ export function registerRoutes(router, deps) {
298
188
  });
299
189
  router.add({
300
190
  method: 'DELETE',
301
- pattern: '/push',
191
+ pattern: '/devices/me/push',
302
192
  auth: 'device',
303
193
  handler: async (rc) => {
304
194
  await deps.devices.clearPush(rc.device.deviceId);
@@ -333,121 +223,6 @@ export function registerRoutes(router, deps) {
333
223
  sendJson(rc.res, 200, result);
334
224
  },
335
225
  });
336
- router.add({
337
- method: 'GET',
338
- pattern: '/schedules',
339
- auth: 'device',
340
- handler: async (rc) => {
341
- const result = await listSchedules(deps.ctx, rc.signal);
342
- sendJson(rc.res, 200, result);
343
- },
344
- });
345
- router.add({
346
- method: 'GET',
347
- pattern: '/schedule-marks',
348
- auth: 'device',
349
- handler: async (rc) => {
350
- sendJson(rc.res, 200, await sessionScheduleMarks(deps.ctx, rc.signal));
351
- },
352
- });
353
- router.add({
354
- method: 'GET',
355
- pattern: '/schedules/:id',
356
- auth: 'device',
357
- handler: async (rc) => {
358
- const result = await viewSchedule(deps.ctx, rc.params.id, rc.signal);
359
- if (result === undefined)
360
- throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
361
- const code = scheduleCode(result);
362
- if (code === 'schedule_not_found')
363
- throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
364
- sendJson(rc.res, 200, result);
365
- },
366
- });
367
- router.add({
368
- method: 'GET',
369
- pattern: '/schedules/:id/history',
370
- auth: 'device',
371
- handler: async (rc) => {
372
- const rawLimit = rc.query.get('limit');
373
- const parsed = rawLimit === null ? 20 : Number(rawLimit);
374
- if (!Number.isInteger(parsed) || parsed < 1 || parsed > 100) {
375
- throw new HttpError(400, 'bad-limit', 'limit must be an integer from 1 to 100');
376
- }
377
- const before = rc.query.get('before') ?? undefined;
378
- const result = await scheduleHistory(deps.ctx, rc.params.id, parsed, before, rc.signal);
379
- if (result === undefined)
380
- throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
381
- const code = scheduleCode(result);
382
- if (code === 'schedule_not_found')
383
- throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
384
- if (code === 'delivery_cursor_not_found')
385
- throw new HttpError(404, 'delivery-cursor-not-found', 'the history cursor is no longer valid');
386
- sendJson(rc.res, 200, result);
387
- },
388
- });
389
- router.add({
390
- method: 'POST',
391
- pattern: '/schedules/:id/run',
392
- auth: 'device',
393
- handler: async (rc) => {
394
- const result = await runSchedule(deps.ctx, rc.params.id, rc.signal);
395
- if (result === undefined)
396
- throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
397
- const code = scheduleCode(result);
398
- if (code === 'schedule_not_found')
399
- throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
400
- if (code === 'schedule_execution_pending') {
401
- throw new HttpError(409, 'schedule-execution-pending', 'the task is already running or cooling down');
402
- }
403
- sendJson(rc.res, 200, result);
404
- },
405
- });
406
- router.add({
407
- method: 'PUT',
408
- pattern: '/schedules/:id',
409
- auth: 'device',
410
- handler: async (rc) => {
411
- const body = (rc.body ?? {});
412
- if (typeof body.active !== 'boolean') {
413
- throw new HttpError(400, 'bad-schedule-patch', 'active must be a boolean');
414
- }
415
- const expectedUpdatedAt = typeof body.expectedUpdatedAt === 'string' || body.expectedUpdatedAt === null
416
- ? body.expectedUpdatedAt
417
- : undefined;
418
- const result = await editSchedule(deps.ctx, rc.params.id, { active: body.active }, expectedUpdatedAt, rc.signal);
419
- if (result === undefined)
420
- throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
421
- const code = scheduleCode(result);
422
- if (code === 'schedule_not_found')
423
- throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
424
- if (code === 'schedule_conflict')
425
- throw new HttpError(409, 'schedule-conflict', 'the task changed on the Host');
426
- sendJson(rc.res, 200, result);
427
- },
428
- });
429
- router.add({
430
- method: 'DELETE',
431
- pattern: '/schedules/:id',
432
- auth: 'device',
433
- handler: async (rc) => {
434
- const body = (rc.body ?? {});
435
- const fromBody = body.expectedUpdatedAt;
436
- const fromQuery = rc.query.get('expectedUpdatedAt') ?? undefined;
437
- const expectedUpdatedAt = typeof fromBody === 'string' || fromBody === null
438
- ? fromBody
439
- : fromQuery;
440
- const result = await deleteSchedule(deps.ctx, rc.params.id, expectedUpdatedAt, rc.signal);
441
- if (result === undefined)
442
- throw new HttpError(404, 'schedule-unavailable', 'the Host has no schedule service');
443
- const code = scheduleCode(result);
444
- if (code === 'schedule_not_found')
445
- throw new HttpError(404, 'schedule-not-found', 'the task no longer exists');
446
- if (code === 'schedule_conflict')
447
- throw new HttpError(409, 'schedule-conflict', 'the task changed on the Host');
448
- sendJson(rc.res, 200, result);
449
- },
450
- });
451
226
  router.add({
452
227
  method: 'GET',
453
228
  pattern: '/sessions',
@@ -501,7 +276,7 @@ export function registerRoutes(router, deps) {
501
276
  pattern: '/workspaces/:id/files',
502
277
  auth: 'device',
503
278
  handler: async (rc) => {
504
- const response = await listWorkspaceFilesByWorkspace(deps.ctx, rc.params.id, rc.query.get('path') ?? '', rc.signal);
279
+ const response = await listWorkspaceFilesByWorkspace(deps.ctx, rc.params.id, rc.query.get('path') ?? '');
505
280
  sendJson(rc.res, 200, response);
506
281
  },
507
282
  });
@@ -514,7 +289,7 @@ export function registerRoutes(router, deps) {
514
289
  if (path === null || path.length === 0)
515
290
  throw new HttpError(400, 'empty-path', 'path is required');
516
291
  const offset = numberParam(rc.query.get('offset')) ?? 0;
517
- const response = await readWorkspaceFileByWorkspace(deps.ctx, rc.params.id, path, rc.signal, offset);
292
+ const response = await readWorkspaceFileByWorkspace(deps.ctx, rc.params.id, path, offset);
518
293
  sendJson(rc.res, 200, response);
519
294
  },
520
295
  });
@@ -594,7 +369,7 @@ export function registerRoutes(router, deps) {
594
369
  },
595
370
  });
596
371
  router.add({
597
- method: 'POST',
372
+ method: 'PATCH',
598
373
  pattern: '/read-state',
599
374
  auth: 'device',
600
375
  handler: async (rc) => {
@@ -624,7 +399,7 @@ export function registerRoutes(router, deps) {
624
399
  },
625
400
  });
626
401
  router.add({
627
- method: 'POST',
402
+ method: 'PUT',
628
403
  pattern: '/sessions/:id/model',
629
404
  auth: 'device',
630
405
  handler: async (rc) => {
@@ -656,10 +431,10 @@ export function registerRoutes(router, deps) {
656
431
  auth: 'device',
657
432
  handler: async (rc) => {
658
433
  const beforeSeq = numberParam(rc.query.get('beforeSeq'));
659
- const maxMessages = numberParam(rc.query.get('maxMessages'));
434
+ const limit = numberParam(rc.query.get('limit'));
660
435
  const response = await deps.sessions.transcript(rc.params.id, {
661
436
  ...(beforeSeq === undefined ? {} : { beforeSeq }),
662
- ...(maxMessages === undefined ? {} : { maxMessages }),
437
+ ...(limit === undefined ? {} : { maxMessages: limit }),
663
438
  }, rc.signal);
664
439
  sendJson(rc.res, 200, response);
665
440
  },
@@ -751,8 +526,8 @@ export function registerRoutes(router, deps) {
751
526
  },
752
527
  });
753
528
  router.add({
754
- method: 'POST',
755
- pattern: '/sessions/:id/rename',
529
+ method: 'PATCH',
530
+ pattern: '/sessions/:id',
756
531
  auth: 'device',
757
532
  handler: async (rc) => {
758
533
  const body = rc.body;
@@ -772,9 +547,6 @@ export function registerRoutes(router, deps) {
772
547
  if (body.atSeq !== undefined && (!Number.isSafeInteger(body.atSeq) || body.atSeq < 0)) {
773
548
  throw new HttpError(400, 'invalid-fork-seq', 'atSeq must be a non-negative safe integer');
774
549
  }
775
- if (typeof deps.ctx.sessionController.fork !== 'function') {
776
- throw new HttpError(501, 'fork-unavailable', 'this dsh version does not expose session/fork');
777
- }
778
550
  const forked = await deps.sessions.fork(rc.params.id, typeof body.atSeq === 'number' ? body.atSeq : undefined);
779
551
  sendJson(rc.res, 201, forked);
780
552
  },
@@ -789,27 +561,17 @@ export function registerRoutes(router, deps) {
789
561
  },
790
562
  });
791
563
  router.add({
792
- method: 'POST',
564
+ method: 'PUT',
793
565
  pattern: '/sessions/:id/pin',
794
566
  auth: 'device',
795
567
  handler: async (rc) => {
796
- try {
797
- await setSessionPinned(deps.ctx, rc.params.id, true);
798
- sendJson(rc.res, 200, { ok: true });
799
- }
800
- catch (error) {
801
- throw new HttpError(409, 'session-pin-failed', shortError(error));
568
+ const body = rc.body;
569
+ if (typeof body?.pinned !== 'boolean') {
570
+ throw new HttpError(400, 'bad-pin', 'pinned must be true or false');
802
571
  }
803
- },
804
- });
805
- router.add({
806
- method: 'POST',
807
- pattern: '/sessions/:id/unpin',
808
- auth: 'device',
809
- handler: async (rc) => {
810
572
  try {
811
- await setSessionPinned(deps.ctx, rc.params.id, false);
812
- sendJson(rc.res, 200, { ok: true });
573
+ await setSessionPinned(deps.ctx, rc.params.id, body.pinned);
574
+ sendJson(rc.res, 200, { pinned: body.pinned });
813
575
  }
814
576
  catch (error) {
815
577
  throw new HttpError(409, 'session-pin-failed', shortError(error));
@@ -817,28 +579,17 @@ export function registerRoutes(router, deps) {
817
579
  },
818
580
  });
819
581
  router.add({
820
- method: 'POST',
582
+ method: 'PUT',
821
583
  pattern: '/sessions/:id/archive',
822
584
  auth: 'device',
823
585
  handler: async (rc) => {
824
- const body = (rc.body ?? {});
825
- try {
826
- await setSessionArchived(deps.ctx, rc.params.id, true, body.stopActivity === true);
827
- sendJson(rc.res, 200, { ok: true });
828
- }
829
- catch (error) {
830
- throw new HttpError(409, 'session-archive-failed', shortError(error));
586
+ const body = rc.body;
587
+ if (typeof body?.archived !== 'boolean') {
588
+ throw new HttpError(400, 'bad-archive', 'archived must be true or false');
831
589
  }
832
- },
833
- });
834
- router.add({
835
- method: 'POST',
836
- pattern: '/sessions/:id/unarchive',
837
- auth: 'device',
838
- handler: async (rc) => {
839
590
  try {
840
- await setSessionArchived(deps.ctx, rc.params.id, false);
841
- sendJson(rc.res, 200, { ok: true });
591
+ await setSessionArchived(deps.ctx, rc.params.id, body.archived, body.archived && body.stopActivity === true);
592
+ sendJson(rc.res, 200, { archived: body.archived });
842
593
  }
843
594
  catch (error) {
844
595
  throw new HttpError(409, 'session-archive-failed', shortError(error));
@@ -894,300 +645,8 @@ export function registerRoutes(router, deps) {
894
645
  }
895
646
  },
896
647
  });
897
- router.add({
898
- method: 'GET',
899
- pattern: '/sessions/:id/terminals',
900
- auth: 'device',
901
- handler: (rc) => {
902
- sendJson(rc.res, 200, { items: deps.terminals.list(rc.params.id) });
903
- },
904
- });
905
- router.add({
906
- method: 'POST',
907
- pattern: '/sessions/:id/terminals',
908
- auth: 'device',
909
- handler: async (rc) => {
910
- const sessionId = rc.params.id;
911
- const body = rc.body;
912
- const state = await deps.sessions.state(sessionId, rc.signal);
913
- const cwd = state.session.cwd;
914
- if (typeof cwd !== 'string' || cwd.length === 0) {
915
- throw new HttpError(409, 'session-cwd-unknown', 'the session has no working directory yet');
916
- }
917
- const created = await deps.terminals.create(sessionId, cwd, {
918
- ...(typeof body?.cols === 'number' ? { cols: body.cols } : {}),
919
- ...(typeof body?.rows === 'number' ? { rows: body.rows } : {}),
920
- });
921
- sendJson(rc.res, 201, created);
922
- },
923
- });
924
- router.add({
925
- method: 'GET',
926
- pattern: '/sessions/:id/terminals/:terminalId/events',
927
- auth: 'device',
928
- handler: async (rc) => {
929
- const sessionId = rc.params.id;
930
- const terminalId = rc.params.terminalId;
931
- // Resolve before headers so a missing terminal is a JSON 404.
932
- const snapshot = deps.terminals.snapshot(sessionId, terminalId);
933
- markStreaming(rc.res);
934
- startSse(rc.res);
935
- const heartbeat = setInterval(() => writeSse(rc.res, 'heartbeat', { time: Date.now() }), 15_000);
936
- heartbeat.unref?.();
937
- let ready = false;
938
- const pending = [];
939
- let release = () => undefined;
940
- const stopped = new Promise(resolve => { release = resolve; });
941
- const shutdown = () => {
942
- if (!rc.res.writableEnded)
943
- rc.res.end();
944
- release();
945
- };
946
- // Subscribe before the snapshot is sent, then flush anything that raced
947
- // in while the reconnect replay was being written.
948
- const unsubscribe = deps.terminals.subscribe(sessionId, terminalId, event => {
949
- if (!ready) {
950
- pending.push(event);
951
- return;
952
- }
953
- writeSse(rc.res, event.type, event);
954
- });
955
- rc.signal.addEventListener('abort', shutdown);
956
- const untrack = deps.hub.trackDevice(rc.device.deviceId, shutdown);
957
- writeSse(rc.res, 'ready', { ...snapshot, time: Date.now() });
958
- ready = true;
959
- for (const event of pending.splice(0))
960
- writeSse(rc.res, event.type, event);
961
- try {
962
- await stopped;
963
- }
964
- finally {
965
- untrack();
966
- rc.signal.removeEventListener('abort', shutdown);
967
- unsubscribe();
968
- clearInterval(heartbeat);
969
- if (!rc.res.writableEnded)
970
- rc.res.end();
971
- }
972
- },
973
- });
974
- router.add({
975
- method: 'POST',
976
- pattern: '/sessions/:id/terminals/:terminalId/input',
977
- auth: 'device',
978
- handler: async (rc) => {
979
- const body = rc.body;
980
- const data = body?.data;
981
- if (typeof data !== 'string' || data.length === 0) {
982
- throw new HttpError(400, 'bad-input', 'data must be a non-empty string');
983
- }
984
- if (data.length > 65_536)
985
- throw new HttpError(413, 'input-too-large', 'terminal input is limited to 64 KiB');
986
- await deps.terminals.write(rc.params.id, rc.params.terminalId, data);
987
- sendJson(rc.res, 200, { accepted: true });
988
- },
989
- });
990
- router.add({
991
- method: 'POST',
992
- pattern: '/sessions/:id/terminals/:terminalId/resize',
993
- auth: 'device',
994
- handler: async (rc) => {
995
- const body = rc.body;
996
- if (typeof body?.cols !== 'number' || typeof body?.rows !== 'number') {
997
- throw new HttpError(400, 'bad-size', 'cols and rows must be numbers');
998
- }
999
- const info = await deps.terminals.resize(rc.params.id, rc.params.terminalId, body.cols, body.rows);
1000
- sendJson(rc.res, 200, info);
1001
- },
1002
- });
1003
- router.add({
1004
- method: 'DELETE',
1005
- pattern: '/sessions/:id/terminals/:terminalId',
1006
- auth: 'device',
1007
- handler: async (rc) => {
1008
- const closed = await deps.terminals.close(rc.params.id, rc.params.terminalId);
1009
- if (!closed)
1010
- throw new HttpError(404, 'terminal-not-found', 'no such terminal in this session');
1011
- sendNoContent(rc.res);
1012
- },
1013
- });
1014
- router.add({
1015
- method: 'GET',
1016
- pattern: '/events',
1017
- auth: 'device',
1018
- handler: (rc) => {
1019
- markStreaming(rc.res);
1020
- const clientId = newId();
1021
- deps.hub.add(clientId, rc.device.deviceId, rc.res);
1022
- writeSse(rc.res, 'hello', {
1023
- server: serverFacts(deps, requestOrigin(deps, rc)),
1024
- features: features(deps),
1025
- pendingApprovals: deps.interactions.listApprovals(),
1026
- pendingQuestions: deps.interactions.listQuestions(),
1027
- time: Date.now(),
1028
- });
1029
- rc.req.on('close', () => {
1030
- // `SseHub` removes the response on close; nothing else is owned here.
1031
- });
1032
- },
1033
- });
1034
- router.add({
1035
- method: 'GET',
1036
- pattern: '/approvals',
1037
- auth: 'device',
1038
- handler: (rc) => {
1039
- sendJson(rc.res, 200, { items: deps.interactions.listApprovals() });
1040
- },
1041
- });
1042
- router.add({
1043
- method: 'POST',
1044
- pattern: '/approvals/:id',
1045
- auth: 'device',
1046
- handler: (rc) => {
1047
- const body = rc.body;
1048
- const decision = body?.decision;
1049
- if (decision !== 'allow' && decision !== 'deny' && decision !== 'always' && decision !== 'later') {
1050
- throw new HttpError(400, 'bad-decision', 'decision must be allow, deny, always, or later');
1051
- }
1052
- const item = deps.interactions.decideApproval(rc.params.id, decision);
1053
- if (item === undefined)
1054
- throw new HttpError(404, 'approval-not-found', 'the approval is no longer pending');
1055
- sendJson(rc.res, 200, { accepted: true, decision });
1056
- },
1057
- });
1058
- router.add({
1059
- method: 'POST',
1060
- pattern: '/presence',
1061
- auth: 'device',
1062
- handler: (rc) => {
1063
- const body = rc.body;
1064
- if (typeof body?.foreground !== 'boolean') {
1065
- throw new HttpError(400, 'bad-presence', 'foreground must be a boolean');
1066
- }
1067
- const device = rc.device;
1068
- if (device === undefined)
1069
- throw new HttpError(401, 'unauthenticated', 'a valid device token is required');
1070
- deps.interactions.setPresence(device.deviceId, body.foreground);
1071
- sendJson(rc.res, 200, { accepted: true });
1072
- },
1073
- });
1074
- router.add({
1075
- method: 'GET',
1076
- pattern: '/questions',
1077
- auth: 'device',
1078
- handler: (rc) => {
1079
- sendJson(rc.res, 200, { items: deps.interactions.listQuestions() });
1080
- },
1081
- });
1082
- router.add({
1083
- method: 'POST',
1084
- pattern: '/questions/:id/answer',
1085
- auth: 'device',
1086
- handler: (rc) => {
1087
- const body = rc.body;
1088
- const answers = normalizeAnswers(body?.answers);
1089
- const answered = deps.interactions.answerQuestion(rc.params.id, { answers });
1090
- if (answered === undefined)
1091
- throw new HttpError(404, 'question-not-found', 'the question is no longer pending');
1092
- sendJson(rc.res, 200, { accepted: true });
1093
- },
1094
- });
1095
- if (config.enableDebugRoutes) {
1096
- router.add({
1097
- method: 'POST',
1098
- pattern: '/debug/approval',
1099
- auth: 'device',
1100
- handler: (rc) => {
1101
- const body = (rc.body ?? {});
1102
- const item = deps.interactions.createDebugApproval({
1103
- ...(typeof body.sessionId === 'string' ? { sessionId: body.sessionId } : {}),
1104
- ...(typeof body.toolName === 'string' ? { toolName: body.toolName } : {}),
1105
- ...(typeof body.reason === 'string' ? { reason: body.reason } : {}),
1106
- ...(typeof body.displayReason === 'object' && body.displayReason !== null
1107
- ? { displayReason: body.displayReason }
1108
- : {}),
1109
- });
1110
- sendJson(rc.res, 201, item);
1111
- },
1112
- });
1113
- router.add({
1114
- method: 'POST',
1115
- pattern: '/debug/question',
1116
- auth: 'device',
1117
- handler: (rc) => {
1118
- const body = (rc.body ?? {});
1119
- const item = deps.interactions.createDebugQuestion({
1120
- ...(typeof body.sessionId === 'string' ? { sessionId: body.sessionId } : {}),
1121
- ...(Array.isArray(body.questions) ? { questions: body.questions } : {}),
1122
- });
1123
- sendJson(rc.res, 201, item);
1124
- },
1125
- });
1126
- deps.logger.warn('[dsh-hello] debug interaction routes are enabled');
1127
- }
1128
648
  deps.logger.info(`[dsh-hello] routes mounted at ${config.basePath} (protocol ${PROTOCOL_VERSION}, push ${config.push.provider})`);
1129
649
  }
1130
- function serverFacts(deps, originOverride) {
1131
- const web = deps.ctx.webServer;
1132
- let fallback = null;
1133
- try {
1134
- fallback = typeof web.getOrigin === 'function' ? web.getOrigin() : null;
1135
- }
1136
- catch {
1137
- fallback = null;
1138
- }
1139
- const origin = originOverride ?? fallback;
1140
- return {
1141
- name: 'dsh-hello',
1142
- version: deps.pluginVersion,
1143
- protocol: PROTOCOL_VERSION,
1144
- dshVersion: deps.version.version,
1145
- dshCompatible: deps.version.compatible,
1146
- origin,
1147
- protocolName: origin !== null && origin.startsWith('https://') ? 'https' : web.protocol === 'https:' ? 'https' : 'http',
1148
- host: web.host ?? null,
1149
- port: web.port ?? null,
1150
- };
1151
- }
1152
- /** `scheme://authority` as the client reached this request, or null when unknown. */
1153
- function requestOrigin(deps, rc) {
1154
- if (rc.authority.length === 0)
1155
- return null;
1156
- const scheme = deps.ctx.webServer.protocol === 'https:' ? 'https' : 'http';
1157
- return `${scheme}://${rc.authority}`;
1158
- }
1159
- function scheduleCode(result) {
1160
- if (typeof result !== 'object' || result === null)
1161
- return undefined;
1162
- const code = result.code;
1163
- return typeof code === 'string' ? code : undefined;
1164
- }
1165
- function features(deps) {
1166
- const target = deps.interactionTarget?.() ?? deps.config.interactionTarget;
1167
- return {
1168
- approvals: target !== 'browser-only',
1169
- questions: target !== 'browser-only',
1170
- interactionTarget: target,
1171
- presence: true,
1172
- push: deps.push.isConfigured(),
1173
- debugRoutes: deps.config.enableDebugRoutes,
1174
- terminal: deps.terminals.available(),
1175
- files: true,
1176
- workspaces: workspacesAvailable(deps.ctx),
1177
- workspaceRename: workspaceRenameAvailable(deps.ctx),
1178
- archive: workspacesAvailable(deps.ctx),
1179
- pin: workspacesAvailable(deps.ctx),
1180
- agentPresets: agentPresetsAvailable(deps.ctx),
1181
- models: modelsAvailable(deps.ctx),
1182
- uploads: uploadsAvailable(deps.ctx),
1183
- readState: tagReadService(deps.ctx) !== undefined,
1184
- schedules: schedulesAvailable(deps.ctx),
1185
- scheduleActions: scheduleActionsAvailable(deps.ctx),
1186
- scheduleHistory: scheduleHistoryAvailable(deps.ctx),
1187
- sessionEvents: 'sse',
1188
- protocol: PROTOCOL_VERSION,
1189
- };
1190
- }
1191
650
  function assertLoopback(rc) {
1192
651
  const address = rc.clientAddress.replace(/^::ffff:/, '');
1193
652
  if (address !== '127.0.0.1' && address !== '::1' && !address.startsWith('127.')) {
@@ -1211,90 +670,6 @@ function randomPairingToken() {
1211
670
  globalThis.crypto.getRandomValues(bytes);
1212
671
  return `dshd_${Buffer.from(bytes).toString('base64url')}`;
1213
672
  }
1214
- function normalizeAnswers(value) {
1215
- if (!Array.isArray(value) || value.length === 0) {
1216
- throw new HttpError(400, 'bad-answers', 'answers must be a non-empty array');
1217
- }
1218
- return value.map((item) => {
1219
- if (typeof item !== 'object' || item === null)
1220
- throw new HttpError(400, 'bad-answers', 'each answer must be an object');
1221
- const candidate = item;
1222
- if (typeof candidate.id !== 'string' || !Array.isArray(candidate.selected) || !candidate.selected.every(label => typeof label === 'string')) {
1223
- throw new HttpError(400, 'bad-answers', 'each answer needs an id and a selected string array');
1224
- }
1225
- return {
1226
- id: candidate.id,
1227
- selected: candidate.selected,
1228
- ...(typeof candidate.custom === 'string' ? { custom: candidate.custom } : {}),
1229
- };
1230
- });
1231
- }
1232
- function adminAuthorized(deps, rc) {
1233
- const connection = deps.ctx.get('connection');
1234
- if (connection !== undefined && typeof connection.admit === 'function') {
1235
- try {
1236
- const admission = connection.admit({ headers: rc.req.headers });
1237
- if (admission.peer !== undefined)
1238
- return true;
1239
- }
1240
- catch {
1241
- // Fall through to the loopback check.
1242
- }
1243
- }
1244
- return rc.clientAddress === '127.0.0.1' || rc.clientAddress === '::1' || rc.clientAddress.startsWith('127.');
1245
- }
1246
- async function adminData(deps, originBase) {
1247
- const view = deps.pairing.current();
1248
- const origin = originBase;
1249
- const payload = JSON.stringify({ v: 1, url: `${origin}${deps.config.basePath}`, code: view.code });
1250
- const qr = await renderQr(payload);
1251
- const qrSvg = await renderQrSvg(payload);
1252
- return {
1253
- code: view.code,
1254
- formatted: view.formatted,
1255
- fixed: view.fixed,
1256
- locked: deps.pairing.isLocked(),
1257
- interactionTarget: deps.interactionTarget?.() ?? deps.config.interactionTarget,
1258
- expiresAt: view.fixed ? null : view.expiresAt,
1259
- origin,
1260
- basePath: deps.config.basePath,
1261
- qr,
1262
- qrSvg,
1263
- time: Date.now(),
1264
- devices: deps.devices.list().map(device => ({
1265
- deviceId: device.deviceId,
1266
- deviceName: device.deviceName,
1267
- platform: device.platform,
1268
- appVersion: device.appVersion,
1269
- authorities: device.authorities,
1270
- pairedAt: device.pairedAt,
1271
- lastSeenAt: device.lastSeenAt,
1272
- push: device.push !== undefined,
1273
- })),
1274
- };
1275
- }
1276
- /**
1277
- * The admin page sends the base directory it was loaded from (`new URL('.',
1278
- * location.href)`). It is the URL the user is actually using, so the Settings
1279
- * QR follows the public URL without any Host-side public-URL configuration.
1280
- * A loopback page yields a loopback QR; the phone can edit the address.
1281
- */
1282
- function requestBase(rc) {
1283
- const value = rc.query.get('base');
1284
- if (value === null || value.length === 0 || value.length > 2048)
1285
- return null;
1286
- try {
1287
- const url = new URL(value);
1288
- if (url.protocol !== 'http:' && url.protocol !== 'https:')
1289
- return null;
1290
- if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '')
1291
- return null;
1292
- return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
1293
- }
1294
- catch {
1295
- return null;
1296
- }
1297
- }
1298
673
  async function sendBinary(rc, file) {
1299
674
  const offset = numberParam(rc.query.get('offset')) ?? 0;
1300
675
  const limit = Math.min(Math.max(numberParam(rc.query.get('limit')) ?? 512 * 1024, 1), 2 * 1024 * 1024);
@@ -1323,95 +698,4 @@ async function sendBinary(rc, file) {
1323
698
  dataBase64: chunk.toString('base64'),
1324
699
  });
1325
700
  }
1326
- async function renderQr(text) {
1327
- const candidates = [];
1328
- try {
1329
- const mod = (await import('qrcode-terminal'));
1330
- candidates.push(mod.default, mod.default?.default, mod);
1331
- }
1332
- catch {
1333
- // Fall through to the CommonJS require below.
1334
- }
1335
- try {
1336
- const { createRequire } = await import('node:module');
1337
- candidates.push(createRequire(import.meta.url)('qrcode-terminal'));
1338
- }
1339
- catch {
1340
- // No terminal QR without the package; callers treat null as "no QR".
1341
- }
1342
- for (const candidate of candidates) {
1343
- const generate = candidate?.generate;
1344
- if (typeof generate !== 'function')
1345
- continue;
1346
- try {
1347
- return await new Promise((resolve) => {
1348
- ;
1349
- candidate
1350
- .generate(text, { small: true }, resolve);
1351
- });
1352
- }
1353
- catch {
1354
- continue;
1355
- }
1356
- }
1357
- return null;
1358
- }
1359
- /**
1360
- * Resolve `qrcode`'s API however this Host loaded the plugin.
1361
- *
1362
- * `mod.default ?? mod` is not enough: depending on how the loader interops the
1363
- * CommonJS package, that expression can land on a plain object, and its
1364
- * inherited `Object.prototype.toString` then returns the string
1365
- * "[object Object]" — which the admin page rendered as the QR. Accept only an
1366
- * object with a real `toString`, and fall back to `createRequire`.
1367
- */
1368
- async function loadQrSvgApi() {
1369
- const isApi = (value) => typeof value === 'object'
1370
- && value !== null
1371
- && typeof value.toString === 'function'
1372
- && value.toString !== Object.prototype.toString;
1373
- try {
1374
- const mod = (await import('qrcode'));
1375
- for (const candidate of [mod.default, mod.default?.default, mod]) {
1376
- if (isApi(candidate))
1377
- return candidate;
1378
- }
1379
- }
1380
- catch (error) {
1381
- console.warn('[dsh-hello] could not import qrcode through ESM:', error);
1382
- }
1383
- try {
1384
- const { createRequire } = await import('node:module');
1385
- const required = createRequire(import.meta.url)('qrcode');
1386
- if (isApi(required))
1387
- return required;
1388
- }
1389
- catch (error) {
1390
- console.warn('[dsh-hello] could not require qrcode:', error);
1391
- }
1392
- return null;
1393
- }
1394
- async function renderQrSvg(text) {
1395
- const qrcode = await loadQrSvgApi();
1396
- if (qrcode === null) {
1397
- console.warn('[dsh-hello] qrcode is unavailable; the admin page will not show a QR code');
1398
- return null;
1399
- }
1400
- try {
1401
- const svg = await qrcode.toString(text, {
1402
- type: 'svg',
1403
- margin: 1,
1404
- width: 320,
1405
- errorCorrectionLevel: 'M',
1406
- color: { dark: '#0b0e14', light: '#ffffff' },
1407
- });
1408
- // Never hand the page something that is not an SVG: a bad value used to
1409
- // render as the literal text "[object Object]".
1410
- return typeof svg === 'string' && svg.trimStart().startsWith('<svg') ? svg : null;
1411
- }
1412
- catch (error) {
1413
- console.warn('[dsh-hello] QR SVG generation failed:', error);
1414
- return null;
1415
- }
1416
- }
1417
701
  //# sourceMappingURL=routes.js.map