@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.8

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 (210) hide show
  1. package/README.en.md +61 -0
  2. package/README.md +60 -2
  3. package/apk/dsh-remote.apk +0 -0
  4. package/approval-summary.mjs +115 -0
  5. package/client.js +197 -0
  6. package/cordis.patch.yml +5 -0
  7. package/doctor-skill.mjs +99 -0
  8. package/doctor-target.mjs +24 -0
  9. package/file-delivery.mjs +84 -0
  10. package/gateway-stats.cjs +501 -0
  11. package/gateway.cjs +8451 -0
  12. package/index.mjs +1784 -0
  13. package/insights.mjs +111 -0
  14. package/market.mjs +86 -0
  15. package/package.json +71 -4
  16. package/peak-reminders.mjs +50 -0
  17. package/plugin-center.mjs +777 -0
  18. package/plugin-transaction.mjs +300 -0
  19. package/public/activity.js +188 -0
  20. package/public/admin.html +820 -0
  21. package/public/admin.js +1167 -0
  22. package/public/announcement-forms.js +89 -0
  23. package/public/announcements.json +464 -0
  24. package/public/app.js +8826 -0
  25. package/public/approval-records.js +301 -0
  26. package/public/approval-summary.js +78 -0
  27. package/public/build.json +5 -0
  28. package/public/cache-upgrade.js +51 -0
  29. package/public/chat-copy.js +59 -0
  30. package/public/chat-files.js +87 -0
  31. package/public/desktop/desktop.css +816 -0
  32. package/public/desktop/desktop.html +871 -0
  33. package/public/desktop/desktop.js +4548 -0
  34. package/public/desktop/i18n.js +85 -0
  35. package/public/diagnostics.js +203 -0
  36. package/public/doctor-entry.js +94 -0
  37. package/public/doctor.css +205 -0
  38. package/public/doctor.js +769 -0
  39. package/public/donate.png +0 -0
  40. package/public/e2ee-transport.js +219 -0
  41. package/public/extensions.css +109 -0
  42. package/public/extensions.js +215 -0
  43. package/public/file-inbox.css +66 -0
  44. package/public/file-inbox.js +289 -0
  45. package/public/genui.css +8 -0
  46. package/public/genui.js +254 -0
  47. package/public/history.js +304 -0
  48. package/public/i18n.js +57 -0
  49. package/public/icon.svg +12 -0
  50. package/public/image-cache.js +141 -0
  51. package/public/image-preview.js +290 -0
  52. package/public/index.html +1548 -0
  53. package/public/insights.css +28 -0
  54. package/public/insights.js +290 -0
  55. package/public/jsqr.min.js +10104 -0
  56. package/public/lan-discovery.js +94 -0
  57. package/public/link-check.js +109 -0
  58. package/public/manifest.webmanifest +16 -0
  59. package/public/md.js +333 -0
  60. package/public/morphicons-init.js +41 -0
  61. package/public/motion.js +557 -0
  62. package/public/network.js +100 -0
  63. package/public/onboarding.css +36 -0
  64. package/public/onboarding.js +253 -0
  65. package/public/operations.js +141 -0
  66. package/public/permission-presets.js +159 -0
  67. package/public/plugin-center.css +120 -0
  68. package/public/plugin-center.js +666 -0
  69. package/public/plugin-icon.svg +5 -0
  70. package/public/plugin.html +68 -0
  71. package/public/plugin.js +211 -0
  72. package/public/qrcode.min.js +2297 -0
  73. package/public/relay-autopair.js +251 -0
  74. package/public/relay-devices.js +80 -0
  75. package/public/relay-settings.css +24 -0
  76. package/public/relay-settings.js +194 -0
  77. package/public/remote-state.js +27 -0
  78. package/public/remote-ui.css +148 -0
  79. package/public/remote-ui.js +243 -0
  80. package/public/session-deck.css +79 -0
  81. package/public/session-deck.js +180 -0
  82. package/public/session-presets.js +47 -0
  83. package/public/setup.css +18 -0
  84. package/public/setup.js +213 -0
  85. package/public/sha256.js +119 -0
  86. package/public/skills.css +81 -0
  87. package/public/skills.js +202 -0
  88. package/public/skins/blue-fish/DESIGN.md +24 -0
  89. package/public/skins/blue-fish/face.png +0 -0
  90. package/public/skins/blue-fish/icon-blush.png +0 -0
  91. package/public/skins/blue-fish/icon-sleep.png +0 -0
  92. package/public/skins/blue-fish/icon-smile.png +0 -0
  93. package/public/skins/blue-fish/icon-star.png +0 -0
  94. package/public/skins/blue-fish/icon-wink.png +0 -0
  95. package/public/skins/blue-fish/icon.png +0 -0
  96. package/public/skins/blue-fish/mascot.png +0 -0
  97. package/public/skins/blue-fish/pattern.png +0 -0
  98. package/public/skins/blue-fish/preview.html +12 -0
  99. package/public/skins/blue-fish/skin.css +122 -0
  100. package/public/skins/blue-fish/sparkles.svg +18 -0
  101. package/public/skins/bocchi/DESIGN.md +99 -0
  102. package/public/skins/bocchi/face.png +0 -0
  103. package/public/skins/bocchi/grain.png +0 -0
  104. package/public/skins/bocchi/icon-blush.png +0 -0
  105. package/public/skins/bocchi/icon-sleep.png +0 -0
  106. package/public/skins/bocchi/icon-smile.png +0 -0
  107. package/public/skins/bocchi/icon-star.png +0 -0
  108. package/public/skins/bocchi/icon-wink.png +0 -0
  109. package/public/skins/bocchi/icon.png +0 -0
  110. package/public/skins/bocchi/pattern-soft.png +0 -0
  111. package/public/skins/bocchi/pattern.png +0 -0
  112. package/public/skins/bocchi/preview.html +55 -0
  113. package/public/skins/bocchi/skin.css +233 -0
  114. package/public/skins/bocchi/stage-bg.png +0 -0
  115. package/public/skins/bocchi/stage-soft.png +0 -0
  116. package/public/skins/bocchi/stand.png +0 -0
  117. package/public/skins/bocchi/sticker-guitar.png +0 -0
  118. package/public/skins/kessoku/DESIGN.md +38 -0
  119. package/public/skins/kessoku/grain.png +0 -0
  120. package/public/skins/kessoku/skin.css +212 -0
  121. package/public/skins/kita/SOURCES.json +51 -0
  122. package/public/skins/kita/face.png +0 -0
  123. package/public/skins/kita/icon-live.png +0 -0
  124. package/public/skins/kita/icon-reddress.png +0 -0
  125. package/public/skins/kita/icon-seifuku.png +0 -0
  126. package/public/skins/kita/pattern.png +0 -0
  127. package/public/skins/kita/preview.html +56 -0
  128. package/public/skins/kita/skin.css +26 -0
  129. package/public/skins/kita/stand.png +0 -0
  130. package/public/skins/kita/sticker-live.png +0 -0
  131. package/public/skins/nijika/SOURCES.json +51 -0
  132. package/public/skins/nijika/face.png +0 -0
  133. package/public/skins/nijika/icon-live.png +0 -0
  134. package/public/skins/nijika/icon-reddress.png +0 -0
  135. package/public/skins/nijika/icon-seifuku.png +0 -0
  136. package/public/skins/nijika/pattern.png +0 -0
  137. package/public/skins/nijika/preview.html +56 -0
  138. package/public/skins/nijika/skin.css +25 -0
  139. package/public/skins/nijika/stand.png +0 -0
  140. package/public/skins/nijika/sticker-live.png +0 -0
  141. package/public/skins/penguin/DESIGN.md +33 -0
  142. package/public/skins/penguin/SOURCES.json +22 -0
  143. package/public/skins/penguin/aic-blueprint.svg +24 -0
  144. package/public/skins/penguin/endfield-triangles.svg +4 -0
  145. package/public/skins/penguin/face.png +0 -0
  146. package/public/skins/penguin/icon-blush.png +0 -0
  147. package/public/skins/penguin/icon-dizzy.png +0 -0
  148. package/public/skins/penguin/icon-laugh.png +0 -0
  149. package/public/skins/penguin/icon-sleep.png +0 -0
  150. package/public/skins/penguin/icon-smile.png +0 -0
  151. package/public/skins/penguin/icon-star.png +0 -0
  152. package/public/skins/penguin/icon-wink.png +0 -0
  153. package/public/skins/penguin/icon.png +0 -0
  154. package/public/skins/penguin/mascot.png +0 -0
  155. package/public/skins/penguin/pattern-night.png +0 -0
  156. package/public/skins/penguin/pattern.png +0 -0
  157. package/public/skins/penguin/preview.html +12 -0
  158. package/public/skins/penguin/skin.css +212 -0
  159. package/public/skins/ryo/SOURCES.json +51 -0
  160. package/public/skins/ryo/face.png +0 -0
  161. package/public/skins/ryo/icon-live.png +0 -0
  162. package/public/skins/ryo/icon-reddress.png +0 -0
  163. package/public/skins/ryo/icon-seifuku.png +0 -0
  164. package/public/skins/ryo/pattern.png +0 -0
  165. package/public/skins/ryo/preview.html +56 -0
  166. package/public/skins/ryo/skin.css +25 -0
  167. package/public/skins/ryo/stand.png +0 -0
  168. package/public/skins/ryo/sticker-live.png +0 -0
  169. package/public/sponsor-entry.js +21 -0
  170. package/public/styles.css +1494 -0
  171. package/public/subagents.css +61 -0
  172. package/public/subagents.js +275 -0
  173. package/public/task-board.js +109 -0
  174. package/public/teams.js +98 -0
  175. package/public/theme-picker.css +58 -0
  176. package/public/theme-vars.css +1044 -0
  177. package/public/theme.js +166 -0
  178. package/public/transcribe-core.js +74 -0
  179. package/public/turn-results.js +121 -0
  180. package/public/update.json +49 -0
  181. package/public/vendor/gsap/NOTICE.md +10 -0
  182. package/public/vendor/gsap/gsap.min.js +11 -0
  183. package/public/vendor/morphicons/LICENSE +21 -0
  184. package/public/vendor/morphicons/README.md +10 -0
  185. package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
  186. package/public/vendor/morphicons/dom.js +206 -0
  187. package/public/vendor/morphicons/element.js +261 -0
  188. package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
  189. package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
  190. package/public/version.json +3 -0
  191. package/public/voice-input.js +739 -0
  192. package/public/workflow.css +365 -0
  193. package/public/workflow.js +409 -0
  194. package/session-file.mjs +39 -0
  195. package/skills/dsh-remote-doctor/SKILL.md +186 -0
  196. package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
  197. package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
  198. package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
  199. package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
  200. package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
  201. package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
  202. package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
  203. package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
  204. package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
  205. package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
  206. package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
  207. package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
  208. package/skills.mjs +53 -0
  209. package/task-board.mjs +57 -0
  210. package/teams.mjs +58 -0
@@ -0,0 +1,301 @@
1
+ /* Durable approval records: session audit events (approval/asked + approval/decided)
2
+ * plus Auto review final denials. Collection, explanation and HTML live here so the
3
+ * mobile and desktop clients render the same record; storage stays in the client. */
4
+ 'use strict'
5
+ ;(function (root) {
6
+ const MAX_RECORDS = 40
7
+ const MAX_TEXT = 600
8
+ const AUTO_DENIED = /^Auto review rejected tool "([^"]+)"; its body was not executed(?::\s*([\s\S]*))?$/
9
+ const AUTO_ASKED = /^Auto review denied tool "([^"]+)"(?::\s*([\s\S]*))?$/
10
+ const AUTO_FAILED = /^Auto review of tool "([^"]+)" failed; its body was not executed(?::\s*([\s\S]*))?$/
11
+ const ESCALATION = /^escalate sandbox to ([a-z-]+):\s*([\s\S]*)$/
12
+ const OUTCOMES = {
13
+ 'allowed-once': 'approval.outcomeAllowed',
14
+ rejected: 'approval.outcomeRejected',
15
+ cancelled: 'approval.outcomeCancelled',
16
+ unavailable: 'approval.outcomeUnavailable',
17
+ pending: 'approval.outcomePending',
18
+ }
19
+ const WHY = {
20
+ 'allowed-once': 'approval.whyAllowed',
21
+ rejected: 'approval.whyRejected',
22
+ cancelled: 'approval.whyCancelled',
23
+ unavailable: 'approval.whyUnavailable',
24
+ pending: 'approval.whyPending',
25
+ 'auto-deny': 'approval.whyAutoDenied',
26
+ }
27
+ const KIND = {
28
+ auto: 'approval.kindAuto', escalation: 'approval.kindEscalation',
29
+ 'auto-deny': 'approval.kindAutoDenied', request: 'approval.kindRequest',
30
+ }
31
+
32
+ const text = (value, max = MAX_TEXT) => {
33
+ if (typeof value !== 'string') return ''
34
+ const trimmed = value.replace(/\s+/g, ' ').trim()
35
+ return trimmed.length > max ? trimmed.slice(0, max) + '…' : trimmed
36
+ }
37
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => (
38
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
39
+ ))
40
+ const timeOf = value => Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : 0
41
+
42
+ // 本地机械词句替换,不调用模型或外部翻译服务。未识别的原文保持不变。
43
+ // 先保护命令、路径、URL 和引号内容,避免翻译工具参数或改变其含义。
44
+ function chineseReference(value) {
45
+ const original = String(value || ''), protectedParts = []
46
+ let output = original.replace(/`[^`]*`|"[^"\n]*"|(?<![A-Za-z0-9])'[^'\n]*'|https?:\/\/[^\s]+|[A-Za-z]:[\\/][^\s,;]+|(?:\.{0,2}\/)[^\s,;]+/g, part => {
47
+ protectedParts.push(part); return '\uE000' + (protectedParts.length - 1) + '\uE001'
48
+ })
49
+ const phrases = [
50
+ [/\b(?:this|the) (?:command|action|operation) (?:would|will) delete files outside (?:of )?(?:the )?workspace\b/gi, '此操作将删除工作区之外的文件'],
51
+ [/\b(?:this|the) (?:command|action|operation) (?:could|may|might|can) delete files outside (?:of )?(?:the )?workspace\b/gi, '此操作可能删除工作区之外的文件'],
52
+ [/\bthe user (?:has not|hasn't) (?:explicitly )?authorized (?:this|the) (?:action|operation|command)\b/gi, '用户尚未明确授权此操作'],
53
+ [/\bthe user (?:did not|didn't) request\b/gi, '用户未要求'],
54
+ [/\bnot (?:explicitly )?requested by the user\b/gi, '用户未明确要求'],
55
+ [/\bno (?:explicit )?user (?:authorization|approval|consent)\b/gi, '没有明确的用户授权'],
56
+ [/\b(?:this|the) (?:command|action|operation|tool call) (?:could|may|might|can)\b/gi, '此操作可能'],
57
+ [/\b(?:this|the) (?:command|action|operation|tool call) (?:would|will)\b/gi, '此操作将'],
58
+ [/\b(?:is|are) not (?:explicitly )?authorized\b/gi, '未获明确授权'],
59
+ [/\b(?:is|are) not allowed\b/gi, '不允许'],
60
+ [/\b(?:does not|doesn't) (?:have|include) (?:explicit )?(?:user )?(?:authorization|approval)\b/gi, '未获得用户明确授权'],
61
+ [/\bwithout (?:explicit )?user (?:approval|authorization|consent)\b/gi, '未经用户明确批准'],
62
+ [/\b(?:requires?|needs?) (?:explicit )?user (?:approval|authorization|confirmation)\b/gi, '需要用户明确批准'],
63
+ [/\b(?:outside|out of) (?:of )?(?:the )?(?:(?:allowed|approved|current) )?workspace\b/gi, '在工作区之外'],
64
+ [/\boutside (?:the )?(?:authorized|approved) scope\b/gi, '超出已授权范围'],
65
+ [/\b(?:user |explicit )?(?:authorization|approval) is (?:missing|required|unclear|insufficient)\b/gi, '缺少明确的用户授权'],
66
+ [/\brecursive(?:ly)? delet(?:e|es|ion|ing)\b/gi, '递归删除'],
67
+ [/\bdelet(?:e|es|ing) (?:existing )?files\b/gi, '删除文件'],
68
+ [/\b(?:overwrite|overwrites|overwriting) (?:existing )?(?:files|data)\b/gi, '覆盖已有文件或数据'],
69
+ [/\birreversible (?:actions?|operations?|changes?)\b/gi, '不可逆操作'],
70
+ [/\bdestructive (?:actions?|operations?|changes?)\b/gi, '破坏性操作'],
71
+ [/\b(?:expose|leak|exfiltrate) (?:secrets|credentials|tokens|sensitive data)\b/gi, '泄露密钥、凭据或敏感数据'],
72
+ [/\b(?:send|transmit|upload) (?:private|sensitive|local) (?:data|files)\b/gi, '发送私有或敏感数据'],
73
+ [/\buntrusted (?:server|endpoint|service|destination)\b/gi, '不可信的服务'],
74
+ [/\bexternal (?:server|endpoint|service|destination)\b/gi, '外部服务'],
75
+ [/\b(?:elevated|administrator|admin) privileges\b/gi, '管理员权限'],
76
+ [/\bpermission denied\b/gi, '权限被拒绝'], [/\baccess denied\b/gi, '访问被拒绝'],
77
+ [/\bread[- ]only\b/gi, '只读'], [/\bnetwork access\b/gi, '网络访问'],
78
+ [/\b(?:review|request) timed out\b/gi, '审查请求超时'], [/\btimeout\b/gi, '超时'],
79
+ [/\b(?:risk of|may cause) data loss\b/gi, '可能导致数据丢失'],
80
+ ]
81
+ for (const [pattern, replacement] of phrases) output = output.replace(pattern, replacement)
82
+ return output.replace(/\uE000(\d+)\uE001/g, (_match, index) => protectedParts[Number(index)] ?? _match)
83
+ }
84
+
85
+ function feedback(value) {
86
+ const raw = String(value || ''), denied = AUTO_DENIED.exec(raw), asked = AUTO_ASKED.exec(raw), failed = AUTO_FAILED.exec(raw)
87
+ const match = denied || asked || failed
88
+ if (!match || root.I18N?.lang === 'en') return { text: raw, translated: false }
89
+ const prefix = failed ? '自动审查失败,工具未执行' : denied ? '自动审查拒绝,工具未执行' : '自动审查未通过,等待人工决定'
90
+ return { text: prefix + '(' + match[1] + ')' + (match[2] ? ':' + chineseReference(match[2]) : ''), translated: true }
91
+ }
92
+
93
+ function displayReason(value) {
94
+ const raw = String(value || ''), rendered = feedback(raw)
95
+ return rendered.translated ? rendered.text + '\n\n原文:' + raw : raw
96
+ }
97
+
98
+ function feedbackHtml(value) {
99
+ let raw = typeof value === 'string' ? value : ''
100
+ if (!raw && value && typeof value === 'object') {
101
+ const blocks = Array.isArray(value) ? value : value.content
102
+ raw = Array.isArray(blocks) ? blocks.filter(block => block?.type === 'text').map(block => String(block.text || '')).join('\n') : typeof value.text === 'string' ? value.text : ''
103
+ }
104
+ const rendered = feedback(raw)
105
+ if (!rendered.translated) return ''
106
+ let original
107
+ try { original = typeof value === 'string' ? value : JSON.stringify(value, null, 2) } catch { original = raw }
108
+ return `<section class="approval-translation"><h4>自动审查反馈 · 中文参考</h4><p>${esc(rendered.text.slice(0, 12000))}</p><details><summary>查看原文</summary><pre>${esc(String(original).slice(0, 12000))}</pre></details></section>`
109
+ }
110
+
111
+ function kindOf(reason) {
112
+ if (AUTO_ASKED.test(reason || '') || AUTO_DENIED.test(reason || '')) return 'auto'
113
+ if (ESCALATION.test(reason || '')) return 'escalation'
114
+ return 'request'
115
+ }
116
+
117
+ function create() { return new Map() }
118
+
119
+ function trim(records) {
120
+ if (records.size <= MAX_RECORDS) return
121
+ const rows = Array.from(records.values()).sort((a, b) => (b.askedAt || b.decidedAt || 0) - (a.askedAt || a.decidedAt || 0))
122
+ for (const row of rows.slice(MAX_RECORDS)) records.delete(row.id)
123
+ }
124
+
125
+ function put(records, next) {
126
+ if (!next.id) return false
127
+ records.set(next.id, { ...(records.get(next.id) || {}), ...next })
128
+ trim(records)
129
+ return true
130
+ }
131
+
132
+ function resultText(event) {
133
+ const message = event?.data?.message || event?.data || {}
134
+ const blocks = message?.content
135
+ if (!Array.isArray(blocks)) return ''
136
+ return blocks.filter(block => block?.type === 'text').map(block => String(block.text ?? '')).join('\n')
137
+ }
138
+
139
+ function fromAutoDenial(records, sessionId, event) {
140
+ const callId = text(event?.data?.message?.toolCallId || event?.data?.callId, 120)
141
+ const match = AUTO_DENIED.exec(resultText(event))
142
+ if (!match) return false
143
+ const id = 'auto-deny:' + String(sessionId || '') + ':' + (callId || String(event?.seq ?? ''))
144
+ if (records.has(id)) return false
145
+ return put(records, {
146
+ id, sessionId: String(sessionId || ''), kind: 'auto-deny',
147
+ toolName: text(match?.[1], 80) || 'tool', reason: text(match?.[2] || ''),
148
+ callId, outcome: 'rejected', askedAt: timeOf(event?.time), decidedAt: timeOf(event?.time),
149
+ askedSeq: Number.isFinite(event?.seq) ? event.seq : null, decidedSeq: Number.isFinite(event?.seq) ? event.seq : null,
150
+ })
151
+ }
152
+
153
+ /** Collect one session-log event. Returns true when the record set changed. */
154
+ function fromEvent(records, sessionId, event) {
155
+ const type = event?.type
156
+ const data = event?.data || {}
157
+ if (type === 'approval/asked') {
158
+ const id = typeof data.id === 'string' ? data.id : ''
159
+ if (!id) return false
160
+ const reason = text(data.reason)
161
+ return put(records, {
162
+ id, sessionId: String(sessionId || ''), kind: kindOf(reason), toolName: text(data.toolName, 80) || 'tool',
163
+ reason, callId: text(data.callId, 120), askedAt: timeOf(event.time), askedSeq: Number.isFinite(event.seq) ? event.seq : null,
164
+ outcome: records.get(id)?.outcome || 'pending', detailsPending: false,
165
+ })
166
+ }
167
+ if (type === 'approval/decided') {
168
+ const id = typeof data.id === 'string' ? data.id : ''
169
+ if (!id) return false
170
+ const previous = records.get(id)
171
+ if (Number.isFinite(previous?.decidedSeq) && Number.isFinite(event.seq) && event.seq < previous.decidedSeq) return false
172
+ return put(records, {
173
+ id, sessionId: previous?.sessionId || String(sessionId || ''), detailsPending: previous?.detailsPending ?? !previous,
174
+ outcome: text(data.outcome, 40) || 'unknown',
175
+ decidedAt: timeOf(event.time), decidedSeq: Number.isFinite(event.seq) ? event.seq : null,
176
+ })
177
+ }
178
+ if (type === 'tool/result') return fromAutoDenial(records, sessionId, event)
179
+ return false
180
+ }
181
+
182
+ /** Collect one live gateway frame (approval/requested or approval/resolved). */
183
+ function fromFrame(records, frame) {
184
+ if (!frame || typeof frame !== 'object') return false
185
+ if (frame.type === 'approval/requested') {
186
+ const id = typeof frame.approvalId === 'string' ? frame.approvalId : ''
187
+ if (!id) return false
188
+ const reason = text(frame.reason)
189
+ return put(records, {
190
+ id, sessionId: String(frame.sessionId || ''), kind: kindOf(reason), toolName: text(frame.toolName, 80) || 'tool',
191
+ reason, callId: text(frame.callId, 120), askedAt: records.get(id)?.askedAt || Date.now(),
192
+ askedSeq: records.get(id)?.askedSeq ?? null, detailsPending: false,
193
+ outcome: records.get(id)?.outcome && records.get(id).outcome !== 'pending' ? records.get(id).outcome : 'pending',
194
+ })
195
+ }
196
+ if (frame.type === 'approval/resolved') {
197
+ const id = typeof frame.approvalId === 'string' ? frame.approvalId : ''
198
+ if (!id) return false
199
+ const previous = records.get(id)
200
+ return put(records, { id, sessionId: previous?.sessionId || String(frame.sessionId || ''),
201
+ detailsPending: previous?.detailsPending ?? !previous, outcome: text(frame.outcome, 40) || 'unknown', decidedAt: Date.now() })
202
+ }
203
+ return false
204
+ }
205
+
206
+ function summary(record) {
207
+ const reason = record?.reason || ''
208
+ const auto = AUTO_ASKED.exec(reason) || AUTO_DENIED.exec(reason)
209
+ if (auto) return { kind: 'auto', text: text(auto[2] || '') }
210
+ const escalation = ESCALATION.exec(reason)
211
+ if (escalation) return { kind: 'escalation', target: escalation[1], text: text(escalation[2]) }
212
+ return { kind: record?.kind === 'auto-deny' ? 'auto-deny' : 'request', text: text(reason) }
213
+ }
214
+
215
+ const outcomeKey = outcome => OUTCOMES[outcome] || 'approval.outcomeUnknown'
216
+ const isPending = record => !record?.outcome || record.outcome === 'pending' || record.outcome === 'unknown'
217
+ const kindKey = record => KIND[record?.kind] || KIND[(summary(record) || {}).kind] || KIND.request
218
+
219
+ function list(records, limit = MAX_RECORDS) {
220
+ if (!(records instanceof Map)) return []
221
+ return Array.from(records.values()).filter(record => !record.detailsPending)
222
+ .sort((a, b) => (b.askedAt || 0) - (a.askedAt || 0))
223
+ .slice(0, Math.max(1, limit))
224
+ }
225
+
226
+ function reasonHtml(record, t) {
227
+ const info = summary(record)
228
+ const label = t(KIND[info.kind] || KIND.request)
229
+ const raw = info.text || t('approval.noReason')
230
+ const localized = root.I18N?.lang !== 'en' && ['auto', 'auto-deny'].includes(info.kind) ? chineseReference(raw) : raw
231
+ const original = localized !== raw ? `<details class="approval-original"><summary>查看原文 · 中文为机械翻译参考</summary><div>${esc(raw)}</div></details>` : ''
232
+ return `<div class="approval-record-reason"><span class="approval-record-kind">${esc(label)}</span><div class="approval-record-copy">${esc(localized)}${original}</div></div>`
233
+ }
234
+
235
+ function recordHtml(record, t, { session = '', now = Date.now() } = {}) {
236
+ const outcome = isPending(record) ? 'pending' : record.outcome
237
+ const badgeKey = outcomeKey(outcome)
238
+ const whyKey = WHY[record?.kind === 'auto-deny' ? 'auto-deny' : outcome] || WHY.pending
239
+ const time = record.decidedAt || record.askedAt
240
+ return `<article class="approval-record${isPending(record) ? ' is-pending' : ''}" data-approval-record="${esc(record.id)}">
241
+ <div class="approval-record-head"><span class="approval-record-title">🔐 ${esc(record.toolName || t('tool.default'))}</span><span class="approval-record-badge ${esc(outcome)}">${esc(t(badgeKey))}</span></div>
242
+ ${reasonHtml(record, t)}
243
+ <div class="approval-record-why">${esc(t(whyKey))}</div>
244
+ <div class="approval-record-meta">${session ? esc(session) + ' · ' : ''}${esc(relTime(time, t, now))}</div>
245
+ </article>`
246
+ }
247
+
248
+ function lineHtml(record, t, { now = Date.now() } = {}) {
249
+ const outcome = isPending(record) ? 'pending' : record.outcome
250
+ const badgeKey = outcomeKey(outcome)
251
+ const whyKey = WHY[record?.kind === 'auto-deny' ? 'auto-deny' : outcome] || WHY.pending
252
+ return `<details class="approval-event${isPending(record) ? ' is-pending' : ''}" data-approval-event="${esc(record.id)}">
253
+ <summary>🔐 ${esc(record.toolName || t('tool.default'))}<span class="approval-event-badge ${esc(outcome)}">${esc(t(badgeKey))}</span><span class="approval-event-time">${esc(relTime(record.decidedAt || record.askedAt, t, now))}</span></summary>
254
+ ${reasonHtml(record, t)}
255
+ <div class="approval-record-why">${esc(t(whyKey))}</div>
256
+ </details>`
257
+ }
258
+
259
+ function relTime(millis, t, now = Date.now()) {
260
+ if (!millis) return ''
261
+ const delta = Math.max(0, now - millis)
262
+ if (delta < 60_000) return t('approval.justNow')
263
+ if (delta < 3_600_000) return t('approval.minutesAgo', { n: Math.floor(delta / 60_000) })
264
+ if (delta < 86_400_000) return t('approval.hoursAgo', { n: Math.floor(delta / 3_600_000) })
265
+ const date = new Date(millis)
266
+ const pad = value => String(value).padStart(2, '0')
267
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
268
+ }
269
+
270
+ function serialize(records) {
271
+ return JSON.stringify(Array.from(records.values()).map(record => ({
272
+ id: record.id, sessionId: record.sessionId, kind: record.kind, toolName: record.toolName,
273
+ reason: record.reason, callId: record.callId, outcome: record.outcome,
274
+ askedAt: record.askedAt, decidedAt: record.decidedAt,
275
+ detailsPending: record.detailsPending === true, askedSeq: record.askedSeq, decidedSeq: record.decidedSeq,
276
+ })))
277
+ }
278
+
279
+ function restore(raw) {
280
+ const records = create()
281
+ let rows
282
+ try { rows = JSON.parse(raw || '[]') } catch { return records }
283
+ if (!Array.isArray(rows)) return records
284
+ for (const row of rows.slice(0, MAX_RECORDS)) {
285
+ if (!row || typeof row.id !== 'string' || !row.id) continue
286
+ put(records, {
287
+ id: row.id.slice(0, 512), sessionId: text(row.sessionId, 120), kind: kindOf(text(row.reason)) === 'auto' && row.kind === 'auto-deny' ? 'auto-deny' : (['auto', 'escalation', 'auto-deny', 'request'].includes(row.kind) ? row.kind : kindOf(text(row.reason))),
288
+ toolName: text(row.toolName, 80) || 'tool', reason: text(row.reason), callId: text(row.callId, 120),
289
+ outcome: text(row.outcome, 40) || 'pending', askedAt: timeOf(row.askedAt), decidedAt: timeOf(row.decidedAt),
290
+ detailsPending: row.detailsPending === true,
291
+ askedSeq: Number.isFinite(row.askedSeq) ? row.askedSeq : null, decidedSeq: Number.isFinite(row.decidedSeq) ? row.decidedSeq : null,
292
+ })
293
+ }
294
+ return records
295
+ }
296
+
297
+ root.DshApprovalRecords = {
298
+ create, fromEvent, fromFrame, summary, kindOf, list, recordHtml, lineHtml,
299
+ outcomeKey, isPending, serialize, restore, relTime, chineseReference, displayReason, feedbackHtml, MAX: MAX_RECORDS,
300
+ }
301
+ })(window)
@@ -0,0 +1,78 @@
1
+ /* Explicit, cached explanations. No summary request is made during rendering. */
2
+ ;(function (root) {
3
+ 'use strict'
4
+ const cache = new Map()
5
+ let config, scope, mounted = false
6
+ const text = (zh, en) => root.I18N?.lang === 'en' ? en : zh
7
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' }[c]))
8
+ function context() {
9
+ const connection = config?.capture()
10
+ if (scope && !scope.valid()) reset()
11
+ if (connection) scope = connection
12
+ return connection
13
+ }
14
+ const keyOf = item => JSON.stringify([item.sessionId, item.approvalId, item.callId || '', item.reason || ''])
15
+ const eligible = item => /^Auto review denied tool "[^"]+"(?::|$)/.test(item?.reason || '')
16
+ const current = item => config.items().some(value => keyOf(value) === keyOf(item))
17
+ function html(item) {
18
+ if (!eligible(item)) return ''
19
+ context()
20
+ const row = cache.get(keyOf(item))
21
+ const label = text('AI 中文总结(消耗 token)', 'AI Chinese summary (uses tokens)')
22
+ return '<section class="approval-ai" data-approval-ai="' + esc(item.approvalId) + '" data-ai-session="' + esc(item.sessionId) + '">'
23
+ + '<button type="button" class="deck-summary-button" data-ai-generate' + (row ? ' disabled' : '') + '>' + (row?.phase === 'loading' ? text('正在生成…', 'Generating…') : label) + '</button>'
24
+ + '<p class="approval-ai-copy" role="status">' + esc(row?.text || text('按需生成,仅供参考;请结合完整请求决定。', 'Optional reference; decide using the full request.')) + '</p></section>'
25
+ }
26
+ function update(item) {
27
+ for (const node of root.document?.querySelectorAll('[data-approval-ai]') || []) {
28
+ if (node.dataset.approvalAi !== item.approvalId || node.dataset.aiSession !== item.sessionId) continue
29
+ // Set text only; model output is never interpreted as HTML or Markdown.
30
+ const row = cache.get(keyOf(item)), button = node.querySelector('[data-ai-generate]'), copy = node.querySelector('[role="status"]')
31
+ if (button) { button.disabled = !!row; button.textContent = row?.phase === 'loading' ? text('正在生成…','Generating…') : text('AI 中文总结(消耗 token)','AI Chinese summary (uses tokens)') }
32
+ if (copy && row) copy.textContent = row.text
33
+ }
34
+ }
35
+ async function generate(item) {
36
+ const connection = context(), key = keyOf(item)
37
+ if (!connection?.valid() || !eligible(item) || cache.has(key) || !current(item)) return
38
+ if (!root.confirm(text('将此审批的工具名和审查理由交给当前会话配置的模型生成中文短摘要,会消耗 token;不发送完整对话或工具参数。摘要仅供参考,原始请求和审批决定保持不变。是否继续?',
39
+ 'Send this approval’s tool name and review reason to the current session model for a Chinese summary? This uses tokens. Full conversation and tool arguments are excluded. The summary is only a reference; the request and approval decision remain unchanged.'))) return
40
+ if (!connection.valid() || !current(item)) return
41
+ while (cache.size >= 40) {
42
+ const old = [...cache].find(([, value]) => value.phase !== 'loading')
43
+ if (!old) return
44
+ cache.delete(old[0])
45
+ }
46
+ const controller = new AbortController(), row = { phase: 'loading', controller, text: text('正在生成,不影响允许或拒绝。','Generating; Allow and Reject remain available.') }
47
+ cache.set(key, row); update(item)
48
+ const timer = setTimeout(() => controller.abort(), 18_000)
49
+ try {
50
+ const response = await root.fetch(config.url(connection, '/remote/api/approval-summary'), { method: 'POST',
51
+ headers: { ...config.headers(connection), 'content-type':'application/json' },
52
+ body: JSON.stringify({ sessionId:item.sessionId, approvalId:item.approvalId, ...(item.callId ? { callId:item.callId } : {}), consent:true }),
53
+ signal:controller.signal })
54
+ const value = await response.json()
55
+ if (!response.ok || value.ok !== true || typeof value.summary !== 'string' || value.summary.length > 240) throw Error('unavailable')
56
+ row.phase = 'done'; row.text = text('AI 中文总结(仅供参考):','AI Chinese summary (reference only): ') + value.summary
57
+ } catch {
58
+ row.phase = 'error'; row.text = text('摘要未生成,可能已产生 token 消耗;请查看原始理由。本请求不会自动重试。','Summary unavailable; tokens may have been used. Read the original reason. This request will not retry automatically.')
59
+ } finally {
60
+ clearTimeout(timer)
61
+ if (connection.valid() && cache.get(key) === row && current(item)) update(item)
62
+ }
63
+ }
64
+ function reset() { for (const row of cache.values()) row.controller?.abort(); cache.clear(); scope = null }
65
+ function mount(value) {
66
+ config = value
67
+ if (mounted) return
68
+ mounted = true
69
+ root.document?.addEventListener('click', event => {
70
+ const button = event.target?.closest?.('[data-ai-generate]'), node = button?.closest('[data-approval-ai]')
71
+ if (!node) return
72
+ event.preventDefault(); event.stopPropagation()
73
+ const item = config.items().find(item => item.approvalId === node.dataset.approvalAi && item.sessionId === node.dataset.aiSession)
74
+ if (item) void generate(item)
75
+ })
76
+ }
77
+ root.DshApprovalSummary = { html, mount, reset, generate }
78
+ })(window)
@@ -0,0 +1,5 @@
1
+ {
2
+ "schema": 1,
3
+ "version": "0.8.8",
4
+ "buildId": "db1965b1fd55b19b6b76fca1c6fbbce17629afaaf951617208205ff154140ea7"
5
+ }
@@ -0,0 +1,51 @@
1
+ /* Trusted package/build identity and upgrade handling. Never clears credentials. */
2
+ ;(function(root){
3
+ 'use strict'
4
+ const HEX=/^[a-f0-9]{64}$/, loaded=root.document?.querySelector('meta[name="dsh-remote-build"]')?.content
5
+ const script=root.document?.currentScript?.src
6
+ let config,checking=false,banner,autoReloaded=false
7
+ const text=(zh,en)=>root.I18N?.lang==='en'?en:zh
8
+ async function check(){
9
+ if(checking||!config||!HEX.test(loaded||'')||!script)return
10
+ checking=true
11
+ try{
12
+ const url=new URL('build.json',script);url.searchParams.set('fresh',String(Date.now()))
13
+ const response=await root.fetch(url.href,{cache:'no-store',signal:AbortSignal.timeout(5000)})
14
+ if(!response.ok)return
15
+ const next=(await response.json()).buildId
16
+ if(!HEX.test(next||'')||next===loaded)return
17
+ if(!banner){
18
+ banner=root.document.createElement('aside');banner.className='cache-upgrade-notice';banner.setAttribute('role','status')
19
+ banner.style.cssText='position:fixed;z-index:39;top:8px;left:12px;right:12px;padding:12px;background:var(--dsr-panel,#fff);color:var(--dsr-text,#182331);border:1px solid var(--dsr-line,#778899);border-radius:12px;display:flex;gap:10px;align-items:center'
20
+ const copy=root.document.createElement('span'),button=root.document.createElement('button')
21
+ copy.textContent=text('新界面已就绪,重新载入即可更新;未发送内容会保留。','An updated interface is ready. Reload to update; unsent content is preserved.')
22
+ button.type='button';button.textContent=text('重新载入','Reload')
23
+ button.style.minHeight='44px'
24
+ button.addEventListener('click',()=>{if(config.safe())root.location.reload();else root.alert(text('请先处理当前审批、上传或未发送内容,再重新载入。','Finish pending approvals/uploads or save unsent content before reloading.'))})
25
+ banner.append(copy,button);root.document.body.append(banner)
26
+ }
27
+ // A running turn, draft, approval or upload must never be interrupted.
28
+ // One automatic reload per target build also prevents a bad cache loop.
29
+ const key='dshRemoteBuildReload:'+root.location.pathname
30
+ if(!autoReloaded&&config.safe()){
31
+ let saved
32
+ try{saved=root.sessionStorage.getItem(key)}catch{return}
33
+ if(saved===next)return
34
+ try{root.sessionStorage.setItem(key,next);if(root.sessionStorage.getItem(key)!==next)return}catch{return}
35
+ autoReloaded=true;root.location.reload()
36
+ }
37
+ }catch{}finally{checking=false}
38
+ }
39
+ async function migrate(){
40
+ try{const scopes=config?.scopes?.();if(scopes?.length)await root.DshHistory?.migrateLegacy?.(scopes)}catch{}
41
+ }
42
+ function mount(value){
43
+ if(config)return
44
+ config=value
45
+ const run=()=>{void check();void migrate()}
46
+ root.setTimeout(run,1500);root.setInterval(run,60_000)
47
+ root.document?.addEventListener('visibilitychange',()=>{if(!root.document.hidden)run()})
48
+ root.addEventListener?.('online',run)
49
+ }
50
+ root.DshCacheUpgrade={mount,check,migrate}
51
+ })(window)
@@ -0,0 +1,59 @@
1
+ /* Clipboard actions belong to one displayed source block, never a whole reply. */
2
+ ;(function(root) {
3
+ 'use strict'
4
+ const scopes = new WeakMap(); let nextScope = 0
5
+ const resetTimers = new WeakMap()
6
+ const label = (zh, en) => root.I18N?.lang === 'en' ? en : zh
7
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))
8
+ function scope(history) { if (!scopes.has(history)) scopes.set(history, String(++nextScope)); return scopes.get(history) }
9
+ function code(source, language = '', options = {}) {
10
+ const lang = /^[a-zA-Z0-9_+.-]{1,40}$/.test(String(language)) ? String(language) : ''
11
+ const markdown = /^(?:md|markdown)$/i.test(lang)
12
+ const name = markdown ? 'Markdown' : lang || label('代码', 'Code')
13
+ const action = markdown ? label('复制 Markdown', 'Copy Markdown') : options.label || label('复制代码', 'Copy code')
14
+ const scoped = options.scope == null ? '' : ` data-chat-copy-scope="${esc(options.scope)}"`
15
+ return `<div class="chat-code"><div class="chat-code-toolbar"><span class="chat-code-language">${esc(name)}</span><button type="button" class="chat-copy-button" data-chat-copy-code${scoped} aria-label="${esc(action)}" title="${esc(action)}"><svg class="chat-copy-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/></svg><svg class="chat-copy-check" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 4 4L19 6"/></svg><span class="chat-copy-status" aria-live="polite"></span></button></div><pre><code>${esc(source)}</code></pre></div>`
16
+ }
17
+ function bind(box, host) {
18
+ if (!box || box.dataset.chatCopyBound) return
19
+ box.dataset.chatCopyBound = '1'
20
+ box.addEventListener('click', async event => {
21
+ const button = event.target.closest?.('[data-chat-copy-code]')
22
+ if (!button || !box.contains(button) || button.disabled) return
23
+ const context = host.capture()
24
+ if (!context.valid()) return
25
+ if (context.history && button.dataset.chatCopyScope !== scope(context.history)) return
26
+ const source = button.closest('.chat-code')?.querySelector('pre code')?.textContent
27
+ if (source == null || source === '') return
28
+ event.preventDefault(); event.stopPropagation()
29
+ clearTimeout(resetTimers.get(button))
30
+ delete button.dataset.copyState
31
+ button.disabled = true
32
+ const original = button.getAttribute('aria-label')
33
+ const status = button.querySelector('.chat-copy-status')
34
+ if (status) status.textContent = ''
35
+ try {
36
+ const ok = await host.copy(source)
37
+ if (context.valid() && box.contains(button)) {
38
+ button.dataset.copyState = ok ? 'copied' : 'error'
39
+ const feedback = label(ok ? '已复制' : '复制失败,请重试', ok ? 'Copied' : 'Copy failed. Please retry.')
40
+ button.setAttribute('aria-label', feedback); button.title = feedback
41
+ if (status) status.textContent = ok ? feedback : ''
42
+ if (!ok) host.notice(feedback, 'err')
43
+ }
44
+ } catch { if (context.valid()) host.notice(label('复制失败,请重试', 'Copy failed. Please retry.'), 'err') }
45
+ finally {
46
+ button.disabled = false
47
+ resetTimers.set(button, setTimeout(() => {
48
+ delete button.dataset.copyState
49
+ resetTimers.delete(button)
50
+ if (status) status.textContent = ''
51
+ if (original) { button.setAttribute('aria-label', original); button.title = original }
52
+ }, 1600))
53
+ }
54
+ })
55
+ }
56
+ const api = { scope, code, bind }
57
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
58
+ else root.DshChatCopy = api
59
+ })(typeof window === 'undefined' ? globalThis : window)
@@ -0,0 +1,87 @@
1
+ /* Explicit user downloads only; attachment IDs never become filesystem paths. */
2
+ (function(root,factory){const api=factory(root);if(typeof module==='object')module.exports=api;root.DshChatFiles=api})(typeof window!=='undefined'?window:globalThis,(root)=>{
3
+ const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))
4
+ function relativePath(path) {
5
+ return typeof path==='string' && !!path && path.length<=4096 && !/[\x00-\x1f]/.test(path) && !/^(?:[a-z][a-z0-9+.-]*:|[\\/]|#|\?)/i.test(path)
6
+ && !/^[a-f0-9]{64}$/i.test(path) && !/[?#]/.test(path)
7
+ && (/^\.{1,2}[\\/]/.test(path) || /(?:^|[\\/])[^\\/]+\.[^\\/.]+$/.test(path))
8
+ }
9
+ function pathOf(value,cwd='') {
10
+ if(typeof value!=='string'||value.length>4096||/[\x00-\x1f]/.test(value))return ''
11
+ let path=value.trim()
12
+ if(/^file:/i.test(path)){try{const u=new URL(path);if(u.hostname&&u.hostname!=='localhost')return '';path=decodeURIComponent(u.pathname);if(/^\/[a-z]:\//i.test(path))path=path.slice(1)}catch{return ''}}
13
+ if(/[\x00-\x1f]/.test(path))return ''
14
+ if(/^(?:[a-z]:[\\/]|\/(?!\/))/i.test(path))return path
15
+ if(relativePath(path)){const base=pathOf(cwd);if(base)return base.replace(/[\\/]+$/,'')+'/'+path}
16
+ return ''
17
+ }
18
+
19
+ function render(block) {
20
+ const a=block.attachment||block,raw=a.path||block.path||''
21
+ const path=pathOf(raw)||(relativePath(raw)?raw:''),id=/^[a-f0-9]{64}$/.test(a.attachmentId||'')?a.attachmentId:''
22
+ const name=a.name||block.name||'file'
23
+ const preview=path&&/\.(?:txt|md|markdown|log|json|jsonl|js|ts|py|css|html|htm|xml|yaml|yml|toml)$/i.test(name||path)&&Number(a.bytes??block.bytes??0)<=1048576
24
+ return `<div class="chat-file"><span class="chat-file-name">📎 ${esc(name)} <small>${esc(a.bytes??block.bytes??'')} bytes</small></span>${preview?`<button type="button" data-dsh-preview="1" data-dsh-file-path="${esc(path)}" data-dsh-file-name="${esc(name)}">预览</button>`:''}${id||path?`<button type="button" ${id?'data-dsh-attachment="'+esc(id)+'"':''} ${path?'data-dsh-file-path="'+esc(path)+'"':''} data-dsh-file-name="${esc(name)}">下载文件</button>`:''}</div>`
25
+ }
26
+ async function trackDownload(id,control,c) {
27
+ // New shells expose DownloadManager state; older shells keep their enqueue-only contract.
28
+ for (;;) {
29
+ await new Promise(resolve=>setTimeout(resolve,1000))
30
+ if(!c.valid() || control.isConnected===false)return
31
+ const status=JSON.parse(root.NativeFile.getFileDownloadStatus(String(id))||'{}')
32
+ if(status.phase==='complete'){
33
+ control.textContent='下载完成 · 再次下载'
34
+ c.notice('下载完成:下载/dsh-remote/'+status.name,'ok');return
35
+ }
36
+ if(status.phase==='error')throw Error(status.error||'下载失败,请重试')
37
+ if(status.phase==='unknown')throw Error('系统下载任务已移除,请重试')
38
+ control.textContent=status.phase==='paused'?'下载暂停,等待网络…':'下载中…'
39
+ }
40
+ }
41
+ function bind(target,config){target.addEventListener('click',async event=>{
42
+ const control=event.target.closest?.('[data-dsh-file-path],[data-dsh-attachment]')
43
+ if(!control||!target.contains(control)||control.getAttribute('aria-busy')==='true')return
44
+ event.preventDefault()
45
+ const c=config(),id=control.dataset.dshAttachment,path=pathOf(control.dataset.dshFilePath,c.cwd)
46
+ if(!c.valid())return
47
+ if(!id&&!path){c.notice('无法定位文件,请核对当前会话的工作目录','err');return}
48
+ const name=(control.dataset.dshFileName||path.split(/[\\/]/).pop()||'download').replace(/[\\/\x00-\x1f]/g,'_')
49
+ if(control.dataset.dshPreview){if(c.preview)await c.preview(path,name);return}
50
+ const makeUrl=attachment=>{
51
+ const url=new URL(c.server+(attachment?'/remote/api/session-file':'/fs/file'),root.location?.href)
52
+ if(attachment){url.searchParams.set('sessionId',c.sessionId);url.searchParams.set('attachmentId',id)}
53
+ else url.searchParams.set('path',path)
54
+ return url
55
+ }
56
+ const head=url=>fetch(url,{method:'HEAD',redirect:'error',headers:c.headers,signal:AbortSignal.timeout(15000)})
57
+ const original=control.textContent
58
+ control.setAttribute('aria-busy','true')
59
+ try{
60
+ let url=makeUrl(!!id),response=await head(url)
61
+ if(!c.valid())return
62
+ // Only an explicit host path can back up an unsupported attachment endpoint.
63
+ if(id&&path&&[404,405,501,503].includes(response.status)){
64
+ url=makeUrl(false);response=await head(url);if(!c.valid())return
65
+ }
66
+ if(!response.ok)throw Error(response.status===403?'主机不允许下载这个文件':response.status===404?'文件不存在或不属于当前会话':[405,501,503].includes(response.status)?'主机版本暂不支持附件下载,请更新主机插件':'文件下载失败(HTTP '+response.status+')')
67
+ if(c.native){
68
+ if(!root.NativeFile?.downloadToDownloads)throw Error('当前 App 不支持系统下载,请更新 App')
69
+ const task=root.NativeFile.downloadToDownloads(url.href,name,c.token)
70
+ if(root.NativeFile.getFileDownloadStatus&&!task)throw Error('系统下载未能启动,请重试')
71
+ c.notice('已交给系统下载,请在下载目录查看','ok')
72
+ if(root.NativeFile.getFileDownloadStatus&&task){
73
+ control.textContent='下载中…'
74
+ await trackDownload(task,control,c)
75
+ }
76
+ }else{
77
+ if(c.token)url.searchParams.set('token',c.token)
78
+ const link=document.createElement('a');link.href=url.href;link.download=name;link.referrerPolicy='no-referrer'
79
+ document.body.append(link);link.click();link.remove()
80
+ c.notice('已交给浏览器下载,请在下载目录查看','ok')
81
+ }
82
+ }catch(error){
83
+ if(c.valid()){control.textContent=original;c.notice(error.message,'err')}
84
+ }finally{control.removeAttribute('aria-busy')}
85
+ })}
86
+ return {pathOf,relativePath,render,bind}
87
+ })