@deep-podder/dsh-remote-mobile 0.0.0-stage → 0.0.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.
@@ -0,0 +1,2800 @@
1
+ #!/usr/bin/env node
2
+ /* ==========================================================================
3
+ DSH Remote — DEV-ONLY mock server
4
+ --------------------------------------------------------------------------
5
+ This file is not imported or served by the plugin; it exists only for local SPA development (and is published only so a checkout can run it). It
6
+ exists so the SPA in this folder can be exercised end to end without the
7
+ real DeepSeek Harness host.
8
+
9
+ It implements, with Node built-ins only (no npm dependencies):
10
+
11
+ GET / the SPA shell
12
+ GET /app.js the SPA bundle
13
+ GET /styles.css the stylesheet
14
+ GET /api/state { paired, device, version }
15
+ POST /api/pair { pin } or { token } -> Set-Cookie: rm_session
16
+ POST /api/rotate-pin rotates the demo PIN
17
+ POST /api/unpair revokes this demo device
18
+ GET /health { ok, version }
19
+ WS /ws PROTOCOL.md frames over a hand-rolled RFC 6455
20
+ server (handshake, masked client frames, unmasked
21
+ server text frames, ping/pong, close codes)
22
+
23
+ Run: node mock-server.js [port]
24
+ Env: PORT, HOST, RM_PIN, RM_RATE_WINDOW_MS, RM_RATE_MAX
25
+ ========================================================================== */
26
+
27
+ import { createServer } from 'node:http';
28
+ import { readFile } from 'node:fs/promises';
29
+ import { createHash, createECDH, randomBytes } from 'node:crypto';
30
+ import { fileURLToPath } from 'node:url';
31
+ import { dirname, extname, join } from 'node:path';
32
+ import { networkInterfaces } from 'node:os';
33
+
34
+ const HERE = dirname(fileURLToPath(import.meta.url));
35
+ const PORT = Number(process.env.PORT || process.argv[2] || 3456);
36
+ const HOST = process.env.HOST || '0.0.0.0';
37
+ const VERSION = '0.0.5';
38
+ const PAIRING_TOKEN = randomBytes(24).toString('base64url');
39
+ const RATE_WINDOW_MS = Number(process.env.RM_RATE_WINDOW_MS || 5 * 60 * 1000);
40
+ const RATE_MAX = Number(process.env.RM_RATE_MAX || 5);
41
+ const MAX_UPLOAD_BYTES = Number(process.env.RM_MAX_UPLOAD_BYTES || 32 * 1024 * 1024);
42
+ const UPLOAD_DELAY_MS = Number(process.env.RM_UPLOAD_DELAY_MS || 0);
43
+ const UPLOAD_FILE_LIMIT = 10;
44
+ const SESSION_COOKIE = 'rm_session';
45
+ const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
46
+ const SEED_PREVIEW_PATH = '.mock-uploads/seed/screenshot.png';
47
+ const SEED_PREVIEW_BASE64 =
48
+ 'iVBORw0KGgoAAAANSUhEUgAAABgAAAASCAYAAABB7B6eAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAATZSURBVDhPBcEBp+psAMDxPk5EREQiosmiyaLJQxYP2ZhrrrNzTFpa8qgljyRJSpLkOI5zXdf75f7v75fLGwEF4xdFI6Rk/KZsvFEx3qkaH9SMmLoxoWFMaRozWsactrGgYyzpGoqesaJvrBkYG4SxZWhoRsYOaewZGwd840gub/6iYIYUzd+UzDfK5jsV84OqGVMzJ9TNKQ1zRtOc0zIXtM0lHVPRNVf0zDV9c8PA3CJMzdDcMTL3SPPA2DzimydyeSukYP2maL1Rst4pWx9UrJiqNaFmTalbMxrWnKa1oGUtaVuKjrWia63pWRv61paBpRHWjqG1Z2QdkNaRsXXCt87k8vZvCvYbRfudkv1B2Y6p2BOq9pSaPaNuz2nYC5r2kpataNsrOvaarr2hZ2/p25qBvUPYe4b2gZF9RNonxvYZ376QyztvFJx3is4HJSem7EyoOFOqzoyaM6fuLGg4S5qOouWsaDtrOs6GrrOl52j6zo6Bs0c4B4bOkZFzQjpnxs4F37mSy4t3CuKDoogpiQllMaUiZlTFnJpYUBdLGkLRFCtaYk1bbOiILV2h6YkdfbFnIA4IcWQoTozEGSkujMUVX9zI5d0PCm5M0Z1QcqeU3RkVd07VXVBzl9RdRcNd0XTXtNwNbXdLx9V03R09d0/fPTBwjwj3xNA9M3IvSPfK2L3hu3dyeRlTkBOKckpJzijLORW5oCqX1KSiLlc05Jqm3NCSW9pS05E7unJPTx7oyyMDeULIM0N5YSSvSHljLO/48kEu700oeFOK3oySN6fsLah4S6qeouatqHtrGt6Gprel5Wna3o6Ot6frHeh5R/reiYF3RngXht6VkXdDenfG3gPfe5LLB1MKwYxiMKcULCgHSyqBohqsqAVr6sGGRrClGWhawY52sKcTHOgGR3rBiX5wZhBcEMGVYXBjFNyRwYNx8MQPXuTy4YxCOKcYLiiFS8qhohKuqIZrauGGerilEWqa4Y5WuKcdHuiER7rhiV54ph9eGIRXRHhjGN4ZhQ9k+GQcvvDDT3L5aE4hWlCMlpQiRTlaUYnWVKMNtWhLPdI0oh3NaE8rOtCOjnSiE93oTC+60I+uDKIbIrozjB6MoicyejGOPvGjL3L5eEEhXlKMFaV4RTleU4k3VOMttVhTj3c04j3N+EArPtKOT3TiM934Qi++0o9vDOI7In4wjJ+M4hcy/mQcf+HH3+TyyZJCoigmK0rJmnKyoZJsqSaaWrKjnuxpJAeayZFWcqKdnOkkF7rJlV5yo5/cGSQPRPJkmLwYJZ/I5Itx8o2f/JDLp4pCuqKYrimlG8rplkqqqaY7aumeenqgkR5ppida6Zl2eqGTXummN3rpnX76YJA+EemLYfrJKP1Cpt+M0x/89A+5vFpRUGuKakNJbSkrTUXtqKo9NXWgro401ImmOtNSF9rqSkfd6Ko7PfWgr54M1AuhPhmqL0bqG6l+GKs/+OovuXy2ppBtKGZbSpmmnO2oZHuq2YFadqSenWhkZ5rZhVZ2pZ3d6GR3utmDXvakn70YZJ+I7Ith9s0o+0Fmfxhnf/Gzf+TyekNBbylqTUnvKOs9FX2gqo/U9Im6PtPQF5r6SkvfaOs7Hf2gq5/09Iu+/mSgvxD6m6H+YaT/IPVfxvofvv6P/wFmwtpi1twkpwAAAABJRU5ErkJggg==';
49
+ const SEED_PREVIEW_BYTES = Buffer.from(SEED_PREVIEW_BASE64, 'base64');
50
+
51
+ const MIME = {
52
+ '.html': 'text/html; charset=utf-8',
53
+ '.js': 'text/javascript; charset=utf-8',
54
+ '.css': 'text/css; charset=utf-8',
55
+ '.png': 'image/png',
56
+ '.svg': 'image/svg+xml',
57
+ '.webmanifest': 'application/manifest+json; charset=utf-8'
58
+ };
59
+
60
+ const STATIC_FILES = {
61
+ '/': 'index.html',
62
+ '/index.html': 'index.html',
63
+ '/app.js': 'app.js',
64
+ '/styles.css': 'styles.css',
65
+ '/manifest.webmanifest': 'manifest.webmanifest',
66
+ '/sw.js': 'sw.js',
67
+ '/favicon.svg': 'favicon.svg',
68
+ '/icons/icon-192.png': 'icons/icon-192.png',
69
+ '/icons/icon-512.png': 'icons/icon-512.png',
70
+ '/icons/icon-maskable-512.png': 'icons/icon-maskable-512.png',
71
+ '/icons/apple-touch-icon.png': 'icons/apple-touch-icon.png'
72
+ };
73
+
74
+ /* Mirrors the Host's strict CSP so the mock catches inline-script and
75
+ cross-origin regressions before they reach the real plugin. */
76
+ const CONTENT_SECURITY_POLICY = [
77
+ "default-src 'self'",
78
+ "script-src 'self'",
79
+ "worker-src 'self'",
80
+ "style-src 'self' 'unsafe-inline'",
81
+ "img-src 'self' data:",
82
+ "connect-src 'self' ws: wss:",
83
+ "font-src 'self'",
84
+ "base-uri 'none'",
85
+ "form-action 'none'",
86
+ "frame-ancestors 'none'"
87
+ ].join('; ');
88
+
89
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
90
+
91
+ /* Web Push fixtures: a fresh, genuinely valid P-256 VAPID public key per mock
92
+ process (65-byte uncompressed point, base64url). Mock deliveries never leave
93
+ the process; the subscription store only proves the client wiring. */
94
+ const PUSH_ECDH = createECDH('prime256v1');
95
+ PUSH_ECDH.generateKeys();
96
+ const PUSH_PUBLIC_KEY = PUSH_ECDH.getPublicKey().toString('base64url');
97
+ const pushSubscriptions = new Map(); // endpoint -> { endpoint, deviceId, subscription }
98
+ const deviceVisibility = new Map(); // deviceId -> boolean
99
+
100
+ function log(...args) {
101
+ console.log('[mock]', ...args);
102
+ }
103
+
104
+ function randomPin() {
105
+ return String(Math.floor(Math.random() * 10000)).padStart(4, '0');
106
+ }
107
+
108
+ /* ---------- In-memory demo state ---------------------------------------- */
109
+
110
+ let currentPin = process.env.RM_PIN || '1234';
111
+ let pairingTokenConsumed = false;
112
+ /* Simulate a read-only approval device (the Host advertises canApprove). */
113
+ const APPROVALS_READONLY = process.env.RM_APPROVAL_READONLY === '1';
114
+
115
+ const devices = []; // { id, name, createdAt, cookie }
116
+ const clients = new Set(); // WsConnection
117
+ const histories = new Map(); // sessionId -> HistoryItem[]
118
+ const runs = new Map(); // sessionId -> run token
119
+ const pendingApprovals = new Map(); // requestId -> { requestId, resolve, done }
120
+ const pendingQuestions = new Map(); // requestId -> { requestId, callId, questions, resolve, done }
121
+ const uploadedFiles = new Map(); // path -> { bytes, sessionId, mediaType, name }
122
+ const rateLimit = new Map(); // ip -> number[] timestamps
123
+ let historySeq = 1000;
124
+
125
+ uploadedFiles.set(SEED_PREVIEW_PATH, {
126
+ bytes: SEED_PREVIEW_BYTES,
127
+ sessionId: 'sess-release',
128
+ mediaType: 'image/png',
129
+ name: 'screenshot.png'
130
+ });
131
+
132
+ const serverState = {
133
+ sessions: [],
134
+ activeSessionId: null,
135
+ models: {
136
+ catalog: [
137
+ { provider: 'deepseek', model: 'deepseek-chat', label: 'DeepSeek Chat' },
138
+ {
139
+ provider: 'deepseek',
140
+ model: 'deepseek-v4.1-flash',
141
+ label: 'V4.1 Flash',
142
+ reasoning: {
143
+ efforts: [
144
+ { id: 'low', name: 'Low', description: 'Faster answers with a short reasoning pass.' },
145
+ { id: 'medium', name: 'Medium', description: 'The balanced default for everyday work.' },
146
+ { id: 'high', name: 'High', description: 'Deeper reasoning; slower and more tokens.' }
147
+ ],
148
+ defaultEffort: 'medium'
149
+ }
150
+ },
151
+ { provider: 'deepseek', model: 'deepseek-reasoner', label: 'DeepSeek Reasoner' },
152
+ {
153
+ provider: 'anthropic',
154
+ model: 'claude-sonnet-4.5',
155
+ label: 'Claude Sonnet 4.5',
156
+ reasoning: {
157
+ /* No defaultEffort: the sheet offers "Provider default" explicitly. */
158
+ efforts: [
159
+ { id: 'low', name: 'Low', description: null },
160
+ { id: 'high', name: 'High', description: 'Extends thinking before answering.' }
161
+ ],
162
+ defaultEffort: null
163
+ }
164
+ },
165
+ { provider: 'local', model: 'qwen2.5-coder:32b', label: 'Qwen 2.5 Coder 32B' }
166
+ ],
167
+ current: {
168
+ provider: 'deepseek',
169
+ model: 'deepseek-chat',
170
+ reasoningEffort: null
171
+ }
172
+ },
173
+ presets: {
174
+ presets: [
175
+ {
176
+ id: 'standard',
177
+ title: 'Standard',
178
+ description:
179
+ 'Balanced planning with full tool access. The default working preset.'
180
+ },
181
+ {
182
+ id: 'ptc',
183
+ title: 'Plan · Think · Check',
184
+ description:
185
+ 'Explains the plan before acting and verifies each step before reporting back.'
186
+ },
187
+ {
188
+ id: 'minimal',
189
+ title: 'Minimal',
190
+ description:
191
+ 'Fast, terse answers with minimal tool use and no commentary.'
192
+ },
193
+ {
194
+ id: 'cordis',
195
+ title: 'Cordis',
196
+ description:
197
+ 'Plugin and harness development with Cordis-aware context and tooling.'
198
+ }
199
+ ],
200
+ current: 'standard'
201
+ },
202
+ /* Batch D attachment limits as advertised by the live Host. */
203
+ limits: {
204
+ image: {
205
+ maxBytes: 5242880,
206
+ maxDimension: 65535,
207
+ maxImages: 4,
208
+ maxMessageBytes: 209715200,
209
+ mediaTypes: ['image/png', 'image/jpeg', 'image/webp', 'image/gif']
210
+ }
211
+ }
212
+ };
213
+
214
+ /* Batch C: the live prompt queue per session (never history until claimed). */
215
+ const queues = new Map(); // sessionId -> [{ id, placement, rpcId?, text }]
216
+
217
+ function queueOf(sessionId) {
218
+ if (!queues.has(sessionId)) queues.set(sessionId, []);
219
+ return queues.get(sessionId);
220
+ }
221
+
222
+ function broadcastQueue(sessionId) {
223
+ const items = queueOf(sessionId);
224
+ broadcast({ type: 'queue.changed', sessionId, items });
225
+ }
226
+
227
+ function sendQueueFrame(conn, sessionId) {
228
+ const session = findSession(sessionId);
229
+ conn.sendText(
230
+ JSON.stringify({
231
+ type: 'queue',
232
+ sessionId,
233
+ items: queueOf(sessionId),
234
+ pendingInput: [],
235
+ running: !!(session && session.running),
236
+ active: !!(session && session.agentAvailable)
237
+ })
238
+ );
239
+ }
240
+
241
+ function nextHistoryId(kind) {
242
+ historySeq += 1;
243
+ return kind === 'tool' ? 'tool:' + historySeq : 'seq:' + historySeq;
244
+ }
245
+
246
+ /* Demo projects shown by the project-grouped Sessions sheet. Paths are generic
247
+ placeholders; the mock never reads them. */
248
+ const WORKSPACES = [
249
+ {
250
+ id: 'ws-mobile',
251
+ title: 'dsh-remote-mobile',
252
+ path: 'C:\\workspace\\dsh-remote-mobile',
253
+ sessionIds: ['sess-release', 'sess-api']
254
+ },
255
+ {
256
+ id: 'ws-agent',
257
+ title: 'personal-agent',
258
+ path: 'C:\\workspace\\personal-agent',
259
+ sessionIds: ['sess-design']
260
+ }
261
+ ];
262
+
263
+ function seed() {
264
+ const now = Date.now();
265
+
266
+ const release = {
267
+ id: 'sess-release',
268
+ title: 'Release checklist',
269
+ running: false,
270
+ updatedAt: now - 3 * 60 * 1000,
271
+ preset: 'standard',
272
+ model: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: null },
273
+ turn: 0,
274
+ agentAvailable: true,
275
+ pinned: true,
276
+ archived: false,
277
+ workspaceId: WORKSPACES[0].id
278
+ };
279
+ const api = {
280
+ id: 'sess-api',
281
+ title: 'API refactor notes',
282
+ running: false,
283
+ updatedAt: now - 96 * 60 * 1000,
284
+ preset: 'ptc',
285
+ model: { provider: 'deepseek', model: 'deepseek-reasoner', reasoningEffort: null },
286
+ turn: 0,
287
+ agentAvailable: true,
288
+ pinned: false,
289
+ archived: false,
290
+ workspaceId: WORKSPACES[0].id
291
+ };
292
+ const design = {
293
+ id: 'sess-design',
294
+ title: 'Design review — mobile shell',
295
+ running: false,
296
+ updatedAt: now - 26 * 60 * 60 * 1000,
297
+ preset: 'minimal',
298
+ model: { provider: 'anthropic', model: 'claude-sonnet-4.5', reasoningEffort: null },
299
+ turn: 0,
300
+ agentAvailable: true,
301
+ pinned: false,
302
+ archived: true,
303
+ workspaceId: WORKSPACES[1].id
304
+ };
305
+ const notes = {
306
+ id: 'sess-notes',
307
+ title: 'Scratchpad',
308
+ running: false,
309
+ updatedAt: now - 5 * 60 * 60 * 1000,
310
+ preset: 'standard',
311
+ model: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: null },
312
+ turn: 0,
313
+ agentAvailable: true,
314
+ pinned: false,
315
+ archived: false,
316
+ workspaceId: null
317
+ };
318
+
319
+ serverState.sessions = [release, api, notes, design];
320
+ serverState.activeSessionId = release.id;
321
+
322
+ const releaseAttachments = [
323
+ {
324
+ path: SEED_PREVIEW_PATH,
325
+ name: 'screenshot.png',
326
+ mediaType: 'image/png',
327
+ size: SEED_PREVIEW_BYTES.length
328
+ },
329
+ {
330
+ path: '.mock-uploads/seed/release-notes.txt',
331
+ name: 'release-notes.txt',
332
+ mediaType: 'text/plain',
333
+ size: 24
334
+ }
335
+ ];
336
+ if (process.env.RM_BROKEN_PREVIEW_FIXTURE === '1') {
337
+ releaseAttachments.splice(1, 0, {
338
+ path: '.mock-uploads/seed/missing-preview.png',
339
+ name: 'missing-preview.png',
340
+ mediaType: 'image/png',
341
+ size: 0
342
+ });
343
+ }
344
+
345
+ histories.set(release.id, [
346
+ {
347
+ id: 'seq:1',
348
+ kind: 'user',
349
+ text: 'Give me a quick release checklist for the mobile plugin.',
350
+ ts: now - 8 * 60 * 1000,
351
+ attachments: releaseAttachments
352
+ },
353
+ {
354
+ id: 'seq:2',
355
+ kind: 'assistant',
356
+ text: [
357
+ '## Release checklist',
358
+ '',
359
+ 'Before tagging `v1.0.0`, verify the following:',
360
+ '',
361
+ '1. **Protocol** — the SPA consumes only documented frames.',
362
+ '2. **Pairing** — QR token and 4-digit PIN both pair successfully.',
363
+ '3. `node --check app.js` and `node --check mock-server.js` pass.',
364
+ '',
365
+ '| Check | Status |',
366
+ '| --- | --- |',
367
+ '| Protocol frames | Done |',
368
+ '| iOS Safari pairing | Open |',
369
+ '',
370
+ '> Remote access is local-network only. No camera, no audio, no cloud relay.',
371
+ '',
372
+ '```js',
373
+ "const socket = new WebSocket('/ws');",
374
+ "socket.addEventListener('message', (event) => {",
375
+ " const frame = JSON.parse(event.data);",
376
+ " console.log(frame.type);",
377
+ '});',
378
+ '```',
379
+ '',
380
+ '- [ ] Token pairing tested on iOS Safari',
381
+ '- [ ] PIN rate limit shows a countdown',
382
+ '',
383
+ 'See the [protocol notes](https://example.com/dsh-remote) for details.'
384
+ ].join('\n'),
385
+ ts: now - 7 * 60 * 1000
386
+ },
387
+ {
388
+ id: 'tool:1',
389
+ kind: 'tool',
390
+ callId: 'call-history-1',
391
+ name: 'read',
392
+ title: 'Read file',
393
+ argsPreview: 'mobile/app.js',
394
+ ok: true,
395
+ output:
396
+ "1 (function () {\n2 'use strict';\n3 ...\n4 })();\n\n(read 1.8 kB)",
397
+ diff: null,
398
+ durationMs: 42,
399
+ ts: now - 6 * 60 * 1000
400
+ },
401
+ {
402
+ id: 'tool:1q',
403
+ kind: 'tool',
404
+ callId: 'call-history-q1',
405
+ name: 'ask_user_question',
406
+ title: 'Confirm deployment',
407
+ argsPreview: '2 questions',
408
+ ok: true,
409
+ output: JSON.stringify({
410
+ answers: [
411
+ { id: 'environment', selected: ['Staging'] },
412
+ { id: 'checks', selected: ['Unit tests'], custom: 'Also run the linter' }
413
+ ],
414
+ outcome: 'answered'
415
+ }),
416
+ diff: null,
417
+ durationMs: 5400,
418
+ ts: now - 5.5 * 60 * 1000,
419
+ question: { callId: 'call-history-q1', questions: deployQuestions() }
420
+ },
421
+ {
422
+ id: 'seq:3',
423
+ kind: 'assistant',
424
+ text: [
425
+ 'The checklist is covered in the release notes. Two things are still open:',
426
+ '',
427
+ '- token pairing on **iOS Safari**',
428
+ '- the **rate-limit countdown** copy',
429
+ '',
430
+ 'Want me to run the checks now?'
431
+ ].join('\n'),
432
+ ts: now - 5 * 60 * 1000
433
+ }
434
+ ]);
435
+
436
+ histories.set(api.id, [
437
+ {
438
+ id: 'seq:4',
439
+ kind: 'user',
440
+ text: 'Summarise the refactor decisions from yesterday.',
441
+ ts: now - 2 * 60 * 60 * 1000
442
+ },
443
+ {
444
+ id: 'seq:5',
445
+ kind: 'assistant',
446
+ text: [
447
+ '### Decisions',
448
+ '',
449
+ '- One **generic runtime**: `core/runtime.py` owns the tool loop.',
450
+ '- Playbooks became data, not subclasses.',
451
+ '- Approvals are content-bound; a changed draft asks again.',
452
+ '',
453
+ 'The related tests moved under `tests/test_runtime.py`.'
454
+ ].join('\n'),
455
+ ts: now - 110 * 60 * 1000
456
+ },
457
+ {
458
+ id: 'tool:2',
459
+ kind: 'tool',
460
+ callId: 'call-history-2',
461
+ name: 'grep',
462
+ title: 'Search sources',
463
+ argsPreview: 'class .*Worker',
464
+ ok: false,
465
+ output: 'No matches for /class .*Worker/ in src/.',
466
+ diff: null,
467
+ durationMs: 18,
468
+ ts: now - 105 * 60 * 1000
469
+ }
470
+ ]);
471
+
472
+ histories.set(design.id, [
473
+ {
474
+ id: 'seq:6',
475
+ kind: 'user',
476
+ text: 'Review the mobile top bar spacing.',
477
+ ts: now - 27 * 60 * 60 * 1000
478
+ },
479
+ {
480
+ id: 'seq:7',
481
+ kind: 'assistant',
482
+ text: [
483
+ 'The top bar reads well at 390 px. One note: the title block sits **2 px** higher than the icon buttons because of the status dot line-height. Tighten the `session-sub` line box to `15px` and it aligns.'
484
+ ].join('\n'),
485
+ ts: now - 26 * 60 * 60 * 1000
486
+ }
487
+ ]);
488
+ }
489
+
490
+ seed();
491
+
492
+ /* ---------- Session / frame helpers ------------------------------------- */
493
+
494
+ function findSession(id) {
495
+ return serverState.sessions.find((session) => session.id === id) || null;
496
+ }
497
+
498
+ function publicSession(session) {
499
+ return {
500
+ id: session.id,
501
+ title: session.title,
502
+ running: !!session.running,
503
+ updatedAt: session.updatedAt,
504
+ preset: session.preset || null,
505
+ model: session.model || null,
506
+ agentAvailable: session.agentAvailable !== false,
507
+ pinned: !!session.pinned,
508
+ archived: !!session.archived,
509
+ workspaceId: session.workspaceId || null
510
+ };
511
+ }
512
+
513
+ function publicSessions() {
514
+ return serverState.sessions.map(publicSession);
515
+ }
516
+
517
+ function historyOf(sessionId) {
518
+ return histories.get(sessionId) || [];
519
+ }
520
+
521
+ /* Batch C3 fixtures: a live context projection, change summaries and diffs. */
522
+ function contextFor() {
523
+ return {
524
+ usedTokens: 11214,
525
+ pressureTokens: 11214,
526
+ projectedTokens: 12480,
527
+ contextWindow: 1000000,
528
+ basis: 'usage',
529
+ tokenUsage: {
530
+ inputTokens: 10400,
531
+ outputTokens: 814,
532
+ totalTokens: 11214,
533
+ reasoningTokens: 0
534
+ }
535
+ };
536
+ }
537
+
538
+ function changesFor() {
539
+ return [
540
+ {
541
+ seq: 41,
542
+ available: true,
543
+ turn: 2,
544
+ total: 2,
545
+ added: 18,
546
+ deleted: 4,
547
+ files: [
548
+ {
549
+ index: 0,
550
+ path: 'src/app.ts',
551
+ display: 'src/app.ts',
552
+ added: 12,
553
+ deleted: 3,
554
+ binary: false,
555
+ oversized: false
556
+ },
557
+ {
558
+ index: 1,
559
+ path: 'assets/logo.png',
560
+ display: 'assets/logo.png',
561
+ added: 0,
562
+ deleted: 0,
563
+ binary: true,
564
+ oversized: false
565
+ }
566
+ ]
567
+ },
568
+ { seq: 40, available: false, files: [] }
569
+ ];
570
+ }
571
+
572
+ function diffFor(seq, index) {
573
+ const file = changesFor()
574
+ .map((item) => (item.files || []).find((entry) => entry.index === index))
575
+ .find(Boolean);
576
+ if (!file) return null;
577
+ if (file.binary) {
578
+ return { kind: 'binary', path: file.display, coarse: false, hunks: [] };
579
+ }
580
+ return {
581
+ kind: 'text',
582
+ path: file.display,
583
+ coarse: false,
584
+ hunks: [
585
+ {
586
+ oldStart: 10,
587
+ oldLines: 3,
588
+ newStart: 10,
589
+ newLines: 5,
590
+ lines: [
591
+ ' export function createBridge(ctx) {',
592
+ '- const sessions = ctx.sessions;',
593
+ '+ const sessions = ctx.sessionController;',
594
+ '+ const queue = ctx.queue;',
595
+ ' return sessions;',
596
+ ' }'
597
+ ]
598
+ }
599
+ ]
600
+ };
601
+ }
602
+
603
+ function appendHistory(sessionId, item) {
604
+ const list = historyOf(sessionId);
605
+ list.push(item);
606
+ if (list.length > 400) list.splice(0, list.length - 400);
607
+ histories.set(sessionId, list);
608
+ }
609
+
610
+ function sendJson(res, status, body, extraHeaders) {
611
+ const payload = JSON.stringify(body);
612
+ res.writeHead(status, {
613
+ 'Content-Type': 'application/json; charset=utf-8',
614
+ 'Content-Length': Buffer.byteLength(payload),
615
+ 'Cache-Control': 'no-store',
616
+ ...(extraHeaders || {})
617
+ });
618
+ res.end(payload);
619
+ }
620
+
621
+ function errorFrame(code, message) {
622
+ return { type: 'error', code, message };
623
+ }
624
+
625
+ function broadcast(frame) {
626
+ for (const client of clients) {
627
+ client.sendText(JSON.stringify(frame));
628
+ }
629
+ }
630
+
631
+ function broadcastSessions() {
632
+ broadcast({
633
+ type: 'sessions',
634
+ sessions: publicSessions(),
635
+ workspaces: WORKSPACES,
636
+ activeSessionId: serverState.activeSessionId
637
+ });
638
+ }
639
+
640
+ function broadcastStatus(sessionId, running) {
641
+ broadcast({ type: 'session.status', sessionId, running });
642
+ }
643
+
644
+ function readProviderModel(provider, model) {
645
+ return (
646
+ serverState.models.catalog.find(
647
+ (entry) => entry.provider === provider && entry.model === model
648
+ ) || null
649
+ );
650
+ }
651
+
652
+ /* ---------- Streaming simulation ---------------------------------------- */
653
+
654
+ function splitChunks(text) {
655
+ return text.match(/\s*\S+/g) || [text];
656
+ }
657
+
658
+ async function streamAssistant(sessionId, turn, step, text, runToken) {
659
+ broadcast({ type: 'assistant.start', sessionId, turn, step });
660
+ const chunks = splitChunks(text);
661
+ let accumulated = '';
662
+ for (const chunk of chunks) {
663
+ if (runToken.cancelled) break;
664
+ accumulated += chunk;
665
+ broadcast({
666
+ type: 'assistant.delta',
667
+ sessionId,
668
+ text: chunk,
669
+ reasoning: null
670
+ });
671
+ await sleep(32 + Math.floor(Math.random() * 28));
672
+ }
673
+ broadcast({ type: 'assistant.end', sessionId, turn, step });
674
+ return accumulated;
675
+ }
676
+
677
+ function firstStepText(promptText, attachments) {
678
+ if (attachments && attachments.length) {
679
+ const names = attachments
680
+ .map((attachment) => String(attachment.name || 'file'))
681
+ .join(', ');
682
+ return (
683
+ 'I received ' +
684
+ attachments.length +
685
+ ' attachment' +
686
+ (attachments.length === 1 ? '' : 's') +
687
+ ': ' +
688
+ names +
689
+ '. I will take a look and report back.'
690
+ );
691
+ }
692
+ if (/deploy/i.test(promptText)) {
693
+ return 'Deploying needs an approval first. The command is ready — approve it and I will run it.';
694
+ }
695
+ if (/test|pytest|suite/i.test(promptText)) {
696
+ return 'Running the test suite now. I will report the failing cases and any leaked database state.';
697
+ }
698
+ return 'On it. Let me check the working tree first, then I will summarise what changed.';
699
+ }
700
+
701
+ function deployQuestions() {
702
+ return [
703
+ {
704
+ id: 'environment',
705
+ question: 'Which environment should I deploy to?',
706
+ header: 'Deploy',
707
+ detail: 'Staging is safe to retry; production carries live traffic.',
708
+ multiSelect: false,
709
+ options: [
710
+ { label: 'Staging', description: 'Shared staging slot' },
711
+ { label: 'Production', description: 'Live traffic — use with care' }
712
+ ]
713
+ },
714
+ {
715
+ id: 'checks',
716
+ question: 'Which checks should run before the deploy?',
717
+ header: 'Deploy',
718
+ multiSelect: true,
719
+ options: [
720
+ { label: 'Unit tests', description: 'Fast pytest pass' },
721
+ { label: 'Browser smoke', description: 'Drive the mobile SPA headlessly' },
722
+ { label: 'Skip checks' }
723
+ ]
724
+ }
725
+ ];
726
+ }
727
+
728
+ /* Ask a batch through the full tool shape: tool.start (with question) +
729
+ question.request, then question.resolved + tool.end once the phone answers. */
730
+ async function askQuestions(sessionId, callId, questions, runToken, opts = {}) {
731
+ const requestId = 'qst-' + randomBytes(4).toString('hex');
732
+ const pending = {
733
+ requestId,
734
+ callId,
735
+ questions,
736
+ resolve: null,
737
+ done: false
738
+ };
739
+ const decisionPromise = new Promise((resolve) => {
740
+ pending.resolve = resolve;
741
+ });
742
+ pendingQuestions.set(requestId, pending);
743
+ runToken.question = pending;
744
+
745
+ broadcast({
746
+ type: 'tool.start',
747
+ sessionId,
748
+ callId,
749
+ name: 'ask_user_question',
750
+ title: opts.toolTitle || 'Ask user',
751
+ argsPreview: questions.length + ' questions',
752
+ detail: null,
753
+ question: { callId, questions }
754
+ });
755
+ broadcast({
756
+ type: 'question.request',
757
+ sessionId,
758
+ requestId,
759
+ callId,
760
+ questions
761
+ });
762
+
763
+ const decision = await Promise.race([
764
+ decisionPromise,
765
+ sleep(120000).then(() => 'timeout')
766
+ ]);
767
+ pendingQuestions.delete(requestId);
768
+ runToken.question = null;
769
+ pending.done = true;
770
+ if (decision !== 'timeout') await sleep(650);
771
+
772
+ if (decision === 'timeout') {
773
+ broadcast({
774
+ type: 'question.resolved',
775
+ sessionId,
776
+ requestId,
777
+ callId,
778
+ answers: null,
779
+ outcome: 'unavailable'
780
+ });
781
+ broadcast({
782
+ type: 'tool.end',
783
+ sessionId,
784
+ callId,
785
+ ok: false,
786
+ output: 'Question timed out.',
787
+ durationMs: 120000
788
+ });
789
+ return { answers: [], outcome: 'unavailable', requestId, callId };
790
+ }
791
+
792
+ const answers = Array.isArray(decision.answers) ? decision.answers : [];
793
+ const outcome = answers.length ? 'answered' : 'declined';
794
+ const output = JSON.stringify({ answers, outcome });
795
+
796
+ broadcast({
797
+ type: 'question.resolved',
798
+ sessionId,
799
+ requestId,
800
+ callId,
801
+ answers,
802
+ outcome
803
+ });
804
+ broadcast({
805
+ type: 'tool.end',
806
+ sessionId,
807
+ callId,
808
+ ok: true,
809
+ output,
810
+ durationMs: 1200
811
+ });
812
+ appendHistory(sessionId, {
813
+ id: 'tool:' + callId,
814
+ kind: 'tool',
815
+ callId,
816
+ name: 'ask_user_question',
817
+ title: opts.toolTitle || 'Ask user',
818
+ argsPreview: questions.length + ' questions',
819
+ ok: true,
820
+ output,
821
+ diff: null,
822
+ durationMs: 1200,
823
+ ts: Date.now(),
824
+ question: { callId, questions }
825
+ });
826
+ return { answers, outcome, requestId, callId };
827
+ }
828
+
829
+ /* Blocking-question edge case: question.request with no matching tool row.
830
+ Resends once so the SPA's dedupe + draft survival can be exercised. */
831
+ async function askBlockingQuestion(sessionId, questions, runToken, opts = {}) {
832
+ const requestId = 'qst-' + randomBytes(4).toString('hex');
833
+ const pending = {
834
+ requestId,
835
+ callId: null,
836
+ questions,
837
+ resolve: null,
838
+ done: false
839
+ };
840
+ const decisionPromise = new Promise((resolve) => {
841
+ pending.resolve = resolve;
842
+ });
843
+ pendingQuestions.set(requestId, pending);
844
+ runToken.question = pending;
845
+
846
+ const send = () =>
847
+ broadcast({
848
+ type: 'question.request',
849
+ sessionId,
850
+ requestId,
851
+ callId: null,
852
+ questions
853
+ });
854
+ send();
855
+ if (opts.resend) setTimeout(send, 900);
856
+
857
+ const decision = await Promise.race([
858
+ decisionPromise,
859
+ sleep(120000).then(() => 'timeout')
860
+ ]);
861
+ pendingQuestions.delete(requestId);
862
+ runToken.question = null;
863
+ pending.done = true;
864
+ if (decision !== 'timeout') await sleep(650);
865
+
866
+ const answers =
867
+ decision && Array.isArray(decision.answers) ? decision.answers : [];
868
+ const outcome = decision === 'timeout' ? 'unavailable' : answers.length ? 'answered' : 'declined';
869
+ broadcast({
870
+ type: 'question.resolved',
871
+ sessionId,
872
+ requestId,
873
+ callId: null,
874
+ answers: outcome === 'answered' ? answers : null,
875
+ outcome
876
+ });
877
+ return { answers, outcome, requestId };
878
+ }
879
+
880
+ /* Cross-session fixture: one pending approval for the active session, one
881
+ approval and one question for non-active sessions. Used by the layout and
882
+ scoping harness; triggered by a "cross-session fixture" prompt. */
883
+ function fixtureApproval(sessionId, displayReason) {
884
+ const requestId = 'appr-fix-' + randomBytes(3).toString('hex');
885
+ const entry = {
886
+ requestId,
887
+ done: false,
888
+ resolve: null
889
+ };
890
+ entry.resolve = (decision) => {
891
+ pendingApprovals.delete(requestId);
892
+ broadcast({
893
+ type: 'approval.resolved',
894
+ requestId,
895
+ outcome: decision === 'allow' ? 'allowed-once' : 'rejected'
896
+ });
897
+ };
898
+ pendingApprovals.set(requestId, entry);
899
+ broadcast({
900
+ type: 'approval.request',
901
+ sessionId,
902
+ requestId,
903
+ toolName: 'pwsh',
904
+ title: 'Approval required',
905
+ reason: 'pwsh -File scripts\\deploy.ps1 -Environment staging',
906
+ displayReason,
907
+ argsKind: 'command',
908
+ argsPreview:
909
+ 'pwsh -File scripts\\deploy.ps1 -Environment staging\n' +
910
+ '# step 1/3: verify build output\n' +
911
+ '# step 2/3: upload to staging\n' +
912
+ '# step 3/3: restart the staging app',
913
+ detail: { kind: 'command', path: 'scripts\\deploy.ps1' },
914
+ callId: null,
915
+ expiresAt: Date.now() + 120000
916
+ });
917
+ return requestId;
918
+ }
919
+
920
+ function fixtureQuestion(sessionId, question) {
921
+ const requestId = 'qst-fix-' + randomBytes(3).toString('hex');
922
+ const entry = {
923
+ requestId,
924
+ callId: null,
925
+ questions: [question],
926
+ done: false,
927
+ resolve: null
928
+ };
929
+ entry.resolve = (decision) => {
930
+ const answers =
931
+ decision && Array.isArray(decision.answers) ? decision.answers : [];
932
+ pendingQuestions.delete(requestId);
933
+ broadcast({
934
+ type: 'question.resolved',
935
+ sessionId,
936
+ requestId,
937
+ callId: null,
938
+ answers: answers.length ? answers : null,
939
+ outcome: answers.length ? 'answered' : 'declined'
940
+ });
941
+ };
942
+ pendingQuestions.set(requestId, entry);
943
+ broadcast({
944
+ type: 'question.request',
945
+ sessionId,
946
+ requestId,
947
+ callId: null,
948
+ questions: [question]
949
+ });
950
+ return requestId;
951
+ }
952
+
953
+ function emitCrossSessionFixtures(activeSessionId) {
954
+ const others = serverState.sessions.filter(
955
+ (session) => session.id !== activeSessionId
956
+ );
957
+ const approvalSession = others[0] || null;
958
+ const questionSession = others[1] || others[0] || null;
959
+
960
+ /* Active approval first: it must render inline. */
961
+ fixtureApproval(activeSessionId, 'Deploy the active-session build');
962
+ if (approvalSession) {
963
+ fixtureApproval(
964
+ approvalSession.id,
965
+ 'Approve the deploy in ' + approvalSession.title
966
+ );
967
+ }
968
+ if (questionSession) {
969
+ fixtureQuestion(questionSession.id, {
970
+ id: 'fixture-channel',
971
+ question: 'Which release channel should I use?',
972
+ header: 'Cross-session fixture',
973
+ detail: 'This question belongs to ' + questionSession.title + '.',
974
+ multiSelect: false,
975
+ options: [{ label: 'Stable' }, { label: 'Beta' }]
976
+ });
977
+ }
978
+
979
+ /* Force a history reload so the active pending approval must survive it. */
980
+ setTimeout(() => {
981
+ if (!findSession(activeSessionId)) return;
982
+ broadcast({
983
+ type: 'history',
984
+ sessionId: activeSessionId,
985
+ items: historyOf(activeSessionId).slice(-200),
986
+ hasMore: false
987
+ });
988
+ }, 350);
989
+ }
990
+
991
+ async function runTurn(sessionId, promptText, attachments) {
992
+ const session = findSession(sessionId);
993
+ if (!session) return;
994
+ if (runs.has(sessionId)) return;
995
+
996
+ const runToken = { cancelled: false, approval: null };
997
+ runs.set(sessionId, runToken);
998
+ session.running = true;
999
+ session.updatedAt = Date.now();
1000
+ const turn = (session.turn = (session.turn || 0) + 1);
1001
+
1002
+ broadcastStatus(sessionId, true);
1003
+ broadcastSessions();
1004
+
1005
+ try {
1006
+ let accumulated = await streamAssistant(
1007
+ sessionId,
1008
+ turn,
1009
+ 1,
1010
+ firstStepText(promptText, attachments),
1011
+ runToken
1012
+ );
1013
+ appendHistory(sessionId, {
1014
+ id: nextHistoryId('assistant'),
1015
+ kind: 'assistant',
1016
+ text: accumulated,
1017
+ ts: Date.now()
1018
+ });
1019
+ if (runToken.cancelled) return;
1020
+
1021
+ if (/blocking|ask me/i.test(promptText)) {
1022
+ await askBlockingQuestion(
1023
+ sessionId,
1024
+ [
1025
+ {
1026
+ id: 'workspace-name',
1027
+ question: 'What should I call this workspace?',
1028
+ header: 'Blocking question',
1029
+ detail: 'This request arrived without a tool row — a request-only question.',
1030
+ multiSelect: false,
1031
+ options: [{ label: 'Demo workspace' }, { label: 'DSH Remote' }]
1032
+ }
1033
+ ],
1034
+ runToken,
1035
+ { resend: true }
1036
+ );
1037
+ if (runToken.cancelled) return;
1038
+ accumulated = await streamAssistant(
1039
+ sessionId,
1040
+ turn,
1041
+ 2,
1042
+ 'Noted. I will use that name for the workspace summary.',
1043
+ runToken
1044
+ );
1045
+ appendHistory(sessionId, {
1046
+ id: nextHistoryId('assistant'),
1047
+ kind: 'assistant',
1048
+ text: accumulated,
1049
+ ts: Date.now()
1050
+ });
1051
+ return;
1052
+ }
1053
+
1054
+ const callId = 'call-' + randomBytes(4).toString('hex');
1055
+ const argsPreview = 'git status --short';
1056
+ const toolOutput =
1057
+ ' M mobile/styles.css\\n M mobile/app.js\\n?? notes/todo.md\\n';
1058
+ broadcast({
1059
+ type: 'tool.start',
1060
+ sessionId,
1061
+ callId,
1062
+ name: 'pwsh',
1063
+ title: 'Run command',
1064
+ argsPreview,
1065
+ detail: { command: argsPreview, cwd: 'C:\\workspace\\demo' }
1066
+ });
1067
+ await sleep(850);
1068
+ if (runToken.cancelled) return;
1069
+ broadcast({
1070
+ type: 'tool.end',
1071
+ sessionId,
1072
+ callId,
1073
+ ok: true,
1074
+ output: toolOutput,
1075
+ durationMs: 812
1076
+ });
1077
+ appendHistory(sessionId, {
1078
+ id: 'tool:' + callId,
1079
+ kind: 'tool',
1080
+ callId,
1081
+ name: 'pwsh',
1082
+ title: 'Run command',
1083
+ argsPreview,
1084
+ ok: true,
1085
+ output: toolOutput,
1086
+ diff: null,
1087
+ durationMs: 812,
1088
+ ts: Date.now()
1089
+ });
1090
+
1091
+ const wantsQuestion = /deploy/i.test(promptText);
1092
+ let asked = null;
1093
+ if (wantsQuestion) {
1094
+ const questionCallId = 'call-' + randomBytes(4).toString('hex');
1095
+ asked = await askQuestions(
1096
+ sessionId,
1097
+ questionCallId,
1098
+ deployQuestions(),
1099
+ runToken,
1100
+ { toolTitle: 'Confirm deployment' }
1101
+ );
1102
+ if (runToken.cancelled) return;
1103
+ }
1104
+
1105
+ let denied = false;
1106
+ const wantsApproval = /deploy/i.test(promptText);
1107
+ if (wantsApproval) {
1108
+ const requestId = 'appr-' + randomBytes(4).toString('hex');
1109
+ const approval = { requestId, resolve: null, done: false };
1110
+ const decisionPromise = new Promise((resolve) => {
1111
+ approval.resolve = resolve;
1112
+ });
1113
+ pendingApprovals.set(requestId, approval);
1114
+ runToken.approval = approval;
1115
+
1116
+ broadcast({
1117
+ type: 'approval.request',
1118
+ sessionId,
1119
+ requestId,
1120
+ toolName: 'pwsh',
1121
+ title: 'Approval required',
1122
+ reason: 'pwsh -File scripts\\deploy.ps1 -Environment staging',
1123
+ displayReason: 'Deploy the current build to staging',
1124
+ argsKind: 'command',
1125
+ argsPreview:
1126
+ 'pwsh -File scripts\\deploy.ps1 -Environment staging\n' +
1127
+ 'Set-Location C:\\workspace\\demo\n' +
1128
+ '$env:DEPLOY_ENV = "staging"\n' +
1129
+ '& scripts\\deploy.ps1 -Environment staging -Verbose\n' +
1130
+ '# step 1/4: verify build output\n' +
1131
+ '# step 2/4: upload artefacts\n' +
1132
+ '# step 3/4: restart staging app\n' +
1133
+ '# step 4/4: smoke check /health',
1134
+ detail: { kind: 'command', path: 'scripts\\deploy.ps1' },
1135
+ callId,
1136
+ expiresAt: Date.now() + 120000
1137
+ });
1138
+
1139
+ const decision = await Promise.race([
1140
+ decisionPromise,
1141
+ sleep(120000).then(() => 'timeout')
1142
+ ]);
1143
+ pendingApprovals.delete(requestId);
1144
+ runToken.approval = null;
1145
+ approval.done = true;
1146
+
1147
+ if (runToken.cancelled) {
1148
+ broadcast({
1149
+ type: 'approval.resolved',
1150
+ requestId,
1151
+ outcome: 'cancelled'
1152
+ });
1153
+ return;
1154
+ }
1155
+ if (decision === 'allow') {
1156
+ broadcast({
1157
+ type: 'approval.resolved',
1158
+ requestId,
1159
+ outcome: 'allowed-once'
1160
+ });
1161
+ } else {
1162
+ broadcast({
1163
+ type: 'approval.resolved',
1164
+ requestId,
1165
+ outcome: decision === 'timeout' ? 'unavailable' : 'rejected'
1166
+ });
1167
+ denied = true;
1168
+ }
1169
+ }
1170
+ if (runToken.cancelled) return;
1171
+
1172
+ let secondText;
1173
+ if (denied) {
1174
+ secondText =
1175
+ 'Understood — I did not run the deploy. Nothing was changed on the staging server.';
1176
+ } else if (wantsApproval) {
1177
+ let target = 'staging';
1178
+ if (asked) {
1179
+ const envAnswer = asked.answers.find((answer) => answer.id === 'environment');
1180
+ if (envAnswer && envAnswer.selected && envAnswer.selected.length) {
1181
+ target = String(envAnswer.selected[0]).toLowerCase();
1182
+ }
1183
+ }
1184
+ secondText =
1185
+ 'Approved. The deploy command finished with exit code 0 and ' +
1186
+ target +
1187
+ ' is on the new build.';
1188
+ } else {
1189
+ secondText =
1190
+ 'The working tree shows three changes. I would commit the mobile styles and app changes together and leave `notes/todo.md` uncommitted.';
1191
+ }
1192
+
1193
+ accumulated = await streamAssistant(sessionId, turn, 2, secondText, runToken);
1194
+ appendHistory(sessionId, {
1195
+ id: nextHistoryId('assistant'),
1196
+ kind: 'assistant',
1197
+ text: accumulated,
1198
+ ts: Date.now()
1199
+ });
1200
+ } finally {
1201
+ const latest = findSession(sessionId);
1202
+ if (latest) {
1203
+ latest.running = false;
1204
+ latest.updatedAt = Date.now();
1205
+ }
1206
+ runs.delete(sessionId);
1207
+ broadcastStatus(sessionId, false);
1208
+ broadcastSessions();
1209
+ }
1210
+ }
1211
+
1212
+ /* ---------- WebSocket server (RFC 6455, no dependencies) ---------------- */
1213
+
1214
+ class WsConnection {
1215
+ constructor(socket, head, device) {
1216
+ this.socket = socket;
1217
+ this.device = device || null;
1218
+ this.buffer = Buffer.alloc(0);
1219
+ this.fragments = [];
1220
+ this.fragmentOpcode = 0;
1221
+ this.closed = false;
1222
+ this.socket.setNoDelay(true);
1223
+ socket.on('data', (chunk) => this.consume(chunk));
1224
+ socket.on('error', () => this.destroy());
1225
+ socket.on('close', () => this.onClose());
1226
+ if (head && head.length) this.consume(head);
1227
+ }
1228
+
1229
+ onClose() {
1230
+ this.closed = true;
1231
+ clients.delete(this);
1232
+ }
1233
+
1234
+ destroy() {
1235
+ if (this.closed) return;
1236
+ this.closed = true;
1237
+ clients.delete(this);
1238
+ try {
1239
+ this.socket.destroy();
1240
+ } catch (err) {
1241
+ /* ignore */
1242
+ }
1243
+ }
1244
+
1245
+ consume(chunk) {
1246
+ if (this.closed) return;
1247
+ this.buffer = Buffer.concat([this.buffer, chunk]);
1248
+ this.parse();
1249
+ }
1250
+
1251
+ parse() {
1252
+ while (!this.closed) {
1253
+ const buf = this.buffer;
1254
+ if (buf.length < 2) return;
1255
+
1256
+ const first = buf[0];
1257
+ const second = buf[1];
1258
+ const fin = (first & 0x80) !== 0;
1259
+ const opcode = first & 0x0f;
1260
+ const masked = (second & 0x80) !== 0;
1261
+ let length = second & 0x7f;
1262
+ let offset = 2;
1263
+
1264
+ if (length === 126) {
1265
+ if (buf.length < 4) return;
1266
+ length = buf.readUInt16BE(2);
1267
+ offset = 4;
1268
+ } else if (length === 127) {
1269
+ if (buf.length < 10) return;
1270
+ const high = buf.readUInt32BE(2);
1271
+ const low = buf.readUInt32BE(6);
1272
+ length = high * 0x100000000 + low;
1273
+ offset = 10;
1274
+ }
1275
+
1276
+ if (length > 10 * 1024 * 1024) {
1277
+ this.close(1009, 'frame too large');
1278
+ return;
1279
+ }
1280
+
1281
+ let maskKey = null;
1282
+ if (masked) {
1283
+ if (buf.length < offset + 4) return;
1284
+ maskKey = buf.subarray(offset, offset + 4);
1285
+ offset += 4;
1286
+ }
1287
+ if (buf.length < offset + length) return;
1288
+
1289
+ let payload = Buffer.from(buf.subarray(offset, offset + length));
1290
+ if (masked && maskKey) {
1291
+ for (let i = 0; i < payload.length; i++) {
1292
+ payload[i] ^= maskKey[i & 3];
1293
+ }
1294
+ }
1295
+ this.buffer = buf.subarray(offset + length);
1296
+
1297
+ if (opcode === 0x8) {
1298
+ let code = 1000;
1299
+ if (payload.length >= 2) code = payload.readUInt16BE(0);
1300
+ this.close(code === 1005 || code === 0 ? 1000 : code, '');
1301
+ return;
1302
+ }
1303
+ if (opcode === 0x9) {
1304
+ this.sendFrame(0xa, payload);
1305
+ continue;
1306
+ }
1307
+ if (opcode === 0xa) {
1308
+ continue;
1309
+ }
1310
+ if (opcode === 0x1 || opcode === 0x2) {
1311
+ if (fin) {
1312
+ this.onMessage(payload.toString('utf8'));
1313
+ } else {
1314
+ this.fragments = [payload];
1315
+ this.fragmentOpcode = opcode;
1316
+ }
1317
+ continue;
1318
+ }
1319
+ if (opcode === 0x0) {
1320
+ if (!this.fragments.length) continue;
1321
+ this.fragments.push(payload);
1322
+ if (fin) {
1323
+ const full = Buffer.concat(this.fragments);
1324
+ this.fragments = [];
1325
+ if (this.fragmentOpcode === 0x1) {
1326
+ this.onMessage(full.toString('utf8'));
1327
+ }
1328
+ this.fragmentOpcode = 0;
1329
+ }
1330
+ continue;
1331
+ }
1332
+ /* Unknown opcodes are ignored, matching the protocol's tolerance. */
1333
+ }
1334
+ }
1335
+
1336
+ onMessage(text) {
1337
+ let frame;
1338
+ try {
1339
+ frame = JSON.parse(text);
1340
+ } catch (err) {
1341
+ this.sendText(JSON.stringify(errorFrame('bad-request', 'Invalid JSON frame.')));
1342
+ return;
1343
+ }
1344
+ if (!frame || typeof frame !== 'object' || typeof frame.type !== 'string') {
1345
+ this.sendText(JSON.stringify(errorFrame('bad-request', 'Frame needs a type.')));
1346
+ return;
1347
+ }
1348
+ handleClientFrame(this, frame);
1349
+ }
1350
+
1351
+ sendFrame(opcode, payload) {
1352
+ if (this.closed) return;
1353
+ const length = payload.length;
1354
+ let header;
1355
+ if (length < 126) {
1356
+ header = Buffer.from([0x80 | opcode, length]);
1357
+ } else if (length < 65536) {
1358
+ header = Buffer.alloc(4);
1359
+ header[0] = 0x80 | opcode;
1360
+ header[1] = 126;
1361
+ header.writeUInt16BE(length, 2);
1362
+ } else {
1363
+ header = Buffer.alloc(10);
1364
+ header[0] = 0x80 | opcode;
1365
+ header[1] = 127;
1366
+ header.writeUInt32BE(0, 2);
1367
+ header.writeUInt32BE(length, 6);
1368
+ }
1369
+ try {
1370
+ this.socket.write(Buffer.concat([header, payload]));
1371
+ } catch (err) {
1372
+ this.destroy();
1373
+ }
1374
+ }
1375
+
1376
+ sendText(text) {
1377
+ this.sendFrame(0x1, Buffer.from(String(text), 'utf8'));
1378
+ }
1379
+
1380
+ close(code, reason) {
1381
+ if (this.closed) return;
1382
+ const reasonBuffer = Buffer.from(String(reason || ''), 'utf8');
1383
+ const payload = Buffer.alloc(2 + reasonBuffer.length);
1384
+ payload.writeUInt16BE(code || 1000, 0);
1385
+ reasonBuffer.copy(payload, 2);
1386
+ this.sendFrame(0x8, payload);
1387
+ this.closed = true;
1388
+ clients.delete(this);
1389
+ try {
1390
+ this.socket.end();
1391
+ } catch (err) {
1392
+ this.destroy();
1393
+ }
1394
+ }
1395
+ }
1396
+
1397
+ /* ---------- Client -> server frame handling ----------------------------- */
1398
+
1399
+ function handleClientFrame(conn, frame) {
1400
+ switch (frame.type) {
1401
+ case 'sessions.list':
1402
+ conn.sendText(
1403
+ JSON.stringify({
1404
+ type: 'sessions',
1405
+ sessions: publicSessions(),
1406
+ workspaces: WORKSPACES,
1407
+ activeSessionId: serverState.activeSessionId
1408
+ })
1409
+ );
1410
+ return;
1411
+
1412
+ case 'sessions.open': {
1413
+ const session = findSession(frame.sessionId);
1414
+ if (!session) {
1415
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1416
+ return;
1417
+ }
1418
+ serverState.activeSessionId = session.id;
1419
+ const limit = clampLimit(frame.limit, 200);
1420
+ conn.sendText(
1421
+ JSON.stringify({
1422
+ type: 'session.opened',
1423
+ session: publicSession(session),
1424
+ history: historyOf(session.id).slice(-limit),
1425
+ queue: queueOf(session.id),
1426
+ context: contextFor()
1427
+ })
1428
+ );
1429
+ return;
1430
+ }
1431
+
1432
+ case 'sessions.create': {
1433
+ const preset =
1434
+ frame.preset &&
1435
+ serverState.presets.presets.some((entry) => entry.id === frame.preset)
1436
+ ? frame.preset
1437
+ : serverState.presets.current;
1438
+ const session = {
1439
+ id: 'sess-' + randomBytes(3).toString('hex'),
1440
+ title: 'New session',
1441
+ running: false,
1442
+ updatedAt: Date.now(),
1443
+ preset: preset || null,
1444
+ model: serverState.models.current
1445
+ ? {
1446
+ provider: serverState.models.current.provider,
1447
+ model: serverState.models.current.model
1448
+ }
1449
+ : null,
1450
+ turn: 0,
1451
+ agentAvailable: true,
1452
+ pinned: false,
1453
+ archived: false
1454
+ };
1455
+ serverState.sessions.unshift(session);
1456
+ histories.set(session.id, []);
1457
+ queues.set(session.id, []);
1458
+ serverState.activeSessionId = session.id;
1459
+ broadcastSessions();
1460
+ conn.sendText(
1461
+ JSON.stringify({
1462
+ type: 'session.opened',
1463
+ session: publicSession(session),
1464
+ history: [],
1465
+ queue: []
1466
+ })
1467
+ );
1468
+ return;
1469
+ }
1470
+
1471
+ case 'history.load': {
1472
+ const session = findSession(frame.sessionId);
1473
+ if (!session) {
1474
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1475
+ return;
1476
+ }
1477
+ const limit = clampLimit(frame.limit, 200);
1478
+ const all = historyOf(session.id);
1479
+ conn.sendText(
1480
+ JSON.stringify({
1481
+ type: 'history',
1482
+ sessionId: session.id,
1483
+ items: all.slice(-limit),
1484
+ hasMore: all.length > limit
1485
+ })
1486
+ );
1487
+ return;
1488
+ }
1489
+
1490
+ case 'sessions.search': {
1491
+ if (process.env.RM_SEARCH_DISABLED === '1') {
1492
+ conn.sendText(
1493
+ JSON.stringify(
1494
+ errorFrame('unavailable', 'Message search is disabled on this deployment.')
1495
+ )
1496
+ );
1497
+ return;
1498
+ }
1499
+ const query = String(frame.query || '').trim();
1500
+ if (!query) {
1501
+ conn.sendText(JSON.stringify(errorFrame('bad-request', 'Empty search query.')));
1502
+ return;
1503
+ }
1504
+ const needle = query.toLowerCase();
1505
+ const results = [];
1506
+ for (const session of serverState.sessions) {
1507
+ const hit = historyOf(session.id).find((item) => {
1508
+ const text = String(item.text || '').toLowerCase();
1509
+ return text.indexOf(needle) !== -1;
1510
+ });
1511
+ if (!hit) continue;
1512
+ const text = String(hit.text || '');
1513
+ const at = text.toLowerCase().indexOf(needle);
1514
+ const start = Math.max(0, at - 60);
1515
+ results.push({
1516
+ id: session.id,
1517
+ title: session.title,
1518
+ snippet:
1519
+ (start > 0 ? '…' : '') +
1520
+ text.slice(start, start + 220) +
1521
+ (text.length > start + 220 ? '…' : ''),
1522
+ updatedAt: session.updatedAt,
1523
+ running: !!session.running,
1524
+ pinned: !!session.pinned,
1525
+ archived: !!session.archived,
1526
+ agentAvailable: session.agentAvailable !== false
1527
+ });
1528
+ }
1529
+ results.sort((a, b) => b.updatedAt - a.updatedAt);
1530
+ conn.sendText(
1531
+ JSON.stringify({
1532
+ type: 'sessions.found',
1533
+ query,
1534
+ hasMore: results.length > 20,
1535
+ results: results.slice(0, 20)
1536
+ })
1537
+ );
1538
+ return;
1539
+ }
1540
+
1541
+ case 'session.rename': {
1542
+ const session = findSession(frame.sessionId);
1543
+ if (!session) {
1544
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1545
+ return;
1546
+ }
1547
+ const title = String(frame.title || '').trim().slice(0, 120);
1548
+ if (!title) {
1549
+ conn.sendText(JSON.stringify(errorFrame('bad-request', 'A title is required.')));
1550
+ return;
1551
+ }
1552
+ session.title = title;
1553
+ session.updatedAt = Date.now();
1554
+ broadcast({
1555
+ type: 'session.updated',
1556
+ sessionId: session.id,
1557
+ title,
1558
+ session: publicSession(session)
1559
+ });
1560
+ broadcastSessions();
1561
+ return;
1562
+ }
1563
+
1564
+ case 'session.pin':
1565
+ case 'session.unpin': {
1566
+ const session = findSession(frame.sessionId);
1567
+ if (!session) {
1568
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1569
+ return;
1570
+ }
1571
+ const pinned = frame.type === 'session.pin';
1572
+ if (pinned && session.archived) {
1573
+ conn.sendText(
1574
+ JSON.stringify(errorFrame('bad-request', 'Unarchive the session before pinning it.'))
1575
+ );
1576
+ return;
1577
+ }
1578
+ session.pinned = pinned;
1579
+ broadcast({
1580
+ type: 'session.pinned',
1581
+ sessionId: session.id,
1582
+ pinned,
1583
+ archived: !!session.archived
1584
+ });
1585
+ broadcastSessions();
1586
+ return;
1587
+ }
1588
+
1589
+ case 'session.archive':
1590
+ case 'session.unarchive': {
1591
+ const session = findSession(frame.sessionId);
1592
+ if (!session) {
1593
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1594
+ return;
1595
+ }
1596
+ if (frame.type === 'session.unarchive') {
1597
+ session.archived = false;
1598
+ broadcast({
1599
+ type: 'session.archived',
1600
+ sessionId: session.id,
1601
+ archived: false,
1602
+ pinned: !!session.pinned
1603
+ });
1604
+ broadcastSessions();
1605
+ return;
1606
+ }
1607
+ if (session.running && frame.stopActivity !== true) {
1608
+ conn.sendText(
1609
+ JSON.stringify(
1610
+ errorFrame('bad-request', 'Archive requires stopActivity for a running session.')
1611
+ )
1612
+ );
1613
+ return;
1614
+ }
1615
+ if (session.running) {
1616
+ const runToken = runs.get(session.id);
1617
+ if (runToken) {
1618
+ runToken.cancelled = true;
1619
+ if (runToken.approval) runToken.approval.resolve('cancelled');
1620
+ if (runToken.question && !runToken.question.done) runToken.question.resolve({ answers: [] });
1621
+ }
1622
+ session.running = false;
1623
+ broadcastStatus(session.id, false);
1624
+ }
1625
+ session.archived = true;
1626
+ session.pinned = false;
1627
+ broadcast({
1628
+ type: 'session.archived',
1629
+ sessionId: session.id,
1630
+ archived: true,
1631
+ pinned: false
1632
+ });
1633
+ broadcastSessions();
1634
+ return;
1635
+ }
1636
+
1637
+ case 'session.fork': {
1638
+ const session = findSession(frame.sessionId);
1639
+ if (!session) {
1640
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1641
+ return;
1642
+ }
1643
+ const fork = {
1644
+ id: 'sess-' + randomBytes(3).toString('hex'),
1645
+ title: session.title + ' (fork)',
1646
+ running: false,
1647
+ updatedAt: Date.now(),
1648
+ preset: session.preset || null,
1649
+ model: session.model || null,
1650
+ turn: 0,
1651
+ agentAvailable: true,
1652
+ pinned: false,
1653
+ archived: false
1654
+ };
1655
+ serverState.sessions.unshift(fork);
1656
+ histories.set(fork.id, historyOf(session.id).slice());
1657
+ queues.set(fork.id, []);
1658
+ serverState.activeSessionId = fork.id;
1659
+ broadcastSessions();
1660
+ conn.sendText(
1661
+ JSON.stringify({
1662
+ type: 'session.opened',
1663
+ session: publicSession(fork),
1664
+ history: historyOf(fork.id),
1665
+ queue: []
1666
+ })
1667
+ );
1668
+ return;
1669
+ }
1670
+
1671
+ case 'queue.list': {
1672
+ const session = findSession(frame.sessionId);
1673
+ if (!session) {
1674
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1675
+ return;
1676
+ }
1677
+ if (session.agentAvailable === false) {
1678
+ conn.sendText(
1679
+ JSON.stringify(errorFrame('not-live', 'This session is not live on the desktop yet.'))
1680
+ );
1681
+ return;
1682
+ }
1683
+ sendQueueFrame(conn, session.id);
1684
+ return;
1685
+ }
1686
+
1687
+ case 'queue.update': {
1688
+ const session = findSession(frame.sessionId);
1689
+ if (!session) {
1690
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1691
+ return;
1692
+ }
1693
+ if (session.agentAvailable === false) {
1694
+ conn.sendText(
1695
+ JSON.stringify(errorFrame('not-live', 'This session is not live on the desktop yet.'))
1696
+ );
1697
+ return;
1698
+ }
1699
+ if (session.archived) {
1700
+ conn.sendText(JSON.stringify(errorFrame('bad-request', 'This session is archived.')));
1701
+ return;
1702
+ }
1703
+ const items = queueOf(session.id);
1704
+ const index = items.findIndex((item) => item.id === frame.itemId);
1705
+ if (index === -1) {
1706
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown queue item.')));
1707
+ return;
1708
+ }
1709
+ if (frame.action === 'edit') {
1710
+ const text = String(frame.text || '').trim();
1711
+ if (!text) {
1712
+ conn.sendText(JSON.stringify(errorFrame('bad-request', 'Empty queue text.')));
1713
+ return;
1714
+ }
1715
+ items[index].text = text;
1716
+ } else if (frame.action === 'remove') {
1717
+ items.splice(index, 1);
1718
+ } else if (frame.action === 'steer') {
1719
+ if (items[index].placement !== 'queued' || !session.running) {
1720
+ conn.sendText(
1721
+ JSON.stringify(errorFrame('bad-request', 'Only a queued item of a running turn can steer.'))
1722
+ );
1723
+ return;
1724
+ }
1725
+ items[index].placement = 'steering';
1726
+ broadcast({
1727
+ type: 'assistant.start',
1728
+ sessionId: session.id,
1729
+ turn: 1,
1730
+ step: 1
1731
+ });
1732
+ broadcast({
1733
+ type: 'assistant.delta',
1734
+ sessionId: session.id,
1735
+ text: 'Steered: ' + items[index].text,
1736
+ reasoning: null
1737
+ });
1738
+ broadcast({
1739
+ type: 'assistant.end',
1740
+ sessionId: session.id,
1741
+ turn: 1,
1742
+ step: 1
1743
+ });
1744
+ items.splice(index, 1);
1745
+ } else {
1746
+ conn.sendText(JSON.stringify(errorFrame('bad-request', 'Unknown queue action.')));
1747
+ return;
1748
+ }
1749
+ broadcastQueue(session.id);
1750
+ sendQueueFrame(conn, session.id);
1751
+ return;
1752
+ }
1753
+
1754
+ case 'limits':
1755
+ conn.sendText(JSON.stringify({ type: 'limits', image: serverState.limits.image }));
1756
+ return;
1757
+
1758
+ case 'context.get': {
1759
+ const session = findSession(frame.sessionId);
1760
+ if (!session) {
1761
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1762
+ return;
1763
+ }
1764
+ conn.sendText(
1765
+ JSON.stringify({ type: 'context', sessionId: session.id, ...contextFor() })
1766
+ );
1767
+ return;
1768
+ }
1769
+
1770
+ case 'changes.list': {
1771
+ const session = findSession(frame.sessionId);
1772
+ if (!session) {
1773
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1774
+ return;
1775
+ }
1776
+ conn.sendText(
1777
+ JSON.stringify({
1778
+ type: 'changes',
1779
+ sessionId: session.id,
1780
+ items: changesFor()
1781
+ })
1782
+ );
1783
+ return;
1784
+ }
1785
+
1786
+ case 'changes.diff': {
1787
+ const session = findSession(frame.sessionId);
1788
+ if (!session) {
1789
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1790
+ return;
1791
+ }
1792
+ const diff = diffFor(frame.seq, Number(frame.index));
1793
+ if (!diff) {
1794
+ conn.sendText(
1795
+ JSON.stringify(errorFrame('unavailable', 'Diff is no longer available.'))
1796
+ );
1797
+ return;
1798
+ }
1799
+ conn.sendText(
1800
+ JSON.stringify({
1801
+ type: 'changes.diff',
1802
+ sessionId: session.id,
1803
+ seq: frame.seq,
1804
+ index: Number(frame.index),
1805
+ ...diff
1806
+ })
1807
+ );
1808
+ return;
1809
+ }
1810
+
1811
+ case 'commands.list': {
1812
+ const session = findSession(frame.sessionId);
1813
+ if (!session) {
1814
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1815
+ return;
1816
+ }
1817
+ const available = session.agentAvailable !== false && !session.archived;
1818
+ conn.sendText(
1819
+ JSON.stringify({
1820
+ type: 'commands',
1821
+ sessionId: session.id,
1822
+ available,
1823
+ items: available
1824
+ ? [
1825
+ {
1826
+ name: 'compact',
1827
+ description: 'Compact older conversation history',
1828
+ hint: null,
1829
+ attachments: false
1830
+ },
1831
+ {
1832
+ name: 'feedback',
1833
+ description: 'Record feedback about this session',
1834
+ hint: '<text>',
1835
+ attachments: false
1836
+ },
1837
+ {
1838
+ name: 'goal',
1839
+ description: 'Set or view the goal for a long-running task',
1840
+ hint: '[<objective>|clear|edit <objective>|pause|resume]',
1841
+ attachments: true
1842
+ },
1843
+ {
1844
+ name: 'plan',
1845
+ description: 'Enter or leave plan mode',
1846
+ hint: '[off|message]',
1847
+ attachments: true
1848
+ }
1849
+ ]
1850
+ : [],
1851
+ reason: available ? null : 'not-live'
1852
+ })
1853
+ );
1854
+ return;
1855
+ }
1856
+
1857
+ case 'commands.execute': {
1858
+ const session = findSession(frame.sessionId);
1859
+ if (!session) {
1860
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1861
+ return;
1862
+ }
1863
+ if (session.agentAvailable === false) {
1864
+ conn.sendText(
1865
+ JSON.stringify(errorFrame('not-live', 'This session is not live on the desktop yet.'))
1866
+ );
1867
+ return;
1868
+ }
1869
+ const line = String(frame.line || '').trim();
1870
+ const name = line.replace(/^\//, '').split(/\s+/)[0];
1871
+ if (!['compact', 'feedback', 'goal', 'plan'].includes(name)) {
1872
+ conn.sendText(
1873
+ JSON.stringify(errorFrame('forbidden', 'That command is not allowed from the phone.'))
1874
+ );
1875
+ return;
1876
+ }
1877
+ const results = {
1878
+ compact: 'Compacted 4 history items (~909 tokens).',
1879
+ feedback: 'Feedback recorded (mock).',
1880
+ goal: 'No goal is currently set.',
1881
+ plan: 'Plan mode on.'
1882
+ };
1883
+ appendHistory(session.id, {
1884
+ id: nextHistoryId('system'),
1885
+ kind: 'system',
1886
+ text: 'Command /' + name + ' completed (mock).',
1887
+ ts: Date.now()
1888
+ });
1889
+ broadcast({
1890
+ type: 'command.result',
1891
+ sessionId: session.id,
1892
+ commandId: 'cmd-' + randomBytes(3).toString('hex'),
1893
+ name,
1894
+ kind: 'success',
1895
+ text: results[name],
1896
+ sourceEventSeq: 42
1897
+ });
1898
+ return;
1899
+ }
1900
+
1901
+ case 'prompt': {
1902
+ const session = findSession(frame.sessionId);
1903
+ if (!session) {
1904
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1905
+ return;
1906
+ }
1907
+ const attachments = Array.isArray(frame.attachments)
1908
+ ? frame.attachments
1909
+ .filter(
1910
+ (attachment) =>
1911
+ attachment && typeof attachment.name === 'string' && attachment.name
1912
+ )
1913
+ .slice(0, UPLOAD_FILE_LIMIT)
1914
+ .map((attachment) => ({
1915
+ name: String(attachment.name),
1916
+ size: Number(attachment.size) || 0,
1917
+ mediaType: attachment.mediaType
1918
+ ? String(attachment.mediaType)
1919
+ : 'application/octet-stream',
1920
+ path: attachment.path ? String(attachment.path) : '',
1921
+ relativePath: attachment.relativePath
1922
+ ? String(attachment.relativePath)
1923
+ : ''
1924
+ }))
1925
+ : [];
1926
+ const promptText = typeof frame.text === 'string' ? frame.text : '';
1927
+ if (!promptText.trim() && !attachments.length) {
1928
+ conn.sendText(JSON.stringify(errorFrame('bad-request', 'Empty prompt.')));
1929
+ return;
1930
+ }
1931
+ if (session.archived) {
1932
+ conn.sendText(
1933
+ JSON.stringify(errorFrame('bad-request', 'This session is archived.'))
1934
+ );
1935
+ return;
1936
+ }
1937
+ const mode = frame.mode === 'steer' ? 'steer' : 'queue';
1938
+ if (mode === 'steer') {
1939
+ if (!session.running) {
1940
+ conn.sendText(
1941
+ JSON.stringify(
1942
+ errorFrame('bad-request', 'The agent is not running; nothing to steer.')
1943
+ )
1944
+ );
1945
+ return;
1946
+ }
1947
+ queueOf(session.id).push({
1948
+ id: 'q-' + randomBytes(3).toString('hex'),
1949
+ placement: 'steering',
1950
+ rpcId: frame.requestId ? String(frame.requestId) : '',
1951
+ text: promptText
1952
+ });
1953
+ broadcastQueue(session.id);
1954
+ return;
1955
+ }
1956
+ if (runs.has(session.id) || session.running) {
1957
+ queueOf(session.id).push({
1958
+ id: 'q-' + randomBytes(3).toString('hex'),
1959
+ placement: 'queued',
1960
+ rpcId: frame.requestId ? String(frame.requestId) : '',
1961
+ text: promptText
1962
+ });
1963
+ broadcastQueue(session.id);
1964
+ return;
1965
+ }
1966
+ const historyItem = {
1967
+ id: nextHistoryId('user'),
1968
+ kind: 'user',
1969
+ text: promptText,
1970
+ ts: Date.now()
1971
+ };
1972
+ if (attachments.length) {
1973
+ historyItem.attachments = attachments.map((attachment) => ({
1974
+ name: attachment.name,
1975
+ size: attachment.size,
1976
+ mediaType: attachment.mediaType,
1977
+ path: attachment.path,
1978
+ relativePath: attachment.relativePath
1979
+ }));
1980
+ }
1981
+ appendHistory(session.id, historyItem);
1982
+ session.updatedAt = Date.now();
1983
+ broadcastSessions();
1984
+ if (/cross-session fixture|fixture test/i.test(promptText)) {
1985
+ emitCrossSessionFixtures(session.id);
1986
+ return;
1987
+ }
1988
+ runTurn(session.id, promptText, attachments);
1989
+ return;
1990
+ }
1991
+
1992
+ case 'stop': {
1993
+ const runToken = runs.get(frame.sessionId);
1994
+ if (runToken) {
1995
+ runToken.cancelled = true;
1996
+ if (runToken.approval) runToken.approval.resolve('cancelled');
1997
+ if (runToken.question && !runToken.question.done) {
1998
+ runToken.question.resolve({ answers: [] });
1999
+ }
2000
+ }
2001
+ return;
2002
+ }
2003
+
2004
+ case 'question.answer': {
2005
+ let question = frame.requestId
2006
+ ? pendingQuestions.get(frame.requestId)
2007
+ : null;
2008
+ if (!question && frame.callId) {
2009
+ for (const entry of pendingQuestions.values()) {
2010
+ if (entry.callId === frame.callId) {
2011
+ question = entry;
2012
+ break;
2013
+ }
2014
+ }
2015
+ }
2016
+ if (!question || question.done) {
2017
+ conn.sendText(
2018
+ JSON.stringify(
2019
+ errorFrame('not-found', 'Question is unknown or already resolved.')
2020
+ )
2021
+ );
2022
+ return;
2023
+ }
2024
+ question.done = true;
2025
+ question.resolve({
2026
+ answers: Array.isArray(frame.answers) ? frame.answers : []
2027
+ });
2028
+ return;
2029
+ }
2030
+
2031
+ case 'approval.answer': {
2032
+ const approval = pendingApprovals.get(frame.requestId);
2033
+ if (!approval || approval.done) {
2034
+ conn.sendText(
2035
+ JSON.stringify(
2036
+ errorFrame('not-found', 'Approval is unknown or already resolved.')
2037
+ )
2038
+ );
2039
+ return;
2040
+ }
2041
+ approval.done = true;
2042
+ approval.resolve(frame.decision === 'allow' ? 'allow' : 'reject');
2043
+ return;
2044
+ }
2045
+
2046
+ case 'model.list':
2047
+ conn.sendText(
2048
+ JSON.stringify({
2049
+ type: 'models',
2050
+ catalog: serverState.models.catalog,
2051
+ current: serverState.models.current
2052
+ })
2053
+ );
2054
+ return;
2055
+
2056
+ case 'model.select': {
2057
+ const session = findSession(frame.sessionId);
2058
+ const entry = readProviderModel(frame.provider, frame.model);
2059
+ if (!session) {
2060
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
2061
+ return;
2062
+ }
2063
+ if (!entry) {
2064
+ conn.sendText(JSON.stringify(errorFrame('bad-request', 'Unknown model.')));
2065
+ return;
2066
+ }
2067
+ const requestedEffort =
2068
+ typeof frame.reasoningEffort === 'string' && frame.reasoningEffort
2069
+ ? frame.reasoningEffort
2070
+ : null;
2071
+ /* Reason about effort ids exactly like the Host: an id is only legal for a
2072
+ model that advertises it; absent/null means the provider default. */
2073
+ if (requestedEffort) {
2074
+ const efforts =
2075
+ entry.reasoning && Array.isArray(entry.reasoning.efforts)
2076
+ ? entry.reasoning.efforts
2077
+ : [];
2078
+ if (!efforts.some((effort) => effort && effort.id === requestedEffort)) {
2079
+ conn.sendText(
2080
+ JSON.stringify(errorFrame('bad-request', 'Unknown reasoning effort.'))
2081
+ );
2082
+ return;
2083
+ }
2084
+ }
2085
+ session.model = {
2086
+ provider: entry.provider,
2087
+ model: entry.model,
2088
+ reasoningEffort: requestedEffort
2089
+ };
2090
+ serverState.models.current = {
2091
+ provider: entry.provider,
2092
+ model: entry.model,
2093
+ reasoningEffort: requestedEffort
2094
+ };
2095
+ conn.sendText(
2096
+ JSON.stringify({
2097
+ type: 'models',
2098
+ catalog: serverState.models.catalog,
2099
+ current: serverState.models.current
2100
+ })
2101
+ );
2102
+ broadcastSessions();
2103
+ return;
2104
+ }
2105
+
2106
+ case 'preset.list':
2107
+ conn.sendText(
2108
+ JSON.stringify({
2109
+ type: 'presets',
2110
+ presets: serverState.presets.presets,
2111
+ current: serverState.presets.current
2112
+ })
2113
+ );
2114
+ return;
2115
+
2116
+ case 'preset.select': {
2117
+ const session = findSession(frame.sessionId);
2118
+ if (!session) {
2119
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
2120
+ return;
2121
+ }
2122
+ const entry = serverState.presets.presets.find(
2123
+ (preset) => preset.id === frame.preset
2124
+ );
2125
+ if (!entry) {
2126
+ conn.sendText(JSON.stringify(errorFrame('bad-request', 'Unknown preset.')));
2127
+ return;
2128
+ }
2129
+ session.preset = entry.id;
2130
+ serverState.presets.current = entry.id;
2131
+ conn.sendText(
2132
+ JSON.stringify({
2133
+ type: 'presets',
2134
+ presets: serverState.presets.presets,
2135
+ current: serverState.presets.current
2136
+ })
2137
+ );
2138
+ broadcastSessions();
2139
+ return;
2140
+ }
2141
+
2142
+ case 'client.visibility': {
2143
+ const visible = frame.visible === true;
2144
+ if (conn.device) deviceVisibility.set(conn.device.id, visible);
2145
+ conn.sendText(JSON.stringify({ type: 'visibility', visible }));
2146
+ return;
2147
+ }
2148
+
2149
+ case 'ping':
2150
+ conn.sendText(JSON.stringify({ type: 'pong', t: frame.t || 0 }));
2151
+ return;
2152
+
2153
+ default:
2154
+ conn.sendText(
2155
+ JSON.stringify(
2156
+ errorFrame('bad-request', 'Unknown frame type: ' + frame.type)
2157
+ )
2158
+ );
2159
+ }
2160
+ }
2161
+
2162
+ function clampLimit(value, max) {
2163
+ const n = Number(value);
2164
+ if (!isFinite(n) || n <= 0) return 50;
2165
+ return Math.min(Math.floor(n), max);
2166
+ }
2167
+
2168
+ /* ---------- HTTP helpers ------------------------------------------------ */
2169
+
2170
+ function parseCookies(header) {
2171
+ const out = {};
2172
+ if (!header) return out;
2173
+ String(header)
2174
+ .split(';')
2175
+ .forEach((part) => {
2176
+ const index = part.indexOf('=');
2177
+ if (index < 0) return;
2178
+ const key = part.slice(0, index).trim();
2179
+ const value = part.slice(index + 1).trim();
2180
+ if (key) out[key] = decodeURIComponent(value);
2181
+ });
2182
+ return out;
2183
+ }
2184
+
2185
+ function deviceForRequest(req) {
2186
+ const cookies = parseCookies(req.headers.cookie);
2187
+ const cookie = cookies[SESSION_COOKIE];
2188
+ if (!cookie) return null;
2189
+ return devices.find((device) => device.cookie === cookie) || null;
2190
+ }
2191
+
2192
+ function readJsonBody(req, limit) {
2193
+ const max = limit || 64 * 1024;
2194
+ return new Promise((resolve) => {
2195
+ let size = 0;
2196
+ const chunks = [];
2197
+ req.on('data', (chunk) => {
2198
+ size += chunk.length;
2199
+ if (size > max) {
2200
+ req.destroy();
2201
+ resolve({});
2202
+ return;
2203
+ }
2204
+ chunks.push(chunk);
2205
+ });
2206
+ req.on('end', () => {
2207
+ if (!chunks.length) {
2208
+ resolve({});
2209
+ return;
2210
+ }
2211
+ try {
2212
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
2213
+ } catch (err) {
2214
+ resolve({});
2215
+ }
2216
+ });
2217
+ req.on('error', () => resolve({}));
2218
+ });
2219
+ }
2220
+
2221
+ /* Raw body for the upload endpoint. Resolves null when the limit is exceeded
2222
+ so the handler can answer 413 without buffering an oversized payload. */
2223
+ function readRawBody(req, max) {
2224
+ return new Promise((resolve) => {
2225
+ let size = 0;
2226
+ let over = false;
2227
+ const chunks = [];
2228
+ req.on('data', (chunk) => {
2229
+ size += chunk.length;
2230
+ if (size > max) {
2231
+ over = true;
2232
+ chunks.length = 0;
2233
+ return;
2234
+ }
2235
+ if (!over) chunks.push(chunk);
2236
+ });
2237
+ req.on('end', () => {
2238
+ resolve(over ? null : Buffer.concat(chunks));
2239
+ });
2240
+ req.on('error', () => resolve(null));
2241
+ });
2242
+ }
2243
+
2244
+ function safeUploadName(name) {
2245
+ let base = String(name || 'file')
2246
+ .split(/[\\/]/)
2247
+ .pop();
2248
+ base = base
2249
+ .replace(/[\u0000-\u001f<>:"/\\|?*]+/g, '_')
2250
+ .replace(/^\.+$/, 'file')
2251
+ .trim();
2252
+ if (!base) base = 'file';
2253
+ return base.slice(0, 160);
2254
+ }
2255
+
2256
+ function mintDevice(req) {
2257
+ const ua = String(req.headers['user-agent'] || '');
2258
+ let name = 'Demo phone';
2259
+ if (/iPhone/i.test(ua)) name = 'iPhone · Safari';
2260
+ else if (/Android/i.test(ua)) name = 'Android · Chrome';
2261
+ else if (/iPad/i.test(ua)) name = 'iPad · Safari';
2262
+ const device = {
2263
+ id: 'dev-' + randomBytes(4).toString('hex'),
2264
+ name,
2265
+ createdAt: Date.now(),
2266
+ cookie: randomBytes(24).toString('base64url')
2267
+ };
2268
+ devices.push(device);
2269
+ if (devices.length > 8) {
2270
+ const dropped = devices.shift();
2271
+ for (const client of [...clients]) {
2272
+ if (client.device && client.device.id === dropped.id) client.close(4401, 'revoked');
2273
+ }
2274
+ }
2275
+ return device;
2276
+ }
2277
+
2278
+ function sessionCookie(device, secure) {
2279
+ const parts = [
2280
+ SESSION_COOKIE + '=' + encodeURIComponent(device.cookie),
2281
+ 'HttpOnly',
2282
+ 'SameSite=Lax',
2283
+ 'Path=/',
2284
+ 'Max-Age=86400'
2285
+ ];
2286
+ if (secure) parts.push('Secure');
2287
+ return parts.join('; ');
2288
+ }
2289
+
2290
+ function recentFailures(ip) {
2291
+ const cutoff = Date.now() - RATE_WINDOW_MS;
2292
+ const list = (rateLimit.get(ip) || []).filter((ts) => ts > cutoff);
2293
+ rateLimit.set(ip, list);
2294
+ return list;
2295
+ }
2296
+
2297
+ function rateLimitedResponse(req, res) {
2298
+ const ip = req.socket.remoteAddress || 'unknown';
2299
+ const failures = recentFailures(ip);
2300
+ if (failures.length < RATE_MAX) return false;
2301
+ const retryAfterMs = Math.max(
2302
+ 1000,
2303
+ RATE_WINDOW_MS - (Date.now() - failures[0])
2304
+ );
2305
+ sendJson(res, 429, { error: 'rate-limited', retryAfterMs });
2306
+ return true;
2307
+ }
2308
+
2309
+ function noteFailure(req) {
2310
+ const ip = req.socket.remoteAddress || 'unknown';
2311
+ const list = recentFailures(ip);
2312
+ list.push(Date.now());
2313
+ rateLimit.set(ip, list);
2314
+ }
2315
+
2316
+ function safeDecode(value) {
2317
+ try {
2318
+ return decodeURIComponent(value);
2319
+ } catch (err) {
2320
+ return value;
2321
+ }
2322
+ }
2323
+
2324
+ /* ---------- Static + API ------------------------------------------------ */
2325
+
2326
+ async function serveStatic(req, res) {
2327
+ const url = new URL(req.url, 'http://localhost');
2328
+ const name = STATIC_FILES[url.pathname];
2329
+ if (!name) {
2330
+ res.writeHead(404, {
2331
+ 'Content-Type': 'text/plain; charset=utf-8',
2332
+ 'Cache-Control': 'no-store'
2333
+ });
2334
+ res.end('Not found');
2335
+ return;
2336
+ }
2337
+ try {
2338
+ const body = await readFile(join(HERE, name));
2339
+ const headers = {
2340
+ 'Content-Type': MIME[extname(name)] || 'application/octet-stream',
2341
+ 'Content-Length': body.length,
2342
+ 'Cache-Control': 'no-store, must-revalidate',
2343
+ 'X-Content-Type-Options': 'nosniff'
2344
+ };
2345
+ if (name === 'sw.js') {
2346
+ /* The service worker is served from the root so its scope is "/";
2347
+ never let the HTTP cache pin an old worker. */
2348
+ headers['Service-Worker-Allowed'] = '/';
2349
+ headers['Cache-Control'] = 'no-cache';
2350
+ }
2351
+ if (name.endsWith('.html')) {
2352
+ headers['Content-Security-Policy'] = CONTENT_SECURITY_POLICY;
2353
+ }
2354
+ res.writeHead(200, headers);
2355
+ res.end(body);
2356
+ } catch (err) {
2357
+ res.writeHead(500, {
2358
+ 'Content-Type': 'text/plain; charset=utf-8',
2359
+ 'Cache-Control': 'no-store'
2360
+ });
2361
+ res.end('Could not read ' + name + ': ' + err.message);
2362
+ }
2363
+ }
2364
+
2365
+ async function handleRequest(req, res) {
2366
+ const url = new URL(req.url, 'http://localhost');
2367
+ const path = url.pathname;
2368
+
2369
+ if (path === '/favicon.ico') {
2370
+ res.writeHead(204, { 'Cache-Control': 'no-store' });
2371
+ res.end();
2372
+ return;
2373
+ }
2374
+
2375
+ if (path === '/health') {
2376
+ sendJson(res, 200, { ok: true, version: VERSION });
2377
+ return;
2378
+ }
2379
+
2380
+ if (path === '/api/state' && req.method === 'GET') {
2381
+ const device = deviceForRequest(req);
2382
+ sendJson(res, 200, {
2383
+ paired: !!device,
2384
+ device: device
2385
+ ? { id: device.id, name: device.name, createdAt: device.createdAt }
2386
+ : null,
2387
+ version: VERSION
2388
+ });
2389
+ return;
2390
+ }
2391
+
2392
+ if (path === '/api/push/key' && req.method === 'GET') {
2393
+ /* Unauthenticated by design: the VAPID public key is public. */
2394
+ sendJson(res, 200, { enabled: true, publicKey: PUSH_PUBLIC_KEY });
2395
+ return;
2396
+ }
2397
+
2398
+ if (path.startsWith('/api/push/') && req.method === 'POST') {
2399
+ const device = deviceForRequest(req);
2400
+ if (!device) {
2401
+ req.resume();
2402
+ sendJson(res, 401, { error: 'unauthorized' });
2403
+ return;
2404
+ }
2405
+ const body = await readJsonBody(req);
2406
+ if (path === '/api/push/subscribe') {
2407
+ const subscription =
2408
+ body && body.subscription && typeof body.subscription === 'object'
2409
+ ? body.subscription
2410
+ : null;
2411
+ const endpoint =
2412
+ subscription && typeof subscription.endpoint === 'string'
2413
+ ? subscription.endpoint
2414
+ : '';
2415
+ const loopback = /^http:\/\/(127\.0\.0\.1|localhost)(:|\/)/.test(endpoint);
2416
+ if (!endpoint || (!/^https:\/\//.test(endpoint) && !loopback)) {
2417
+ sendJson(res, 400, { error: 'invalid-subscription' });
2418
+ return;
2419
+ }
2420
+ pushSubscriptions.set(endpoint, {
2421
+ endpoint,
2422
+ deviceId: device.id,
2423
+ subscription
2424
+ });
2425
+ log('push subscription stored for', device.name);
2426
+ sendJson(res, 200, { ok: true, deviceId: device.id });
2427
+ return;
2428
+ }
2429
+ if (path === '/api/push/unsubscribe') {
2430
+ const endpoint = body && typeof body.endpoint === 'string' ? body.endpoint : '';
2431
+ if (!endpoint) {
2432
+ sendJson(res, 400, { error: 'bad-request' });
2433
+ return;
2434
+ }
2435
+ const entry = pushSubscriptions.get(endpoint);
2436
+ if (entry && entry.deviceId === device.id) pushSubscriptions.delete(endpoint);
2437
+ sendJson(res, 200, { ok: true });
2438
+ return;
2439
+ }
2440
+ if (path === '/api/push/report') {
2441
+ /* Service-worker/SPA diagnostics are a bounded no-op in the mock. */
2442
+ sendJson(res, 200, { ok: true });
2443
+ return;
2444
+ }
2445
+ if (path === '/api/push/test') {
2446
+ let stored = 0;
2447
+ for (const entry of pushSubscriptions.values()) {
2448
+ if (entry.deviceId === device.id) stored += 1;
2449
+ }
2450
+ /* The mock cannot reach a real push service; report one accepted test
2451
+ notification so the client's success path is exercisable. */
2452
+ sendJson(res, 200, { ok: true, sent: stored || 1, gone: 0 });
2453
+ return;
2454
+ }
2455
+ sendJson(res, 404, { error: 'not-found' });
2456
+ return;
2457
+ }
2458
+
2459
+ /* Web Share Target: the manifest points Android's share sheet here; we
2460
+ bounce back into the SPA with the payload in the query string. */
2461
+ if (path === '/share-target' && req.method === 'GET') {
2462
+ const payload = encodeURIComponent(JSON.stringify({
2463
+ title: (url.searchParams.get('title') || '').slice(0, 200),
2464
+ text: (url.searchParams.get('text') || '').slice(0, 4000),
2465
+ url: (url.searchParams.get('url') || '').slice(0, 2000)
2466
+ }));
2467
+ res.writeHead(302, {
2468
+ Location: '/?share=' + payload,
2469
+ 'Cache-Control': 'no-store',
2470
+ 'Referrer-Policy': 'no-referrer'
2471
+ });
2472
+ res.end();
2473
+ return;
2474
+ }
2475
+
2476
+ if (path === '/api/upload' && req.method === 'POST') {
2477
+ const device = deviceForRequest(req);
2478
+ if (!device) {
2479
+ req.resume();
2480
+ sendJson(res, 401, { ok: false, error: 'unauthorized' });
2481
+ return;
2482
+ }
2483
+ const sessionId = String(req.headers['x-dsh-session'] || '').trim();
2484
+ const filename = safeUploadName(req.headers['x-dsh-filename']);
2485
+ let mediaType = String(req.headers['x-dsh-media-type'] || '')
2486
+ .replace(/[\r\n]+/g, '')
2487
+ .trim();
2488
+ if (!/^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/.test(mediaType)) {
2489
+ mediaType = 'application/octet-stream';
2490
+ }
2491
+ const session = sessionId ? findSession(sessionId) : null;
2492
+ if (!sessionId || !session) {
2493
+ req.resume();
2494
+ sendJson(res, sessionId ? 404 : 400, {
2495
+ ok: false,
2496
+ error: sessionId ? 'unknown-session' : 'missing-session'
2497
+ });
2498
+ return;
2499
+ }
2500
+ const declared = Number(req.headers['content-length'] || 0);
2501
+ if (declared > MAX_UPLOAD_BYTES) {
2502
+ req.resume();
2503
+ sendJson(res, 413, { ok: false, error: 'too-large' });
2504
+ return;
2505
+ }
2506
+ const body = await readRawBody(req, MAX_UPLOAD_BYTES);
2507
+ if (body === null) {
2508
+ sendJson(res, 413, { ok: false, error: 'too-large' });
2509
+ return;
2510
+ }
2511
+ if (!body.length) {
2512
+ sendJson(res, 400, { ok: false, error: 'empty-file' });
2513
+ return;
2514
+ }
2515
+ if (UPLOAD_DELAY_MS > 0) await sleep(UPLOAD_DELAY_MS);
2516
+ const stored = Date.now().toString(36) + '-' + filename;
2517
+ const relativePath = '.mock-uploads/' + device.id + '/' + stored;
2518
+ const absolutePath = 'C:\\mock-uploads\\' + device.id + '\\' + stored;
2519
+ uploadedFiles.set(absolutePath, {
2520
+ bytes: body,
2521
+ sessionId,
2522
+ mediaType,
2523
+ name: filename
2524
+ });
2525
+ if (uploadedFiles.size > 64) {
2526
+ uploadedFiles.delete(uploadedFiles.keys().next().value);
2527
+ }
2528
+ log('upload', filename, body.length + ' bytes', 'session', sessionId);
2529
+ sendJson(res, 200, {
2530
+ ok: true,
2531
+ name: filename,
2532
+ path: absolutePath,
2533
+ relativePath,
2534
+ size: body.length,
2535
+ mediaType
2536
+ });
2537
+ return;
2538
+ }
2539
+
2540
+ if (path === '/api/preview' && req.method === 'GET') {
2541
+ const device = deviceForRequest(req);
2542
+ if (!device) {
2543
+ sendJson(res, 401, { ok: false, error: 'unauthorized' });
2544
+ return;
2545
+ }
2546
+ const sessionId = String(url.searchParams.get('session') || '');
2547
+ const filePath = String(url.searchParams.get('path') || '');
2548
+ if (!sessionId || !filePath) {
2549
+ sendJson(res, 400, { ok: false, error: 'bad-request' });
2550
+ return;
2551
+ }
2552
+ const file = uploadedFiles.get(filePath);
2553
+ if (!file || file.sessionId !== sessionId) {
2554
+ sendJson(res, 404, { ok: false, error: 'not-found' });
2555
+ return;
2556
+ }
2557
+ if (!/^image\/(png|jpeg|webp|gif)$/i.test(file.mediaType)) {
2558
+ sendJson(res, 415, { ok: false, error: 'unsupported-media' });
2559
+ return;
2560
+ }
2561
+ res.writeHead(200, {
2562
+ 'Content-Type': file.mediaType,
2563
+ 'Content-Length': file.bytes.length,
2564
+ 'Cache-Control': 'no-store'
2565
+ });
2566
+ res.end(file.bytes);
2567
+ return;
2568
+ }
2569
+
2570
+ if (path === '/api/pair' && req.method === 'POST') {
2571
+ const body = await readJsonBody(req);
2572
+ const secure = !!req.socket.encrypted;
2573
+
2574
+ if (typeof body.token === 'string' && body.token) {
2575
+ if (pairingTokenConsumed || body.token !== PAIRING_TOKEN) {
2576
+ sendJson(res, 401, { error: 'invalid-token' });
2577
+ return;
2578
+ }
2579
+ pairingTokenConsumed = true;
2580
+ const device = mintDevice(req);
2581
+ log('paired via token as', device.name);
2582
+ sendJson(
2583
+ res,
2584
+ 200,
2585
+ {
2586
+ paired: true,
2587
+ device: { id: device.id, name: device.name, createdAt: device.createdAt, canApprove: !APPROVALS_READONLY }
2588
+ },
2589
+ { 'Set-Cookie': sessionCookie(device, secure) }
2590
+ );
2591
+ return;
2592
+ }
2593
+
2594
+ if (rateLimitedResponse(req, res)) return;
2595
+
2596
+ const pin = typeof body.pin === 'string' ? body.pin.trim() : '';
2597
+ if (!pin) {
2598
+ sendJson(res, 400, { error: 'bad-request' });
2599
+ return;
2600
+ }
2601
+ if (pin !== currentPin) {
2602
+ noteFailure(req);
2603
+ sendJson(res, 401, { error: 'invalid-pin' });
2604
+ return;
2605
+ }
2606
+
2607
+ const device = mintDevice(req);
2608
+ log('paired via PIN as', device.name);
2609
+ sendJson(
2610
+ res,
2611
+ 200,
2612
+ {
2613
+ paired: true,
2614
+ device: { id: device.id, name: device.name, createdAt: device.createdAt, canApprove: !APPROVALS_READONLY }
2615
+ },
2616
+ { 'Set-Cookie': sessionCookie(device, secure) }
2617
+ );
2618
+ if (process.env.RM_KEEP_PIN !== '1') {
2619
+ currentPin = randomPin();
2620
+ log('new PIN:', currentPin);
2621
+ }
2622
+ return;
2623
+ }
2624
+
2625
+ if (path === '/api/rotate-pin' && req.method === 'POST') {
2626
+ const device = deviceForRequest(req);
2627
+ if (!device) {
2628
+ sendJson(res, 401, { error: 'unauthorized' });
2629
+ return;
2630
+ }
2631
+ currentPin = randomPin();
2632
+ log('rotated PIN:', currentPin);
2633
+ sendJson(res, 200, { pin: currentPin, pinExpiresAt: Date.now() + 300000 });
2634
+ return;
2635
+ }
2636
+
2637
+ if (path === '/api/unpair' && req.method === 'POST') {
2638
+ const device = deviceForRequest(req);
2639
+ if (!device) {
2640
+ sendJson(res, 401, { error: 'unauthorized' });
2641
+ return;
2642
+ }
2643
+ const index = devices.indexOf(device);
2644
+ if (index >= 0) devices.splice(index, 1);
2645
+ deviceVisibility.delete(device.id);
2646
+ for (const [endpoint, entry] of pushSubscriptions) {
2647
+ if (entry.deviceId === device.id) pushSubscriptions.delete(endpoint);
2648
+ }
2649
+ for (const client of [...clients]) {
2650
+ if (client.device && client.device.id === device.id) {
2651
+ client.close(1000, 'unpaired');
2652
+ }
2653
+ }
2654
+ log('unpaired', device.name);
2655
+ sendJson(
2656
+ res,
2657
+ 200,
2658
+ { ok: true },
2659
+ {
2660
+ 'Set-Cookie':
2661
+ SESSION_COOKIE + '=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0'
2662
+ }
2663
+ );
2664
+ return;
2665
+ }
2666
+
2667
+ if (path.startsWith('/api/')) {
2668
+ sendJson(res, 404, { error: 'not-found' });
2669
+ return;
2670
+ }
2671
+
2672
+ if (req.method === 'GET' || req.method === 'HEAD') {
2673
+ await serveStatic(req, res);
2674
+ return;
2675
+ }
2676
+
2677
+ res.writeHead(405, { Allow: 'GET, HEAD', 'Content-Type': 'text/plain' });
2678
+ res.end('Method not allowed');
2679
+ }
2680
+
2681
+ /* ---------- Server ------------------------------------------------------ */
2682
+
2683
+ const server = createServer((req, res) => {
2684
+ handleRequest(req, res).catch((err) => {
2685
+ log('request error:', err && err.stack ? err.stack : err);
2686
+ if (!res.headersSent) {
2687
+ sendJson(res, 500, { error: 'internal', message: 'Mock server error.' });
2688
+ } else {
2689
+ try {
2690
+ res.end();
2691
+ } catch (nextErr) {
2692
+ /* ignore */
2693
+ }
2694
+ }
2695
+ });
2696
+ });
2697
+
2698
+ server.on('upgrade', (req, socket, head) => {
2699
+ let path = '/';
2700
+ try {
2701
+ path = new URL(req.url, 'http://localhost').pathname;
2702
+ } catch (err) {
2703
+ path = '/';
2704
+ }
2705
+ if (path !== '/ws') {
2706
+ socket.destroy();
2707
+ return;
2708
+ }
2709
+ const key = req.headers['sec-websocket-key'];
2710
+ if (!key || req.headers.upgrade !== 'websocket') {
2711
+ socket.destroy();
2712
+ return;
2713
+ }
2714
+ const accept = createHash('sha1')
2715
+ .update(key + WS_GUID)
2716
+ .digest('base64');
2717
+ socket.write(
2718
+ 'HTTP/1.1 101 Switching Protocols\r\n' +
2719
+ 'Upgrade: websocket\r\n' +
2720
+ 'Connection: Upgrade\r\n' +
2721
+ 'Sec-WebSocket-Accept: ' +
2722
+ accept +
2723
+ '\r\n\r\n'
2724
+ );
2725
+
2726
+ const device = deviceForRequest(req);
2727
+ const conn = new WsConnection(socket, head, device);
2728
+
2729
+ if (!device) {
2730
+ conn.close(4401, 'unauthorized');
2731
+ return;
2732
+ }
2733
+
2734
+ clients.add(conn);
2735
+ conn.sendText(
2736
+ JSON.stringify({
2737
+ type: 'ready',
2738
+ version: VERSION,
2739
+ device: {
2740
+ id: device.id,
2741
+ name: device.name,
2742
+ canApprove: !APPROVALS_READONLY
2743
+ },
2744
+ sessions: publicSessions(),
2745
+ workspaces: WORKSPACES,
2746
+ activeSessionId: serverState.activeSessionId,
2747
+ queue: [],
2748
+ limits: serverState.limits
2749
+ })
2750
+ );
2751
+ });
2752
+
2753
+ server.on('error', (err) => {
2754
+ if (err && err.code === 'EADDRINUSE') {
2755
+ console.error('[mock] Port ' + PORT + ' is already in use.');
2756
+ } else {
2757
+ console.error('[mock] Server error:', err);
2758
+ }
2759
+ process.exit(1);
2760
+ });
2761
+
2762
+ function lanAddress() {
2763
+ const interfaces = networkInterfaces();
2764
+ for (const name of Object.keys(interfaces)) {
2765
+ for (const entry of interfaces[name] || []) {
2766
+ if (entry.family === 'IPv4' && !entry.internal) return entry.address;
2767
+ }
2768
+ }
2769
+ return null;
2770
+ }
2771
+
2772
+ server.listen(PORT, HOST, () => {
2773
+ const lan = lanAddress();
2774
+ console.log('');
2775
+ console.log(' DSH Remote — mock server (DEV ONLY)');
2776
+ console.log(' -----------------------------------');
2777
+ console.log(' Local: http://localhost:' + PORT + '/');
2778
+ if (lan) console.log(' Network: http://' + lan + ':' + PORT + '/');
2779
+ console.log(' PIN: ' + currentPin + ' (rotates after a successful PIN pair)');
2780
+ console.log(
2781
+ ' One-tap: http://localhost:' + PORT + '/?t=' + PAIRING_TOKEN
2782
+ );
2783
+ if (lan) {
2784
+ console.log(' http://' + lan + ':' + PORT + '/?t=' + PAIRING_TOKEN);
2785
+ }
2786
+ console.log('');
2787
+ console.log(' Type "deploy" in a prompt to trigger the approval card.');
2788
+ console.log(' Rate limit wire-compatible; set RM_RATE_WINDOW_MS=20000 for demos.');
2789
+ console.log('');
2790
+ });
2791
+
2792
+ function shutdown() {
2793
+ log('shutting down');
2794
+ for (const client of [...clients]) client.close(1001, 'server shutdown');
2795
+ server.close(() => process.exit(0));
2796
+ setTimeout(() => process.exit(0), 500).unref();
2797
+ }
2798
+
2799
+ process.on('SIGINT', shutdown);
2800
+ process.on('SIGTERM', shutdown);