@soffits/dsh-plugin-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,540 @@
1
+ /**
2
+ * Subagent activity in chats.
3
+ *
4
+ * Each chat (a Telegram topic, a Matrix room) has at most one status card listing the subagents its session
5
+ * started (description, model, elapsed time), across turns: a subagent
6
+ * started while the card still shows running ones joins it. The card is
7
+ * edited in place as they start and finish; changes that land close together
8
+ * share one edit, and a running card is refreshed once a minute so its times
9
+ * move. On a network whose message ids grow (Telegram), the card stays the
10
+ * last message of the chat while anything runs: a pin sits at the top, so
11
+ * when any message lands below the card it is sent again, silently, and the
12
+ * old copy deleted (the usual "sticky message" approach of chat bots). A
13
+ * bridge that never reports messages (`noteMessage`) gets a card edited in
14
+ * place. Once every subagent on it is
15
+ * done the card is left where it is as the final state; the next subagent
16
+ * opens a new one. Subagents started by subagents are listed under their
17
+ * parent, in the chat of the session at the top of the chain.
18
+ *
19
+ * `/agents` lists a session's subagents from DSH's durable catalogs, so it
20
+ * also works after a restart.
21
+ *
22
+ * Texts take the bridge's translator `tr(en, ru)`; English is the default.
23
+ */
24
+ import { messageAnswer } from './answer.js'
25
+
26
+ /** Pause that lets several starts or ends share one edit. */
27
+ const EDIT_DELAY_MS = 1500
28
+ /** How often a board with running subagents is refreshed for its times. */
29
+ const TICK_MS = 60_000
30
+ /** Parent links followed from a subagent up to a bound session. */
31
+ const MAX_DEPTH = 8
32
+ /** Subagents `/agents` lists at most, running ones first. */
33
+ const LIST_LIMIT = 8
34
+ /** Lines a status message shows at most; older finished lines are folded. */
35
+ const MAX_LINES = 25
36
+ /** Longest description shown on a line. */
37
+ const LABEL_MAX = 60
38
+ /** Longest report preview `/agents` shows per subagent. */
39
+ const REPORT_MAX = 240
40
+
41
+ /** @returns the text cut to `max` characters with an ellipsis. */
42
+ function clip(text, max) {
43
+ const value = String(text ?? '')
44
+ return value.length <= max ? value : `${value.slice(0, Math.max(0, max - 1)).trimEnd()}…`
45
+ }
46
+
47
+ /**
48
+ * Format a duration. Running times are shown in whole minutes, so a board
49
+ * refreshed once a minute stays accurate; finished times also show seconds.
50
+ * @param ms - duration in milliseconds.
51
+ * @param precise - include seconds.
52
+ */
53
+ export function formatElapsed(ms, precise) {
54
+ const seconds = Math.max(0, Math.floor(ms / 1000))
55
+ const minutes = Math.floor(seconds / 60)
56
+ const hours = Math.floor(minutes / 60)
57
+ if (hours > 0) return `${hours}h ${minutes % 60}m`
58
+ if (!precise) return minutes < 1 ? '<1m' : `${minutes}m`
59
+ if (minutes < 1) return `${seconds}s`
60
+ return `${minutes}m ${seconds % 60}s`
61
+ }
62
+
63
+ /** @returns true when a finished run did not complete normally. */
64
+ function failed(stopReason) {
65
+ return stopReason !== undefined && stopReason !== 'completed'
66
+ }
67
+
68
+ /** @returns the reason text for a failed run (`max_tokens` → `max tokens`). */
69
+ function reasonText(stopReason) {
70
+ return String(stopReason).replace(/[_-]+/gu, ' ')
71
+ }
72
+
73
+ /**
74
+ * The status text of one board.
75
+ * @param entries - `{ label, model, depth, startedAt, endedAt, stopReason }` in start order.
76
+ * @param now - current time in ms.
77
+ * @param tr - `(en, ru) => text` for the bot language.
78
+ */
79
+ export function boardText(entries, now, tr = (en) => en) {
80
+ const running = entries.filter((entry) => entry.endedAt === undefined).length
81
+ const failures = entries.filter((entry) => entry.endedAt !== undefined && failed(entry.stopReason)).length
82
+ const total = entries.length
83
+ const noun = tr(total === 1 ? 'subagent' : 'subagents', 'субагент(ов)')
84
+ let head
85
+ if (running > 0) head = `🤖 ${total} ${noun} · ${running} ${tr('running', 'работают')}`
86
+ else if (failures > 0) head = `🤖 ${total} ${noun} · ${tr('done', 'готово')}, ${failures} ${tr('failed', 'с ошибкой')}`
87
+ else head = `🤖 ${total} ${noun} · ${tr('all done', 'все готовы')}`
88
+ const lines = entries.map((entry) => {
89
+ const indent = entry.depth > 1 ? `${' '.repeat(entry.depth - 2)}↳ ` : ''
90
+ const parts = [clip(entry.label, LABEL_MAX)]
91
+ if (entry.model) parts.push(entry.model)
92
+ if (entry.endedAt === undefined) {
93
+ parts.push(formatElapsed(now - entry.startedAt, false))
94
+ return `${indent}⏳ ${parts.join(' · ')}`
95
+ }
96
+ parts.push(formatElapsed(entry.endedAt - entry.startedAt, true))
97
+ if (failed(entry.stopReason)) parts.push(reasonText(entry.stopReason))
98
+ return `${indent}${failed(entry.stopReason) ? '✗' : '✓'} ${parts.join(' · ')}`
99
+ })
100
+ if (lines.length > MAX_LINES) {
101
+ // Keep running lines and the newest ones; fold the oldest finished lines.
102
+ const keep = new Set()
103
+ entries.forEach((entry, index) => { if (entry.endedAt === undefined) keep.add(index) })
104
+ for (let index = entries.length - 1; index >= 0 && keep.size < MAX_LINES - 1; index -= 1) keep.add(index)
105
+ const folded = lines.length - keep.size
106
+ const shown = lines.filter((_line, index) => keep.has(index))
107
+ return [head, `… ${folded} ${tr('earlier finished', 'завершённых ранее')}`, ...shown].join('\n')
108
+ }
109
+ return [head, ...lines].join('\n')
110
+ }
111
+
112
+ /** @returns whether a tool name is the subagent reporting tool (`send_message`, maybe prefixed). */
113
+ function isReportTool(name) {
114
+ return typeof name === 'string' && (name === 'send_message' || name.endsWith('__send_message'))
115
+ }
116
+
117
+ /** @returns the `message` argument of a tool call, or ''. */
118
+ function reportArgument(block) {
119
+ let args = block?.arguments ?? block?.input
120
+ if (typeof args === 'string') {
121
+ try {
122
+ args = JSON.parse(args)
123
+ } catch {
124
+ return ''
125
+ }
126
+ }
127
+ return typeof args?.message === 'string' ? args.message.trim() : ''
128
+ }
129
+
130
+ /**
131
+ * The latest report a subagent left: a message it sent its parent, or the
132
+ * answer of its last tool-free message, whichever is newer.
133
+ * @param events - the child's session events (`{ type, data }`).
134
+ * @returns the report text, or ''.
135
+ */
136
+ export function reportOf(events) {
137
+ if (!Array.isArray(events)) return ''
138
+ for (let index = events.length - 1; index >= 0; index -= 1) {
139
+ const event = events[index]
140
+ if (event?.type !== 'assistant/message') continue
141
+ const message = event.data?.message ?? event.data
142
+ const content = Array.isArray(message?.content) ? message.content : []
143
+ for (let block = content.length - 1; block >= 0; block -= 1) {
144
+ const item = content[block]
145
+ if (item?.type === 'tool-call' && isReportTool(item.name)) {
146
+ const text = reportArgument(item)
147
+ if (text.length > 0) return text
148
+ }
149
+ }
150
+ const answer = messageAnswer(message)
151
+ if (answer.length > 0) return answer
152
+ }
153
+ return ''
154
+ }
155
+
156
+ /**
157
+ * State of one listed subagent, from its live agent and durable timing.
158
+ * @param facts - `{ status, timing }`: live agent status (or undefined when not loaded) and the `subagentTiming` view.
159
+ * @param now - current time in ms.
160
+ * @returns `{ state, elapsedMs }`; state is running, done, failed, interrupted or idle.
161
+ */
162
+ export function childState({ status, timing }, now) {
163
+ const settled = Number.isFinite(timing?.settledMs) ? timing.settledMs : 0
164
+ const active = timing?.active
165
+ if (status === 'running') {
166
+ return { state: 'running', elapsedMs: active === undefined ? settled : settled + Math.max(0, now - active.since) }
167
+ }
168
+ if (active !== undefined) {
169
+ // A turn left open with no live agent was cut off, usually by a restart.
170
+ return { state: status === undefined ? 'interrupted' : 'running', elapsedMs: settled + Math.max(0, (status === undefined ? active.through : now) - active.since) }
171
+ }
172
+ if (timing?.lastTurnCompleted === false) return { state: 'failed', elapsedMs: settled }
173
+ if (timing?.lastTurnCompleted === true) return { state: 'done', elapsedMs: settled }
174
+ return { state: 'idle', elapsedMs: settled }
175
+ }
176
+
177
+ /** @returns relative age such as `5m ago`. */
178
+ function ageText(createdAt, now, tr = (en) => en) {
179
+ if (!Number.isFinite(createdAt)) return ''
180
+ const minutes = Math.max(0, Math.floor((now - createdAt) / 60_000))
181
+ if (minutes < 1) return tr('just now', 'только что')
182
+ if (minutes < 60) return tr(`${minutes}m ago`, `${minutes} мин назад`)
183
+ const hours = Math.floor(minutes / 60)
184
+ if (hours < 48) return tr(`${hours}h ago`, `${hours} ч назад`)
185
+ return tr(`${Math.floor(hours / 24)}d ago`, `${Math.floor(hours / 24)} дн назад`)
186
+ }
187
+
188
+ const STATE_ICONS = { running: '⏳', done: '✓', failed: '✗', interrupted: '⚠️', idle: '•' }
189
+
190
+ /**
191
+ * The `/agents` reply.
192
+ * @param rows - `{ label, model, depth, state, elapsedMs, createdAt, report }`, newest first.
193
+ * @param total - how many subagents the session has in all.
194
+ * @param now - current time in ms.
195
+ * @param tr - `(en, ru) => text`.
196
+ */
197
+ export function agentsListText(rows, total, now, tr = (en) => en) {
198
+ if (rows.length === 0) return tr('This session has started no subagents.', 'Эта сессия не запускала субагентов.')
199
+ const head = total > rows.length
200
+ ? tr(`🤖 Subagents (latest ${rows.length} of ${total}):`, `🤖 Субагенты (последние ${rows.length} из ${total}):`)
201
+ : tr('🤖 Subagents:', '🤖 Субагенты:')
202
+ const states = {
203
+ running: tr('running', 'работает'),
204
+ done: tr('done', 'готово'),
205
+ failed: tr('failed', 'ошибка'),
206
+ interrupted: tr('interrupted', 'прерван'),
207
+ idle: tr('idle', 'ожидает'),
208
+ }
209
+ const blocks = rows.map((row) => {
210
+ const indent = row.depth > 1 ? '↳ ' : ''
211
+ const facts = [states[row.state] ?? row.state]
212
+ if (row.model) facts.push(row.model)
213
+ if (row.elapsedMs > 0 || row.state === 'running') facts.push(formatElapsed(row.elapsedMs, row.state !== 'running'))
214
+ const age = ageText(row.createdAt, now, tr)
215
+ if (age) facts.push(age)
216
+ const lines = [`${indent}${STATE_ICONS[row.state] ?? '•'} ${clip(row.label, LABEL_MAX)}`, ` ${facts.join(' · ')}`]
217
+ const report = clip(String(row.report ?? '').replace(/\s+/gu, ' ').trim(), REPORT_MAX)
218
+ if (report) lines.push(` “${report}”`)
219
+ return lines.join('\n')
220
+ })
221
+ return [head, '', blocks.join('\n\n')].join('\n')
222
+ }
223
+
224
+ /**
225
+ * Track subagent runs and keep one status card per chat.
226
+ * @param deps - Host and Telegram access:
227
+ * - `parentOf(sessionId)`: the parent session id of a live session, or undefined.
228
+ * - `topicOf(sessionId)`: the chat (`{ key }`) a session is bound to, or undefined.
229
+ * - `showsTurn(topic)`: whether the chat is showing a turn now; a new card opens only then.
230
+ * - `labelOf(parentId, childId)`: the child's description from its parent's catalog.
231
+ * - `modelOf(childId)`: the child's model id.
232
+ * - `post(topic, text)`: send a message silently, resolves to its id or undefined.
233
+ * - `edit(topic, messageId, text)`: resolves to `ok`, `gone` (send a new one) or `failed` (try later).
234
+ * - `remove(topic, messageId)`: delete a message.
235
+ * - `reportError(scope, error)`, `tr(en, ru)`, `now()`, `delayMs`, `tickMs`.
236
+ * @returns `{ onStart, onEnd, noteMessage, dispose, boards }`; a bridge whose message ids grow
237
+ * calls `noteMessage(topicKey, messageId)` for every message that lands in a chat, so the card
238
+ * can follow it down.
239
+ */
240
+ export function createAgentBoards(deps) {
241
+ const {
242
+ parentOf, topicOf, showsTurn, labelOf, modelOf, post, edit, remove, reportError,
243
+ tr = (en) => en, now = Date.now, delayMs = EDIT_DELAY_MS, tickMs = TICK_MS,
244
+ } = deps
245
+ /** The open card of each topic, by topic key. */
246
+ const open = new Map()
247
+ let disposed = false
248
+
249
+ function closeBoard(board) {
250
+ if (open.get(board.topic.key) === board) open.delete(board.topic.key)
251
+ if (board.tick !== undefined) clearInterval(board.tick)
252
+ board.tick = undefined
253
+ }
254
+
255
+ /** Publish soon; changes before the timer fires share the edit. */
256
+ function schedule(board) {
257
+ if (disposed || board.timer !== undefined) return
258
+ board.timer = setTimeout(() => {
259
+ board.timer = undefined
260
+ board.chain = board.chain
261
+ .then(() => publish(board))
262
+ .catch((error) => reportError('subagent status', error))
263
+ }, delayMs)
264
+ board.timer.unref?.()
265
+ }
266
+
267
+ async function fillLabels(board) {
268
+ await Promise.all([...board.entries.values()].filter((entry) => !entry.labelKnown).map(async (entry) => {
269
+ const label = await Promise.resolve(labelOf(entry.parentId, entry.id)).catch(() => undefined)
270
+ if (typeof label === 'string' && label.trim()) {
271
+ entry.label = label.trim()
272
+ entry.labelKnown = true
273
+ }
274
+ }))
275
+ }
276
+
277
+ /** Entries in start order, each nested subagent right under its parent. */
278
+ function displayOrder(board) {
279
+ const entries = [...board.entries.values()]
280
+ const ids = new Set(entries.map((entry) => entry.id))
281
+ const children = new Map()
282
+ for (const entry of entries) {
283
+ const parent = ids.has(entry.parentId) ? entry.parentId : undefined
284
+ if (!children.has(parent)) children.set(parent, [])
285
+ children.get(parent).push(entry)
286
+ }
287
+ const ordered = []
288
+ const seen = new Set()
289
+ const walk = (parent) => {
290
+ for (const entry of children.get(parent) ?? []) {
291
+ if (seen.has(entry)) continue
292
+ seen.add(entry)
293
+ ordered.push(entry)
294
+ walk(entry.id)
295
+ }
296
+ }
297
+ walk(undefined)
298
+ // A cycle cannot come from DSH's parent links; keep any entry it would hide.
299
+ for (const entry of entries) if (!seen.has(entry)) ordered.push(entry)
300
+ return ordered
301
+ }
302
+
303
+ /** Whether a message landed in the topic after the card. */
304
+ function buried(board) {
305
+ return board.messageId !== undefined && board.latestSeen > board.messageId
306
+ }
307
+
308
+ async function publish(board) {
309
+ if (disposed) return
310
+ await fillLabels(board)
311
+ const entries = displayOrder(board)
312
+ const done = entries.every((entry) => entry.endedAt !== undefined)
313
+ // Freeze before any wait, so a subagent starting meanwhile opens a new card.
314
+ if (done) closeBoard(board)
315
+ const text = boardText(entries, now(), tr)
316
+ // A finished card stays where it is as the final state.
317
+ if (!done && buried(board)) {
318
+ await repost(board, text)
319
+ return
320
+ }
321
+ if (text === board.lastText) return
322
+ if (board.messageId !== undefined) {
323
+ const outcome = await edit(board.topic, board.messageId, text)
324
+ if (outcome === 'ok') {
325
+ board.lastText = text
326
+ return
327
+ }
328
+ if (outcome !== 'gone') {
329
+ // A running card retries with its next change or tick; a finished
330
+ // one has neither, so it tries once more after a pause.
331
+ if (done) {
332
+ await new Promise((resolve) => { setTimeout(resolve, delayMs * 4).unref?.() })
333
+ if (!disposed && (await edit(board.topic, board.messageId, text)) === 'ok') board.lastText = text
334
+ }
335
+ return
336
+ }
337
+ board.messageId = undefined
338
+ }
339
+ await repost(board, text)
340
+ }
341
+
342
+ /** Send the card as the newest message, then delete the copy above. */
343
+ async function repost(board, text) {
344
+ const previous = board.messageId
345
+ const messageId = await post(board.topic, text)
346
+ if (messageId === undefined) return
347
+ board.messageId = messageId
348
+ board.lastText = text
349
+ board.latestSeen = Math.max(board.latestSeen, messageId)
350
+ if (previous !== undefined) await Promise.resolve(remove(board.topic, previous)).catch(() => {})
351
+ // Something landed while the card was being sent: follow it down.
352
+ if (buried(board) && open.get(board.topic.key) === board) schedule(board)
353
+ }
354
+
355
+ /**
356
+ * A subagent run started (`subagent/start`).
357
+ * @param info - `{ runId, id }`.
358
+ */
359
+ async function onStart(info) {
360
+ if (disposed || typeof info?.id !== 'string') return
361
+ const parentId = parentOf(info.id)
362
+ let topic
363
+ let depth = 1
364
+ let current = parentId
365
+ for (let hop = 0; hop < MAX_DEPTH && typeof current === 'string'; hop += 1) {
366
+ topic = topicOf(current)
367
+ if (topic !== undefined) break
368
+ depth += 1
369
+ current = parentOf(current)
370
+ }
371
+ if (topic === undefined) return
372
+ let board = open.get(topic.key)
373
+ if (board === undefined) {
374
+ // A nested subagent belongs to a chain the topic already shows; a
375
+ // top-level one opens a card only while the topic shows a turn.
376
+ if (depth === 1 && !showsTurn(topic)) return
377
+ board = { topic, entries: new Map(), messageId: undefined, lastText: undefined, latestSeen: 0, timer: undefined, tick: undefined, chain: Promise.resolve() }
378
+ open.set(topic.key, board)
379
+ board.tick = setInterval(() => schedule(board), tickMs)
380
+ board.tick.unref?.()
381
+ }
382
+ const entry = {
383
+ id: info.id,
384
+ parentId,
385
+ label: tr(`subagent ${info.id.slice(0, 8)}`, `субагент ${info.id.slice(0, 8)}`),
386
+ labelKnown: false,
387
+ model: '',
388
+ depth,
389
+ startedAt: now(),
390
+ endedAt: undefined,
391
+ stopReason: undefined,
392
+ }
393
+ board.entries.set(info.runId ?? info.id, entry)
394
+ schedule(board)
395
+ const model = await Promise.resolve(modelOf(info.id)).catch(() => undefined)
396
+ if (typeof model === 'string' && model.length > 0) entry.model = model
397
+ }
398
+
399
+ /**
400
+ * A subagent run ended (`subagent/end`).
401
+ * @param info - `{ runId, id, stopReason }`.
402
+ */
403
+ function onEnd(info) {
404
+ const key = info?.runId ?? info?.id
405
+ for (const board of open.values()) {
406
+ const entry = board.entries.get(key)
407
+ if (entry === undefined || entry.endedAt !== undefined) continue
408
+ entry.endedAt = now()
409
+ entry.stopReason = info.stopReason
410
+ schedule(board)
411
+ return
412
+ }
413
+ }
414
+
415
+ /**
416
+ * A message landed in a topic (sent by anyone, the bot included).
417
+ * @param topicKey - the topic's key.
418
+ * @param messageId - the Telegram message id; ids grow within a chat.
419
+ */
420
+ function noteMessage(topicKey, messageId) {
421
+ const board = open.get(topicKey)
422
+ if (board === undefined || !Number.isSafeInteger(messageId)) return
423
+ board.latestSeen = Math.max(board.latestSeen, messageId)
424
+ if (buried(board)) schedule(board)
425
+ }
426
+
427
+ function dispose() {
428
+ disposed = true
429
+ for (const board of open.values()) {
430
+ if (board.timer !== undefined) clearTimeout(board.timer)
431
+ if (board.tick !== undefined) clearInterval(board.tick)
432
+ }
433
+ open.clear()
434
+ }
435
+
436
+ return { onStart, onEnd, noteMessage, dispose, boards: open }
437
+ }
438
+
439
+ /**
440
+ * Collect a session's subagents for `/agents`: every descendant reachable
441
+ * through the catalogs of recent children, newest first, running ones kept.
442
+ * @param listChildren - `(sessionId) => Promise<[{ id, label, createdAt, mode }]>`.
443
+ * @param rootId - the topic's session.
444
+ * @param isRunning - `(id) => boolean` for live, working subagents.
445
+ * @param limit - rows to return.
446
+ * @returns `{ rows: [{ id, label, createdAt, depth }], total }`.
447
+ */
448
+ export async function collectSubagents(listChildren, rootId, isRunning, limit = LIST_LIMIT) {
449
+ const found = []
450
+ const seen = new Set([rootId])
451
+ /** Catalog reads are bounded: descendants of old children are old too. */
452
+ let budget = limit * 4
453
+ const walk = async (parentId, depth) => {
454
+ let children
455
+ try {
456
+ children = await listChildren(parentId)
457
+ } catch {
458
+ return
459
+ }
460
+ if (!Array.isArray(children)) return
461
+ const recent = [...children].sort((left, right) => (right.createdAt ?? 0) - (left.createdAt ?? 0))
462
+ for (const child of recent) {
463
+ if (seen.has(child.id)) continue
464
+ seen.add(child.id)
465
+ found.push({ id: child.id, label: child.label, createdAt: child.createdAt, depth })
466
+ }
467
+ for (const child of recent) {
468
+ if (child.mode === 'external' || depth >= MAX_DEPTH) continue
469
+ if (budget <= 0 && !isRunning(child.id)) continue
470
+ budget -= 1
471
+ await walk(child.id, depth + 1)
472
+ }
473
+ }
474
+ await walk(rootId, 1)
475
+ found.sort((left, right) => (right.createdAt ?? 0) - (left.createdAt ?? 0))
476
+ const running = found.filter((row) => isRunning(row.id))
477
+ const rows = [...running, ...found.filter((row) => !isRunning(row.id)).slice(0, Math.max(0, limit - running.length))]
478
+ rows.sort((left, right) => (right.createdAt ?? 0) - (left.createdAt ?? 0))
479
+ return { rows, total: found.length }
480
+ }
481
+
482
+ /**
483
+ * The description a parent gave one of its subagents, from its catalog.
484
+ * @param ctx - Host context.
485
+ * @param parentId - parent session.
486
+ * @param childId - subagent session.
487
+ * @returns the label, or undefined.
488
+ */
489
+ export async function subagentLabel(ctx, parentId, childId) {
490
+ if (typeof parentId !== 'string') return undefined
491
+ const children = await ctx.get('subagents')?.listChildren(parentId).catch(() => undefined)
492
+ const label = Array.isArray(children) ? children.find((child) => child.id === childId)?.label : undefined
493
+ return typeof label === 'string' && label.trim().length > 0 ? label.trim() : undefined
494
+ }
495
+
496
+ /**
497
+ * The `/agents` text for a session: its running and latest subagents with
498
+ * their state and the start of their last report. Read from DSH's durable
499
+ * catalogs and session logs, so it works for subagents of earlier runs.
500
+ * @param ctx - Host context.
501
+ * @param sessionId - the chat's session.
502
+ * @param tr - `(en, ru) => text`.
503
+ * @returns the reply text, or undefined when this DSH has no subagent service.
504
+ */
505
+ export async function subagentsText(ctx, sessionId, tr = (en) => en) {
506
+ const subagents = ctx.get('subagents')
507
+ if (typeof subagents?.listChildren !== 'function') return undefined
508
+ const agents = ctx.get('agents')
509
+ const isRunning = (id) => agents?.get(id)?.status === 'running'
510
+ const { rows, total } = await collectSubagents((id) => subagents.listChildren(id), sessionId, isRunning)
511
+ const now = Date.now()
512
+ const query = ctx.get('sessionQuery')
513
+ const detailed = await Promise.all(rows.map(async (row) => {
514
+ let timing
515
+ let model
516
+ let observation
517
+ try {
518
+ observation = await query?.observeSession(row.id)
519
+ const values = observation?.projections?.values
520
+ timing = values?.subagentTiming
521
+ const selection = values?.modelSelection
522
+ model = (selection?.next ?? selection?.pending ?? selection?.lastUsed)?.model
523
+ } catch {
524
+ // State falls back to what the live agent says.
525
+ } finally {
526
+ observation?.[Symbol.dispose]?.()
527
+ }
528
+ const live = agents?.get(row.id)
529
+ if (typeof live?.model?.current === 'function') model = live.model.current()?.model ?? model
530
+ let events = []
531
+ try {
532
+ events = (await query?.readSurface(row.id))?.events ?? []
533
+ } catch {
534
+ // No report preview.
535
+ }
536
+ const { state, elapsedMs } = childState({ status: live?.status, timing }, now)
537
+ return { ...row, label: (typeof row.label === 'string' ? row.label.trim() : '') || `subagent ${String(row.id).slice(0, 8)}`, model, state, elapsedMs, report: reportOf(events) }
538
+ }))
539
+ return agentsListText(detailed, total, now, tr)
540
+ }
@@ -0,0 +1,127 @@
1
+ /** Voice messages and audio files: decoding and transcription. */
2
+ import { spawn } from 'node:child_process'
3
+
4
+ /**
5
+ * Wrap raw 16 kHz mono 16-bit PCM in the canonical 44-byte WAV header that
6
+ * DSH speech providers accept.
7
+ * @param pcm - little-endian samples.
8
+ * @returns WAV bytes.
9
+ */
10
+ export function pcmToWave(pcm) {
11
+ const data = pcm.length % 2 === 0 ? pcm : pcm.subarray(0, pcm.length - 1)
12
+ const header = Buffer.alloc(44)
13
+ header.write('RIFF', 0, 'ascii')
14
+ header.writeUInt32LE(36 + data.length, 4)
15
+ header.write('WAVE', 8, 'ascii')
16
+ header.write('fmt ', 12, 'ascii')
17
+ header.writeUInt32LE(16, 16)
18
+ header.writeUInt16LE(1, 20)
19
+ header.writeUInt16LE(1, 22)
20
+ header.writeUInt32LE(16000, 24)
21
+ header.writeUInt32LE(32000, 28)
22
+ header.writeUInt16LE(2, 32)
23
+ header.writeUInt16LE(16, 34)
24
+ header.write('data', 36, 'ascii')
25
+ header.writeUInt32LE(data.length, 40)
26
+ return Buffer.concat([header, data])
27
+ }
28
+
29
+ /**
30
+ * Run one program and collect its output.
31
+ * @param argv - program and arguments; no shell is involved.
32
+ * @param signal - cancellation.
33
+ * @param timeoutMs - upper bound for the run.
34
+ * @returns stdout bytes; rejects with stderr on a non-zero exit.
35
+ */
36
+ export function runProgram(argv, signal, timeoutMs) {
37
+ return new Promise((resolve, reject) => {
38
+ if (signal?.aborted) {
39
+ reject(signal.reason ?? new Error('aborted'))
40
+ return
41
+ }
42
+ const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'pipe'] })
43
+ const out = []
44
+ const err = []
45
+ let settled = false
46
+ const finish = (error, value) => {
47
+ if (settled) return
48
+ settled = true
49
+ clearTimeout(timer)
50
+ signal?.removeEventListener('abort', abort)
51
+ if (error) reject(error)
52
+ else resolve(value)
53
+ }
54
+ const abort = () => {
55
+ child.kill('SIGKILL')
56
+ finish(new Error(`${argv[0]} was cancelled`))
57
+ }
58
+ const timer = setTimeout(() => {
59
+ child.kill('SIGKILL')
60
+ finish(new Error(`${argv[0]} took longer than ${Math.round(timeoutMs / 1000)} s`))
61
+ }, timeoutMs)
62
+ signal?.addEventListener('abort', abort, { once: true })
63
+ child.stdout.on('data', (chunk) => out.push(chunk))
64
+ child.stderr.on('data', (chunk) => err.push(chunk))
65
+ child.on('error', (error) => finish(new Error(`${argv[0]} could not start: ${error.message}`)))
66
+ child.on('close', (code) => {
67
+ if (code === 0) finish(undefined, Buffer.concat(out))
68
+ else finish(new Error(`${argv[0]} exited with ${code}: ${Buffer.concat(err).toString('utf8').trim().slice(-400)}`))
69
+ })
70
+ })
71
+ }
72
+
73
+ /**
74
+ * Transcribe one recording.
75
+ * @param options - `{ mode, path, language, command, ffmpeg, speech, signal, timeoutMs }`:
76
+ * `mode` is `dsh` (the DSH speech-to-text service, `speech`), `command`
77
+ * (`command` argv, `{file}` replaced by `path`, transcript on stdout) or `off`.
78
+ * @returns `{ text, by }`; rejects when transcription fails.
79
+ */
80
+ export async function transcribe(options) {
81
+ const { mode, path, signal } = options
82
+ const timeoutMs = options.timeoutMs ?? 180_000
83
+ if (mode === 'command') {
84
+ const command = Array.isArray(options.command) ? options.command.filter((part) => typeof part === 'string') : []
85
+ if (command.length === 0) throw new Error('no transcription command is configured')
86
+ const argv = command.some((part) => part.includes('{file}'))
87
+ ? command.map((part) => part.replaceAll('{file}', path))
88
+ : [...command, path]
89
+ const text = (await runProgram(argv, signal, timeoutMs)).toString('utf8').trim()
90
+ return { text, by: 'the configured transcription command' }
91
+ }
92
+ if (mode !== 'dsh') throw new Error('transcription is turned off')
93
+ const speech = options.speech
94
+ if (speech === undefined || typeof speech.resolve !== 'function') throw new Error('the DSH speech-to-text service is not enabled')
95
+ const pcm = await runProgram(
96
+ [options.ffmpeg || 'ffmpeg', '-nostdin', '-hide_banner', '-loglevel', 'error', '-i', path, '-vn', '-ac', '1', '-ar', '16000', '-f', 's16le', 'pipe:1'],
97
+ signal,
98
+ timeoutMs,
99
+ )
100
+ if (pcm.length === 0) throw new Error('the recording has no audio')
101
+ const spec = speech.resolve({
102
+ audio: pcmToWave(pcm),
103
+ ...(typeof options.language === 'string' && options.language.length > 0 ? { language: options.language } : {}),
104
+ })
105
+ const result = await speech.transcribe(spec, signal ?? new AbortController().signal)
106
+ const provider = spec.provider?.info?.name ?? spec.provider?.info?.id
107
+ return { text: String(result?.text ?? '').trim(), by: `DSH speech-to-text${provider ? ` (${provider})` : ''}` }
108
+ }
109
+
110
+ /**
111
+ * The text the agent reads next to a spoken recording.
112
+ * @param media - `{ kind, name, seconds }`, e.g. `{ kind: 'voice message', name: 'memo.ogg', seconds: 75 }`.
113
+ * @param outcome - `{ path, text, by, error }`.
114
+ * @param network - the chat network it came from, as people name it (`Telegram`, `Matrix`).
115
+ * @returns prompt text.
116
+ */
117
+ export function transcriptNote(media, outcome, network) {
118
+ const length = media.seconds === undefined ? '' : `, ${Math.floor(media.seconds / 60)}:${String(media.seconds % 60).padStart(2, '0')}`
119
+ const where = typeof outcome.path === 'string' ? `the file is attached and saved at ${outcome.path}` : 'the file is attached'
120
+ if (outcome.error !== undefined) {
121
+ return `[${network} ${media.kind} "${media.name}"${length}: not transcribed (${outcome.error}); ${where}]`
122
+ }
123
+ if (outcome.text.length === 0) {
124
+ return `[${network} ${media.kind} "${media.name}"${length}: ${outcome.by} heard no speech; ${where}]`
125
+ }
126
+ return `[${network} ${media.kind} "${media.name}"${length}, transcribed by ${outcome.by}; the transcript may contain mistakes, and ${where} to check it]\n${outcome.text}`
127
+ }