dsh-remote-plugin 0.8.8 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) 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 +583 -84
  5. package/index.mjs +1 -0
  6. package/package.json +8 -3
  7. package/public/activity.js +97 -10
  8. package/public/admin.html +34 -33
  9. package/public/admin.js +10 -2
  10. package/public/announcements.json +36 -0
  11. package/public/app.js +1564 -226
  12. package/public/bc-integration.css +81 -0
  13. package/public/build.json +2 -2
  14. package/public/composer-tools.css +184 -0
  15. package/public/composer-tools.js +888 -0
  16. package/public/desktop/desktop.html +94 -73
  17. package/public/desktop/desktop.js +726 -83
  18. package/public/e2ee-config.js +5 -0
  19. package/public/e2ee-transport.js +23 -4
  20. package/public/file-inbox.js +77 -18
  21. package/public/genui.css +10 -0
  22. package/public/genui.js +22 -4
  23. package/public/history.js +114 -17
  24. package/public/host-queue.js +232 -0
  25. package/public/host-schedule.js +301 -0
  26. package/public/host-state.css +19 -0
  27. package/public/index.html +332 -140
  28. package/public/md.js +21 -1
  29. package/public/network.js +33 -1
  30. package/public/onboarding.js +3 -3
  31. package/public/operations.js +4 -3
  32. package/public/plan-review.css +297 -0
  33. package/public/plan-review.js +642 -0
  34. package/public/plugin.html +29 -28
  35. package/public/relay-autopair.js +30 -10
  36. package/public/relay-devices.js +7 -3
  37. package/public/relay-settings.css +11 -0
  38. package/public/relay-settings.js +372 -30
  39. package/public/session-cache.js +85 -0
  40. package/public/session-management.css +61 -0
  41. package/public/session-management.js +742 -0
  42. package/public/session-search.css +137 -0
  43. package/public/session-search.js +977 -0
  44. package/public/skins/blue-fish/preview.html +3 -3
  45. package/public/skins/bocchi/preview.html +5 -5
  46. package/public/skins/kita/preview.html +6 -6
  47. package/public/skins/miku/SOURCES.json +10 -0
  48. package/public/skins/miku/chibi.png +0 -0
  49. package/public/skins/miku/preview.html +33 -0
  50. package/public/skins/miku/skin.css +82 -0
  51. package/public/skins/nijika/preview.html +6 -6
  52. package/public/skins/penguin/preview.html +3 -3
  53. package/public/skins/ryo/preview.html +6 -6
  54. package/public/slash-suggestions.js +15 -3
  55. package/public/sponsor-entry.js +11 -3
  56. package/public/styles.css +141 -21
  57. package/public/subagents.css +5 -0
  58. package/public/subagents.js +52 -0
  59. package/public/theme-vars.css +65 -1
  60. package/public/theme.js +4 -3
  61. package/public/turn-diff.css +323 -0
  62. package/public/turn-diff.js +778 -0
  63. package/public/update.json +12 -12
  64. package/public/version.json +1 -1
  65. package/public/workflow.css +305 -34
  66. package/public/workflow.js +141 -41
@@ -0,0 +1,642 @@
1
+ /* Plan mode status, reviewed-plan requests and read-only plan history.
2
+ *
3
+ * This module owns no durable state: every value comes from the Host through an
4
+ * explicit adapter. Plan mode is the `plan` Session projection
5
+ * (`{ active, pending }`, written by @deepseek-ai/dsh-plan-mode); entering and
6
+ * leaving use the Host `/plan` and `/plan off` slash-command bridge; a pending
7
+ * review is the Host `user-questions` waterfall request whose question carries
8
+ * `intent.kind === "plan-review"`, and it is answered through the Host
9
+ * client-response channel with the Host-provided option label — never through a
10
+ * normal chat message.
11
+ *
12
+ * Adapter contract (all optional except the used ones):
13
+ * command(line, { sessionId }) -> Promise<{ executed:boolean, message?:string }>
14
+ * Host slash-command bridge (`POST /remote/api/command`, polls command status).
15
+ * respond(rpcId, value) -> Promise<boolean>
16
+ * Host interaction answer channel (`POST /api/respond`); true when accepted.
17
+ * state.sessionId() -> string|null
18
+ * state.snapshot(sessionId) -> {
19
+ * plan?: { active:boolean, pending:boolean }, // Session projection value
20
+ * questions?: Array<{ rpcId, sessionId, questions }>, // pending mux frames
21
+ * connected?: boolean, readOnly?: boolean,
22
+ * capability?: boolean | { plan?: boolean }
23
+ * } | null
24
+ * state.entries(sessionId) -> Array<{ seq, event }> // Session log entries
25
+ * dom.root -> Element // container for rendered HTML
26
+ * onOpenPlan({ sessionId, planText, title, source, seq, callId }) -> void
27
+ * notify(message, kind) -> void // optional toast bridge
28
+ */
29
+ 'use strict'
30
+ ;(function (root) {
31
+ const text = (zh, en) => (root.I18N?.lang === 'en' ? en : zh)
32
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
33
+ const MAX_HISTORY = 20
34
+ const MAX_PLAN_CHARS = 24000
35
+
36
+ function clip(value, max) {
37
+ const body = String(value ?? '')
38
+ return body.length > max ? body.slice(0, max) + '…' : body
39
+ }
40
+ function cleanup(body) {
41
+ return String(body ?? '').replace(/\r\n/g, '\n').trim()
42
+ }
43
+ function firstHeading(plan) {
44
+ for (const line of String(plan || '').split('\n')) {
45
+ const match = /^#{1,6}\s+(.+?)\s*$/.exec(line)
46
+ if (match) return match[1]
47
+ }
48
+ return ''
49
+ }
50
+ function preview(plan, max = 180) {
51
+ const lines = cleanup(plan).split('\n').map(line => line.replace(/^#{1,6}\s+/, '').replace(/^[-*+]\s+/, '').trim()).filter(Boolean)
52
+ return clip(lines.slice(0, 2).join(' · '), max)
53
+ }
54
+ function safeArray(value) { return Array.isArray(value) ? value : [] }
55
+ function safeCount(value) {
56
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0
57
+ }
58
+ function parseArguments(value) {
59
+ if (value && typeof value === 'object') return value
60
+ if (typeof value !== 'string' || !value.trim()) return null
61
+ try {
62
+ const parsed = JSON.parse(value)
63
+ return parsed && typeof parsed === 'object' ? parsed : null
64
+ } catch { return null }
65
+ }
66
+ function resultText(data) {
67
+ const direct = data?.result ?? data?.output ?? data?.message ?? data
68
+ if (typeof direct === 'string') return direct
69
+ const blocks = Array.isArray(direct?.content) ? direct.content : Array.isArray(data?.content) ? data.content : []
70
+ if (Array.isArray(blocks)) return blocks.filter(block => block?.type === 'text').map(block => String(block.text ?? '')).join('\n')
71
+ if (direct && typeof direct.text === 'string') return direct.text
72
+ return ''
73
+ }
74
+
75
+ /* ---------------------------------------------------------------- plan state */
76
+
77
+ /**
78
+ * The Host plan projection value, never a client guess. Capability absence is
79
+ * the key's absence, so an unknown value is reported as unsupported instead of
80
+ * being rendered as "inactive".
81
+ */
82
+ function normalizePlan(value) {
83
+ if (!value || typeof value !== 'object') return { supported: false, active: false, pending: false, target: null }
84
+ const active = value.active === true
85
+ const pending = value.pending === true
86
+ return { supported: true, active, pending, target: pending ? !active : active }
87
+ }
88
+
89
+ function capabilityOf(snapshot) {
90
+ const capability = snapshot?.capability
91
+ if (typeof capability === 'boolean') return capability
92
+ if (capability && typeof capability === 'object' && typeof capability.plan === 'boolean') return capability.plan
93
+ return null
94
+ }
95
+
96
+ /**
97
+ * Derive everything the chip renders, including why an action is unavailable.
98
+ * The returned `action.kind` is `enter` or `exit`; a pending selection disables
99
+ * the control until the Host projection settles.
100
+ */
101
+ function describePlan(snapshot) {
102
+ const snap = snapshot && typeof snapshot === 'object' ? snapshot : {}
103
+ const capability = capabilityOf(snap)
104
+ const plan = normalizePlan(snap.plan)
105
+ const connected = snap.connected !== false
106
+ const readOnly = snap.readOnly === true
107
+ const supported = capability === true || (capability !== false && plan.supported)
108
+ // A plan is only "known" when the Host says it is active or a switch/review is pending.
109
+ // Disconnected sessions must not surface a stale Plan card when neither is true.
110
+ const exists = plan.supported && (plan.active || plan.pending)
111
+ const state = {
112
+ supported, connected, readOnly, exists,
113
+ active: plan.active, pending: plan.pending, target: plan.target,
114
+ status: 'unsupported', label: '', hint: '', action: null,
115
+ }
116
+ if (!supported) {
117
+ state.label = text('此主机不支持 Plan 模式', 'Plan mode is not available on this host')
118
+ state.hint = text('主机未提供 plan 投影(旧版主机或未启用 plan-mode 插件)。', 'The Host exposes no plan projection (older Host or plan-mode not enabled).')
119
+ return state
120
+ }
121
+ if (!connected) {
122
+ state.status = 'disconnected'
123
+ state.label = text('连接已断开,无法读取 Plan 状态', 'Disconnected — plan state unavailable')
124
+ state.hint = text('重新连接后以主机状态为准。', 'Reconnect to read the Host state.')
125
+ return state
126
+ }
127
+ if (!plan.supported) {
128
+ state.status = 'unavailable'
129
+ state.label = text('等待主机 Plan 状态', 'Waiting for the Host plan state')
130
+ state.hint = text('投影尚未加载,不能推断当前模式。', 'The projection has not loaded; the current mode is unknown.')
131
+ return state
132
+ }
133
+ if (readOnly) {
134
+ state.status = 'readonly'
135
+ state.label = plan.active
136
+ ? text('Plan 模式已开启(只读会话)', 'Plan mode is on (read-only session)')
137
+ : text('Plan 模式未开启(只读会话)', 'Plan mode is off (read-only session)')
138
+ state.hint = text('只读会话不能进入、退出或审批计划。', 'A read-only session cannot enter, leave, or review a plan.')
139
+ return state
140
+ }
141
+ if (plan.pending) {
142
+ state.status = plan.active ? 'leaving' : 'entering'
143
+ state.label = plan.active
144
+ ? text('正在退出 Plan 模式…', 'Leaving plan mode…')
145
+ : text('正在进入 Plan 模式…', 'Entering plan mode…')
146
+ state.hint = text('等待主机确认,暂不可再次切换。', 'Waiting for Host confirmation; switching is paused.')
147
+ state.action = { kind: plan.active ? 'exit' : 'enter', label: text('切换中…', 'Switching…'), disabled: true }
148
+ return state
149
+ }
150
+ if (plan.active) {
151
+ state.status = 'active'
152
+ state.label = text('Plan 模式已开启', 'Plan mode is on')
153
+ state.action = { kind: 'exit', label: text('退出计划模式', 'Leave plan mode'), disabled: false }
154
+ } else {
155
+ state.status = 'inactive'
156
+ state.label = text('Plan 模式未开启', 'Plan mode is off')
157
+ state.action = { kind: 'enter', label: text('进入计划模式', 'Enter plan mode'), disabled: false }
158
+ }
159
+ return state
160
+ }
161
+
162
+ /* ------------------------------------------------------------ review request */
163
+
164
+ /**
165
+ * Recognize the Host plan-review question. The plan markdown is the question
166
+ * `detail`; the approve label is named by `intent.approve` and any other option
167
+ * declines. No intent means this is an ordinary question, not a plan review.
168
+ */
169
+ function planReviewOf(question) {
170
+ // Accept one question, a questions array, or a frame-like `{ questions }`
171
+ // object so both ingestion shapes used by the clients resolve the review.
172
+ if (Array.isArray(question)) {
173
+ for (const item of question) {
174
+ const found = planReviewOf(item)
175
+ if (found) return found
176
+ }
177
+ return null
178
+ }
179
+ if (!question || typeof question !== 'object') return null
180
+ if (!question.intent && Array.isArray(question.questions)) return planReviewOf(question.questions)
181
+ const intent = question.intent
182
+ if (!intent || intent.kind !== 'plan-review') return null
183
+ const planText = cleanup(question.detail)
184
+ const options = safeArray(question.options).filter(option => option && typeof option.label === 'string' && option.label)
185
+ const approveLabel = typeof intent.approve === 'string' && intent.approve ? intent.approve : ''
186
+ const decline = options.find(option => option.label !== approveLabel) || null
187
+ const header = typeof question.header === 'string' ? question.header.trim() : ''
188
+ return {
189
+ questionId: typeof question.id === 'string' ? question.id : '',
190
+ header,
191
+ title: firstHeading(planText) || header || text('计划审阅', 'Plan review'),
192
+ planText,
193
+ hasPlan: planText.length > 0,
194
+ summary: preview(planText),
195
+ options,
196
+ approveLabel,
197
+ approveDescription: (options.find(option => option.label === approveLabel) || {}).description || '',
198
+ keepLabel: decline ? decline.label : '',
199
+ keepDescription: decline ? decline.description || '' : '',
200
+ callId: typeof intent.callId === 'string' ? intent.callId : '',
201
+ }
202
+ }
203
+
204
+ /** Extract a plan review from one mux `question/requested` frame. */
205
+ function reviewFromFrame(frame) {
206
+ const payload = frame && frame.payload && typeof frame.payload === 'object' ? frame.payload : frame
207
+ if (!payload || payload.type !== 'question/requested') return null
208
+ for (const question of safeArray(payload.questions)) {
209
+ const review = planReviewOf(question)
210
+ if (review) return { rpcId: String(frame?.rpcId ?? payload.rpcId ?? ''), sessionId: String(payload.sessionId || ''), ...review }
211
+ }
212
+ return null
213
+ }
214
+
215
+ /* ------------------------------------------------------------- plan history */
216
+
217
+ /** Read-only plan invocations recorded by the Host as `exit_plan_mode` calls. */
218
+ function historyPlans(entries) {
219
+ const rows = safeArray(entries).filter(entry => entry && entry.event && typeof entry.event === 'object')
220
+ const sorted = rows.slice().sort((a, b) => safeCount(a.seq) - safeCount(b.seq))
221
+ const seen = new Set()
222
+ const calls = new Map()
223
+ const outcomes = new Map()
224
+ for (const entry of sorted) {
225
+ if (Number.isSafeInteger(entry.seq)) {
226
+ if (seen.has(entry.seq)) continue
227
+ seen.add(entry.seq)
228
+ }
229
+ const event = entry.event
230
+ const data = event.data || {}
231
+ if (event.type === 'tool/call') {
232
+ const name = data.name || data.toolName
233
+ if (name !== 'exit_plan_mode') continue
234
+ const args = parseArguments(data.arguments ?? data.args ?? data.input)
235
+ const planText = cleanup(args?.plan)
236
+ if (!planText) continue
237
+ const callId = String(data.callId || '')
238
+ calls.set(callId || 'seq-' + entry.seq, {
239
+ seq: Number.isSafeInteger(entry.seq) ? entry.seq : null,
240
+ turn: Number.isSafeInteger(data.turn) ? data.turn : null,
241
+ callId,
242
+ planText,
243
+ title: firstHeading(planText) || text('未命名计划', 'Untitled plan'),
244
+ outcome: 'unknown',
245
+ })
246
+ continue
247
+ }
248
+ if (event.type !== 'tool/result') continue
249
+ const callId = String(data.callId || data.message?.source?.callId || '')
250
+ if (!callId) continue
251
+ const failed = data.error !== undefined || data.ok === false || data.isError === true
252
+ const body = resultText(data)
253
+ outcomes.set(callId, failed ? 'failed' : /plan approved/i.test(body) ? 'approved' : /dismissed|keep planning/i.test(body) ? 'dismissed' : 'unknown')
254
+ }
255
+ for (const [key, call] of calls) {
256
+ const outcome = outcomes.get(call.callId) || 'unknown'
257
+ calls.set(key, { ...call, outcome, readOnly: true })
258
+ }
259
+ return Array.from(calls.values()).sort((a, b) => (b.seq || 0) - (a.seq || 0)).slice(0, MAX_HISTORY)
260
+ }
261
+
262
+ /* ------------------------------------------------------------------ markup */
263
+
264
+ function statusHtml(view) {
265
+ const state = view.plan
266
+ // There is nothing to show while disconnected and no plan was ever active or pending.
267
+ if (state.status === 'disconnected' && !state.exists) return ''
268
+ const reviewClass = view.review ? ' dr-plan-status--review' : ''
269
+ const action = state.action
270
+ const button = action
271
+ ? `<button type="button" class="dr-plan-btn dr-plan-btn--${esc(action.kind)}" data-dr-plan-action="${esc(action.kind)}"${action.disabled ? ' disabled' : ''}>${esc(action.label)}</button>`
272
+ : ''
273
+ return `<div class="dr-plan-status dr-plan-status--${esc(state.status)}${reviewClass}" data-dr-plan-status role="status" aria-live="polite">
274
+ <span class="dr-plan-badge">Plan</span>
275
+ <span class="dr-plan-status-copy">${esc(state.label)}</span>
276
+ ${button}
277
+ ${state.hint ? `<span class="dr-plan-status-hint">${esc(state.hint)}</span>` : ''}
278
+ ${view.review ? `<span class="dr-plan-status-review">${esc(text('有待审阅计划', 'Plan awaiting review'))}</span>` : ''}
279
+ </div>`
280
+ }
281
+
282
+ function reviewHtml(view) {
283
+ const review = view.review
284
+ if (!review) return ''
285
+ const locked = view.busy === 'approve' || view.busy === 'keep' || !view.plan.connected || view.plan.readOnly
286
+ const disabled = locked || !review.rpcId
287
+ const approveButton = review.approveLabel
288
+ ? `<button type="button" class="dr-plan-btn dr-plan-btn--approve" data-dr-plan-action="approve" title="${esc(text('主机选项:', 'Host option: ') + review.approveLabel)}"${disabled ? ' disabled' : ''}>${esc(text('批准并退出计划模式', 'Approve and leave plan mode'))}<span class="dr-plan-option">${esc(review.approveLabel)}</span></button>`
289
+ : ''
290
+ const keepButton = review.keepLabel
291
+ ? `<button type="button" class="dr-plan-btn dr-plan-btn--keep" data-dr-plan-action="keep" title="${esc(text('主机选项:', 'Host option: ') + review.keepLabel)}"${disabled ? ' disabled' : ''}>${esc(text('继续完善计划', 'Keep planning'))}<span class="dr-plan-option">${esc(review.keepLabel)}</span></button>`
292
+ : ''
293
+ const feedback = review.keepLabel
294
+ ? `<label class="dr-plan-feedback"><span>${esc(text('反馈(随主机选项提交,可留空)', 'Feedback (sent with the Host option, optional)'))}</span><textarea rows="2" maxlength="2000" data-dr-plan-feedback placeholder="${esc(text('希望计划如何调整…', 'What should change in the plan…'))}"></textarea></label>`
295
+ : ''
296
+ let hint = ''
297
+ if (!review.hasPlan) hint = text('主机未提供计划正文,无法查看完整计划。', 'The Host supplied no plan text, so the full plan cannot be shown.')
298
+ else if (!review.approveLabel) hint = text('主机未提供批准选项,不能猜测审批结果。', 'The Host named no approve option; the verdict is not guessed.')
299
+ else if (!review.rpcId) hint = text('主机未提供请求标识,无法提交审批。', 'The Host supplied no request id, so the review cannot be answered.')
300
+ else if (!view.plan.connected) hint = text('连接已断开,无法提交审批。', 'Disconnected — the review cannot be submitted.')
301
+ else if (view.plan.readOnly) hint = text('只读会话不能提交审批。', 'A read-only session cannot answer the review.')
302
+ else if (view.busy === 'approve' || view.busy === 'keep') hint = text('正在提交…', 'Submitting…')
303
+ return `<section class="dr-plan-review" data-dr-plan-scope data-dr-plan-review="${esc(review.rpcId)}" aria-label="${esc(text('计划审阅', 'Plan review'))}">
304
+ <div class="dr-plan-review-head"><span class="dr-plan-review-strip">${esc(text('计划审阅', 'Plan review'))}</span><span class="dr-plan-review-state">${esc(text('待审阅', 'Awaiting review'))}</span></div>
305
+ <h4 class="dr-plan-review-title">${esc(review.title)}</h4>
306
+ ${review.hasPlan ? `<p class="dr-plan-review-summary">${esc(review.summary)}</p>
307
+ <details class="dr-plan-doc" data-dr-plan-doc><summary>${esc(text('查看完整计划', 'View full plan'))}</summary><pre>${esc(clip(review.planText, MAX_PLAN_CHARS))}</pre></details>` : ''}
308
+ ${hint ? `<p class="dr-plan-hint">${esc(hint)}</p>` : ''}
309
+ <div class="dr-plan-review-actions">${approveButton}${keepButton}</div>
310
+ ${feedback}
311
+ <p class="dr-plan-review-note">${esc(text('审批通过与继续完善都会按主机提供的选项经交互接口提交,不会作为普通聊天消息发送。', 'Approve and keep-planning are submitted through the Host interaction channel using the Host options, never as chat messages.'))}</p>
312
+ <span class="dr-plan-review-status" data-dr-plan-review-status role="status" aria-live="polite"></span>
313
+ </section>`
314
+ }
315
+
316
+ const OUTCOME_LABELS = {
317
+ approved: () => text('已批准', 'Approved'),
318
+ dismissed: () => text('继续计划中', 'Kept planning'),
319
+ failed: () => text('审批失败', 'Review failed'),
320
+ unknown: () => text('结果未知', 'Outcome unknown'),
321
+ }
322
+
323
+ function historyHtml(plans) {
324
+ const rows = safeArray(plans)
325
+ if (!rows.length) return ''
326
+ return `<section class="dr-plan-history" data-dr-plan-history aria-label="${esc(text('历史计划(只读)', 'Plan history (read-only)'))}">
327
+ <h4 class="dr-plan-history-head">${esc(text('历史计划(只读)', 'Plan history (read-only)'))}</h4>
328
+ ${rows.map(plan => `<article class="dr-plan-history-item" data-dr-plan-history-item="${plan.seq ?? ''}">
329
+ <div class="dr-plan-history-top"><span class="dr-plan-history-title">${esc(plan.title)}</span><span class="dr-plan-history-badge">${esc(text('历史 · 只读', 'History · read-only'))}</span></div>
330
+ <div class="dr-plan-history-meta">${plan.turn != null ? esc(text('回合 ', 'Turn ') + plan.turn) + ' · ' : ''}${esc((OUTCOME_LABELS[plan.outcome] || OUTCOME_LABELS.unknown)())}</div>
331
+ <details class="dr-plan-doc"><summary>${esc(text('查看计划正文', 'View plan text'))}</summary><pre>${esc(clip(plan.planText, MAX_PLAN_CHARS))}</pre></details>
332
+ </article>`).join('')}
333
+ </section>`
334
+ }
335
+
336
+ function noticeHtml(view) {
337
+ if (!view.notice) return ''
338
+ return `<p class="dr-plan-notice dr-plan-notice--${esc(view.notice.kind || 'info')}" data-dr-plan-notice role="status" aria-live="polite">${esc(view.notice.text)}</p>`
339
+ }
340
+
341
+ function viewHtml(view) {
342
+ return `<div class="dr-plan" data-dr-plan-root>${statusHtml(view)}${noticeHtml(view)}${reviewHtml(view)}${historyHtml(view.plans)}</div>`
343
+ }
344
+
345
+ /**
346
+ * Whether the plan section has anything meaningful to show. Kept outside the
347
+ * DOM so the app can hide the whole section when a disconnected session has
348
+ * no plan and no review/history to display.
349
+ */
350
+ function hasContent(view) {
351
+ if (!view || typeof view !== 'object') return false
352
+ if (view.review) return true
353
+ if (Array.isArray(view.plans) && view.plans.length) return true
354
+ const plan = view.plan
355
+ if (!plan || typeof plan !== 'object') return false
356
+ if (!plan.supported) return plan.status === 'unsupported'
357
+ if (plan.status === 'disconnected') return plan.exists === true
358
+ return true
359
+ }
360
+
361
+ /* --------------------------------------------------------------- controller */
362
+
363
+ function create(adapter) {
364
+ const api = adapter && typeof adapter === 'object' ? adapter : {}
365
+ const stateApi = api.state && typeof api.state === 'object' ? api.state : {}
366
+ let sessionId = typeof stateApi.sessionId === 'function' ? stateApi.sessionId() : (stateApi.sessionId || null)
367
+ let rootEl = api.dom?.root || null
368
+ let unbind = null
369
+ let disposed = false
370
+ let busy = ''
371
+ let notice = null
372
+ const frameReviews = new Map()
373
+ const resolved = new Set()
374
+ const answered = new Set()
375
+ const knownReviews = new Set()
376
+ const extraEntries = new Map()
377
+
378
+ function currentSnapshot(id) {
379
+ if (typeof stateApi.snapshot !== 'function') return {}
380
+ const value = stateApi.snapshot(id)
381
+ return value && typeof value === 'object' ? value : {}
382
+ }
383
+ function currentEntries(id) {
384
+ const base = typeof stateApi.entries === 'function' ? safeArray(stateApi.entries(id)) : []
385
+ const extra = extraEntries.get(id) || []
386
+ if (!extra.length) return base
387
+ const seen = new Set(base.map(entry => entry?.seq))
388
+ return base.concat(extra.filter(entry => entry && !seen.has(entry.seq))).sort((a, b) => safeCount(a.seq) - safeCount(b.seq))
389
+ }
390
+ function currentReview(id) {
391
+ const snap = currentSnapshot(id)
392
+ for (const frame of safeArray(snap.questions)) {
393
+ if (!frame || typeof frame !== 'object') continue
394
+ if (frame.sessionId && id && String(frame.sessionId) !== String(id)) continue
395
+ const rpcId = String(frame.rpcId || '')
396
+ if (rpcId && (resolved.has(rpcId) || answered.has(rpcId))) continue
397
+ for (const question of safeArray(frame.questions)) {
398
+ const review = planReviewOf(question)
399
+ if (review) return { rpcId, sessionId: id, source: 'state', ...review }
400
+ }
401
+ }
402
+ const frames = Array.from(frameReviews.entries()).reverse()
403
+ for (const [rpcId, review] of frames) {
404
+ if (review.sessionId && id && String(review.sessionId) !== String(id)) continue
405
+ if (resolved.has(rpcId) || answered.has(rpcId)) continue
406
+ return { ...review, rpcId, sessionId: id, source: 'frame' }
407
+ }
408
+ return null
409
+ }
410
+ function buildView() {
411
+ const snap = currentSnapshot(sessionId)
412
+ const plan = describePlan(snap)
413
+ const review = currentReview(sessionId)
414
+ if (review && review.rpcId) knownReviews.add(review.rpcId)
415
+ return {
416
+ sessionId,
417
+ plan,
418
+ review,
419
+ plans: historyPlans(currentEntries(sessionId)),
420
+ busy,
421
+ notice,
422
+ }
423
+ }
424
+ function render(container) {
425
+ if (container && typeof container === 'object') {
426
+ if (rootEl && rootEl !== container) { if (unbind) unbind(); unbind = null }
427
+ rootEl = container
428
+ }
429
+ const view = buildView()
430
+ if (rootEl && typeof rootEl === 'object' && 'innerHTML' in rootEl) {
431
+ rootEl.innerHTML = viewHtml(view)
432
+ if (!unbind) unbind = bind(rootEl, controller)
433
+ }
434
+ return view
435
+ }
436
+ function describeProblem() {
437
+ if (disposed) return text('模块已释放', 'The module was disposed')
438
+ if (!sessionId) return text('未选择会话', 'No session selected')
439
+ const plan = describePlan(currentSnapshot(sessionId))
440
+ if (!plan.supported) return text('此主机不支持 Plan 模式', 'Plan mode is not available on this host')
441
+ if (!plan.connected) return text('连接已断开,无法提交', 'Disconnected — nothing was submitted')
442
+ if (plan.readOnly) return text('只读会话无法提交', 'A read-only session cannot submit')
443
+ return ''
444
+ }
445
+ function fail(message) {
446
+ notice = { kind: 'err', text: message }
447
+ render()
448
+ return { ok: false, error: message }
449
+ }
450
+ function succeed(message) {
451
+ notice = { kind: 'ok', text: message }
452
+ render()
453
+ return { ok: true }
454
+ }
455
+ async function runPlanCommand(line, message) {
456
+ if (busy) return { ok: false, error: text('操作进行中', 'An action is already running') }
457
+ const problem = describeProblem()
458
+ if (problem) return fail(problem)
459
+ if (typeof api.command !== 'function') return fail(text('未接入主机命令接口,无法切换 Plan 模式', 'The Host command bridge is not connected'))
460
+ busy = 'command'
461
+ render()
462
+ try {
463
+ const result = await api.command(line, { sessionId })
464
+ if (disposed) return { ok: false, error: text('模块已释放', 'The module was disposed') }
465
+ if (!result || result.executed !== true) {
466
+ const reason = result?.message ? String(result.message).slice(0, 300) : text('主机未执行该命令', 'The Host did not execute the command')
467
+ return fail(reason)
468
+ }
469
+ return succeed(message)
470
+ } catch (error) {
471
+ if (disposed) return { ok: false, error: text('模块已释放', 'The module was disposed') }
472
+ return fail(error?.message ? String(error.message).slice(0, 300) : text('主机命令失败', 'The Host command failed'))
473
+ } finally {
474
+ busy = ''
475
+ render()
476
+ }
477
+ }
478
+ async function submitAnswer(review, value, successMessage) {
479
+ if (busy) return { ok: false, error: text('操作进行中', 'An action is already running') }
480
+ if (typeof api.respond !== 'function') return fail(text('未接入主机交互接口,无法提交审批', 'The Host interaction channel is not connected'))
481
+ const problem = describeProblem()
482
+ if (problem) return fail(problem)
483
+ if (!review.rpcId) return fail(text('主机未提供请求标识,无法提交审批', 'The Host supplied no request id'))
484
+ busy = 'approve'
485
+ render()
486
+ try {
487
+ const accepted = await api.respond(review.rpcId, value)
488
+ if (disposed) return { ok: false, error: text('模块已释放', 'The module was disposed') }
489
+ if (accepted !== true) return fail(text('主机未接受本次提交:待审阅请求可能已在其他终端处理或已失效。', 'The Host did not accept the submission; the review may have been handled elsewhere or expired.'))
490
+ answered.add(review.rpcId)
491
+ frameReviews.delete(review.rpcId)
492
+ return succeed(successMessage)
493
+ } catch (error) {
494
+ if (disposed) return { ok: false, error: text('模块已释放', 'The module was disposed') }
495
+ return fail(error?.message ? String(error.message).slice(0, 300) : text('提交审批失败', 'The review submission failed'))
496
+ } finally {
497
+ busy = ''
498
+ render()
499
+ api.notify?.(notice?.text || '', notice?.kind)
500
+ }
501
+ }
502
+ const controller = {
503
+ get session() { return sessionId },
504
+ view: buildView,
505
+ render,
506
+ refresh() { return render() },
507
+ setSession(next) {
508
+ sessionId = next === null || next === undefined || next === '' ? null : String(next)
509
+ notice = null
510
+ busy = ''
511
+ return render()
512
+ },
513
+ handleFrame(frame) {
514
+ if (disposed) return false
515
+ const payload = frame && frame.payload && typeof frame.payload === 'object' ? frame.payload : frame
516
+ if (!payload || typeof payload !== 'object') return false
517
+ if (payload.type === 'question/requested') {
518
+ const review = reviewFromFrame(frame)
519
+ if (!review || !review.rpcId) return false
520
+ resolved.delete(review.rpcId)
521
+ answered.delete(review.rpcId)
522
+ frameReviews.set(review.rpcId, review)
523
+ notice = null
524
+ render()
525
+ return true
526
+ }
527
+ if (payload.type === 'question/resolved') {
528
+ const rpcId = String(payload.questionRpcId || '')
529
+ if (!rpcId) return false
530
+ const frameReview = frameReviews.get(rpcId)
531
+ const sameSession = !frameReview?.sessionId || !sessionId || String(frameReview.sessionId) === String(sessionId)
532
+ const known = sameSession && (frameReviews.has(rpcId) || knownReviews.has(rpcId))
533
+ const ours = answered.has(rpcId)
534
+ resolved.add(rpcId)
535
+ frameReviews.delete(rpcId)
536
+ if (known && !ours) notice = { kind: 'info', text: text('待审阅请求已在其他终端处理或已结束。', 'The review was handled in another client or has ended.') }
537
+ render()
538
+ return known || ours
539
+ }
540
+ if (payload.type === 'session/projection') {
541
+ if (payload.key !== 'plan') return false
542
+ render()
543
+ return true
544
+ }
545
+ return false
546
+ },
547
+ handleEvent(eventSessionId, event) {
548
+ if (disposed || !event || typeof event !== 'object') return false
549
+ const id = eventSessionId || sessionId
550
+ if (!id) return false
551
+ if (event.type !== 'tool/call' && event.type !== 'tool/result') return false
552
+ const extra = extraEntries.get(String(id)) || []
553
+ if (!extra.some(entry => entry.seq === event.seq)) extra.push({ seq: event.seq, event })
554
+ extraEntries.set(String(id), extra)
555
+ if (event.type === 'tool/result') render()
556
+ return true
557
+ },
558
+ enter() { return runPlanCommand('/plan', text('已提交进入 Plan 模式的主机命令,等待 Plan 状态更新。', 'Host command submitted to enter plan mode; waiting for the plan state.')) },
559
+ exit() { return runPlanCommand('/plan off', text('已提交退出 Plan 模式的主机命令,等待 Plan 状态更新。', 'Host command submitted to leave plan mode; waiting for the plan state.')) },
560
+ approve() {
561
+ const review = currentReview(sessionId)
562
+ if (!review) return Promise.resolve(fail(text('待审阅请求已结束或已由其他终端处理。', 'The review has ended or was handled in another client.')))
563
+ if (!review.approveLabel) return Promise.resolve(fail(text('主机未提供批准选项,不能猜测审批结果。', 'The Host named no approve option; the verdict is not guessed.')))
564
+ if (!review.questionId) return Promise.resolve(fail(text('主机未提供问题标识,无法提交审批。', 'The Host supplied no question id')))
565
+ return submitAnswer(review, { sessionId, answer: { answers: [{ id: review.questionId, selected: [review.approveLabel] }] } },
566
+ text('已提交批准;主机确认后会退出 Plan 模式。', 'Approval submitted; plan mode exits once the Host confirms.'))
567
+ },
568
+ keep(feedback) {
569
+ const review = currentReview(sessionId)
570
+ if (!review) return Promise.resolve(fail(text('待审阅请求已结束或已由其他终端处理。', 'The review has ended or was handled in another client.')))
571
+ const custom = cleanup(feedback).slice(0, 2000)
572
+ if (!review.keepLabel && !custom) return Promise.resolve(fail(text('主机未提供“继续计划”选项,且没有反馈内容。', 'The Host named no keep-planning option and no feedback was provided.')))
573
+ if (!review.questionId) return Promise.resolve(fail(text('主机未提供问题标识,无法提交审批。', 'The Host supplied no question id')))
574
+ const answer = { id: review.questionId, selected: review.keepLabel ? [review.keepLabel] : [] }
575
+ if (custom) answer.custom = custom
576
+ return submitAnswer(review, { sessionId, answer: { answers: [answer] } },
577
+ text('已提交“继续完善计划”的反馈;等待主机继续。', 'Keep-planning feedback submitted; waiting for the Host to continue.'))
578
+ },
579
+ isCurrentPlanReview(rpcId) {
580
+ const review = currentReview(sessionId)
581
+ return !!review && review.rpcId === String(rpcId || '')
582
+ },
583
+ dispose() {
584
+ disposed = true
585
+ if (unbind) unbind()
586
+ unbind = null
587
+ frameReviews.clear()
588
+ resolved.clear()
589
+ answered.clear()
590
+ knownReviews.clear()
591
+ extraEntries.clear()
592
+ notice = null
593
+ },
594
+ }
595
+ if (rootEl) render()
596
+ return controller
597
+ }
598
+
599
+ /* ------------------------------------------------------------------ binding */
600
+
601
+ function bind(container, controller) {
602
+ if (!container || typeof container.addEventListener !== 'function') return () => {}
603
+ if (container.dataset && container.dataset.drPlanBound === '1') return () => {}
604
+ if (container.dataset) container.dataset.drPlanBound = '1'
605
+ const onClick = event => {
606
+ const target = event?.target
607
+ const button = target && typeof target.closest === 'function' ? target.closest('[data-dr-plan-action]') : null
608
+ if (!button || button.disabled === true) return
609
+ const action = button.dataset?.drPlanAction || button.getAttribute?.('data-dr-plan-action') || ''
610
+ const box = typeof button.closest === 'function' ? button.closest('[data-dr-plan-scope]') : null
611
+ const feedback = box && typeof box.querySelector === 'function' ? box.querySelector('[data-dr-plan-feedback]')?.value || '' : ''
612
+ const run = {
613
+ enter: () => controller.enter(),
614
+ exit: () => controller.exit(),
615
+ approve: () => controller.approve(),
616
+ keep: () => controller.keep(feedback),
617
+ refresh: () => controller.refresh(),
618
+ 'view-plan': () => {
619
+ const details = box?.querySelector?.('[data-dr-plan-doc]')
620
+ if (details && typeof details.setAttribute === 'function') details.setAttribute('open', '')
621
+ return controller.view().review
622
+ },
623
+ }[action]
624
+ if (!run) return
625
+ Promise.resolve(run()).catch(() => {})
626
+ }
627
+ container.addEventListener('click', onClick)
628
+ return () => {
629
+ container.removeEventListener?.('click', onClick)
630
+ if (container.dataset) delete container.dataset.drPlanBound
631
+ }
632
+ }
633
+
634
+ const api = {
635
+ MAX_HISTORY,
636
+ normalizePlan, describePlan, planReviewOf, reviewFromFrame, historyPlans, hasContent,
637
+ statusHtml, reviewHtml, historyHtml, noticeHtml, viewHtml,
638
+ create, init: create, bind, esc, firstHeading,
639
+ }
640
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
641
+ else root.DshPlanReview = api
642
+ })(typeof window === 'undefined' ? globalThis : window)