dsh-lite 0.0.0-stage → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,2261 @@
1
+ /**
2
+ * dsh-lite — a deliberately small mobile surface for one DSH Web host.
3
+ *
4
+ * The full Web UI fetches every Session projection on list refresh and a full
5
+ * projection baseline when a Session opens. This plugin serves a separate page
6
+ * and a separate API that only reads:
7
+ * - recent Session headers + cached title/list metadata (no projection fold),
8
+ * - the model catalog and one Session's modelSelection,
9
+ * - a bounded newest segment of one Session plus incremental message tails
10
+ * (no tool calls, old turns, attachments, trace, or context projections),
11
+ * - queue edits and slash-command execution through the host seams.
12
+ *
13
+ * The page is public (it contains no data); every /api/lite route is registered
14
+ * through connection.fetch and therefore inherits DSH's Host/Origin fence and
15
+ * browser/API cookie authentication. No second auth scheme.
16
+ */
17
+
18
+ import { randomUUID } from 'node:crypto'
19
+ import { readFileSync, statSync } from 'node:fs'
20
+ import { basename, join } from 'node:path'
21
+ import { fileURLToPath } from 'node:url'
22
+
23
+ export const name = 'dsh-lite'
24
+
25
+ const PUBLIC_DIR = fileURLToPath(new URL('../public/', import.meta.url))
26
+ const LIST_LIMIT = 30
27
+ const BOOTSTRAP_TTL_MS = 10_000
28
+ const CATALOG_TTL_MS = 5 * 60_000
29
+ const CATALOG_FAILURE_TTL_MS = 15_000
30
+ const COMMAND_TTL_MS = 30_000
31
+ const MAX_MESSAGE_CHARS = 12_000
32
+ const MAX_GOAL_CHARS = 2_000
33
+ const MAX_PROMPT_CHARS = 16_000
34
+ const MAX_PROMPT_IMAGES = 4
35
+ const MAX_IMAGE_BYTES = 2 * 1024 * 1024
36
+ const MAX_IMAGE_TOTAL_BYTES = 6 * 1024 * 1024
37
+ const MAX_IMAGE_DATA_CHARS = 4 * 1024 * 1024
38
+ const MAX_IMAGE_NAME_CHARS = 120
39
+ const IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
40
+ const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/
41
+ const ACTIVITY_SCAN_EVENTS = 240
42
+ const MAX_ACTIVITY_TARGET_CHARS = 120
43
+ const MAX_ACTIVITY_NAME_CHARS = 60
44
+ const MAX_QUEUE_TEXT = 4_000
45
+ const MAX_TITLE_CHARS = 200
46
+ const MAX_SEARCH_CHARS = 80
47
+ const MAX_QUESTION_CALLS = 3
48
+ const MAX_QUESTION_OPTIONS = 8
49
+ const MAX_QUESTION_TEXT_CHARS = 600
50
+ const MAX_QUESTION_DETAIL_CHARS = 2_000
51
+ const MAX_ANSWERS = 12
52
+ const MAX_ANSWER_SELECTIONS = 12
53
+ const MAX_ANSWER_CUSTOM_CHARS = 2_000
54
+ const QUESTION_FALLBACK_WAIT_MS = 10 * 60_000
55
+ // The Lite page stops polling while hidden. A recent poll of the exact session
56
+ // means someone is looking at it on the phone right now.
57
+ const QUESTION_LITE_ACTIVE_MS = 30_000
58
+ // Approvals block a running tool, so they are held far less patiently than a
59
+ // question. If the phone stops polling, hand the request back (or fail closed).
60
+ const APPROVAL_IDLE_MS = 45_000
61
+ const APPROVAL_WAIT_MS = 5 * 60_000
62
+ const MAX_APPROVAL_CALLS = 3
63
+ const MAX_APPROVAL_TOOL_CHARS = 120
64
+ const MAX_APPROVAL_REASON_CHARS = 2_000
65
+ const MAX_APPROVAL_DISPLAY_CHARS = 600
66
+ const SEGMENT_LIMIT = 12
67
+ const HISTORY_LIMIT = 12
68
+ const HISTORY_CHUNK = 500
69
+ const INCREMENTAL_LIMIT = 60
70
+ const INCREMENTAL_CHARS = 32_000
71
+
72
+ const LIST_HINT_KEYS = ['title', 'sessionListMetadata']
73
+ const SESSION_HINT_KEYS = ['title', 'sessionListMetadata', 'modelSelection', 'userQuestions', 'goal', 'inbox', 'contextPressure', 'plan']
74
+ const INSIGHT_HINT_KEYS = ['tokenUsage', 'contextBreakdown', 'contextPressure', 'plan']
75
+
76
+ const CSP = [
77
+ "default-src 'self'",
78
+ "connect-src 'self'",
79
+ "img-src 'self' data:",
80
+ "style-src 'self'",
81
+ "script-src 'self'",
82
+ "manifest-src 'self'",
83
+ "base-uri 'none'",
84
+ "form-action 'none'",
85
+ "frame-ancestors 'none'",
86
+ ].join('; ')
87
+
88
+ const ASSET_ROUTES = [
89
+ ['/lite/', 'index.html', 'text/html; charset=utf-8', 'no-cache'],
90
+ ['/lite/index.html', 'index.html', 'text/html; charset=utf-8', 'no-cache'],
91
+ ['/lite/app.js', 'app.js', 'text/javascript; charset=utf-8', 'no-cache'],
92
+ ['/lite/i18n.js', 'i18n.js', 'text/javascript; charset=utf-8', 'no-cache'],
93
+ ['/lite/style.css', 'style.css', 'text/css; charset=utf-8', 'no-cache'],
94
+ ['/lite/theme.css', 'theme.css', 'text/css; charset=utf-8', 'no-cache'],
95
+ ['/lite/theme.js', 'theme.js', 'text/javascript; charset=utf-8', 'no-cache'],
96
+ ['/lite/question-answers.js', 'question-answers.js', 'text/javascript; charset=utf-8', 'no-cache'],
97
+ ['/lite/manifest.webmanifest', 'manifest.webmanifest', 'application/manifest+json; charset=utf-8', 'no-cache'],
98
+ ['/lite/sw.js', 'sw.js', 'text/javascript; charset=utf-8', 'no-cache'],
99
+ ['/lite/icon-192.png', 'icon-192.png', 'image/png', 'public, max-age=86400'],
100
+ ['/lite/icon-512.png', 'icon-512.png', 'image/png', 'public, max-age=86400'],
101
+ ['/lite/favicon.svg', 'favicon.svg', 'image/svg+xml', 'public, max-age=86400'],
102
+ ]
103
+
104
+ let bootstrapCache = { at: 0, value: undefined }
105
+ let catalogCache = { at: 0, value: undefined, ttl: CATALOG_TTL_MS }
106
+ const commandCache = new Map()
107
+ const assetCache = new Map()
108
+ const pendingQuestionStores = new WeakMap()
109
+ const pendingApprovalStores = new WeakMap()
110
+ const liteActivity = new WeakMap()
111
+
112
+ /**
113
+ * Mount the static page and the compact API in the Web host.
114
+ * @param ctx - Cordis context of the dsh-lite bundle row.
115
+ */
116
+ export function apply(ctx) {
117
+ ctx.inject(['webServer'], (c) => {
118
+ c.effect(() => {
119
+ const disposers = staticRoutes().map((route) => c.webServer.register(route))
120
+ return () => {
121
+ for (const dispose of disposers) dispose()
122
+ }
123
+ }, 'dsh-lite: static routes')
124
+ })
125
+
126
+ ctx.inject(['connection', 'sessionQuery', 'sessionController', 'sessionProjections'], (c) => {
127
+ c.effect(() => {
128
+ const disposers = apiRoutes(c).map((route) => c.connection.fetch.register(route))
129
+ c.logger?.info?.('dsh-lite: /lite/ ready')
130
+ return () => {
131
+ for (const dispose of disposers) dispose()
132
+ }
133
+ }, 'dsh-lite: api routes')
134
+
135
+ // The Web host's Remote bridge claims every question even when no page is
136
+ // connected, so a phone-only user would otherwise wait forever. This
137
+ // listener runs before that bridge: with a live full page it delegates,
138
+ // and without one it holds the question for the Lite answer card.
139
+ c.effect(() => {
140
+ const dispose = c.on(
141
+ 'user-questions/request',
142
+ (request, next) => relayQuestion(c, request, next),
143
+ { prepend: true, global: true },
144
+ )
145
+ return () => {
146
+ dispose()
147
+ rejectPendingQuestions(c, new Error('dsh-lite: question fallback was disposed'))
148
+ }
149
+ }, 'dsh-lite: user question fallback')
150
+
151
+ // Approvals are blocking: claim one only while this exact session is being
152
+ // polled by Lite. Otherwise the full page (or the host's fail-closed
153
+ // answerer) keeps ownership. A silent phone hands the request back.
154
+ c.effect(() => {
155
+ const dispose = c.on(
156
+ 'approval/request',
157
+ (request, next) => relayApproval(c, request, next),
158
+ { prepend: true, global: true },
159
+ )
160
+ return () => {
161
+ dispose()
162
+ rejectPendingApprovals(c, 'unavailable')
163
+ }
164
+ }, 'dsh-lite: approval fallback')
165
+ })
166
+
167
+ // The slash-command seam is optional: profiles without `commands` keep the
168
+ // rest of /api/lite working instead of leaving every route pending.
169
+ ctx.inject(['connection', 'sessionController', 'commands'], (c) => {
170
+ c.effect(() => {
171
+ const disposers = commandRoutes(c).map((route) => c.connection.fetch.register(route))
172
+ return () => {
173
+ for (const dispose of disposers) dispose()
174
+ }
175
+ }, 'dsh-lite: command routes')
176
+ })
177
+ }
178
+
179
+ function staticRoutes() {
180
+ return [
181
+ {
182
+ kind: 'exact',
183
+ path: '/lite',
184
+ handler: (_req, res) => {
185
+ res.writeHead(302, { location: '/lite/' })
186
+ res.end()
187
+ },
188
+ },
189
+ ...ASSET_ROUTES.map(([path, file, type, cacheControl]) => ({
190
+ kind: 'exact',
191
+ path,
192
+ handler: (req, res) => serveAsset(req, res, file, type, cacheControl),
193
+ })),
194
+ ]
195
+ }
196
+
197
+ function serveAsset(req, res, file, type, cacheControl) {
198
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
199
+ res.writeHead(405, { allow: 'GET, HEAD' })
200
+ res.end()
201
+ return
202
+ }
203
+ let body
204
+ try {
205
+ const path = join(PUBLIC_DIR, file)
206
+ const mtimeMs = statSync(path).mtimeMs
207
+ const cached = assetCache.get(file)
208
+ if (cached !== undefined && cached.mtimeMs === mtimeMs) {
209
+ body = cached.body
210
+ } else {
211
+ body = readFileSync(path)
212
+ assetCache.set(file, { mtimeMs, body })
213
+ }
214
+ } catch {
215
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
216
+ res.end('not found')
217
+ return
218
+ }
219
+ res.writeHead(200, {
220
+ 'content-type': type,
221
+ 'content-length': body.byteLength,
222
+ 'cache-control': cacheControl,
223
+ 'content-security-policy': CSP,
224
+ 'x-content-type-options': 'nosniff',
225
+ 'referrer-policy': 'no-referrer',
226
+ })
227
+ res.end(req.method === 'HEAD' ? undefined : body)
228
+ }
229
+
230
+ function apiRoutes(c) {
231
+ const route = (path, methods, fetch) => ({ path, methods, requestBody: 'buffered', fetch })
232
+ return [
233
+ route('/api/lite/bootstrap', ['GET'], (request) => handleBootstrap(c, request)),
234
+ route('/api/lite/session', ['GET'], (request) => handleSession(c, request)),
235
+ route('/api/lite/insights', ['GET'], (request) => handleInsights(c, request)),
236
+ route('/api/lite/history', ['GET'], (request) => handleHistory(c, request)),
237
+ route('/api/lite/queue', ['POST'], (request) => handleQueue(c, request)),
238
+ route('/api/lite/prompt', ['POST'], (request) => handlePrompt(c, request)),
239
+ route('/api/lite/model', ['POST'], (request) => handleModel(c, request)),
240
+ route('/api/lite/cancel', ['POST'], (request) => handleCancel(c, request)),
241
+ route('/api/lite/new', ['POST'], (request) => handleNew(c, request)),
242
+ route('/api/lite/fork', ['POST'], (request) => handleFork(c, request)),
243
+ route('/api/lite/permissions', ['GET', 'POST'], (request) => handlePermissions(c, request)),
244
+ route('/api/lite/rename', ['POST'], (request) => handleRename(c, request)),
245
+ route('/api/lite/archive', ['POST'], (request) => handleArchive(c, request)),
246
+ route('/api/lite/unarchive', ['POST'], (request) => handleUnarchive(c, request)),
247
+ route('/api/lite/pin', ['POST'], (request) => handlePin(c, request)),
248
+ route('/api/lite/archived', ['GET'], (request) => handleArchivedList(c, request)),
249
+ route('/api/lite/sessions', ['GET'], (request) => handleSessions(c, request)),
250
+ route('/api/lite/answer', ['POST'], (request) => handleAnswer(c, request)),
251
+ route('/api/lite/approval', ['POST'], (request) => handleApproval(c, request)),
252
+ ]
253
+ }
254
+
255
+ function commandRoutes(c) {
256
+ const route = (path, methods, fetch) => ({ path, methods, requestBody: 'buffered', fetch })
257
+ return [
258
+ route('/api/lite/commands', ['GET'], (request) => handleCommands(c, request)),
259
+ route('/api/lite/command', ['POST'], (request) => handleCommand(c, request)),
260
+ ]
261
+ }
262
+
263
+ async function handleBootstrap(c, request) {
264
+ const url = new URL(request.url)
265
+ const force = url.searchParams.get('refresh') === '1'
266
+ if (!force && bootstrapCache.value !== undefined && Date.now() - bootstrapCache.at < BOOTSTRAP_TTL_MS) {
267
+ return jsonResponse(bootstrapCache.value)
268
+ }
269
+ try {
270
+ const [page, models, presets] = await Promise.all([
271
+ buildSessionList(c, request.signal),
272
+ getCatalog(c, force),
273
+ getPresets(c),
274
+ ])
275
+ const value = {
276
+ ok: true,
277
+ sessions: page.rows,
278
+ activeTotal: page.total,
279
+ activeHasMore: page.rows.length < page.total,
280
+ models,
281
+ presets,
282
+ workspaces: workspaceList(c),
283
+ archivedCount: archivedIds(c).length,
284
+ generatedAt: Date.now(),
285
+ }
286
+ bootstrapCache = { at: Date.now(), value }
287
+ return jsonResponse(value)
288
+ } catch (error) {
289
+ return errorResponse(c, 'bootstrap', error)
290
+ }
291
+ }
292
+
293
+ async function handleSession(c, request) {
294
+ const url = new URL(request.url)
295
+ const id = url.searchParams.get('id')
296
+ const afterRaw = url.searchParams.get('after')
297
+ let after
298
+ if (afterRaw !== null) {
299
+ after = Number(afterRaw)
300
+ if (!/^\d+$/.test(afterRaw) || !Number.isSafeInteger(after)) {
301
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'after must be a non-negative integer' } }, 400)
302
+ }
303
+ }
304
+ if (typeof id !== 'string' || id.length === 0) {
305
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'id is required' } }, 400)
306
+ }
307
+ noteLiteActivity(c, id)
308
+ try {
309
+ const session = await buildSessionState(c, id, request.signal, after)
310
+ return jsonResponse({ ok: true, session })
311
+ } catch (error) {
312
+ return errorResponse(c, 'session', error)
313
+ }
314
+ }
315
+
316
+ async function handleInsights(c, request) {
317
+ const url = new URL(request.url)
318
+ const id = url.searchParams.get('id')
319
+ if (typeof id !== 'string' || id.length === 0) {
320
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'id is required' } }, 400)
321
+ }
322
+ try {
323
+ return jsonResponse({ ok: true, insights: await buildInsights(c, id, request.signal) })
324
+ } catch (error) {
325
+ return errorResponse(c, 'insights', error)
326
+ }
327
+ }
328
+
329
+ async function handleHistory(c, request) {
330
+ const url = new URL(request.url)
331
+ const id = url.searchParams.get('id')
332
+ const beforeRaw = url.searchParams.get('beforeSeq')
333
+ const beforeSeq = beforeRaw === null ? undefined : Number(beforeRaw)
334
+ if (typeof id !== 'string' || id.length === 0) {
335
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'id is required' } }, 400)
336
+ }
337
+ if (beforeSeq !== undefined && (!Number.isSafeInteger(beforeSeq) || beforeSeq < 0)) {
338
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'beforeSeq must be a non-negative integer' } }, 400)
339
+ }
340
+ try {
341
+ const page = await buildHistory(c, id, beforeSeq, request.signal)
342
+ return jsonResponse({ ok: true, ...page })
343
+ } catch (error) {
344
+ return errorResponse(c, 'history', error)
345
+ }
346
+ }
347
+
348
+ async function handleQueue(c, request) {
349
+ const body = await readJson(request)
350
+ const sessionId = stringField(body, 'sessionId')
351
+ const itemId = stringField(body, 'itemId')
352
+ const action = stringField(body, 'action')
353
+ if (sessionId === undefined || itemId === undefined || !['edit', 'remove', 'steer'].includes(action)) {
354
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId, itemId, and action (edit|remove|steer) are required' } }, 400)
355
+ }
356
+ const text = stringField(body, 'text')
357
+ if (action === 'edit' && (text === undefined || text.trim().length === 0)) {
358
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'text is required for a queue edit' } }, 400)
359
+ }
360
+ if (action === 'edit' && text.length > MAX_QUEUE_TEXT) {
361
+ return jsonResponse({ ok: false, error: { code: 'lite/too-long', message: `queue text exceeds ${MAX_QUEUE_TEXT} characters` } }, 413)
362
+ }
363
+ try {
364
+ await c.sessionController.updateQueue({
365
+ sessionId,
366
+ itemId,
367
+ action: action === 'edit'
368
+ ? { kind: 'edit', content: [{ type: 'text', text }] }
369
+ : { kind: action },
370
+ })
371
+ bootstrapCache.at = 0
372
+ return jsonResponse({ ok: true, accepted: true })
373
+ } catch (error) {
374
+ return errorResponse(c, 'queue', error)
375
+ }
376
+ }
377
+
378
+ async function handleCommands(c, request) {
379
+ const url = new URL(request.url)
380
+ const id = url.searchParams.get('id')
381
+ if (typeof id !== 'string' || id.length === 0) {
382
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'id is required' } }, 400)
383
+ }
384
+ const force = url.searchParams.get('refresh') === '1'
385
+ try {
386
+ const cached = commandCache.get(id)
387
+ if (!force && cached !== undefined && Date.now() - cached.at < COMMAND_TTL_MS) {
388
+ return jsonResponse({ ok: true, commands: cached.value })
389
+ }
390
+ const agent = await resolveAgentOf(c, id)
391
+ const registry = commandsOf(c, agent)
392
+ const commands = (registry?.list(agent) ?? []).map((command) => ({
393
+ name: command.name,
394
+ description: command.description,
395
+ hint: command.input?.hint ?? '',
396
+ }))
397
+ commandCache.set(id, { at: Date.now(), value: commands })
398
+ return jsonResponse({ ok: true, commands })
399
+ } catch (error) {
400
+ return errorResponse(c, 'commands', error)
401
+ }
402
+ }
403
+
404
+ async function handleCommand(c, request) {
405
+ const body = await readJson(request)
406
+ const sessionId = stringField(body, 'sessionId')
407
+ const line = stringField(body, 'line')
408
+ if (sessionId === undefined || line === undefined || !line.trim().startsWith('/')) {
409
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId and a slash command line are required' } }, 400)
410
+ }
411
+ if (line.length > MAX_PROMPT_CHARS) {
412
+ return jsonResponse({ ok: false, error: { code: 'lite/too-long', message: `command exceeds ${MAX_PROMPT_CHARS} characters` } }, 413)
413
+ }
414
+ try {
415
+ const agent = await resolveAgentOf(c, sessionId)
416
+ const registry = commandsOf(c, agent)
417
+ const value = await registry?.execute(agent, line.trim(), [], request.signal)
418
+ commandCache.delete(sessionId)
419
+ if (value === undefined) return jsonResponse({ ok: true, executed: false })
420
+ bootstrapCache.at = 0
421
+ return jsonResponse({ ok: true, executed: true, commandId: value.commandId, result: value.result })
422
+ } catch (error) {
423
+ commandCache.delete(sessionId)
424
+ return errorResponse(c, 'command', error)
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Unwrap the Session controller's agent lookup. It returns `{agent}` or a
430
+ * stable `{error}` failure; the wrapper is not a scope key, so passing it to
431
+ * the command registry would hide every preset-scoped command.
432
+ */
433
+ async function resolveAgentOf(c, sessionId) {
434
+ const found = await c.sessionController.resolveAgent(sessionId)
435
+ if (found !== null && typeof found === 'object' && found.error !== undefined) throw found.error
436
+ const agent = found !== null && typeof found === 'object' && found.agent !== undefined ? found.agent : found
437
+ if (agent === null || typeof agent !== 'object') throw new Error(`session "${sessionId}" has no agent`)
438
+ return agent
439
+ }
440
+
441
+ /**
442
+ * Resolve the command registry nearest to the agent. Preset realms may isolate
443
+ * `commands`, so the agent context is authoritative and the host service is
444
+ * only a fallback.
445
+ */
446
+ function commandsOf(c, agent) {
447
+ const scoped = agent.ctx?.get?.('commands')
448
+ return scoped ?? c.commands
449
+ }
450
+
451
+ async function handlePrompt(c, request) {
452
+ const body = await readJson(request)
453
+ const sessionId = stringField(body, 'sessionId')
454
+ const text = typeof body?.text === 'string' ? body.text : ''
455
+ const normalized = normalizePromptImages(body?.images)
456
+ if (normalized.error !== undefined) {
457
+ const { status, ...error } = normalized.error
458
+ return jsonResponse({ ok: false, error }, status)
459
+ }
460
+ const images = normalized.images
461
+ if (sessionId === undefined || (text.trim().length === 0 && images.length === 0)) {
462
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId and non-empty text or at least one image are required' } }, 400)
463
+ }
464
+ if (text.length > MAX_PROMPT_CHARS) {
465
+ return jsonResponse({ ok: false, error: { code: 'lite/too-long', message: `prompt exceeds ${MAX_PROMPT_CHARS} characters` } }, 413)
466
+ }
467
+ const content = [
468
+ ...text.trim().length > 0 ? [{ type: 'text', text }] : [],
469
+ ...images,
470
+ ]
471
+ try {
472
+ const result = await c.sessionController.prompt(
473
+ {
474
+ requestId: randomUUID(),
475
+ sessionId,
476
+ mode: 'queue',
477
+ content,
478
+ },
479
+ request.signal,
480
+ )
481
+ bootstrapCache.at = 0
482
+ return jsonResponse({ ok: true, accepted: result.accepted === true })
483
+ } catch (error) {
484
+ return errorResponse(c, 'prompt', error)
485
+ }
486
+ }
487
+
488
+ function normalizePromptImages(value) {
489
+ if (value === undefined || value === null) return { images: [] }
490
+ if (!Array.isArray(value)) return { error: imageError('images must be an array') }
491
+ if (value.length === 0) return { images: [] }
492
+ if (value.length > MAX_PROMPT_IMAGES) {
493
+ return { error: imageError(`at most ${MAX_PROMPT_IMAGES} images are allowed`, 413) }
494
+ }
495
+ const images = []
496
+ let total = 0
497
+ for (const item of value) {
498
+ if (item === null || typeof item !== 'object') return { error: imageError('each image must be an object') }
499
+ const mediaType = stringField(item, 'mediaType')
500
+ const data = stringField(item, 'data')
501
+ if (mediaType === undefined || !IMAGE_MEDIA_TYPES.has(mediaType)) {
502
+ return { error: imageError('mediaType must be image/png, image/jpeg, image/webp, or image/gif') }
503
+ }
504
+ if (data === undefined) return { error: imageError('image data is required') }
505
+ if (data.length > MAX_IMAGE_DATA_CHARS) {
506
+ return { error: imageError('image data is too large', 413) }
507
+ }
508
+ if (!BASE64_PATTERN.test(data)) return { error: imageError('image data must be canonical base64') }
509
+ const bytes = Buffer.from(data, 'base64')
510
+ if (bytes.length === 0 || bytes.toString('base64') !== data) {
511
+ return { error: imageError('image data must be canonical base64') }
512
+ }
513
+ if (!hasImageSignature(bytes, mediaType)) {
514
+ return { error: imageError(`image bytes do not match ${mediaType}`) }
515
+ }
516
+ if (bytes.length > MAX_IMAGE_BYTES) {
517
+ return { error: imageError(`each image must be at most ${MAX_IMAGE_BYTES} bytes`, 413) }
518
+ }
519
+ total += bytes.length
520
+ if (total > MAX_IMAGE_TOTAL_BYTES) {
521
+ return { error: imageError(`images must total at most ${MAX_IMAGE_TOTAL_BYTES} bytes`, 413) }
522
+ }
523
+ const name = typeof item.name === 'string' && item.name.trim().length > 0
524
+ ? truncateText(item.name.trim(), MAX_IMAGE_NAME_CHARS)
525
+ : undefined
526
+ images.push({
527
+ type: 'image',
528
+ mediaType,
529
+ data,
530
+ ...name === undefined ? {} : { name },
531
+ })
532
+ }
533
+ return { images }
534
+ }
535
+
536
+ function hasImageSignature(bytes, mediaType) {
537
+ if (mediaType === 'image/png') {
538
+ return bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
539
+ }
540
+ if (mediaType === 'image/jpeg') {
541
+ return bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff
542
+ }
543
+ if (mediaType === 'image/webp') {
544
+ return bytes.length >= 12 &&
545
+ bytes.toString('ascii', 0, 4) === 'RIFF' &&
546
+ bytes.toString('ascii', 8, 12) === 'WEBP'
547
+ }
548
+ if (mediaType === 'image/gif') {
549
+ return bytes.length >= 6 &&
550
+ (bytes.toString('ascii', 0, 6) === 'GIF87a' || bytes.toString('ascii', 0, 6) === 'GIF89a')
551
+ }
552
+ return false
553
+ }
554
+
555
+ function imageError(message, status = 400) {
556
+ return {
557
+ status,
558
+ code: status === 413 ? 'lite/too-large' : 'lite/bad-request',
559
+ message,
560
+ }
561
+ }
562
+
563
+ async function handleModel(c, request) {
564
+ const body = await readJson(request)
565
+ const sessionId = stringField(body, 'sessionId')
566
+ const provider = stringField(body, 'provider')
567
+ const model = stringField(body, 'model')
568
+ const reasoningEffort = stringField(body, 'reasoningEffort')
569
+ if (sessionId === undefined || provider === undefined || model === undefined) {
570
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId, provider, and model are required' } }, 400)
571
+ }
572
+ try {
573
+ const value = await c.sessionController.selectModel({
574
+ sessionId,
575
+ provider,
576
+ model,
577
+ ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
578
+ })
579
+ bootstrapCache.at = 0
580
+ return jsonResponse({ ok: true, selected: value.selected })
581
+ } catch (error) {
582
+ return errorResponse(c, 'model', error)
583
+ }
584
+ }
585
+
586
+ async function handleCancel(c, request) {
587
+ const body = await readJson(request)
588
+ const sessionId = stringField(body, 'sessionId')
589
+ if (sessionId === undefined) {
590
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId is required' } }, 400)
591
+ }
592
+ try {
593
+ const value = c.sessionController.cancel({ sessionId })
594
+ return jsonResponse({ ok: true, accepted: value.accepted === true })
595
+ } catch (error) {
596
+ return errorResponse(c, 'cancel', error)
597
+ }
598
+ }
599
+
600
+ async function handleNew(c, request) {
601
+ const body = await readJson(request)
602
+ const cwd = stringField(body, 'cwd')
603
+ const workspaceId = stringField(body, 'workspaceId')
604
+ const agentPreset = stringField(body, 'agentPreset')
605
+ const options = {}
606
+ if (cwd !== undefined) options.cwd = cwd
607
+ if (workspaceId !== undefined) options.workspaceId = workspaceId
608
+ if (agentPreset !== undefined) options.agentPreset = agentPreset
609
+ try {
610
+ const value = await c.sessionController.create(options)
611
+ bootstrapCache.at = 0
612
+ return jsonResponse({ ok: true, sessionId: value.sessionId })
613
+ } catch (error) {
614
+ return errorResponse(c, 'new', error)
615
+ }
616
+ }
617
+
618
+ async function handleFork(c, request) {
619
+ const body = await readJson(request)
620
+ const sessionId = stringField(body, 'sessionId')
621
+ if (sessionId === undefined) {
622
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId is required' } }, 400)
623
+ }
624
+ try {
625
+ const value = await c.sessionController.fork({ sessionId })
626
+ bootstrapCache.at = 0
627
+ return jsonResponse({ ok: true, sessionId: value.sessionId })
628
+ } catch (error) {
629
+ return errorResponse(c, 'fork', error)
630
+ }
631
+ }
632
+
633
+ async function handlePermissions(c, request) {
634
+ const service = c.get('permissionPresets') ?? c.permissionPresets
635
+ if (service === undefined || service === null || typeof service.catalog !== 'function' || typeof service.set !== 'function') {
636
+ return jsonResponse({ ok: false, error: { code: 'lite/unsupported', message: 'this deployment has no permission presets' } }, 501)
637
+ }
638
+ const url = new URL(request.url)
639
+ let body = null
640
+ let sessionId
641
+ if (request.method === 'GET') {
642
+ sessionId = url.searchParams.get('id')
643
+ } else {
644
+ body = await readJson(request)
645
+ sessionId = stringField(body, 'sessionId')
646
+ }
647
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
648
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'id is required' } }, 400)
649
+ }
650
+ try {
651
+ const agent = await resolveAgentOf(c, sessionId)
652
+ if (request.method === 'GET') {
653
+ const catalog = service.catalog()
654
+ return jsonResponse({
655
+ ok: true,
656
+ current: service.current(agent.session),
657
+ options: compactPermissionOptions(catalog?.options),
658
+ })
659
+ }
660
+ const preset = stringField(body ?? {}, 'preset')
661
+ if (preset === undefined) {
662
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'preset is required' } }, 400)
663
+ }
664
+ service.set(agent.session, preset)
665
+ return jsonResponse({ ok: true, current: service.current(agent.session), options: compactPermissionOptions(service.catalog()?.options) })
666
+ } catch (error) {
667
+ return errorResponse(c, 'permissions', error)
668
+ }
669
+ }
670
+
671
+ function compactPermissionOptions(options) {
672
+ if (!Array.isArray(options)) return []
673
+ return options.slice(0, 20).map((option) => ({
674
+ value: String(option.value),
675
+ name: typeof option.name === 'string' && option.name.length > 0 ? option.name : String(option.value),
676
+ ...typeof option.description === 'string' && option.description.length > 0 ? { description: option.description } : {},
677
+ }))
678
+ }
679
+
680
+ async function handleRename(c, request) {
681
+ const body = await readJson(request)
682
+ const sessionId = stringField(body, 'sessionId')
683
+ const title = stringField(body, 'title')?.trim()
684
+ if (sessionId === undefined || title === undefined || title.length === 0) {
685
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId and a non-empty title are required' } }, 400)
686
+ }
687
+ if (title.length > MAX_TITLE_CHARS) {
688
+ return jsonResponse({ ok: false, error: { code: 'lite/too-long', message: `title exceeds ${MAX_TITLE_CHARS} characters` } }, 413)
689
+ }
690
+ try {
691
+ const value = await c.sessionController.rename({ sessionId, title })
692
+ bootstrapCache.at = 0
693
+ return jsonResponse({ ok: true, title: typeof value?.title === 'string' ? value.title : title })
694
+ } catch (error) {
695
+ return errorResponse(c, 'rename', error)
696
+ }
697
+ }
698
+
699
+ async function handleArchive(c, request) {
700
+ const body = await readJson(request)
701
+ const sessionId = stringField(body, 'sessionId')
702
+ if (sessionId === undefined) {
703
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId is required' } }, 400)
704
+ }
705
+ const controller = workspaceOf(c)
706
+ if (controller === undefined) {
707
+ return jsonResponse({ ok: false, error: { code: 'lite/unsupported', message: 'this deployment has no workspace controller' } }, 501)
708
+ }
709
+ try {
710
+ await controller.archiveSession({
711
+ sessionId,
712
+ ...body.stopActivity === true ? { stopActivity: true } : {},
713
+ })
714
+ bootstrapCache.at = 0
715
+ return jsonResponse({ ok: true, archivedCount: archivedIds(c).length })
716
+ } catch (error) {
717
+ return errorResponse(c, 'archive', error)
718
+ }
719
+ }
720
+
721
+ async function handleUnarchive(c, request) {
722
+ const body = await readJson(request)
723
+ const sessionId = stringField(body, 'sessionId')
724
+ if (sessionId === undefined) {
725
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId is required' } }, 400)
726
+ }
727
+ const controller = workspaceOf(c)
728
+ if (controller === undefined) {
729
+ return jsonResponse({ ok: false, error: { code: 'lite/unsupported', message: 'this deployment has no workspace controller' } }, 501)
730
+ }
731
+ try {
732
+ await controller.unarchiveSession({ sessionId })
733
+ bootstrapCache.at = 0
734
+ return jsonResponse({ ok: true, archivedCount: archivedIds(c).length })
735
+ } catch (error) {
736
+ return errorResponse(c, 'unarchive', error)
737
+ }
738
+ }
739
+
740
+ async function handleArchivedList(c, request) {
741
+ return respondSessionPage(c, request, true, 'archived')
742
+ }
743
+
744
+ async function handleSessions(c, request) {
745
+ const scope = new URL(request.url).searchParams.get('scope') ?? 'active'
746
+ if (scope !== 'active' && scope !== 'archived') {
747
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'scope must be active or archived' } }, 400)
748
+ }
749
+ return respondSessionPage(c, request, scope === 'archived', 'sessions')
750
+ }
751
+
752
+ async function respondSessionPage(c, request, archivedOnly, operation) {
753
+ const options = pageOptions(new URL(request.url))
754
+ if (options === null) {
755
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'offset must be a non-negative integer' } }, 400)
756
+ }
757
+ try {
758
+ const page = await collectSessionRows(c, request.signal, archivedOnly, options)
759
+ return jsonResponse({
760
+ ok: true,
761
+ sessions: page.rows,
762
+ total: page.total,
763
+ offset: page.offset,
764
+ limit: page.limit,
765
+ hasMore: page.offset + page.rows.length < page.total,
766
+ archivedCount: archivedIds(c).length,
767
+ })
768
+ } catch (error) {
769
+ return errorResponse(c, operation, error)
770
+ }
771
+ }
772
+
773
+ function pageOptions(url) {
774
+ const raw = url.searchParams.get('offset')
775
+ let offset = 0
776
+ if (raw !== null) {
777
+ if (!/^\d+$/.test(raw)) return null
778
+ offset = Number(raw)
779
+ if (!Number.isSafeInteger(offset)) return null
780
+ }
781
+ const query = (url.searchParams.get('q') ?? '').trim().slice(0, MAX_SEARCH_CHARS)
782
+ return { offset, query }
783
+ }
784
+
785
+ async function handlePin(c, request) {
786
+ const body = await readJson(request)
787
+ const sessionId = stringField(body, 'sessionId')
788
+ if (sessionId === undefined || typeof body.pinned !== 'boolean') {
789
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId and a boolean pinned are required' } }, 400)
790
+ }
791
+ const controller = workspaceOf(c)
792
+ if (controller === undefined) {
793
+ return jsonResponse({ ok: false, error: { code: 'lite/unsupported', message: 'this deployment has no workspace controller' } }, 501)
794
+ }
795
+ const pinned = body.pinned
796
+ try {
797
+ if (pinned) await controller.pinSession({ sessionId })
798
+ else await controller.unpinSession({ sessionId })
799
+ bootstrapCache.at = 0
800
+ return jsonResponse({ ok: true, pinned })
801
+ } catch (error) {
802
+ return errorResponse(c, 'pin', error)
803
+ }
804
+ }
805
+
806
+ async function handleAnswer(c, request) {
807
+ const body = await readJson(request)
808
+ const sessionId = stringField(body, 'sessionId')
809
+ const callId = stringField(body, 'callId')
810
+ if (sessionId === undefined || callId === undefined) {
811
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId and callId are required' } }, 400)
812
+ }
813
+ const answers = normalizeAnswerBatch(body.answers)
814
+ if (answers === null) {
815
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'answers must name each question once' } }, 400)
816
+ }
817
+ // A held blocking question is resolved in-process; a timed-out one goes
818
+ // through the user-questions service as a continued reply.
819
+ const held = await answerPendingQuestion(c, sessionId, callId, answers)
820
+ if (held === 'invalid') {
821
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'answers must name each waiting question once' } }, 400)
822
+ }
823
+ if (held === 'not-ready') {
824
+ return jsonResponse({ ok: false, error: { code: 'lite/question-not-ready', message: 'the answer channel is still opening; try again' } }, 409)
825
+ }
826
+ if (held === 'accepted') return jsonResponse({ ok: true, accepted: true })
827
+ const agent = c.get('agents')?.get(sessionId)
828
+ if (agent === undefined) {
829
+ return jsonResponse({ ok: false, error: { code: 'lite/no-live-agent', message: 'the session is not live; reopen it in DSH first' } }, 409)
830
+ }
831
+ const service = c.get('userQuestions') ?? c.userQuestions
832
+ if (service === undefined || typeof service.answer !== 'function') {
833
+ return jsonResponse({ ok: false, error: { code: 'lite/unsupported', message: 'this deployment has no user-questions service' } }, 501)
834
+ }
835
+ try {
836
+ const accepted = await service.answer(agent, callId, { answers })
837
+ if (accepted !== true) {
838
+ return jsonResponse({ ok: false, error: { code: 'lite/question-not-answerable', message: 'the question is no longer waiting for a reply' } }, 409)
839
+ }
840
+ return jsonResponse({ ok: true, accepted: true })
841
+ } catch (error) {
842
+ return errorResponse(c, 'answer', error)
843
+ }
844
+ }
845
+
846
+ async function handleApproval(c, request) {
847
+ const body = await readJson(request)
848
+ const sessionId = stringField(body, 'sessionId')
849
+ const id = stringField(body, 'id')
850
+ const decision = stringField(body, 'decision')
851
+ if (sessionId === undefined || id === undefined || (decision !== 'allow' && decision !== 'reject')) {
852
+ return jsonResponse({ ok: false, error: { code: 'lite/bad-request', message: 'sessionId, id, and decision allow|reject are required' } }, 400)
853
+ }
854
+ const record = pendingApprovalStores.get(c)?.get(sessionId)?.get(id)
855
+ if (record === undefined || record.done) {
856
+ return jsonResponse({ ok: false, error: { code: 'lite/approval-not-answerable', message: 'the approval is no longer waiting for a decision' } }, 409)
857
+ }
858
+ record.finish(undefined, decision === 'allow' ? 'allowed-once' : 'rejected')
859
+ bootstrapCache.at = 0
860
+ c.logger?.info?.(`dsh-lite: ${decision === 'allow' ? 'allowed' : 'rejected'} ${record.toolName} for ${sessionId}`)
861
+ return jsonResponse({ ok: true, accepted: true })
862
+ }
863
+
864
+ function normalizeAnswerBatch(value) {
865
+ if (!Array.isArray(value) || value.length === 0 || value.length > MAX_ANSWERS) return null
866
+ const rows = []
867
+ const seen = new Set()
868
+ for (const item of value) {
869
+ if (item === null || typeof item !== 'object') return null
870
+ const id = stringField(item, 'id')
871
+ if (id === undefined || seen.has(id)) return null
872
+ seen.add(id)
873
+ const selected = Array.isArray(item.selected)
874
+ ? item.selected.filter((option) => typeof option === 'string' && option.length > 0)
875
+ : []
876
+ if (selected.length > MAX_ANSWER_SELECTIONS) return null
877
+ const custom = typeof item.custom === 'string' ? item.custom.trim() : ''
878
+ if (custom.length > MAX_ANSWER_CUSTOM_CHARS) return null
879
+ // Empty selected + no custom is the protocol's explicit "skipped" answer.
880
+ rows.push({ id, selected, ...custom.length > 0 ? { custom } : {} })
881
+ }
882
+ return rows
883
+ }
884
+
885
+ /**
886
+ * Mirror the question on both surfaces when the Web host's gateway exposes its
887
+ * pending-event table. Lite then settles the same pending event a full-page
888
+ * client would, so the gateway sends its normal cancel frame to every other
889
+ * window. Without those internals, fall back to one-surface arbitration.
890
+ *
891
+ * Two request shapes arrive here. The timed schema keys itself with
892
+ * `wait.callId`. The blocking `legacy` tool — the default — carries no such
893
+ * key, so Lite keys that card by a synthetic id and finds the gateway's
894
+ * pending event again by agent plus question identity. Either way the request
895
+ * is also forwarded (`next`) so the full page shows the same card.
896
+ */
897
+ function relayQuestion(c, request, next) {
898
+ const bridge = remoteQuestionBridge(c)
899
+ if (bridge !== null) return relayWithRemoteBridge(c, request, bridge, next)
900
+ return relayAsFallback(c, request, next)
901
+ }
902
+
903
+ function remoteQuestionBridge(c) {
904
+ try {
905
+ const gateway = c.get('typertGateway') ?? c.typertGateway
906
+ if (gateway === undefined || gateway === null) return null
907
+ if (typeof gateway.settleRemoteEvent !== 'function') return null
908
+ if (!(gateway.pendingRemoteEvents instanceof Map)) return null
909
+ return gateway
910
+ } catch {
911
+ return null
912
+ }
913
+ }
914
+
915
+ function relayWithRemoteBridge(c, request, bridge, next) {
916
+ const record = createHeldQuestion(c, request, { mode: 'remote', bridge, timeLimit: false })
917
+ // Nothing to key a card under (no live agent or session): forward the
918
+ // request untouched rather than starve it with NO_PROVIDER.
919
+ if (record === undefined) return Promise.resolve().then(next)
920
+ // Forward first: every full-page client gets the same card, exactly as when
921
+ // another full-page tab is open. A client answer resolves this promise.
922
+ Promise.resolve().then(next).then(
923
+ (value) => record.finish(undefined, value),
924
+ (error) => {
925
+ if (record.done) return
926
+ if (!isNoProvider(error)) {
927
+ record.finish(error)
928
+ return
929
+ }
930
+ // No Remote bridge claimed it: this card is now the only answerer.
931
+ record.mode = 'local'
932
+ record.armTimeout()
933
+ },
934
+ )
935
+ return record.answer
936
+ }
937
+
938
+ /**
939
+ * Degraded path for a DSH build without the gateway internals above: only one
940
+ * surface may hold the question, so prefer whichever one is being looked at.
941
+ */
942
+ function relayAsFallback(c, request, next) {
943
+ const sessionId = request.agent?.session?.id
944
+ const fullPage = hasFullPageAnswerer(c)
945
+ if (isLiteActive(c, sessionId)) {
946
+ const record = createHeldQuestion(c, request, { mode: 'local', timeLimit: true, watchIdle: fullPage })
947
+ if (record === undefined) return Promise.reject(noProviderError())
948
+ return record.answer.catch((error) => {
949
+ if (error?.code !== 'LITE_HANDOFF') throw error
950
+ // The full page may have closed during the idle window; do not hand the
951
+ // request to a bridge with no connected client.
952
+ if (!hasFullPageAnswerer(c)) return holdQuestion(c, request)
953
+ return Promise.resolve().then(next).catch((handoff) => {
954
+ if (!isNoProvider(handoff)) throw handoff
955
+ return holdQuestion(c, request)
956
+ })
957
+ })
958
+ }
959
+ if (!fullPage) return holdQuestion(c, request)
960
+ return Promise.resolve().then(next).catch((error) => {
961
+ if (!isNoProvider(error)) throw error
962
+ // Every full-page client delegated or disconnected: fall back to Lite.
963
+ return holdQuestion(c, request)
964
+ })
965
+ }
966
+
967
+ function noteLiteActivity(c, sessionId) {
968
+ let seen = liteActivity.get(c)
969
+ if (seen === undefined) {
970
+ seen = new Map()
971
+ liteActivity.set(c, seen)
972
+ }
973
+ const now = Date.now()
974
+ seen.set(sessionId, now)
975
+ if (seen.size > 200) {
976
+ for (const [id, at] of seen) if (now - at >= QUESTION_LITE_ACTIVE_MS) seen.delete(id)
977
+ }
978
+ }
979
+
980
+ function isLiteActive(c, sessionId) {
981
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return false
982
+ const at = liteActivity.get(c)?.get(sessionId) ?? 0
983
+ return Date.now() - at < QUESTION_LITE_ACTIVE_MS
984
+ }
985
+
986
+ function hasFullPageAnswerer(c) {
987
+ try {
988
+ const gateway = c.get('typertGateway') ?? c.typertGateway
989
+ return gateway !== undefined && typeof gateway.hasLiveClient === 'function' && gateway.hasLiveClient() === true
990
+ } catch {
991
+ return false
992
+ }
993
+ }
994
+
995
+ function isNoProvider(error) {
996
+ return error !== null && typeof error === 'object' && error.code === 'NO_PROVIDER'
997
+ }
998
+
999
+ function createHeldQuestion(c, request, options) {
1000
+ const sessionId = request.agent?.session?.id
1001
+ const agentId = request.agent?.id
1002
+ // `undefined` for the legacy blocking shape; the gateway's pending event is
1003
+ // then matched by agent plus question identity instead of by call id.
1004
+ const callId = request.wait?.callId
1005
+ const questions = compactQuestionRows(request.questions)
1006
+ const ids = Array.isArray(request.questions) ? request.questions.map((question) => question?.id) : []
1007
+ if (
1008
+ typeof sessionId !== 'string' || sessionId.length === 0 ||
1009
+ typeof agentId !== 'string' || agentId.length === 0 ||
1010
+ (callId !== undefined && (typeof callId !== 'string' || callId.length === 0)) ||
1011
+ ids.length === 0 ||
1012
+ questions.length !== ids.length ||
1013
+ ids.some((id) => typeof id !== 'string' || id.length === 0) ||
1014
+ new Set(ids).size !== ids.length
1015
+ ) {
1016
+ return undefined
1017
+ }
1018
+ // Store and client key: the real call id when the schema provides one, a
1019
+ // synthetic id for legacy questions. The client treats it as opaque.
1020
+ const key = callId ?? legacyQuestionKey(agentId)
1021
+
1022
+ c.logger?.info?.(`dsh-lite: ${options.mode === 'remote' ? 'mirroring' : 'holding'} question ${key} for ${sessionId}`)
1023
+ const store = questionStore(c)
1024
+ let calls = store.get(sessionId)
1025
+ if (calls === undefined) {
1026
+ calls = new Map()
1027
+ store.set(sessionId, calls)
1028
+ }
1029
+ const previous = calls.get(key)
1030
+ if (previous !== undefined) previous.finish(noProviderError())
1031
+
1032
+ let accept
1033
+ let refuse
1034
+ const answer = new Promise((resolve, reject) => {
1035
+ accept = resolve
1036
+ refuse = reject
1037
+ })
1038
+ const record = {
1039
+ sessionId,
1040
+ agentId,
1041
+ callId,
1042
+ key,
1043
+ ids,
1044
+ questions,
1045
+ mode: options.mode,
1046
+ bridge: options.bridge ?? null,
1047
+ done: false,
1048
+ timer: undefined,
1049
+ idle: undefined,
1050
+ answer,
1051
+ finish(error, value) {
1052
+ if (record.done) return
1053
+ record.done = true
1054
+ clearTimeout(record.timer)
1055
+ clearInterval(record.idle)
1056
+ request.signal?.removeEventListener?.('abort', record.abort)
1057
+ const current = store.get(sessionId)
1058
+ if (current?.get(key) === record) {
1059
+ current.delete(key)
1060
+ if (current.size === 0) store.delete(sessionId)
1061
+ }
1062
+ if (error === undefined) accept(value)
1063
+ else refuse(error)
1064
+ },
1065
+ armTimeout() {
1066
+ if (record.done || record.timer !== undefined) return
1067
+ record.timer = setTimeout(() => {
1068
+ record.finish(questionTimeoutError())
1069
+ }, QUESTION_FALLBACK_WAIT_MS)
1070
+ record.timer?.unref?.()
1071
+ },
1072
+ abort() {
1073
+ record.finish(abortError(request.signal))
1074
+ },
1075
+ }
1076
+ if (options.timeLimit !== false) record.armTimeout()
1077
+ if (options.watchIdle === true) {
1078
+ // The phone was in front when the question arrived. Once it stops polling
1079
+ // (screen locked, tab closed, network gone), leave the request untouched
1080
+ // for the full page instead of stranding it on a silent phone.
1081
+ record.idle = setInterval(() => {
1082
+ if (!isLiteActive(c, sessionId)) record.finish(handoffError())
1083
+ }, 5_000)
1084
+ record.idle?.unref?.()
1085
+ }
1086
+ calls.set(key, record)
1087
+ if (request.signal?.aborted === true) record.abort()
1088
+ else request.signal?.addEventListener?.('abort', record.abort, { once: true })
1089
+ return record
1090
+ }
1091
+
1092
+ let legacyQuestionSeq = 0
1093
+
1094
+ /** Synthetic, process-unique card key for a request the schema left unkeyed. */
1095
+ function legacyQuestionKey(agentId) {
1096
+ legacyQuestionSeq = (legacyQuestionSeq + 1) % Number.MAX_SAFE_INTEGER
1097
+ return `legacy:${agentId}:${legacyQuestionSeq.toString(36)}`
1098
+ }
1099
+
1100
+ function holdQuestion(c, request) {
1101
+ const record = createHeldQuestion(c, request, { mode: 'local', timeLimit: true })
1102
+ return record === undefined ? Promise.reject(noProviderError()) : record.answer
1103
+ }
1104
+
1105
+ function questionStore(c) {
1106
+ let store = pendingQuestionStores.get(c)
1107
+ if (store === undefined) {
1108
+ store = new Map()
1109
+ pendingQuestionStores.set(c, store)
1110
+ }
1111
+ return store
1112
+ }
1113
+
1114
+ function pendingQuestionsFor(c, sessionId) {
1115
+ const calls = pendingQuestionStores.get(c)?.get(sessionId)
1116
+ if (calls === undefined) return []
1117
+ return [...calls.values()]
1118
+ .filter((record) => !record.done)
1119
+ .slice(0, MAX_QUESTION_CALLS)
1120
+ .map((record) => ({ callId: record.key, state: 'live', questions: record.questions }))
1121
+ }
1122
+
1123
+ /**
1124
+ * Resolve a held request before it reaches the user-questions service.
1125
+ * @returns `accepted`, `invalid`, `missing` (no blocking call), or `not-ready`
1126
+ * when the gateway has not exposed the pending event yet.
1127
+ */
1128
+ async function answerPendingQuestion(c, sessionId, key, answers) {
1129
+ const record = pendingQuestionStores.get(c)?.get(sessionId)?.get(key)
1130
+ if (record === undefined || record.done) return 'missing'
1131
+ if (answers.length !== record.ids.length) return 'invalid'
1132
+ const seen = new Set(answers.map((answer) => answer.id))
1133
+ if (seen.size !== record.ids.length || !record.ids.every((id) => seen.has(id))) return 'invalid'
1134
+ if (record.mode === 'local' || record.bridge === null) {
1135
+ record.finish(undefined, { answers })
1136
+ return 'accepted'
1137
+ }
1138
+
1139
+ // The pending event is created asynchronously by the gateway's event queue;
1140
+ // wait briefly for it instead of failing a fast tap.
1141
+ for (let attempt = 0; attempt < 20; attempt += 1) {
1142
+ if (record.done) return 'missing'
1143
+ if (record.mode === 'local') {
1144
+ record.finish(undefined, { answers })
1145
+ return 'accepted'
1146
+ }
1147
+ const pending = findPendingRemoteQuestion(record.bridge, record)
1148
+ if (pending !== undefined) {
1149
+ try {
1150
+ record.bridge.settleRemoteEvent(pending, { kind: 'result', value: { answers } })
1151
+ } catch {
1152
+ return record.done ? 'missing' : 'not-ready'
1153
+ }
1154
+ c.logger?.info?.(`dsh-lite: answered question ${record.key} from Lite`)
1155
+ return 'accepted'
1156
+ }
1157
+ await delay(50)
1158
+ }
1159
+ return record.done ? 'missing' : 'not-ready'
1160
+ }
1161
+
1162
+ /**
1163
+ * Locate the gateway's pending event for a held question. Timed requests
1164
+ * carry `wait.callId` on both sides. Legacy blocking requests carry no key
1165
+ * at all, so identity is "same agent, same unanswered questions in the same
1166
+ * order" — the gateway keys those events by an internal id Lite never sees.
1167
+ */
1168
+ function findPendingRemoteQuestion(bridge, record) {
1169
+ const pending = bridge.pendingRemoteEvents
1170
+ if (!(pending instanceof Map)) return undefined
1171
+ for (const entry of pending.values()) {
1172
+ const frame = entry?.frame
1173
+ if (frame?.event !== 'user-questions/request') continue
1174
+ if (frame.agentId !== record.agentId) continue
1175
+ if (record.callId === undefined) {
1176
+ if (frame.request?.wait !== undefined) continue
1177
+ if (!sameQuestionIds(frame.request?.questions, record.ids)) continue
1178
+ } else if (frame.request?.wait?.callId !== record.callId) continue
1179
+ return entry
1180
+ }
1181
+ return undefined
1182
+ }
1183
+
1184
+ function sameQuestionIds(questions, ids) {
1185
+ if (!Array.isArray(questions) || questions.length !== ids.length) return false
1186
+ return questions.every((question, index) => question?.id === ids[index])
1187
+ }
1188
+
1189
+ function delay(ms) {
1190
+ return new Promise((resolve) => {
1191
+ setTimeout(resolve, ms)
1192
+ })
1193
+ }
1194
+
1195
+ function rejectPendingQuestions(c, error) {
1196
+ const store = pendingQuestionStores.get(c)
1197
+ if (store === undefined) return
1198
+ pendingQuestionStores.delete(c)
1199
+ for (const calls of store.values()) {
1200
+ for (const record of calls.values()) {
1201
+ if (record.mode === 'remote' && record.bridge !== null) {
1202
+ const pending = findPendingRemoteQuestion(record.bridge, record)
1203
+ if (pending !== undefined && typeof record.bridge.cancelRemoteEvent === 'function') {
1204
+ try {
1205
+ record.bridge.cancelRemoteEvent(pending, error)
1206
+ } catch {
1207
+ // The gateway already settled or tore the event down.
1208
+ }
1209
+ }
1210
+ }
1211
+ record.finish(error)
1212
+ }
1213
+ }
1214
+ }
1215
+
1216
+ /**
1217
+ * Hold a blocking approval only while the phone is polling that exact session.
1218
+ * Otherwise the full page keeps ownership; a silent phone hands it back.
1219
+ * Unlike questions there is no mirroring: the approval waterfall allows one
1220
+ * answerer, and a stuck full-page card would be worse than one-surface
1221
+ * arbitration.
1222
+ */
1223
+ function relayApproval(c, request, next) {
1224
+ const sessionId = request?.agent?.session?.id
1225
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
1226
+ return Promise.resolve().then(next)
1227
+ }
1228
+ if (!isLiteActive(c, sessionId)) return Promise.resolve().then(next)
1229
+ const record = createHeldApproval(c, request)
1230
+ if (record === undefined) return Promise.resolve().then(next)
1231
+ return record.answer.catch((error) => {
1232
+ if (error?.code !== 'LITE_HANDOFF') throw error
1233
+ // The tool may have been cancelled while the phone was idle; do not invoke
1234
+ // a waterfall that the host already withdrew.
1235
+ if (request?.signal?.aborted === true) return 'cancelled'
1236
+ return Promise.resolve().then(next)
1237
+ })
1238
+ }
1239
+
1240
+ function createHeldApproval(c, request) {
1241
+ const sessionId = request?.agent?.session?.id
1242
+ const view = compactApproval(request)
1243
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || view === undefined) return undefined
1244
+ const store = approvalStore(c)
1245
+ let calls = store.get(sessionId)
1246
+ if (calls === undefined) {
1247
+ calls = new Map()
1248
+ store.set(sessionId, calls)
1249
+ }
1250
+ if (calls.size >= MAX_APPROVAL_CALLS) return undefined
1251
+
1252
+ const id = randomUUID()
1253
+ let accept
1254
+ let refuse
1255
+ const answer = new Promise((resolve, reject) => {
1256
+ accept = resolve
1257
+ refuse = reject
1258
+ })
1259
+ const record = {
1260
+ id,
1261
+ sessionId,
1262
+ view,
1263
+ toolName: view.toolName,
1264
+ done: false,
1265
+ timer: undefined,
1266
+ idle: undefined,
1267
+ answer,
1268
+ finish(error, value) {
1269
+ if (record.done) return
1270
+ record.done = true
1271
+ clearTimeout(record.timer)
1272
+ clearInterval(record.idle)
1273
+ request.signal?.removeEventListener?.('abort', record.cancel)
1274
+ const current = store.get(sessionId)
1275
+ if (current?.get(id) === record) {
1276
+ current.delete(id)
1277
+ if (current.size === 0) store.delete(sessionId)
1278
+ }
1279
+ if (error === undefined) accept(value)
1280
+ else refuse(error)
1281
+ },
1282
+ cancel() {
1283
+ record.finish(undefined, 'cancelled')
1284
+ },
1285
+ }
1286
+ record.timer = setTimeout(() => {
1287
+ record.finish(handoffError())
1288
+ }, APPROVAL_WAIT_MS)
1289
+ record.timer?.unref?.()
1290
+ record.idle = setInterval(() => {
1291
+ if (!isLiteActive(c, sessionId)) record.finish(handoffError())
1292
+ }, 5_000)
1293
+ record.idle?.unref?.()
1294
+ calls.set(id, record)
1295
+ c.logger?.info?.(`dsh-lite: holding approval ${view.toolName} for ${sessionId}`)
1296
+ if (request.signal?.aborted === true) record.cancel()
1297
+ else request.signal?.addEventListener?.('abort', record.cancel, { once: true })
1298
+ return record
1299
+ }
1300
+
1301
+ function approvalStore(c) {
1302
+ let store = pendingApprovalStores.get(c)
1303
+ if (store === undefined) {
1304
+ store = new Map()
1305
+ pendingApprovalStores.set(c, store)
1306
+ }
1307
+ return store
1308
+ }
1309
+
1310
+ function pendingApprovalsFor(c, sessionId) {
1311
+ const calls = pendingApprovalStores.get(c)?.get(sessionId)
1312
+ if (calls === undefined) return []
1313
+ return [...calls.values()]
1314
+ .filter((record) => !record.done)
1315
+ .slice(0, MAX_APPROVAL_CALLS)
1316
+ .map((record) => ({ id: record.id, ...record.view }))
1317
+ }
1318
+
1319
+ function rejectPendingApprovals(c, outcome) {
1320
+ const store = pendingApprovalStores.get(c)
1321
+ if (store === undefined) return
1322
+ pendingApprovalStores.delete(c)
1323
+ for (const calls of store.values()) {
1324
+ for (const record of calls.values()) record.finish(undefined, outcome)
1325
+ }
1326
+ }
1327
+
1328
+ function compactApproval(value) {
1329
+ if (value === null || typeof value !== 'object') return undefined
1330
+ const toolName = typeof value.toolName === 'string' ? value.toolName.trim() : ''
1331
+ if (toolName.length === 0) return undefined
1332
+ const callId = stringField(value, 'callId')
1333
+ const reason = typeof value.reason === 'string' && value.reason.trim().length > 0
1334
+ ? truncateText(value.reason.trim(), MAX_APPROVAL_REASON_CHARS)
1335
+ : undefined
1336
+ const displayReason = compactDisplayReason(value.displayReason)
1337
+ return {
1338
+ toolName: truncateText(toolName, MAX_APPROVAL_TOOL_CHARS),
1339
+ ...callId === undefined ? {} : { callId: truncateText(callId, 200) },
1340
+ ...reason === undefined ? {} : { reason },
1341
+ ...displayReason === undefined ? {} : { displayReason },
1342
+ }
1343
+ }
1344
+
1345
+ function compactDisplayReason(value) {
1346
+ if (value === null || typeof value !== 'object') return undefined
1347
+ const en = typeof value.en === 'string' && value.en.trim().length > 0
1348
+ ? truncateText(value.en.trim(), MAX_APPROVAL_DISPLAY_CHARS)
1349
+ : undefined
1350
+ const zh = typeof value.zh === 'string' && value.zh.trim().length > 0
1351
+ ? truncateText(value.zh.trim(), MAX_APPROVAL_DISPLAY_CHARS)
1352
+ : undefined
1353
+ if (en === undefined && zh === undefined) return undefined
1354
+ return { ...en === undefined ? {} : { en }, ...zh === undefined ? {} : { zh } }
1355
+ }
1356
+
1357
+ function noProviderError() {
1358
+ return Object.assign(new Error('no answer surface can hold this question'), { code: 'NO_PROVIDER' })
1359
+ }
1360
+
1361
+ function questionTimeoutError() {
1362
+ return Object.assign(
1363
+ new Error(`dsh-lite: no answer arrived within ${String(QUESTION_FALLBACK_WAIT_MS / 60_000)} minutes`),
1364
+ { code: 'LITE_QUESTION_TIMEOUT' },
1365
+ )
1366
+ }
1367
+
1368
+ function handoffError() {
1369
+ return Object.assign(new Error('dsh-lite: handing the question back to the full page'), { code: 'LITE_HANDOFF' })
1370
+ }
1371
+
1372
+ function abortError(signal) {
1373
+ const reason = signal?.reason
1374
+ return reason instanceof Error ? reason : new Error('dsh-lite: the question was cancelled')
1375
+ }
1376
+
1377
+ function workspaceOf(c) {
1378
+ return c.get('workspaceController') ?? c.workspaceController
1379
+ }
1380
+
1381
+ function archivedIds(c) {
1382
+ const registry = c.get('workspaceRegistry') ?? c.workspaceRegistry
1383
+ const value = registry?.archivedSessionIds
1384
+ return Array.isArray(value) ? value : []
1385
+ }
1386
+
1387
+ function pinnedIds(c) {
1388
+ const registry = c.get('workspaceRegistry') ?? c.workspaceRegistry
1389
+ const value = registry?.pinnedSessionIds
1390
+ return Array.isArray(value) ? value : []
1391
+ }
1392
+
1393
+ function readWorkspaces(c) {
1394
+ const registry = c.get('workspaceRegistry') ?? c.workspaceRegistry
1395
+ if (typeof registry?.list !== 'function') return { list: [], bySession: new Map() }
1396
+ try {
1397
+ const list = registry.list()
1398
+ const bySession = new Map()
1399
+ for (const workspace of list) {
1400
+ // The registry entity exposes `id`; the wire `WorkspaceView` shape uses
1401
+ // `workspaceId`. Accept both so a host may hand us either projection.
1402
+ const identity = workspace.id ?? workspace.workspaceId
1403
+ if (identity === undefined || identity === null) continue
1404
+ const value = {
1405
+ id: String(identity),
1406
+ title: typeof workspace.title === 'string' && workspace.title.length > 0
1407
+ ? workspace.title
1408
+ : String(workspace.path),
1409
+ path: String(workspace.path),
1410
+ }
1411
+ for (const sessionId of Array.isArray(workspace.sessionIds) ? workspace.sessionIds : []) {
1412
+ bySession.set(String(sessionId), value)
1413
+ }
1414
+ }
1415
+ return { list, bySession }
1416
+ } catch {
1417
+ return { list: [], bySession: new Map() }
1418
+ }
1419
+ }
1420
+
1421
+ function workspaceList(c) {
1422
+ return readWorkspaces(c).list.slice(0, 50).flatMap((workspace) => {
1423
+ const identity = workspace.id ?? workspace.workspaceId
1424
+ if (identity === undefined || identity === null) return []
1425
+ return [{
1426
+ id: String(identity),
1427
+ title: typeof workspace.title === 'string' && workspace.title.length > 0 ? workspace.title : workspace.path,
1428
+ path: String(workspace.path),
1429
+ }]
1430
+ })
1431
+ }
1432
+
1433
+ async function buildSessionList(c, signal) {
1434
+ return collectSessionRows(c, signal, false)
1435
+ }
1436
+
1437
+ async function collectSessionRows(c, signal, archivedOnly, options = {}) {
1438
+ const records = await c.sessionQuery.listSessions(signal)
1439
+ const membership = readWorkspaces(c).bySession
1440
+ const cache = c.get('sessionProjectionCache')
1441
+ const projections = c.get('sessionProjections')
1442
+ const agents = c.get('agents')
1443
+ const archived = new Set(archivedIds(c))
1444
+ const pinned = new Set(archivedOnly ? [] : pinnedIds(c))
1445
+ const query = typeof options.query === 'string' ? options.query.trim().toLowerCase() : ''
1446
+ const rows = []
1447
+ for (const record of records) {
1448
+ const header = record.header
1449
+ if (header.origin === 'subagent') continue
1450
+ if (archived.has(header.id) !== archivedOnly) continue
1451
+ const agent = agents?.get(header.id)
1452
+ // Live sessions have in-memory projection cells; cold rows only have the
1453
+ // checkpoint cache. Neither path folds the log or reads events.
1454
+ const hint = (
1455
+ agent === undefined
1456
+ ? cache?.cachedSnapshot(header, LIST_HINT_KEYS)?.values
1457
+ : projections?.cachedSnapshot(agent.session, LIST_HINT_KEYS)?.values
1458
+ ) ?? {}
1459
+ const metadata = hint.sessionListMetadata
1460
+ // The active list hides auto-created blanks; an archived blank is still a
1461
+ // user action and must stay reachable through the archive tab.
1462
+ if (!archivedOnly && metadata?.blank === true && !record.live) continue
1463
+ const title = titleOf(header, hint)
1464
+ const cwd = header.cwd ?? null
1465
+ const workspace = membership.get(String(header.id))
1466
+ if (query.length > 0) {
1467
+ const haystack = `${title}\n${cwd ?? ''}\n${workspace?.title ?? ''}`.toLowerCase()
1468
+ if (!haystack.includes(query)) continue
1469
+ }
1470
+ const updatedAt = typeof metadata?.lastPromptAt === 'number' ? metadata.lastPromptAt : header.createdAt
1471
+ const createdAt = Number.isFinite(header.createdAt) ? header.createdAt : updatedAt
1472
+ const running = record.live && agent?.status === 'running'
1473
+ rows.push({
1474
+ id: header.id,
1475
+ title,
1476
+ updatedAt,
1477
+ createdAt,
1478
+ live: record.live,
1479
+ running,
1480
+ cwd,
1481
+ workspaceId: workspace?.id ?? null,
1482
+ ...workspace === undefined ? {} : { workspaceTitle: workspace.title },
1483
+ ...pinned.has(header.id) ? { pinned: true } : {},
1484
+ ...archivedOnly ? { archived: true } : {},
1485
+ })
1486
+ }
1487
+ rows.sort((left, right) => Number(right.pinned === true) - Number(left.pinned === true) || right.updatedAt - left.updatedAt)
1488
+ const total = rows.length
1489
+ const offset = Number.isSafeInteger(options.offset) && options.offset > 0 ? options.offset : 0
1490
+ return { rows: rows.slice(offset, offset + LIST_LIMIT), total, offset, limit: LIST_LIMIT }
1491
+ }
1492
+
1493
+ async function buildSessionState(c, id, signal, after) {
1494
+ const observation = await c.sessionQuery.observeSession(id, { signal, projectionMode: 'none' })
1495
+ try {
1496
+ const header = observation.header
1497
+ const agent = c.get('agents')?.get(id)
1498
+ const live = observation.source === 'live' || agent !== undefined
1499
+ const running = agent?.status === 'running'
1500
+ const cursor = observation.cursor
1501
+ const cache = c.get('sessionProjectionCache')
1502
+ const projections = c.get('sessionProjections')
1503
+ const hint = (
1504
+ agent === undefined
1505
+ ? cache?.cachedSnapshot(header, SESSION_HINT_KEYS)?.values
1506
+ : projections?.cachedSnapshot(agent.session, SESSION_HINT_KEYS)?.values
1507
+ ) ?? {}
1508
+ const selection = hint.modelSelection ?? null
1509
+ const catalog = await getCatalog(c)
1510
+ const model = normalizeSelection(selection) ?? catalog.default ?? null
1511
+
1512
+ const liveSession = live && agent?.session !== undefined ? agent.session : null
1513
+ const activity = running ? compactActivity(activityEvents(liveSession, cursor, observation.events)) : null
1514
+ let messages
1515
+ let reset = false
1516
+ let includePaging = false
1517
+ let historyCursor = null
1518
+ let historyHasMore = false
1519
+ let gap = false
1520
+ if (after !== undefined && after === cursor) {
1521
+ // Nothing new since the previous poll: only the small state payload moves.
1522
+ messages = []
1523
+ } else {
1524
+ const incremental = after !== undefined && after < cursor
1525
+ ? liveSession !== null
1526
+ ? incrementalFromLive(liveSession, cursor, after)
1527
+ : incrementalFromArray(observation.events, after)
1528
+ : null
1529
+ if (incremental !== null) {
1530
+ messages = incremental
1531
+ } else {
1532
+ const fresh = cursor < 0
1533
+ ? { messages: [], historyCursor: null, hasMore: false, gap: false }
1534
+ : liveSession !== null
1535
+ ? segmentFromLive(liveSession, cursor)
1536
+ : segmentFromArray(observation.events)
1537
+ messages = fresh.messages
1538
+ historyCursor = fresh.historyCursor
1539
+ historyHasMore = fresh.hasMore
1540
+ gap = fresh.gap
1541
+ includePaging = true
1542
+ reset = after !== undefined
1543
+ }
1544
+ }
1545
+
1546
+ const activeQuestions = Array.isArray(hint.userQuestions?.active) ? hint.userQuestions.active : []
1547
+ // A held blocking question does not exist in the projection: the host is
1548
+ // still inside the tool call. Expose it here so the Lite card can answer.
1549
+ const heldQuestions = live ? pendingQuestionsFor(c, id) : []
1550
+ const questions = mergeQuestions(compactQuestions(hint.userQuestions), heldQuestions)
1551
+ // Held approvals only exist while this Lite page is polling the session,
1552
+ // so they are answerable even if the observation itself looks cold.
1553
+ const heldApprovals = pendingApprovalsFor(c, id)
1554
+ const plan = compactPlan(hint.plan)
1555
+ return {
1556
+ id,
1557
+ title: titleOf(header, hint),
1558
+ cwd: header.cwd ?? null,
1559
+ live,
1560
+ archived: archivedIds(c).includes(id),
1561
+ pinned: pinnedIds(c).includes(id),
1562
+ running,
1563
+ ...activity === null ? {} : { activity },
1564
+ waiting: activeQuestions.length > 0 || heldQuestions.length > 0 || heldApprovals.length > 0,
1565
+ ...questions.length > 0 ? { questions } : {},
1566
+ ...heldApprovals.length > 0 ? { approval: heldApprovals } : {},
1567
+ model,
1568
+ plan,
1569
+ context: compactContext(hint.contextPressure),
1570
+ goal: compactGoal(hint.goal),
1571
+ messages,
1572
+ reset,
1573
+ ...includePaging ? { historyCursor, historyHasMore, gap } : {},
1574
+ queued: queueFromInbox(hint.inbox, running),
1575
+ cursor,
1576
+ updatedAt: typeof hint.sessionListMetadata?.lastPromptAt === 'number'
1577
+ ? hint.sessionListMetadata.lastPromptAt
1578
+ : header.createdAt,
1579
+ }
1580
+ } finally {
1581
+ observation[Symbol.dispose]?.()
1582
+ }
1583
+ }
1584
+
1585
+ async function buildInsights(c, id, signal) {
1586
+ const observation = await c.sessionQuery.observeSession(id, { signal, projectionMode: 'none' })
1587
+ try {
1588
+ const agent = c.get('agents')?.get(id)
1589
+ const projections = c.get('sessionProjections')
1590
+ const cache = c.get('sessionProjectionCache')
1591
+ const hint = (
1592
+ agent === undefined
1593
+ ? cache?.cachedSnapshot(observation.header, INSIGHT_HINT_KEYS)?.values
1594
+ : projections?.cachedSnapshot(agent.session, INSIGHT_HINT_KEYS)?.values
1595
+ ) ?? {}
1596
+ return {
1597
+ plan: compactPlan(hint.plan),
1598
+ context: compactContext(hint.contextPressure),
1599
+ usage: compactUsage(hint.tokenUsage),
1600
+ breakdown: compactBreakdown(hint.contextBreakdown),
1601
+ }
1602
+ } finally {
1603
+ observation[Symbol.dispose]?.()
1604
+ }
1605
+ }
1606
+
1607
+ function activityEvents(liveSession, cursor, events) {
1608
+ if (liveSession !== null && typeof liveSession.snapshotEvents === 'function' && cursor >= 0) {
1609
+ try {
1610
+ const end = cursor + 1
1611
+ const start = Math.max(0, end - ACTIVITY_SCAN_EVENTS)
1612
+ const slice = liveSession.snapshotEvents(start, end)
1613
+ if (Array.isArray(slice)) return slice
1614
+ } catch {
1615
+ // Fall through to the observation snapshot.
1616
+ }
1617
+ }
1618
+ return Array.isArray(events) ? events.slice(-ACTIVITY_SCAN_EVENTS) : []
1619
+ }
1620
+
1621
+ /**
1622
+ * One compact line for the running turn. It deliberately reads only turn/tool
1623
+ * boundary events: no arguments beyond a display target, no results, no trace.
1624
+ */
1625
+ function compactActivity(events) {
1626
+ if (!Array.isArray(events) || events.length === 0) return null
1627
+ const completed = new Set()
1628
+ const pending = []
1629
+ let turnStart = null
1630
+ for (let index = events.length - 1; index >= 0; index -= 1) {
1631
+ const event = eventOf(events[index])
1632
+ if (event === null || typeof event !== 'object') continue
1633
+ if (event.type === 'turn/end') return null
1634
+ if (event.type === 'turn/start') {
1635
+ turnStart = event
1636
+ break
1637
+ }
1638
+ if (event.type === 'tool/result') {
1639
+ const callId = event.data?.message?.toolCallId
1640
+ if (typeof callId === 'string') completed.add(callId)
1641
+ continue
1642
+ }
1643
+ if (event.type === 'tool/call') {
1644
+ const callId = event.data?.callId
1645
+ if (typeof callId === 'string' && !completed.has(callId)) pending.push(event)
1646
+ }
1647
+ }
1648
+ if (pending.length > 0) {
1649
+ const latest = pending[0]
1650
+ const data = latest.data ?? {}
1651
+ const name = typeof data.name === 'string' && data.name.length > 0
1652
+ ? truncateText(data.name, MAX_ACTIVITY_NAME_CHARS)
1653
+ : 'tool'
1654
+ const target = toolTarget(data.arguments)
1655
+ return {
1656
+ kind: 'tool',
1657
+ name,
1658
+ ...target === undefined ? {} : { target },
1659
+ startedAt: typeof latest.time === 'number' && Number.isFinite(latest.time) ? latest.time : null,
1660
+ count: pending.length,
1661
+ }
1662
+ }
1663
+ if (turnStart !== null) {
1664
+ return {
1665
+ kind: 'thinking',
1666
+ startedAt: typeof turnStart.time === 'number' && Number.isFinite(turnStart.time) ? turnStart.time : null,
1667
+ }
1668
+ }
1669
+ return null
1670
+ }
1671
+
1672
+ function toolTarget(argumentsText) {
1673
+ if (typeof argumentsText !== 'string' || argumentsText.length === 0 || argumentsText.length > 64_000) return undefined
1674
+ let value
1675
+ try {
1676
+ value = JSON.parse(argumentsText)
1677
+ } catch {
1678
+ return undefined
1679
+ }
1680
+ if (value === null || typeof value !== 'object') return undefined
1681
+ for (const key of ['command', 'path', 'file_path', 'pattern', 'url', 'query', 'prompt', 'name', 'description']) {
1682
+ const field = value[key]
1683
+ if (typeof field === 'string' && field.trim().length > 0) {
1684
+ return truncateText(field.trim().replace(/\s+/g, ' '), MAX_ACTIVITY_TARGET_CHARS)
1685
+ }
1686
+ }
1687
+ return undefined
1688
+ }
1689
+
1690
+ async function buildHistory(c, id, beforeSeq, signal) {
1691
+ const observation = await c.sessionQuery.observeSession(id, { signal, projectionMode: 'none' })
1692
+ try {
1693
+ const agent = c.get('agents')?.get(id)
1694
+ const live = observation.source === 'live' || agent !== undefined
1695
+ if (live && agent?.session !== undefined) {
1696
+ return collectFromLive(agent.session, observation.cursor, beforeSeq)
1697
+ }
1698
+ return collectFromArray(observation.events, beforeSeq)
1699
+ } finally {
1700
+ observation[Symbol.dispose]?.()
1701
+ }
1702
+ }
1703
+
1704
+ async function getCatalog(c, force = false) {
1705
+ if (!force && catalogCache.value !== undefined && Date.now() - catalogCache.at < catalogCache.ttl) return catalogCache.value
1706
+ try {
1707
+ const value = compactCatalog(await c.sessionController.modelCatalog())
1708
+ catalogCache = { at: Date.now(), value, ttl: CATALOG_TTL_MS }
1709
+ return value
1710
+ } catch (error) {
1711
+ // A transient catalog failure must not poison the list for the whole TTL;
1712
+ // keep the empty fallback for a short backoff so polls do not hammer it.
1713
+ c.logger?.warn?.(`dsh-lite: model catalog failed: ${String(error)}`)
1714
+ const value = { default: null, groups: [] }
1715
+ catalogCache = { at: Date.now(), value, ttl: CATALOG_FAILURE_TTL_MS }
1716
+ return value
1717
+ }
1718
+ }
1719
+
1720
+ function compactCatalog(catalog) {
1721
+ const groups = Array.isArray(catalog?.groups)
1722
+ ? catalog.groups.map((group) => ({
1723
+ id: group.id,
1724
+ name: group.name,
1725
+ models: Array.isArray(group.models)
1726
+ ? group.models.map((model) => ({
1727
+ id: model.id,
1728
+ name: model.name,
1729
+ ...model.reasoning === undefined
1730
+ ? {}
1731
+ : {
1732
+ reasoning: {
1733
+ efforts: model.reasoning.efforts.map((effort) => ({ id: effort.id, name: effort.name })),
1734
+ ...model.reasoning.defaultEffort === undefined ? {} : { defaultEffort: model.reasoning.defaultEffort },
1735
+ },
1736
+ },
1737
+ }))
1738
+ : [],
1739
+ }))
1740
+ : []
1741
+ return {
1742
+ default: normalizeSelection(catalog?.default) ?? null,
1743
+ groups,
1744
+ }
1745
+ }
1746
+
1747
+ function normalizeSelection(value) {
1748
+ if (value === null || typeof value !== 'object') return null
1749
+ const selection = value.next ?? value.pending ?? value.lastUsed ?? value
1750
+ if (selection === null || typeof selection !== 'object') return null
1751
+ if (typeof selection.provider !== 'string' || typeof selection.model !== 'string') return null
1752
+ return {
1753
+ provider: selection.provider,
1754
+ model: selection.model,
1755
+ ...typeof selection.reasoningEffort === 'string' ? { reasoningEffort: selection.reasoningEffort } : {},
1756
+ }
1757
+ }
1758
+
1759
+ function titleOf(header, hint) {
1760
+ const title = typeof hint?.title === 'string' ? hint.title.trim() : ''
1761
+ if (title.length > 0) return title
1762
+ const cwd = header?.cwd
1763
+ if (typeof cwd === 'string' && cwd.length > 0) {
1764
+ const base = basename(cwd)
1765
+ if (base.length > 0) return base
1766
+ }
1767
+ const id = typeof header?.id === 'string' ? header.id : ''
1768
+ return id.length > 8 ? `…${id.slice(-8)}` : id
1769
+ }
1770
+
1771
+ function textFromContent(content) {
1772
+ if (typeof content === 'string') return content
1773
+ if (!Array.isArray(content)) return ''
1774
+ let text = ''
1775
+ for (const block of content) {
1776
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') text += block.text
1777
+ }
1778
+ return text
1779
+ }
1780
+
1781
+ function eventOf(entry) {
1782
+ if (entry === null || typeof entry !== 'object') return null
1783
+ if (entry.type === 'event' && entry.event !== null && typeof entry.event === 'object') return entry.event
1784
+ return entry
1785
+ }
1786
+
1787
+ function messageText(event) {
1788
+ return textFromContent(event.data?.message?.content ?? event.data?.content)
1789
+ }
1790
+
1791
+ function isHumanPrompt(event) {
1792
+ return event?.type === 'user/message' && event.data?.source?.kind === 'user' && messageText(event).trim().length > 0
1793
+ }
1794
+
1795
+ /** One rendered conversation item, including command results and failures. */
1796
+ function visibleMessageAt(event) {
1797
+ if (event === null || typeof event !== 'object') return null
1798
+ const base = {
1799
+ time: typeof event.time === 'number' ? event.time : null,
1800
+ seq: typeof event.seq === 'number' ? event.seq : null,
1801
+ }
1802
+ if (event.type === 'user/message') {
1803
+ if (event.data?.source?.kind !== 'user') return null
1804
+ const text = messageText(event).trim()
1805
+ return text.length === 0 ? null : { role: 'user', text: clipText(text), ...base }
1806
+ }
1807
+ if (event.type === 'assistant/message') {
1808
+ const text = messageText(event).trim()
1809
+ return text.length === 0 ? null : { role: 'assistant', text: clipText(text), ...base }
1810
+ }
1811
+ if (event.type === 'command/run') {
1812
+ const name = typeof event.data?.name === 'string' ? event.data.name : ''
1813
+ if (name.length === 0) return null
1814
+ const args = typeof event.data?.args === 'string' ? event.data.args.trim() : ''
1815
+ return { role: 'command', text: `/${name}${args.length > 0 ? ` ${args}` : ''}`, ...base }
1816
+ }
1817
+ if (event.type === 'command/done') {
1818
+ const failed = event.data?.kind === 'error'
1819
+ const text = typeof event.data?.text === 'string' ? event.data.text.trim() : ''
1820
+ return {
1821
+ role: failed ? 'error' : 'system',
1822
+ text: clipText(text.length > 0 ? text : failed ? '指令执行失败' : '指令已完成'),
1823
+ ...base,
1824
+ }
1825
+ }
1826
+ if (event.type === 'turn/end' && event.data?.reason?.kind === 'error') {
1827
+ const failure = event.data.reason.error ?? {}
1828
+ const message = typeof failure.message === 'string' ? failure.message : '模型调用失败'
1829
+ const code = typeof failure.code === 'string' && failure.code !== 'UNKNOWN' ? ` (${failure.code})` : ''
1830
+ return { role: 'error', text: clipText(`模型调用失败${code}:${message}`), ...base }
1831
+ }
1832
+ if (event.type === 'compaction/end' && typeof event.data?.error === 'string' && event.data.error.trim().length > 0) {
1833
+ return { role: 'error', text: clipText(`上下文压缩失败:${event.data.error.trim()}`), ...base }
1834
+ }
1835
+ return null
1836
+ }
1837
+
1838
+ function assembleSegment(recent, human) {
1839
+ let messages = recent
1840
+ let gap = false
1841
+ if (human !== null && !recent.includes(human)) {
1842
+ messages = [human, ...recent]
1843
+ gap = true
1844
+ }
1845
+ const oldest = recent.find((message) => typeof message.seq === 'number')
1846
+ const historyCursor = oldest?.seq ?? human?.seq ?? null
1847
+ return {
1848
+ messages,
1849
+ historyCursor,
1850
+ hasMore: typeof historyCursor === 'number' && historyCursor > 0,
1851
+ gap,
1852
+ }
1853
+ }
1854
+
1855
+ /**
1856
+ * The opening segment: the newest visible messages and the last human prompt.
1857
+ * The history cursor points at the oldest of the newest window, not at the
1858
+ * human prompt, so paging back fills any gap instead of skipping it.
1859
+ */
1860
+ function segmentFromArray(events) {
1861
+ if (!Array.isArray(events)) return { messages: [], historyCursor: null, hasMore: false, gap: false }
1862
+ let human = null
1863
+ let humanEvent = null
1864
+ for (let index = events.length - 1; index >= 0; index -= 1) {
1865
+ const event = eventOf(events[index])
1866
+ if (isHumanPrompt(event)) {
1867
+ humanEvent = event
1868
+ human = visibleMessageAt(event)
1869
+ break
1870
+ }
1871
+ }
1872
+ const recent = []
1873
+ const floor = human === null ? null : human.seq
1874
+ for (let index = events.length - 1; index >= 0; index -= 1) {
1875
+ const event = eventOf(events[index])
1876
+ if (floor !== null && typeof event.seq === 'number' && event.seq < floor) break
1877
+ // Reuse the already-rendered human item so the segment does not duplicate it.
1878
+ const message = event === humanEvent && human !== null ? human : visibleMessageAt(event)
1879
+ if (message === null) continue
1880
+ if (recent.length >= SEGMENT_LIMIT) break
1881
+ recent.push(message)
1882
+ }
1883
+ recent.reverse()
1884
+ return assembleSegment(recent, human)
1885
+ }
1886
+
1887
+ /** Live variant of {@link segmentFromArray}, reading bounded slices of the log. */
1888
+ function segmentFromLive(session, cursor) {
1889
+ const recent = []
1890
+ let human = null
1891
+ let end = cursor + 1
1892
+ while (end > 0 && human === null) {
1893
+ const start = Math.max(0, end - HISTORY_CHUNK)
1894
+ const slice = session.snapshotEvents(start, end)
1895
+ for (let index = slice.length - 1; index >= 0; index -= 1) {
1896
+ const event = eventOf(slice[index])
1897
+ if (isHumanPrompt(event)) {
1898
+ human = visibleMessageAt(event)
1899
+ if (human !== null && recent.length < SEGMENT_LIMIT) recent.push(human)
1900
+ break
1901
+ }
1902
+ const message = visibleMessageAt(event)
1903
+ if (message === null) continue
1904
+ if (recent.length < SEGMENT_LIMIT) recent.push(message)
1905
+ }
1906
+ end = start
1907
+ }
1908
+ recent.reverse()
1909
+ return assembleSegment(recent, human)
1910
+ }
1911
+
1912
+ function collectFromArray(events, beforeSeq) {
1913
+ const messages = []
1914
+ let hasMore = false
1915
+ const upper = typeof beforeSeq === 'number' ? beforeSeq : Infinity
1916
+ for (let index = events.length - 1; index >= 0; index -= 1) {
1917
+ const message = visibleMessageAt(eventOf(events[index]))
1918
+ if (message === null) continue
1919
+ if (typeof message.seq === 'number' && message.seq >= upper) continue
1920
+ if (messages.length === HISTORY_LIMIT) {
1921
+ hasMore = true
1922
+ break
1923
+ }
1924
+ messages.push(message)
1925
+ }
1926
+ messages.reverse()
1927
+ return {
1928
+ messages,
1929
+ nextBeforeSeq: messages.length > 0 ? messages[0].seq : null,
1930
+ hasMore: hasMore && messages.length > 0,
1931
+ }
1932
+ }
1933
+
1934
+ function collectFromLive(session, cursor, beforeSeq) {
1935
+ const upper = typeof beforeSeq === 'number' ? beforeSeq : cursor + 1
1936
+ let end = Math.min(cursor + 1, upper)
1937
+ const messages = []
1938
+ let hasMore = false
1939
+ while (end > 0 && !hasMore) {
1940
+ const start = Math.max(0, end - HISTORY_CHUNK)
1941
+ const slice = session.snapshotEvents(start, end)
1942
+ for (let index = slice.length - 1; index >= 0; index -= 1) {
1943
+ const message = visibleMessageAt(eventOf(slice[index]))
1944
+ if (message === null) continue
1945
+ if (typeof message.seq === 'number' && message.seq >= upper) continue
1946
+ if (messages.length === HISTORY_LIMIT) {
1947
+ hasMore = true
1948
+ break
1949
+ }
1950
+ messages.push(message)
1951
+ }
1952
+ end = start
1953
+ }
1954
+ messages.reverse()
1955
+ return {
1956
+ messages,
1957
+ nextBeforeSeq: messages.length > 0 ? messages[0].seq : null,
1958
+ hasMore: hasMore && messages.length > 0,
1959
+ }
1960
+ }
1961
+
1962
+ /**
1963
+ * Messages newer than the client's cursor. Returns null when the backlog is too
1964
+ * large to stream safely; the caller then falls back to a fresh segment.
1965
+ */
1966
+ function collectIncremental(count, read, after) {
1967
+ const messages = []
1968
+ let chars = 0
1969
+ let end = count
1970
+ while (end > 0) {
1971
+ const start = Math.max(0, end - HISTORY_CHUNK)
1972
+ const slice = read(start, end)
1973
+ for (let index = slice.length - 1; index >= 0; index -= 1) {
1974
+ const event = eventOf(slice[index])
1975
+ if (typeof event.seq === 'number' && event.seq <= after) {
1976
+ messages.reverse()
1977
+ return messages
1978
+ }
1979
+ const message = visibleMessageAt(event)
1980
+ if (message === null) continue
1981
+ if (messages.length >= INCREMENTAL_LIMIT || chars + message.text.length > INCREMENTAL_CHARS) return null
1982
+ chars += message.text.length
1983
+ messages.push(message)
1984
+ }
1985
+ end = start
1986
+ }
1987
+ messages.reverse()
1988
+ return messages
1989
+ }
1990
+
1991
+ function incrementalFromArray(events, after) {
1992
+ if (!Array.isArray(events)) return []
1993
+ return collectIncremental(events.length, (start, end) => events.slice(start, end), after)
1994
+ }
1995
+
1996
+ function incrementalFromLive(session, cursor, after) {
1997
+ return collectIncremental(cursor + 1, (start, end) => session.snapshotEvents(start, end), after)
1998
+ }
1999
+
2000
+ function queueFromInbox(inbox, running) {
2001
+ const rows = []
2002
+ if (inbox === null || typeof inbox !== 'object') return rows
2003
+ for (const target of ['next-turn', 'next-step']) {
2004
+ const list = Array.isArray(inbox[target]) ? inbox[target] : []
2005
+ for (const item of list) {
2006
+ if (item === null || typeof item !== 'object') continue
2007
+ if (item.source?.kind !== 'user') continue
2008
+ if (typeof item.id !== 'string' || item.id.length === 0) continue
2009
+ const text = textFromContent(item.content).trim()
2010
+ if (text.length === 0) continue
2011
+ rows.push({
2012
+ id: item.id,
2013
+ text: clipText(text, MAX_QUEUE_TEXT),
2014
+ target,
2015
+ steerable: target === 'next-turn' && running === true,
2016
+ editable: !Array.isArray(item.content) || item.content.every((block) => block?.type === 'text'),
2017
+ })
2018
+ }
2019
+ }
2020
+ return rows
2021
+ }
2022
+
2023
+ /**
2024
+ * Read the preset roster for the "new session" picker. The registry is
2025
+ * optional, so a profile without presets simply reports an empty roster.
2026
+ */
2027
+ async function getPresets(c) {
2028
+ const registry = c.get('agentPresets')
2029
+ if (registry === undefined) return []
2030
+ try {
2031
+ const value = typeof registry.remoteExportList === 'function'
2032
+ ? await registry.remoteExportList()
2033
+ : { presets: await registry.list() }
2034
+ return (Array.isArray(value?.presets) ? value.presets : []).map((preset) => ({
2035
+ id: preset.id,
2036
+ name: typeof preset.name === 'string' && preset.name.length > 0 ? preset.name : preset.id,
2037
+ ...typeof preset.description === 'string' && preset.description.length > 0 ? { description: preset.description } : {},
2038
+ ...preset.isDefault === true ? { isDefault: true } : {},
2039
+ ...typeof preset.broken === 'string' && preset.broken.length > 0 ? { broken: preset.broken } : {},
2040
+ }))
2041
+ } catch (error) {
2042
+ c.logger?.warn?.(`dsh-lite: preset roster failed: ${String(error)}`)
2043
+ return []
2044
+ }
2045
+ }
2046
+
2047
+ /** Prompt-side context occupancy for the header meter. */
2048
+ function compactContext(pressure) {
2049
+ if (pressure === null || typeof pressure !== 'object') return null
2050
+ const used = typeof pressure.projectedTokens === 'number'
2051
+ ? pressure.projectedTokens
2052
+ : typeof pressure.pressureTokens === 'number'
2053
+ ? pressure.pressureTokens
2054
+ : undefined
2055
+ const window = typeof pressure.contextWindow === 'number' && pressure.contextWindow > 0
2056
+ ? pressure.contextWindow
2057
+ : undefined
2058
+ if (used === undefined || window === undefined) return null
2059
+ const tokens = Math.max(0, Math.round(used))
2060
+ return {
2061
+ used: tokens,
2062
+ window: Math.round(window),
2063
+ percent: Math.min(100, Math.round((tokens / window) * 100)),
2064
+ }
2065
+ }
2066
+
2067
+ /** Plan-mode badge state; absence when plan mode is composed but inactive. */
2068
+ function compactPlan(value) {
2069
+ if (value === null || typeof value !== 'object') return null
2070
+ const active = value.active === true
2071
+ const pending = value.pending === true
2072
+ || (value.wanted !== undefined && value.wanted !== null)
2073
+ || (value.running !== undefined && value.running !== null)
2074
+ if (!active && !pending) return null
2075
+ return { active, pending }
2076
+ }
2077
+
2078
+ function tokenCount(value) {
2079
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.round(value) : 0
2080
+ }
2081
+
2082
+ /** Durable provider usage totals for the on-demand insights dialog. */
2083
+ function compactUsage(value) {
2084
+ if (value === null || typeof value !== 'object') return null
2085
+ const totals = value.totals !== null && typeof value.totals === 'object' ? value.totals : value
2086
+ const fields = ['uncachedInputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens']
2087
+ if (!fields.some((field) => typeof totals[field] === 'number')) return null
2088
+ return {
2089
+ input: tokenCount(totals.uncachedInputTokens),
2090
+ output: tokenCount(totals.outputTokens),
2091
+ cacheRead: tokenCount(totals.cacheReadTokens),
2092
+ cacheWrite: tokenCount(totals.cacheWriteTokens),
2093
+ }
2094
+ }
2095
+
2096
+ /** Heuristic composition of the next prompt: system, tool schemas, messages. */
2097
+ function compactBreakdown(value) {
2098
+ if (value === null || typeof value !== 'object') return null
2099
+ const source = value.breakdown !== null && typeof value.breakdown === 'object' ? value.breakdown : value
2100
+ const fields = ['systemTokens', 'toolsTokens', 'messageTokens']
2101
+ if (!fields.some((field) => typeof source[field] === 'number')) return null
2102
+ return {
2103
+ system: tokenCount(source.systemTokens),
2104
+ tools: tokenCount(source.toolsTokens),
2105
+ messages: tokenCount(source.messageTokens),
2106
+ }
2107
+ }
2108
+
2109
+ function compactGoal(value) {
2110
+ const goal = value?.goal
2111
+ if (goal === null || typeof goal !== 'object' || typeof goal.objective !== 'string') return null
2112
+ const objective = goal.objective.trim()
2113
+ if (objective.length === 0) return null
2114
+ const blocked = goal.blockedReason
2115
+ const blockedReason = typeof blocked === 'string'
2116
+ ? blocked
2117
+ : blocked !== null && typeof blocked === 'object' && typeof blocked.message === 'string'
2118
+ ? blocked.message
2119
+ : undefined
2120
+ return {
2121
+ id: typeof goal.id === 'string' ? goal.id : null,
2122
+ objective: clipText(objective, MAX_GOAL_CHARS),
2123
+ phase: typeof goal.phase === 'string' ? goal.phase : null,
2124
+ roundsStarted: typeof value.roundsStarted === 'number' ? value.roundsStarted : null,
2125
+ maxGoalRounds: typeof goal.maxGoalRounds === 'number' ? goal.maxGoalRounds : null,
2126
+ ...blockedReason === undefined || blockedReason.trim().length === 0 ? {} : { blockedReason: clipText(blockedReason.trim(), 500) },
2127
+ }
2128
+ }
2129
+
2130
+ function compactQuestions(value) {
2131
+ const active = Array.isArray(value?.active) ? value.active : []
2132
+ const calls = []
2133
+ for (const call of active) {
2134
+ if (call === null || typeof call !== 'object') continue
2135
+ const callId = typeof call.callId === 'string' ? call.callId : ''
2136
+ if (callId.length === 0) continue
2137
+ // The answer batch must name every question exactly once; a call larger
2138
+ // than the batch cap is left to the full page instead of showing a card
2139
+ // that can never submit.
2140
+ if (Array.isArray(call.questions) && call.questions.length > MAX_ANSWERS) continue
2141
+ const rows = compactQuestionRows(call.questions)
2142
+ if (rows.length === 0) continue
2143
+ calls.push({ callId, state: call.state === 'continued' ? 'continued' : 'open', questions: rows })
2144
+ if (calls.length >= MAX_QUESTION_CALLS) break
2145
+ }
2146
+ return calls
2147
+ }
2148
+
2149
+ function compactQuestionRows(questions) {
2150
+ const rows = []
2151
+ for (const question of Array.isArray(questions) ? questions : []) {
2152
+ if (question === null || typeof question !== 'object') continue
2153
+ const id = typeof question.id === 'string' ? question.id : ''
2154
+ const text = typeof question.question === 'string' ? question.question.trim() : ''
2155
+ if (id.length === 0 || text.length === 0) continue
2156
+ const options = []
2157
+ for (const option of Array.isArray(question.options) ? question.options : []) {
2158
+ if (option === null || typeof option !== 'object') continue
2159
+ const label = typeof option.label === 'string' ? option.label.trim() : ''
2160
+ if (label.length === 0) continue
2161
+ options.push({
2162
+ label: clipText(label, 120),
2163
+ ...typeof option.description === 'string' && option.description.trim().length > 0
2164
+ ? { description: clipText(option.description.trim(), 240) }
2165
+ : {},
2166
+ })
2167
+ if (options.length >= MAX_QUESTION_OPTIONS) break
2168
+ }
2169
+ rows.push({
2170
+ id,
2171
+ question: clipText(text, MAX_QUESTION_TEXT_CHARS),
2172
+ ...typeof question.header === 'string' && question.header.trim().length > 0
2173
+ ? { header: clipText(question.header.trim(), 80) }
2174
+ : {},
2175
+ ...typeof question.detail === 'string' && question.detail.trim().length > 0
2176
+ ? { detail: clipText(question.detail.trim(), MAX_QUESTION_DETAIL_CHARS) }
2177
+ : {},
2178
+ ...options.length > 0 ? { options } : {},
2179
+ ...question.multiSelect === true ? { multiSelect: true } : {},
2180
+ })
2181
+ if (rows.length >= MAX_ANSWERS) break
2182
+ }
2183
+ return rows
2184
+ }
2185
+
2186
+ /** Held calls come first: they are the ones the agent is blocked on. */
2187
+ function mergeQuestions(base, held) {
2188
+ if (held.length === 0) return base
2189
+ const seen = new Set(held.map((call) => call.callId))
2190
+ return [...held, ...base.filter((call) => !seen.has(call.callId))].slice(0, MAX_QUESTION_CALLS)
2191
+ }
2192
+
2193
+ function clipText(text, max = MAX_MESSAGE_CHARS) {
2194
+ if (text.length <= max) return text
2195
+ return `${text.slice(0, max)}\n\n…(已截断,完整内容请在完整页面查看)`
2196
+ }
2197
+
2198
+ function truncateText(text, max) {
2199
+ return text.length <= max ? text : `${text.slice(0, max)}…`
2200
+ }
2201
+
2202
+ function stringField(value, key) {
2203
+ if (value === null || typeof value !== 'object') return undefined
2204
+ const field = value[key]
2205
+ return typeof field === 'string' && field.length > 0 ? field : undefined
2206
+ }
2207
+
2208
+ async function readJson(request) {
2209
+ try {
2210
+ const value = await request.json()
2211
+ return value !== null && typeof value === 'object' ? value : null
2212
+ } catch {
2213
+ return null
2214
+ }
2215
+ }
2216
+
2217
+ function jsonResponse(payload, status = 200) {
2218
+ return new Response(JSON.stringify(payload), {
2219
+ status,
2220
+ headers: {
2221
+ 'content-type': 'application/json; charset=utf-8',
2222
+ 'cache-control': 'no-store',
2223
+ },
2224
+ })
2225
+ }
2226
+
2227
+ function errorResponse(c, operation, error) {
2228
+ const code = error !== null && typeof error === 'object' && typeof error.code === 'string'
2229
+ ? error.code
2230
+ : 'lite/internal'
2231
+ const message = error instanceof Error
2232
+ ? error.message
2233
+ : error !== null && typeof error === 'object' && typeof error.message === 'string'
2234
+ ? error.message
2235
+ : String(error)
2236
+ c.logger?.warn?.(`dsh-lite: ${operation} failed (${code}): ${message}`)
2237
+ return jsonResponse({ ok: false, error: { code, message } })
2238
+ }
2239
+
2240
+ export {
2241
+ clipText,
2242
+ collectFromArray,
2243
+ collectFromLive,
2244
+ compactActivity,
2245
+ compactApproval,
2246
+ compactBreakdown,
2247
+ compactCatalog,
2248
+ compactContext,
2249
+ compactGoal,
2250
+ compactPlan,
2251
+ compactQuestions,
2252
+ compactUsage,
2253
+ isHumanPrompt,
2254
+ normalizeSelection,
2255
+ queueFromInbox,
2256
+ segmentFromArray,
2257
+ segmentFromLive,
2258
+ textFromContent,
2259
+ titleOf,
2260
+ visibleMessageAt,
2261
+ }