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