dsh-remote-plugin 0.8.7 → 0.9.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.
Files changed (70) hide show
  1. package/README.en.md +16 -5
  2. package/README.md +15 -4
  3. package/apk/dsh-remote.apk +0 -0
  4. package/gateway.cjs +659 -130
  5. package/index.mjs +33 -1
  6. package/package.json +8 -3
  7. package/public/activity.js +196 -52
  8. package/public/admin.html +34 -32
  9. package/public/admin.js +11 -2
  10. package/public/app.js +1341 -223
  11. package/public/bc-integration.css +81 -0
  12. package/public/build.json +2 -2
  13. package/public/composer-tools.css +184 -0
  14. package/public/composer-tools.js +888 -0
  15. package/public/desktop/desktop.html +104 -76
  16. package/public/desktop/desktop.js +668 -101
  17. package/public/diagnostics.js +30 -4
  18. package/public/e2ee-transport.js +154 -7
  19. package/public/file-inbox.js +77 -18
  20. package/public/genui.css +10 -0
  21. package/public/genui.js +22 -4
  22. package/public/history.js +15 -2
  23. package/public/host-queue.js +232 -0
  24. package/public/host-schedule.js +301 -0
  25. package/public/host-state.css +19 -0
  26. package/public/index.html +347 -140
  27. package/public/md.js +21 -1
  28. package/public/network.js +33 -1
  29. package/public/onboarding.js +3 -3
  30. package/public/operations.js +26 -12
  31. package/public/plan-review.css +297 -0
  32. package/public/plan-review.js +621 -0
  33. package/public/plugin.html +29 -27
  34. package/public/relay-autopair.js +25 -10
  35. package/public/relay-settings.css +11 -0
  36. package/public/relay-settings.js +350 -28
  37. package/public/session-management.css +61 -0
  38. package/public/session-management.js +742 -0
  39. package/public/session-search.css +137 -0
  40. package/public/session-search.js +977 -0
  41. package/public/skins/blue-fish/preview.html +3 -3
  42. package/public/skins/bocchi/preview.html +5 -5
  43. package/public/skins/kita/preview.html +6 -6
  44. package/public/skins/miku/SOURCES.json +10 -0
  45. package/public/skins/miku/chibi.png +0 -0
  46. package/public/skins/miku/preview.html +33 -0
  47. package/public/skins/miku/skin.css +82 -0
  48. package/public/skins/nijika/preview.html +6 -6
  49. package/public/skins/penguin/preview.html +3 -3
  50. package/public/skins/penguin-logistics/cargo.svg +4 -0
  51. package/public/skins/penguin-logistics/console.svg +4 -0
  52. package/public/skins/penguin-logistics/mark.svg +4 -0
  53. package/public/skins/penguin-logistics/radio.svg +4 -0
  54. package/public/skins/penguin-logistics/skin.css +292 -0
  55. package/public/skins/penguin-logistics/standing.png +0 -0
  56. package/public/skins/ryo/preview.html +6 -6
  57. package/public/slash-suggestions.css +43 -0
  58. package/public/slash-suggestions.js +196 -0
  59. package/public/sponsor-entry.js +11 -3
  60. package/public/styles.css +141 -21
  61. package/public/subagents.css +7 -0
  62. package/public/subagents.js +83 -10
  63. package/public/theme-vars.css +102 -3
  64. package/public/theme.js +7 -4
  65. package/public/turn-diff.css +323 -0
  66. package/public/turn-diff.js +778 -0
  67. package/public/update.json +12 -12
  68. package/public/version.json +1 -1
  69. package/public/workflow.css +322 -43
  70. package/public/workflow.js +148 -44
@@ -0,0 +1,888 @@
1
+ /* B6 组合输入增强:当前会话命令、权限内 @ 引用、消息选段引用。
2
+ *
3
+ * 零依赖、零网络:命令与引用目录、以及“能不能引用”的权限判断都在主机
4
+ * 适配器里完成;本模块只负责触发识别、候选渲染、键盘/触控选择、草稿内
5
+ * 精确插入和待发送引用管理。旧主机没有目录接口时静默降级——/命令 与
6
+ * 纯文本仍可手输发送,@ 文本原样保留,不伪造主机语义。
7
+ *
8
+ * 浏览器用法:root.DshComposerTools.create({ input, menu, hint, quoteList, host })
9
+ * Node 测试:module.exports 暴露 create 与纯函数。
10
+ */
11
+ 'use strict'
12
+ ;(function (root) {
13
+ const MAX_COMMANDS = 40
14
+ const MAX_REFERENCES = 30
15
+ const MAX_QUOTES = 8
16
+ const MAX_QUOTE_CHARS = 4000
17
+ const COMMAND_CACHE_MS = 15000
18
+ const COMMAND_NAME = /^[^\s/]{1,64}$/
19
+ const REFERENCE_TOKEN = /^@[^\r\n]{1,511}$/
20
+ // 触发边界:@ 只能出现在行首或空白/常见开括号之后,避免把邮箱当引用。
21
+ const REFERENCE_BOUNDARY = /[\s([{<'"`]/
22
+ let instanceSeq = 0
23
+
24
+ const asText = value => typeof value === 'string' ? value : ''
25
+ function isPlainObject(value) {
26
+ return !!value && typeof value === 'object' && !Array.isArray(value)
27
+ }
28
+
29
+ /* 返回 null 表示主机明确未提供该目录(降级);空数组表示“已支持但为空”。 */
30
+ function listFrom(payload, keys) {
31
+ if (payload == null) return null
32
+ if (Array.isArray(payload)) return payload
33
+ if (!isPlainObject(payload)) return null
34
+ if (payload.supported === false || payload.available === false) return null
35
+ for (const key of keys) if (Array.isArray(payload[key])) return payload[key]
36
+ return payload.supported === true ? [] : null
37
+ }
38
+
39
+ function normalizeCommandRow(row) {
40
+ if (!isPlainObject(row)) return null
41
+ let name = asText(row.name || row.command || row.id).trim()
42
+ if (name.startsWith('/')) name = name.replace(/^\/+/, '')
43
+ if (!COMMAND_NAME.test(name)) return null
44
+ const aliases = []
45
+ if (Array.isArray(row.aliases)) {
46
+ for (const alias of row.aliases) {
47
+ const value = asText(alias).trim().replace(/^\/+/, '')
48
+ if (COMMAND_NAME.test(value) && !aliases.includes(value)) aliases.push(value)
49
+ }
50
+ }
51
+ const description = asText(row.description || row.summary).trim().slice(0, 200)
52
+ const source = asText(row.source || row.plugin).trim().slice(0, 60)
53
+ const argumentHint = asText(row.argumentHint || row.usageHint || row.args).trim().slice(0, 80)
54
+ return { name, aliases, description, source, argumentHint }
55
+ }
56
+
57
+ /* 主机目录可能带 /,也可能直接是数组;去重、限长,权限字段只做保守过滤。 */
58
+ function normalizeCommandRows(payload) {
59
+ const list = listFrom(payload, ['commands', 'items'])
60
+ if (list == null) return null
61
+ const rows = [], seen = new Set()
62
+ for (const raw of list) {
63
+ const row = normalizeCommandRow(raw)
64
+ if (!row) continue
65
+ const key = row.name.toLowerCase()
66
+ if (seen.has(key)) continue
67
+ seen.add(key)
68
+ rows.push(row)
69
+ if (rows.length >= MAX_COMMANDS) break
70
+ }
71
+ return rows
72
+ }
73
+
74
+ function normalizeReferenceRow(row) {
75
+ if (!isPlainObject(row)) return null
76
+ // 权限由主机执行:显式拒绝项绝不进入候选,也不在客户端猜测权限。
77
+ if (row.allowed === false || row.denied === true || row.permitted === false) return null
78
+ const insert = asText(row.insert || row.token).trim()
79
+ if (!REFERENCE_TOKEN.test(insert)) return null
80
+ const label = asText(row.label || row.name || row.title).trim().slice(0, 120) || insert
81
+ const detail = asText(row.detail || row.description || row.subtitle).trim().slice(0, 160)
82
+ const kind = asText(row.kind || row.type).trim().slice(0, 24)
83
+ return { insert, label, detail, kind }
84
+ }
85
+
86
+ function normalizeReferenceRows(payload) {
87
+ const list = listFrom(payload, ['references', 'items'])
88
+ if (list == null) return null
89
+ const rows = [], seen = new Set()
90
+ for (const raw of list) {
91
+ const row = normalizeReferenceRow(raw)
92
+ if (!row) continue
93
+ if (seen.has(row.insert)) continue
94
+ seen.add(row.insert)
95
+ rows.push(row)
96
+ if (rows.length >= MAX_REFERENCES) break
97
+ }
98
+ return rows
99
+ }
100
+
101
+ const lower = value => asText(value).toLowerCase()
102
+
103
+ /* 命令前缀优先,其次包含匹配;空查询返回全部(主机目录顺序即优先级)。 */
104
+ function filterCommandRows(rows, query) {
105
+ const q = lower(query).trim()
106
+ const list = Array.isArray(rows) ? rows : []
107
+ if (!q) return list.slice()
108
+ const prefix = [], contains = []
109
+ for (const row of list) {
110
+ if (!row) continue
111
+ const names = [row.name, ...(Array.isArray(row.aliases) ? row.aliases : [])].map(lower)
112
+ if (names.some(name => name.startsWith(q))) prefix.push(row)
113
+ else if (names.some(name => name.includes(q))) contains.push(row)
114
+ }
115
+ return prefix.concat(contains)
116
+ }
117
+
118
+ function filterReferenceRows(rows, query) {
119
+ const q = lower(query).trim()
120
+ const list = Array.isArray(rows) ? rows : []
121
+ if (!q) return list.slice()
122
+ const matched = list.filter(row => row && (lower(row.label).includes(q) || lower(row.insert).includes(q) || lower(row.detail).includes(q)))
123
+ // 保持主机返回顺序,稳定的“无匹配”体验由调用方决定。
124
+ return matched
125
+ }
126
+
127
+ function caretOf(input) {
128
+ const value = String(input && input.value != null ? input.value : '')
129
+ const start = input && Number.isInteger(input.selectionStart) ? input.selectionStart : value.length
130
+ return Math.max(0, Math.min(start, value.length))
131
+ }
132
+
133
+ function tokenEnd(value, caret) {
134
+ let end = caret
135
+ while (end < value.length && !/[\s/]/.test(value[end])) end += 1
136
+ return end
137
+ }
138
+
139
+ function referenceStart(value, caret) {
140
+ let at = value.lastIndexOf('@', caret - 1)
141
+ while (at >= 0) {
142
+ if (at === 0 || REFERENCE_BOUNDARY.test(value[at - 1])) return at
143
+ at = value.lastIndexOf('@', at - 1)
144
+ }
145
+ return -1
146
+ }
147
+
148
+ /* 纯函数:根据草稿与光标识别命令/引用触发;无触发返回 null。
149
+ * start..end 是接受候选时要替换的 token 区间(含结尾未输入完的部分)。 */
150
+ function detectTrigger(value, caret) {
151
+ const text = asText(value)
152
+ const pos = Math.max(0, Math.min(Number.isInteger(caret) ? caret : text.length, text.length))
153
+ const before = text.slice(0, pos)
154
+ const command = /^(\/+)([^\s/]*)$/.exec(before)
155
+ if (command) {
156
+ // 命令必须从文档开头起算;end 覆盖当前 token 的剩余部分。
157
+ let end = command[1].length + command[2].length
158
+ while (end < text.length && !/[\s/]/.test(text[end])) end += 1
159
+ return { kind: 'command', query: command[2], start: 0, end, slashes: command[1] }
160
+ }
161
+ const at = referenceStart(text, pos)
162
+ if (at < 0) return null
163
+ const query = text.slice(at + 1, pos)
164
+ // 引用 token 内出现空白说明用户已结束该引用;此时关闭菜单,@ 保持普通文本。
165
+ if (/\s/.test(query)) return null
166
+ return { kind: 'reference', query, start: at, end: tokenEnd(text, pos) }
167
+ }
168
+
169
+ function fileReferenceMention(candidate) {
170
+ const path = asText(candidate?.path)
171
+ if (!path || /[\x00-\x1f\x7f-\x9f"]/.test(path)) return ''
172
+ const value = candidate.kind === 'directory' && !path.endsWith('/') ? path + '/' : path
173
+ return /\s/.test(value) ? '@"' + value + '"' : '@' + value
174
+ }
175
+
176
+ function sameTrigger(a, b) {
177
+ return !!a && !!b && a.kind === b.kind && a.start === b.start && a.end === b.end && a.query === b.query
178
+ }
179
+
180
+ function insertAt(value, start, end, insert) {
181
+ const text = asText(value)
182
+ const from = Math.max(0, Math.min(Number.isInteger(start) ? start : 0, text.length))
183
+ const to = Math.max(from, Math.min(Number.isInteger(end) ? end : from, text.length))
184
+ const addition = asText(insert)
185
+ return { value: text.slice(0, from) + addition + text.slice(to), caret: from + addition.length }
186
+ }
187
+
188
+ /* 选段规格:主机的 messageId/seq 与角色原样保留,正文只做去控制字符与限长。 */
189
+ function sanitizeQuote(raw) {
190
+ if (!isPlainObject(raw)) return null
191
+ const source = asText(raw.text != null ? raw.text : raw.quote).replace(/\r\n?/g, '\n')
192
+ const text = source.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '')
193
+ if (!text.trim()) return null
194
+ const clipped = text.slice(0, MAX_QUOTE_CHARS)
195
+ const rawId = raw.messageId != null ? raw.messageId : raw.seq
196
+ const messageId = rawId == null ? '' : String(rawId).trim().slice(0, 200)
197
+ const role = asText(raw.role).trim().toLowerCase().slice(0, 20)
198
+ return {
199
+ messageId,
200
+ role: /^[a-z-]{1,20}$/.test(role) ? role : '',
201
+ text: clipped,
202
+ truncated: text.length > MAX_QUOTE_CHARS,
203
+ }
204
+ }
205
+
206
+ function quotePreview(text, max = 90) {
207
+ const line = asText(text).split('\n').find(value => value.trim()) || ''
208
+ const flat = line.replace(/\s+/g, ' ').trim()
209
+ if (flat.length <= max) return flat
210
+ return flat.slice(0, Math.max(1, max - 1)) + '…'
211
+ }
212
+
213
+ /* 主机原生语义:消息引用按 Markdown 块引用输出,不添加客户端自造的署名/标签。 */
214
+ function formatQuotes(quotes) {
215
+ const list = Array.isArray(quotes) ? quotes : []
216
+ return list.map(quote => {
217
+ const text = asText(quote && quote.text).replace(/\r\n?/g, '\n')
218
+ if (!text) return ''
219
+ return text.split('\n').map(line => '> ' + line).join('\n')
220
+ }).filter(Boolean).join('\n\n')
221
+ }
222
+
223
+ function create(options) {
224
+ options = options || {}
225
+ const doc = options.document || root.document
226
+ if (!doc || typeof doc.createElement !== 'function') throw new TypeError('composer tools: document is required')
227
+ const input = options.input
228
+ if (!input) throw new TypeError('composer tools: input is required')
229
+ const host = options.host || {}
230
+ const commandsEnabled = options.commands !== false
231
+ const menu = options.menu || null
232
+ const hint = options.hint || null
233
+ const quoteList = options.quoteList || null
234
+ const instance = ++instanceSeq
235
+ const menuId = 'ct-menu-' + instance
236
+
237
+ const state = {
238
+ destroyed: false,
239
+ scopeKey: '',
240
+ quotesByScope: new Map(),
241
+ quotes: [],
242
+ quoteSeq: 0,
243
+ expanded: new Set(),
244
+ generation: 0,
245
+ pending: null,
246
+ hinted: new Set(),
247
+ commandCache: { key: null, at: 0, rows: null },
248
+ capabilities: { commands: 'unknown', references: 'unknown' },
249
+ menu: { open: false, kind: '', items: [], nodes: [], active: -1, trigger: null, scopeKey: '' },
250
+ hintText: '',
251
+ }
252
+
253
+ const english = () => (options.i18n || (root.I18N && root.I18N.lang) || 'zh') === 'en'
254
+ const L = (zh, en) => english() ? en : zh
255
+
256
+ function node(tag, className, text) {
257
+ const element = doc.createElement(tag)
258
+ if (className) element.className = className
259
+ if (text != null) element.textContent = text
260
+ return element
261
+ }
262
+
263
+ function scopeOf(value) {
264
+ if (typeof value === 'string') return value
265
+ if (!isPlainObject(value)) return ''
266
+ const key = value.key != null ? value.key : (value.sessionId != null ? value.sessionId : value.id)
267
+ return key == null ? '' : String(key)
268
+ }
269
+
270
+ function currentScope() {
271
+ let scope = null
272
+ try { scope = typeof host.scope === 'function' ? host.scope() : null } catch { scope = null }
273
+ if (typeof scope === 'string') return { key: scope }
274
+ return isPlainObject(scope) ? scope : { key: '' }
275
+ }
276
+
277
+ function currentKey() {
278
+ return scopeOf(currentScope())
279
+ }
280
+
281
+ function connectionValid(scope) {
282
+ const connection = scope && scope.connection
283
+ return !connection || typeof connection.valid !== 'function' || connection.valid() !== false
284
+ }
285
+
286
+ function live(captured) {
287
+ return !state.destroyed && captured.gen === state.generation &&
288
+ captured.key === currentKey() && connectionValid(currentScope())
289
+ }
290
+
291
+ function showHint(text, kind) {
292
+ if (!hint || !text) return
293
+ const value = String(text)
294
+ if (state.hintText === value && hint.hidden === false) return
295
+ state.hintText = value
296
+ hint.textContent = value
297
+ hint.hidden = false
298
+ if (hint.classList) {
299
+ hint.classList.toggle('ct-hint-error', kind === 'error')
300
+ hint.classList.remove('hidden')
301
+ }
302
+ }
303
+
304
+ function clearHint() {
305
+ state.hintText = ''
306
+ if (!hint) return
307
+ hint.textContent = ''
308
+ hint.hidden = true
309
+ if (hint.classList) hint.classList.add('hidden')
310
+ }
311
+
312
+ function hintOnce(key, zh, en) {
313
+ const id = state.scopeKey + '\u0000' + key
314
+ if (state.hinted.has(id)) return
315
+ state.hinted.add(id)
316
+ showHint(L(zh, en), 'info')
317
+ }
318
+
319
+ function notify(text, kind) {
320
+ try { host.notice?.(text, kind) } catch {}
321
+ }
322
+
323
+ function setInputAria(open) {
324
+ if (!input.setAttribute) return
325
+ if (open) {
326
+ input.setAttribute('aria-expanded', 'true')
327
+ input.setAttribute('aria-controls', menuId)
328
+ } else if (input.getAttribute?.('aria-controls') === menuId) {
329
+ input.setAttribute('aria-expanded', 'false')
330
+ input.removeAttribute?.('aria-controls')
331
+ input.removeAttribute?.('aria-activedescendant')
332
+ }
333
+ }
334
+
335
+ function closeMenu() {
336
+ const wasOpen = state.menu.open
337
+ // 关闭候选即作废所有在途目录请求,避免迟到结果把已关闭的菜单重新打开。
338
+ state.generation += 1
339
+ state.menu = { open: false, kind: '', items: [], nodes: [], active: -1, trigger: null, scopeKey: '' }
340
+ state.pending = null
341
+ if (menu) {
342
+ menu.hidden = true
343
+ if (menu.classList) { menu.classList.add('hidden') }
344
+ if (menu.replaceChildren) menu.replaceChildren()
345
+ }
346
+ setInputAria(false)
347
+ return wasOpen
348
+ }
349
+
350
+ function setActive(index) {
351
+ const count = state.menu.items.length
352
+ if (!state.menu.open || !count) return -1
353
+ const active = ((Number(index) % count) + count) % count
354
+ state.menu.active = active
355
+ state.menu.nodes.forEach((element, i) => {
356
+ const selected = i === active
357
+ if (element.classList) element.classList.toggle('is-active', selected)
358
+ element.setAttribute?.('aria-selected', selected ? 'true' : 'false')
359
+ })
360
+ const activeNode = state.menu.nodes[active]
361
+ if (input.setAttribute && activeNode && activeNode.id) input.setAttribute('aria-activedescendant', activeNode.id)
362
+ try { activeNode?.scrollIntoView?.({ block: 'nearest' }) } catch {}
363
+ return active
364
+ }
365
+
366
+ function move(delta) {
367
+ return setActive(state.menu.active + delta)
368
+ }
369
+
370
+ function commandItem(row) {
371
+ return {
372
+ kind: 'command',
373
+ key: 'cmd:' + row.name.toLowerCase(),
374
+ name: row.name,
375
+ label: '/' + row.name,
376
+ detail: row.description,
377
+ meta: row.argumentHint || row.source,
378
+ }
379
+ }
380
+
381
+ function referenceItem(row) {
382
+ return {
383
+ kind: 'reference',
384
+ key: 'ref:' + row.insert,
385
+ insert: row.insert,
386
+ label: row.label,
387
+ detail: row.detail,
388
+ meta: row.kind || row.insert,
389
+ }
390
+ }
391
+
392
+ function openMenu(kind, trigger, items) {
393
+ if (!items.length) { closeMenu(); return }
394
+ if (!menu) return
395
+ closeMenu()
396
+ menu.hidden = false
397
+ if (menu.classList) { menu.classList.remove('hidden'); menu.classList.add('ct-menu') }
398
+ if (!menu.id) menu.id = menuId
399
+ menu.setAttribute?.('role', 'listbox')
400
+ menu.setAttribute?.('aria-label', kind === 'command' ? L('会话命令', 'Session commands') : L('可引用内容', 'Referenceable items'))
401
+ const nodes = items.map((item, index) => {
402
+ const button = node('button', 'ct-item ct-' + item.kind)
403
+ button.type = 'button'
404
+ button.id = menuId + '-item-' + index
405
+ button.setAttribute('role', 'option')
406
+ button.setAttribute('aria-selected', 'false')
407
+ button.dataset.ctIndex = String(index)
408
+ const main = node('span', 'ct-item-main')
409
+ main.append(node('span', 'ct-item-name', item.label))
410
+ if (item.detail) main.append(node('span', 'ct-item-detail', item.detail))
411
+ if (item.meta && item.meta !== item.label) main.append(node('span', 'ct-item-meta', item.meta))
412
+ button.append(main)
413
+ // 触控:按下时不抢焦点,随后 click 再接受;移动端不必先悬停。
414
+ if (button.addEventListener) {
415
+ button.addEventListener('mousedown', event => { try { event.preventDefault() } catch {} })
416
+ button.addEventListener('click', event => {
417
+ try { event.preventDefault() } catch {}
418
+ accept(index)
419
+ })
420
+ }
421
+ menu.append(button)
422
+ return button
423
+ })
424
+ state.menu = { open: true, kind, items: items.slice(), nodes, active: -1, trigger, scopeKey: currentKey() }
425
+ state.pending = null
426
+ setInputAria(true)
427
+ const active = Number.isInteger(options.activeIndex) && options.activeIndex >= 0 ? options.activeIndex : 0
428
+ setActive(active)
429
+ }
430
+
431
+ function showCommands(rows, trigger) {
432
+ const filtered = filterCommandRows(rows, trigger.query)
433
+ if (!filtered.length) { closeMenu(); return }
434
+ clearHint()
435
+ openMenu('command', trigger, filtered.map(commandItem))
436
+ }
437
+
438
+ function showReferences(rows, trigger) {
439
+ const filtered = filterReferenceRows(rows, trigger.query)
440
+ if (!filtered.length) {
441
+ closeMenu()
442
+ return
443
+ }
444
+ clearHint()
445
+ openMenu('reference', trigger, filtered.map(referenceItem))
446
+ }
447
+
448
+ function commandRowsFor(trigger, generation) {
449
+ const scope = currentScope()
450
+ const key = currentKey()
451
+ if (state.capabilities.commands === 'unsupported') {
452
+ closeMenu()
453
+ hintOnce('commands-unsupported', '当前主机没有命令目录,可手输 /命令 或纯文本发送。', 'This host has no command catalog. Type the /command or plain text and send it.')
454
+ return
455
+ }
456
+ if (!connectionValid(scope)) { closeMenu(); return }
457
+ if (state.commandCache.key === key && state.commandCache.rows && Date.now() - state.commandCache.at < COMMAND_CACHE_MS) {
458
+ showCommands(state.commandCache.rows, trigger)
459
+ return
460
+ }
461
+ if (typeof host.listCommands !== 'function') {
462
+ state.capabilities.commands = 'unsupported'
463
+ closeMenu()
464
+ hintOnce('commands-unsupported', '当前主机没有命令目录,可手输 /命令 或纯文本发送。', 'This host has no command catalog. Type the /command or plain text and send it.')
465
+ return
466
+ }
467
+ const captured = { gen: generation, key }
468
+ showHint(L('正在读取当前会话的命令…', 'Loading this session’s commands…'), 'info')
469
+ Promise.resolve()
470
+ .then(() => host.listCommands(scope))
471
+ .then(payload => {
472
+ if (!live(captured)) return
473
+ state.pending = null
474
+ const rows = normalizeCommandRows(payload)
475
+ if (rows == null) {
476
+ state.capabilities.commands = 'unsupported'
477
+ closeMenu()
478
+ hintOnce('commands-unsupported', '当前主机没有命令目录,可手输 /命令 或纯文本发送。', 'This host has no command catalog. Type the /command or plain text and send it.')
479
+ return
480
+ }
481
+ state.capabilities.commands = 'supported'
482
+ state.commandCache = { key, at: Date.now(), rows }
483
+ showCommands(rows, trigger)
484
+ })
485
+ .catch(() => {
486
+ if (!live(captured)) return
487
+ state.pending = null
488
+ closeMenu()
489
+ hintOnce('commands-error', '暂时无法读取命令目录,仍可手输 /命令 后发送。', 'The command catalog is unavailable right now; you can still type and send the /command.')
490
+ })
491
+ }
492
+
493
+ function referenceRowsFor(trigger, generation) {
494
+ const scope = currentScope()
495
+ const key = currentKey()
496
+ if (state.capabilities.references === 'unsupported') {
497
+ closeMenu()
498
+ hintOnce('references-unsupported', '当前主机不支持 @ 引用,@ 会作为普通文本发送。', 'This host has no @ references; the @ text will be sent as plain text.')
499
+ return
500
+ }
501
+ if (!connectionValid(scope)) { closeMenu(); return }
502
+ if (typeof host.listReferences !== 'function') {
503
+ state.capabilities.references = 'unsupported'
504
+ closeMenu()
505
+ hintOnce('references-unsupported', '当前主机不支持 @ 引用,@ 会作为普通文本发送。', 'This host has no @ references; the @ text will be sent as plain text.')
506
+ return
507
+ }
508
+ const captured = { gen: generation, key }
509
+ showHint(L('正在读取可引用内容…', 'Loading referenceable items…'), 'info')
510
+ Promise.resolve()
511
+ .then(() => host.listReferences(scope, trigger.query))
512
+ .then(payload => {
513
+ if (!live(captured)) return
514
+ state.pending = null
515
+ const rows = normalizeReferenceRows(payload)
516
+ if (rows == null) {
517
+ state.capabilities.references = 'unsupported'
518
+ closeMenu()
519
+ hintOnce('references-unsupported', '当前主机不支持 @ 引用,@ 会作为普通文本发送。', 'This host has no @ references; the @ text will be sent as plain text.')
520
+ return
521
+ }
522
+ state.capabilities.references = 'supported'
523
+ showReferences(rows, trigger)
524
+ })
525
+ .catch(() => {
526
+ if (!live(captured)) return
527
+ state.pending = null
528
+ closeMenu()
529
+ hintOnce('references-error', '暂时无法读取可引用内容,@ 将作为普通文本发送。', 'Referenceable items are unavailable right now; the @ text will be sent as plain text.')
530
+ })
531
+ }
532
+
533
+ function sync() {
534
+ if (state.destroyed) return
535
+ const value = String(input.value != null ? input.value : '')
536
+ const trigger = detectTrigger(value, caretOf(input))
537
+ const key = currentKey()
538
+ if (!trigger || (trigger.kind === 'command' && !commandsEnabled)) { closeMenu(); return }
539
+ // 键位移动/重复事件不重开菜单,否则方向键会把高亮重置回第一项。
540
+ if (state.menu.open && state.menu.scopeKey === key && sameTrigger(state.menu.trigger, trigger)) return
541
+ if (state.pending && state.pending.key === key && sameTrigger(state.pending.trigger, trigger)) return
542
+ const generation = ++state.generation
543
+ state.pending = { gen: generation, key, trigger }
544
+ if (trigger.kind === 'command') commandRowsFor(trigger, generation)
545
+ else referenceRowsFor(trigger, generation)
546
+ }
547
+
548
+ function writeValue(value, caret) {
549
+ input.value = value
550
+ if (typeof input.setSelectionRange === 'function') input.setSelectionRange(caret, caret)
551
+ if (typeof input.focus === 'function') input.focus()
552
+ try { input.dispatchEvent?.(new root.Event('input', { bubbles: true })) } catch {}
553
+ }
554
+
555
+ /* 把触发的 token 换成主机原生文本;已有空白分隔时跳过它,避免接受后
556
+ * 光标仍停在 token 内导致候选立刻重开。 */
557
+ function replaceTrigger(value, trigger, insert) {
558
+ const nextChar = value[trigger.end]
559
+ const pad = nextChar == null || !/\s/.test(nextChar) ? ' ' : ''
560
+ const result = insertAt(value, trigger.start, trigger.end, insert + pad)
561
+ if (!pad) result.caret += 1
562
+ return result
563
+ }
564
+
565
+ function accept(index) {
566
+ if (state.destroyed || !state.menu.open) return false
567
+ const position = Number.isInteger(index) ? index : state.menu.active
568
+ const item = state.menu.items[position]
569
+ if (!item) return false
570
+ const value = String(input.value != null ? input.value : '')
571
+ const trigger = detectTrigger(value, caretOf(input))
572
+ if (!trigger || trigger.kind !== item.kind) { closeMenu(); return false }
573
+ const insert = item.kind === 'command' ? '/' + item.name : item.insert
574
+ const result = replaceTrigger(value, trigger, insert)
575
+ closeMenu()
576
+ writeValue(result.value, result.caret)
577
+ options.onChange?.({
578
+ kind: item.kind,
579
+ item: item.kind === 'command'
580
+ ? { name: item.name, label: item.label }
581
+ : { insert: item.insert, label: item.label },
582
+ value: result.value,
583
+ caret: result.caret,
584
+ })
585
+ return true
586
+ }
587
+
588
+ function keydown(event) {
589
+ if (state.destroyed || !event || event.defaultPrevented) return false
590
+ // 输入法组合期间不拦截按键,避免吞掉中文候选确认。
591
+ if (event.isComposing || event.key === 'Process') return false
592
+ if (!state.menu.open) return false
593
+ const key = event.key
594
+ if (key === 'ArrowDown' || key === 'ArrowUp') {
595
+ try { event.preventDefault() } catch {}
596
+ move(key === 'ArrowDown' ? 1 : -1)
597
+ return true
598
+ }
599
+ if (key === 'Enter' || key === 'Tab') {
600
+ if (!state.menu.items.length) return false
601
+ const accepted = accept()
602
+ if (accepted) { try { event.preventDefault() } catch {} }
603
+ return accepted
604
+ }
605
+ if (key === 'Escape') {
606
+ try { event.preventDefault() } catch {}
607
+ closeMenu()
608
+ return true
609
+ }
610
+ return false
611
+ }
612
+
613
+ /* 供旧静态 chip/触控面板调用:草稿内插入,绝不整框覆盖。 */
614
+ function insertCommand(name) {
615
+ if (state.destroyed) return false
616
+ const clean = asText(name).trim().replace(/^\/+/, '')
617
+ if (!COMMAND_NAME.test(clean)) return false
618
+ const value = String(input.value != null ? input.value : '')
619
+ const trigger = detectTrigger(value, caretOf(input))
620
+ if (trigger && trigger.kind === 'command') {
621
+ const item = { name: clean, label: '/' + clean }
622
+ const result = replaceTrigger(value, trigger, '/' + clean)
623
+ closeMenu()
624
+ writeValue(result.value, result.caret)
625
+ options.onChange?.({ kind: 'command', item, value: result.value, caret: result.caret })
626
+ return true
627
+ }
628
+ // 命令必须位于整条草稿开头才会被主机当作斜杠命令;原文保留为后续参数,
629
+ // 不整框覆盖用户未发送的草稿。
630
+ const result = insertAt(value, 0, 0, '/' + clean + ' ')
631
+ closeMenu()
632
+ writeValue(result.value, result.caret)
633
+ options.onChange?.({ kind: 'command', item: { name: clean, label: '/' + clean }, value: result.value, caret: result.caret })
634
+ return true
635
+ }
636
+
637
+ function insertReference(token) {
638
+ const clean = asText(token).trim()
639
+ if (state.destroyed || !REFERENCE_TOKEN.test(clean)) return false
640
+ const value = String(input.value != null ? input.value : '')
641
+ const trigger = detectTrigger(value, caretOf(input))
642
+ if (trigger && trigger.kind === 'reference') {
643
+ const result = replaceTrigger(value, trigger, clean)
644
+ closeMenu()
645
+ writeValue(result.value, result.caret)
646
+ options.onChange?.({ kind: 'reference', item: { insert: clean, label: clean }, value: result.value, caret: result.caret })
647
+ return true
648
+ }
649
+ const start = caretOf(input)
650
+ const end = Math.max(start, Number.isInteger(input.selectionEnd) ? input.selectionEnd : start)
651
+ // 保留 @ 的主机原生词边界:前面紧贴字符时补一个空格。
652
+ const prefix = start > 0 && !/\s/.test(value[start - 1]) ? ' ' : ''
653
+ const result = insertAt(value, start, end, prefix + clean + ' ')
654
+ closeMenu()
655
+ writeValue(result.value, result.caret)
656
+ options.onChange?.({ kind: 'reference', item: { insert: clean, label: clean }, value: result.value, caret: result.caret })
657
+ return true
658
+ }
659
+
660
+ function roleLabel(role) {
661
+ if (role === 'user') return L('你的消息', 'Your message')
662
+ if (role === 'assistant') return L('助手消息', 'Assistant message')
663
+ return L('消息', 'Message')
664
+ }
665
+
666
+ function quoteView(quote) {
667
+ return {
668
+ id: quote.id,
669
+ messageId: quote.messageId,
670
+ role: quote.role,
671
+ text: quote.text,
672
+ truncated: quote.truncated,
673
+ preview: quote.preview,
674
+ }
675
+ }
676
+
677
+ function renderQuotes() {
678
+ if (!quoteList) return
679
+ if (typeof quoteList.replaceChildren !== 'function') return
680
+ quoteList.replaceChildren()
681
+ if (!state.quotes.length) {
682
+ quoteList.hidden = true
683
+ if (quoteList.classList) quoteList.classList.add('hidden')
684
+ return
685
+ }
686
+ quoteList.hidden = false
687
+ if (quoteList.classList) quoteList.classList.remove('hidden')
688
+ for (const quote of state.quotes) {
689
+ const expanded = state.expanded.has(quote.id)
690
+ const card = node('div', 'ct-quote')
691
+ card.dataset.quoteId = quote.id
692
+ card.setAttribute?.('data-quote-id', quote.id)
693
+ const head = node('div', 'ct-quote-head')
694
+ const meta = node('span', 'ct-quote-meta', L('引用', 'Quote') + ' · ' + roleLabel(quote.role) +
695
+ (quote.messageId ? ' · #' + quote.messageId.slice(0, 40) : ''))
696
+ meta.title = quote.messageId ? L('来源消息:', 'Source message: ') + quote.messageId : ''
697
+ const inspect = node('button', 'ct-quote-inspect', expanded ? L('收起', 'Collapse') : L('展开', 'Expand'))
698
+ inspect.type = 'button'
699
+ inspect.setAttribute?.('aria-expanded', expanded ? 'true' : 'false')
700
+ inspect.addEventListener?.('click', () => toggleQuote(quote.id))
701
+ const remove = node('button', 'ct-quote-remove', L('移除', 'Remove'))
702
+ remove.type = 'button'
703
+ remove.setAttribute?.('aria-label', L('移除引用', 'Remove quote'))
704
+ remove.addEventListener?.('click', () => removeQuote(quote.id))
705
+ head.append(meta, inspect, remove)
706
+ const preview = node('p', 'ct-quote-preview', quote.preview)
707
+ const full = node('pre', 'ct-quote-full', quote.text)
708
+ full.hidden = !expanded
709
+ if (quote.truncated) full.append(node('span', 'ct-quote-truncated', L('(已截断,仅引用前 4000 字符)', ' (truncated to the first 4,000 characters)')))
710
+ card.append(head, preview, full)
711
+ quoteList.append(card)
712
+ }
713
+ }
714
+
715
+ function quotesChanged() {
716
+ options.onQuotesChange?.(quotes())
717
+ }
718
+
719
+ function addQuote(raw) {
720
+ if (state.destroyed) return null
721
+ const sanitized = sanitizeQuote(raw)
722
+ if (!sanitized) return null
723
+ const key = sanitized.messageId + '\u0000' + sanitized.text
724
+ const existing = state.quotes.find(quote => quote.key === key)
725
+ if (existing) return quoteView(existing)
726
+ if (state.quotes.length >= MAX_QUOTES) {
727
+ notify(L('最多同时引用 8 条消息,请先移除部分引用。', 'You can quote up to 8 messages; remove one first.'), 'err')
728
+ return null
729
+ }
730
+ const quote = {
731
+ ...sanitized,
732
+ key,
733
+ id: 'ctq-' + instance + '-' + (++state.quoteSeq),
734
+ preview: quotePreview(sanitized.text),
735
+ }
736
+ state.quotes.push(quote)
737
+ renderQuotes()
738
+ quotesChanged()
739
+ return quoteView(quote)
740
+ }
741
+
742
+ function removeQuote(id) {
743
+ const index = state.quotes.findIndex(quote => quote.id === id)
744
+ if (index < 0) return false
745
+ state.quotes.splice(index, 1)
746
+ state.expanded.delete(id)
747
+ renderQuotes()
748
+ quotesChanged()
749
+ return true
750
+ }
751
+
752
+ function toggleQuote(id) {
753
+ const quote = state.quotes.find(item => item.id === id)
754
+ if (!quote) return false
755
+ if (state.expanded.has(id)) state.expanded.delete(id)
756
+ else state.expanded.add(id)
757
+ renderQuotes()
758
+ return true
759
+ }
760
+
761
+ function quotes() {
762
+ return state.quotes.map(quoteView)
763
+ }
764
+
765
+ function clearQuotes(ids) {
766
+ const remaining = ids ? state.quotes.filter(quote => !ids.includes(quote.id)) : []
767
+ if (remaining.length === state.quotes.length) return
768
+ state.quotes = remaining
769
+ if (ids) for (const id of ids) state.expanded.delete(id)
770
+ else state.expanded.clear()
771
+ renderQuotes()
772
+ quotesChanged()
773
+ }
774
+
775
+ function setScope(next) {
776
+ const key = scopeOf(next)
777
+ if (key === state.scopeKey) return
778
+ state.quotesByScope.set(state.scopeKey, state.quotes)
779
+ state.scopeKey = key
780
+ // 引用跟着所在会话的草稿走,切换会话绝不把引用带进另一条消息。
781
+ state.quotes = (state.quotesByScope.get(key) || []).slice()
782
+ state.expanded.clear()
783
+ state.generation += 1
784
+ state.hinted.clear()
785
+ state.commandCache = { key: null, at: 0, rows: null }
786
+ state.capabilities = { commands: 'unknown', references: 'unknown' }
787
+ closeMenu()
788
+ clearHint()
789
+ renderQuotes()
790
+ }
791
+
792
+ function status() {
793
+ return {
794
+ scope: state.scopeKey,
795
+ commands: state.capabilities.commands,
796
+ references: state.capabilities.references,
797
+ menuOpen: state.menu.open,
798
+ menuKind: state.menu.kind,
799
+ quotes: state.quotes.length,
800
+ }
801
+ }
802
+
803
+ function menuSnapshot() {
804
+ return {
805
+ open: state.menu.open,
806
+ kind: state.menu.kind,
807
+ query: state.menu.trigger ? state.menu.trigger.query : '',
808
+ active: state.menu.active,
809
+ items: state.menu.items.map(item => ({ kind: item.kind, label: item.label, name: item.name, insert: item.insert })),
810
+ }
811
+ }
812
+
813
+ function containsNode(container, target) {
814
+ for (let nodeValue = target; nodeValue; nodeValue = nodeValue.parentElement) {
815
+ if (nodeValue === container) return true
816
+ }
817
+ return false
818
+ }
819
+
820
+ function onDocumentPointerDown(event) {
821
+ const target = event && event.target
822
+ if (!target) return
823
+ if (containsNode(input, target) || (menu && containsNode(menu, target))) return
824
+ closeMenu()
825
+ }
826
+
827
+ const listeners = {
828
+ input: () => sync(),
829
+ keydown: event => keydown(event),
830
+ keyup: event => {
831
+ if (!event || !event.key) { sync(); return }
832
+ if (/^(Arrow|Home|End|Page)/.test(event.key)) sync()
833
+ },
834
+ click: () => sync(),
835
+ pointerdown: event => onDocumentPointerDown(event),
836
+ }
837
+ input.addEventListener?.('input', listeners.input)
838
+ input.addEventListener?.('keydown', listeners.keydown)
839
+ input.addEventListener?.('keyup', listeners.keyup)
840
+ input.addEventListener?.('click', listeners.click)
841
+ doc.addEventListener?.('pointerdown', listeners.pointerdown, true)
842
+
843
+ state.scopeKey = currentKey()
844
+ renderQuotes()
845
+ closeMenu()
846
+
847
+ function destroy() {
848
+ if (state.destroyed) return
849
+ state.destroyed = true
850
+ state.generation += 1
851
+ closeMenu()
852
+ input.removeEventListener?.('input', listeners.input)
853
+ input.removeEventListener?.('keydown', listeners.keydown)
854
+ input.removeEventListener?.('keyup', listeners.keyup)
855
+ input.removeEventListener?.('click', listeners.click)
856
+ doc.removeEventListener?.('pointerdown', listeners.pointerdown, true)
857
+ if (hint) { hint.hidden = true }
858
+ if (quoteList && quoteList.replaceChildren) quoteList.replaceChildren()
859
+ }
860
+
861
+ return {
862
+ sync, keydown, accept, move, close: closeMenu,
863
+ addQuote, removeQuote, toggleQuote, quotes, clearQuotes,
864
+ insertCommand, insertReference, setScope, destroy, status, menuSnapshot,
865
+ formatQuotes: () => formatQuotes(state.quotes),
866
+ }
867
+ }
868
+
869
+ const api = {
870
+ create,
871
+ detectTrigger,
872
+ fileReferenceMention,
873
+ insertAt,
874
+ normalizeCommandRows,
875
+ normalizeReferenceRows,
876
+ filterCommandRows,
877
+ filterReferenceRows,
878
+ sanitizeQuote,
879
+ quotePreview,
880
+ formatQuotes,
881
+ MAX_COMMANDS,
882
+ MAX_REFERENCES,
883
+ MAX_QUOTES,
884
+ MAX_QUOTE_CHARS,
885
+ }
886
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
887
+ else root.DshComposerTools = api
888
+ })(typeof window === 'undefined' ? globalThis : window)