dsh-vscode-mode 0.29.2 → 0.31.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 (80) hide show
  1. package/README.md +120 -11
  2. package/lib/client.js +178 -51
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +4860 -1576
  5. package/lib/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/skills/dsh-vscodemode-html-plan/LICENSE +202 -0
  8. package/skills/dsh-vscodemode-html-plan/SKILL.md +147 -0
  9. package/skills/dsh-vscodemode-html-plan/examples/scheduled-send.html +298 -0
  10. package/skills/dsh-vscodemode-html-plan/references/blocks.md +227 -0
  11. package/skills/dsh-vscodemode-html-plan/references/subagent-brief.md +17 -0
  12. package/skills/dsh-vscodemode-html-plan/references/upstream-SKILL.md +174 -0
  13. package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.css +564 -0
  14. package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.js +1299 -0
  15. package/skills/dsh-vscodemode-html-plan/runtime/pack.mjs +300 -0
  16. package/src/ai/llmTask.ts +178 -0
  17. package/src/ai/llmTypes.ts +6 -0
  18. package/src/ai/svnCommitMsg.ts +107 -0
  19. package/src/ai/svnTriage.ts +34 -85
  20. package/src/client/aiCommit.ts +57 -0
  21. package/src/client/compatSummary.ts +15 -0
  22. package/src/client/editorFlush.ts +55 -0
  23. package/src/client/featurePrefs.ts +63 -0
  24. package/src/client/htmlPlan/HtmlPlanPanel.ts +261 -0
  25. package/src/client/htmlPlan/planActions.ts +347 -0
  26. package/src/client/htmlPlan/planPage.ts +333 -0
  27. package/src/client/htmlPreview.ts +218 -0
  28. package/src/client/index.ts +43 -0
  29. package/src/client/monaco/loader.ts +71 -9
  30. package/src/client/monaco/templateLanguages.ts +300 -0
  31. package/src/client/officialSidebar.ts +16 -4
  32. package/src/client/openPathRouter.ts +7 -0
  33. package/src/client/planState.ts +8 -2
  34. package/src/client/refCopy.ts +70 -0
  35. package/src/client/refIntake.ts +215 -0
  36. package/src/client/sidebar/menuItems.ts +11 -0
  37. package/src/client/sidebar/panels/FileExplorer.ts +11 -0
  38. package/src/client/sidebar/panels/SearchPanel.ts +214 -4
  39. package/src/client/sidebar/panels/SvnPanel.ts +17 -0
  40. package/src/client/sidebar/types.ts +2 -0
  41. package/src/client/styles/editor.css +112 -0
  42. package/src/client/svnActions.ts +7 -0
  43. package/src/client/svnCommit.ts +109 -0
  44. package/src/client/svnNotice.ts +1 -1
  45. package/src/client/svnStatus.ts +5 -2
  46. package/src/client/ui/DiffLauncher.ts +3 -1
  47. package/src/client/ui/EditorView.ts +221 -14
  48. package/src/client/ui/McpSettings.ts +108 -1
  49. package/src/client/ui/SvnAiPlanDialog.ts +24 -4
  50. package/src/client/ui/SvnCommitDialog.ts +458 -0
  51. package/src/client/ui/commandCatalog.ts +11 -0
  52. package/src/client/ui/svnCommitModel.ts +204 -0
  53. package/src/client/univer/UniverCacheSettings.ts +75 -0
  54. package/src/client/univer/UniverHost.ts +177 -0
  55. package/src/client/univer/api.ts +30 -0
  56. package/src/client/univer/routing.ts +32 -0
  57. package/src/client/univer/store.ts +111 -0
  58. package/src/fileOpenSettings.ts +118 -6
  59. package/src/htmlPlanCommand.ts +176 -0
  60. package/src/index.ts +4 -0
  61. package/src/paths.ts +5 -0
  62. package/src/refPointer.ts +193 -0
  63. package/src/rpc.ts +51 -0
  64. package/src/search/replacePlan.ts +144 -0
  65. package/src/search/replaceRun.ts +289 -0
  66. package/src/shared/keybindings.ts +11 -0
  67. package/src/shared/refSyntax.ts +106 -0
  68. package/src/shared/rpc.ts +28 -4
  69. package/src/shared/snippets.ts +17 -0
  70. package/src/shared/svn.ts +191 -10
  71. package/src/shared/svnActions.ts +16 -0
  72. package/src/shared/univer.ts +90 -0
  73. package/src/svn.ts +205 -47
  74. package/src/svnCommit.ts +348 -0
  75. package/src/svnCore.ts +254 -0
  76. package/src/svnToolJson.ts +73 -0
  77. package/src/svnTools.ts +566 -0
  78. package/src/univerBridge.ts +83 -0
  79. package/src/univerCache.ts +205 -0
  80. package/src/univerRpc.ts +144 -0
@@ -0,0 +1,261 @@
1
+ /**
2
+ * dsh-vscode-mode client — HTML 计划页签面板:状态条 + 官方动作 + 沙箱 iframe。
3
+ *
4
+ * 页面由 agent 按 html-plan 技能打包成单文件;这里只负责呈现与转交用户动作:
5
+ * 同意执行 / 继续规划走官方 userQuestions 答案通道,退出计划模式走官方 /plan off,
6
+ * 页面答复经桥接脚本回填对话输入框。iframe 一律 sandbox 且不给 allow-same-origin。
7
+ * @author ddj 2026年11月21号
8
+ */
9
+ import React from 'react'
10
+ import { rpc } from '../rpc.js'
11
+ import {
12
+ buildPlanSrcDoc,
13
+ derivePlanUiState,
14
+ planPagePathOf,
15
+ resolvePlanPagePath,
16
+ unresolvedRuntimeRefs,
17
+ type PendingReview,
18
+ } from './planPage.js'
19
+ import {
20
+ answerPlanReview,
21
+ exitPlanMode,
22
+ fillComposer,
23
+ readPendingReview,
24
+ readPlanProjection,
25
+ revealPlanReview,
26
+ submitPlanResponse,
27
+ subscribePlanFaces,
28
+ } from './planActions.js'
29
+
30
+ /** 面板输入(由 EditorView 从计划页签装配)。 */
31
+ export interface HtmlPlanPanelProps {
32
+ sessionId?: string
33
+ cwd?: string
34
+ address?: string
35
+ title?: string
36
+ htmlPath?: string
37
+ markdown?: string
38
+ }
39
+
40
+ /** 本地刚完成的动作(用于状态文案,不持久化)。 */
41
+ type PlanAct = 'approved' | 'revising' | 'exited'
42
+ type ReadResult = { ok?: boolean; content?: string; error?: string }
43
+
44
+ /**
45
+ * HTML 计划面板。
46
+ * @author ddj 2026年11月21号
47
+ * @param props 会话/工作区/计划页路径与标题
48
+ * @returns 计划页签正文
49
+ */
50
+ export function HtmlPlanPanel(props: HtmlPlanPanelProps) {
51
+ const sessionId = String(props.sessionId ?? '')
52
+ const declared = String(props.htmlPath ?? planPagePathOf(props.markdown) ?? '')
53
+ const absPath = resolvePlanPagePath(props.cwd, declared)
54
+ const title = String(props.title ?? 'HTML 计划')
55
+
56
+ const [html, setHtml] = React.useState<string | null>(null)
57
+ const [error, setError] = React.useState<string | null>(null)
58
+ const [staleRefs, setStaleRefs] = React.useState<string[]>([])
59
+ const [projection, setProjection] = React.useState<unknown>(undefined)
60
+ const [review, setReview] = React.useState<PendingReview | null>(null)
61
+ const [acted, setActed] = React.useState<PlanAct | null>(null)
62
+ const [busy, setBusy] = React.useState(false)
63
+ const [notice, setNotice] = React.useState('')
64
+ const [copied, setCopied] = React.useState('')
65
+ const [reloadToken, setReloadToken] = React.useState(0)
66
+ const frameRef = React.useRef<HTMLIFrameElement | null>(null)
67
+
68
+ // 读取计划页:路径缺失/读取失败/未打包都在面板内说明,不抛错、不白屏。
69
+ React.useEffect(() => {
70
+ let alive = true
71
+ setHtml(null)
72
+ setError(null)
73
+ setStaleRefs([])
74
+ if (!absPath) {
75
+ setError('计划未声明 HTML 页路径(计划正文缺少「HTML 计划页:…」一行)')
76
+ return () => { alive = false }
77
+ }
78
+ rpc('edrv.read', { sessionId, path: absPath }).then((raw) => {
79
+ if (!alive) return
80
+ const result = raw as ReadResult
81
+ if (result?.ok !== true) {
82
+ setError('读取计划页失败:' + String(result?.error ?? '未知原因'))
83
+ return
84
+ }
85
+ const text = String(result.content ?? '')
86
+ setHtml(text)
87
+ setStaleRefs(unresolvedRuntimeRefs(text))
88
+ }).catch((cause) => {
89
+ if (alive) setError('读取计划页失败:' + String(cause))
90
+ })
91
+ return () => { alive = false }
92
+ }, [absPath, sessionId, reloadToken])
93
+
94
+ const refresh = React.useCallback(() => {
95
+ setProjection(readPlanProjection(sessionId))
96
+ setReview(readPendingReview(sessionId))
97
+ }, [sessionId])
98
+
99
+ React.useEffect(() => {
100
+ refresh()
101
+ return subscribePlanFaces(sessionId, refresh)
102
+ }, [refresh])
103
+
104
+ /** 页面「回复」按钮回传的最新处理函数(事件监听只注册一次,经 ref 读最新闭包)。 */
105
+ const respondRef = React.useRef<((text: string) => void) | null>(null)
106
+ respondRef.current = (text: string) => { void sendResponse(text) }
107
+ /** 是否有待审批:页面据此把「回复」标成「回复并执行」。 */
108
+ const reviewRef = React.useRef(false)
109
+ reviewRef.current = review !== null
110
+
111
+ /** 把待审批状态告给页面(iframe ready 或审批状态变化时)。 */
112
+ function postPlanState(): void {
113
+ try {
114
+ frameRef.current?.contentWindow?.postMessage({ source: 'edrv-plan-host', type: 'state', reviewPending: reviewRef.current }, '*')
115
+ } catch {
116
+ /* 页面未加载 */
117
+ }
118
+ }
119
+
120
+ // 页面桥接:只接受来自本 iframe 的消息;复制与直接回复走同一来源校验。
121
+ React.useEffect(() => {
122
+ function onMessage(event: MessageEvent) {
123
+ if (event.source !== frameRef.current?.contentWindow) return
124
+ const data = event.data
125
+ if (!data || data.source !== 'edrv-htmlplan') return
126
+ if (data.type === 'copy' && typeof data.text === 'string') setCopied(data.text)
127
+ if (data.type === 'respond' && typeof data.text === 'string') respondRef.current?.(data.text)
128
+ if (data.type === 'ready') postPlanState()
129
+ }
130
+ window.addEventListener('message', onMessage)
131
+ return () => window.removeEventListener('message', onMessage)
132
+ }, [])
133
+
134
+ React.useEffect(() => { postPlanState() }, [review])
135
+
136
+ const state = derivePlanUiState(projection, review !== null, acted)
137
+
138
+ /**
139
+ * 把页面答复直接发给 agent:成功清空并回传成功,失败回传原因且保留文本。
140
+ * @author ddj 2026年11月21号
141
+ * @param text 答复 markdown
142
+ */
143
+ async function sendResponse(text: string): Promise<void> {
144
+ if (busy) return
145
+ const body = String(text ?? '')
146
+ const hadReview = reviewRef.current
147
+ setCopied(body)
148
+ setBusy(true)
149
+ const result = await submitPlanResponse(sessionId, body)
150
+ setBusy(false)
151
+ setNotice(result.ok
152
+ ? hadReview ? '已批准并发送答复,agent 开始执行' : '已回复并发送给 agent'
153
+ : String(result.error ?? '发送失败'))
154
+ try {
155
+ frameRef.current?.contentWindow?.postMessage({
156
+ source: 'edrv-plan-host',
157
+ type: 'respond-result',
158
+ ok: result.ok,
159
+ message: result.error ?? '',
160
+ }, '*')
161
+ } catch {
162
+ /* 页面已卸载 */
163
+ }
164
+ if (result.ok) setCopied('')
165
+ refresh()
166
+ }
167
+
168
+ /**
169
+ * 执行一条官方动作;忙态防重复,失败原因原样展示。
170
+ * @author ddj 2026年11月21号
171
+ * @param action approve / keep / exit / fill
172
+ */
173
+ async function run(action: PlanAct | 'fill'): Promise<void> {
174
+ if (busy) return
175
+ if (action === 'fill') {
176
+ setBusy(true)
177
+ const result = await fillComposer(sessionId, copied)
178
+ setBusy(false)
179
+ setNotice(result.ok ? '已填入对话输入框(未发送)' : String(result.error ?? '填入失败'))
180
+ return
181
+ }
182
+ setBusy(true)
183
+ const result = action === 'exited' ? await exitPlanMode(sessionId) : await answerPlanReview(sessionId, action === 'approved')
184
+ setBusy(false)
185
+ if (result.ok) {
186
+ setActed(action)
187
+ setNotice(action === 'approved' ? '已批准,等待 agent 开始执行' : action === 'revising' ? '已提交「继续规划」,等待 agent 修订' : '已退出计划模式')
188
+ } else {
189
+ setNotice(String(result.error ?? '操作失败'))
190
+ }
191
+ refresh()
192
+ }
193
+
194
+ /**
195
+ * 打开官方审批卡片(插件内作答不可用时的兜底入口)。
196
+ * @author ddj 2026年11月21号
197
+ */
198
+ function reveal(): void {
199
+ setNotice(revealPlanReview(sessionId) ? '已请求打开官方审批卡片' : '未找到可打开的官方审批卡片,请直接在对话中操作')
200
+ }
201
+
202
+ const canAnswer = review !== null && !busy
203
+ const chrome = React.createElement('div', { className: 'edrv-htmlplan-bar' },
204
+ React.createElement('span', { className: 'edrv-htmlplan-title', title: absPath }, title),
205
+ React.createElement('span', { className: 'edrv-htmlplan-state edrv-htmlplan-state-' + state.mode }, state.label),
206
+ React.createElement('span', { style: { flex: 1 } }),
207
+ React.createElement('button', {
208
+ className: 'edrv-pill edrv-pill-ghost', disabled: !canAnswer,
209
+ title: review ? '用官方批准标签作答(等同对话审批卡片的「同意执行」)' : '没有待审批的计划',
210
+ onClick: () => { void run('approved') },
211
+ }, '同意执行'),
212
+ React.createElement('button', {
213
+ className: 'edrv-pill edrv-pill-ghost', disabled: !canAnswer || !review?.keepLabel,
214
+ title: review?.keepLabel ? '用官方「继续规划」选项作答' : '官方审批没有继续规划选项,请在对话中要求修改',
215
+ onClick: () => { void run('revising') },
216
+ }, '继续规划'),
217
+ React.createElement('button', {
218
+ className: 'edrv-pill edrv-pill-ghost', disabled: busy || !state.active,
219
+ title: '等价 composer 计划徽标的 /plan off',
220
+ onClick: () => { void run('exited') },
221
+ }, '退出计划模式'),
222
+ (review ? React.createElement('button', {
223
+ className: 'edrv-pill edrv-pill-ghost', title: '打开官方审批卡片', onClick: reveal,
224
+ }, '去对话审批') : null),
225
+ React.createElement('button', {
226
+ className: 'edrv-pill edrv-pill-ghost', disabled: busy || !copied,
227
+ title: copied ? '把页面答复填入对话输入框(不自动发送)' : '先在页面里点 Copy response',
228
+ onClick: () => { void run('fill') },
229
+ }, '填入对话输入框'),
230
+ React.createElement('button', {
231
+ className: 'edrv-pill edrv-pill-ghost', title: '重新读取计划页',
232
+ onClick: () => { setCopied(''); setReloadToken((value) => value + 1) },
233
+ }, '⟳'))
234
+
235
+ const noticeLine = notice ? React.createElement('div', { className: 'edrv-htmlplan-notice' }, notice) : null
236
+
237
+ let stage
238
+ if (error) {
239
+ stage = React.createElement('div', { className: 'edrv-empty', role: 'alert' },
240
+ React.createElement('div', null, error),
241
+ React.createElement('div', { style: { fontSize: 12, opacity: 0.75 } }, '可关闭页签回到 Markdown 计划预览;或让 agent 重新打包计划页。'))
242
+ } else if (html === null) {
243
+ stage = React.createElement('div', { className: 'edrv-empty' }, '读取计划页…')
244
+ } else {
245
+ const warn = staleRefs.length
246
+ ? React.createElement('div', { className: 'edrv-htmlplan-warn' },
247
+ '页面未打包:仍引用 ' + staleRefs.join('、') + '。样式/脚本可能缺失,请运行 pack.mjs 后再提交。')
248
+ : null
249
+ stage = React.createElement(React.Fragment, null,
250
+ warn,
251
+ React.createElement('iframe', {
252
+ ref: frameRef,
253
+ className: 'edrv-htmlplan-frame',
254
+ title,
255
+ sandbox: 'allow-scripts allow-forms allow-popups',
256
+ srcDoc: buildPlanSrcDoc(html),
257
+ }))
258
+ }
259
+
260
+ return React.createElement('div', { className: 'edrv-htmlplan' }, chrome, noticeLine, stage)
261
+ }
@@ -0,0 +1,347 @@
1
+ /**
2
+ * dsh-vscode-mode client — HTML 计划页的官方动作桥(状态读取、审批、退出、回填)。
3
+ *
4
+ * 所有官方客户端服务都是可选探测:缺失或版本不符时返回可读错误,绝不抛、绝不伪造批准。
5
+ * 审批仍走官方 ask_user_question 通道(remote.userQuestions.answer);退出计划模式走
6
+ * 官方命令(remote.commands.execute('/plan off')),与 composer 计划徽标同源。
7
+ * @author ddj 2026年11月21号
8
+ */
9
+ import { createAddToConversation } from '../addToConversation.js'
10
+ import { findPendingReview, reviewAnswerOf, reviewLabelsOf, type PendingReview } from './planPage.js'
11
+
12
+ /** 客户端上下文的最小结构面。 */
13
+ export interface PlanActionCtx {
14
+ get: (name: string) => unknown
15
+ }
16
+
17
+ /** 动作结果(失败带可展示原因)。 */
18
+ export interface PlanActionResult {
19
+ ok: boolean
20
+ error?: string
21
+ }
22
+
23
+ /** 已安装的动作宿主(index.ts 装配一次;未安装时所有动作返回未就绪)。 */
24
+ let host: {
25
+ ctx: PlanActionCtx
26
+ appendText: (sessionId: string | undefined, text: string) => Promise<string>
27
+ sendTask: (sessionId: string | undefined, text: string) => Promise<PlanActionResult>
28
+ } | null = null
29
+ /** 取异常的展示文案。 */
30
+ function messageOf(error: unknown): string {
31
+ if (error instanceof Error) return error.message
32
+ return String(error ?? '未知错误')
33
+ }
34
+
35
+ /** 失败结果。 */
36
+ function fail(error: string): PlanActionResult {
37
+ return { ok: false, error }
38
+ }
39
+
40
+ /** 成功结果。 */
41
+ function ok(): PlanActionResult {
42
+ return { ok: true }
43
+ }
44
+
45
+ /** 结构化探测可选服务(缺失/抛错一律 undefined)。 */
46
+ function serviceOf(ctx: PlanActionCtx, name: string): unknown {
47
+ try {
48
+ return ctx.get(name)
49
+ } catch {
50
+ return undefined
51
+ }
52
+ }
53
+
54
+ /** 取会话绑定(sessions.binding);服务缺失返回 undefined。 */
55
+ function bindingOf(ctx: PlanActionCtx, sessionId: string): unknown {
56
+ const sessions = serviceOf(ctx, 'sessions') as { binding?: (id: string) => unknown } | undefined
57
+ if (!sessions || typeof sessions.binding !== 'function') return undefined
58
+ try {
59
+ return sessions.binding(sessionId)
60
+ } catch {
61
+ return undefined
62
+ }
63
+ }
64
+
65
+ /** 取会话投影 face(缺失/抛错返回 undefined)。 */
66
+ function faceOf(ctx: PlanActionCtx, sessionId: string, key: string): unknown {
67
+ const binding = bindingOf(ctx, sessionId) as { session?: { projections?: { faceOf?: (name: string) => unknown } } } | undefined
68
+ const faceOfFn = binding?.session?.projections?.faceOf
69
+ if (typeof faceOfFn !== 'function') return undefined
70
+ try {
71
+ return faceOfFn.call(binding!.session!.projections, key)
72
+ } catch {
73
+ return undefined
74
+ }
75
+ }
76
+
77
+ /** 投影 face 快照(无 face 返回 undefined)。 */
78
+ function faceSnapshot(face: unknown): unknown {
79
+ const getSnapshot = (face as { getSnapshot?: () => unknown } | undefined)?.getSnapshot
80
+ return typeof getSnapshot === 'function' ? getSnapshot.call(face) : undefined
81
+ }
82
+
83
+ /** 读 plan 投影快照({ active, pending } 或 undefined)。 */
84
+ export function readPlanProjection(sessionId: string): unknown {
85
+ if (!host) return undefined
86
+ return faceSnapshot(faceOf(host.ctx, sessionId, 'plan'))
87
+ }
88
+
89
+ /** 在线待审批的会话卡片(PendingQuestion 实例:带 answer 与 intent)。 */
90
+ interface LiveReview {
91
+ pending: { answer: (answer: unknown) => Promise<unknown> }
92
+ labels: { questionId: string; approveLabel: string; keepLabel: string | null }
93
+ callId: string
94
+ }
95
+
96
+ /**
97
+ * 从 uiSession 的 Session 状态里取当前 plan-review 卡片。
98
+ * 计划审批是阻塞请求,不进 userQuestions 投影;只有 pendingInteraction 带着 intent 与实时候选。
99
+ * @author ddj 2026年11月21号
100
+ * @param sessionId 会话 id
101
+ * @returns 在线卡片与解析出的标签,或 null
102
+ */
103
+ function liveReviewOf(sessionId: string): LiveReview | null {
104
+ if (!host) return null
105
+ const ui = serviceOf(host.ctx, 'uiSession') as { sessionStatus?: { getSnapshot?: () => unknown } } | undefined
106
+ const snapshot = ui?.sessionStatus?.getSnapshot?.()
107
+ const get = (snapshot as { get?: (id: string) => unknown } | undefined)?.get
108
+ if (typeof get !== 'function') return null
109
+ let status: unknown
110
+ try {
111
+ status = get.call(snapshot, sessionId)
112
+ } catch {
113
+ return null
114
+ }
115
+ const pending = status !== null && typeof status === 'object'
116
+ ? (status as { pendingInteraction?: unknown }).pendingInteraction
117
+ : undefined
118
+ if (pending === null || typeof pending !== 'object') return null
119
+ const row = pending as { kind?: unknown; sessionId?: unknown; callId?: unknown; questions?: unknown; answer?: unknown }
120
+ if (row.kind !== 'plan-review' || typeof row.answer !== 'function') return null
121
+ if (row.sessionId !== undefined && String(row.sessionId) !== sessionId) return null
122
+ const labels = reviewLabelsOf(Array.isArray(row.questions) ? row.questions[0] : undefined)
123
+ if (!labels) return null
124
+ const callId = typeof row.callId === 'string' ? row.callId : ''
125
+ return { pending: pending as LiveReview['pending'], labels, callId }
126
+ }
127
+
128
+ /** 读当前待审批的 plan-review(先看在线卡片,再退回投影)。 */
129
+ export function readPendingReview(sessionId: string): PendingReview | null {
130
+ if (!host) return null
131
+ const live = liveReviewOf(sessionId)
132
+ if (live) {
133
+ return { callId: live.callId, questionId: live.labels.questionId, approveLabel: live.labels.approveLabel, keepLabel: live.labels.keepLabel }
134
+ }
135
+ return findPendingReview(faceSnapshot(faceOf(host.ctx, sessionId, 'userQuestions')))
136
+ }
137
+
138
+ /** 订阅 plan 与 userQuestions 投影变化;返回合并的退订器。 */
139
+ export function subscribePlanFaces(sessionId: string, listener: () => void): () => void {
140
+ if (!host) return () => {}
141
+ const offs: Array<() => void> = []
142
+ for (const key of ['plan', 'userQuestions']) {
143
+ const face = faceOf(host.ctx, sessionId, key) as { subscribe?: (fn: () => void) => unknown } | undefined
144
+ if (!face || typeof face.subscribe !== 'function') continue
145
+ try {
146
+ const off = face.subscribe(() => listener())
147
+ if (typeof off === 'function') offs.push(off as () => void)
148
+ } catch {
149
+ /* 订阅失败不影响其他 face */
150
+ }
151
+ }
152
+ return () => {
153
+ for (const off of offs) {
154
+ try {
155
+ off()
156
+ } catch {
157
+ /* 退订异常忽略 */
158
+ }
159
+ }
160
+ }
161
+ }
162
+
163
+ /** 官方 Typert 结果解包:{ ok, value } / { ok:false, error } / 裸值。 */
164
+ function unwrap(result: unknown): PlanActionResult {
165
+ if (result === null || typeof result !== 'object') return result === false ? fail('官方服务拒绝了本次操作') : ok()
166
+ const row = result as { ok?: unknown; error?: unknown }
167
+ if (row.ok === false) {
168
+ const detail = row.error as { message?: unknown } | string | undefined
169
+ const message = typeof detail === 'string' ? detail : (typeof detail?.message === 'string' ? detail.message : '官方服务拒绝了本次操作')
170
+ return fail(message)
171
+ }
172
+ return ok()
173
+ }
174
+
175
+ /**
176
+ * 安装动作宿主(index.ts 装配一次)。
177
+ * @author ddj 2026年11月21号
178
+ * @param ctx 客户端上下文
179
+ * @returns 幂等卸载器
180
+ */
181
+ /** 安装选项(appendText / sendTask 可注入,便于单测;生产缺省用会话输入门面)。 */
182
+ export interface HtmlPlanActionOptions {
183
+ appendText?: (sessionId: string | undefined, text: string) => Promise<string>
184
+ sendTask?: (sessionId: string | undefined, text: string) => Promise<unknown>
185
+ }
186
+
187
+ /**
188
+ * 把会话投递结果归一成动作结果:只有 accepted/submitted 视为成功。
189
+ * @author ddj 2026年11月21号
190
+ * @param raw TaskSendResult 或布尔裸值
191
+ * @returns 动作结果
192
+ */
193
+ function sendResultOf(raw: unknown): PlanActionResult {
194
+ if (raw === true) return ok()
195
+ if (raw === false) return fail('会话拒绝接收答复')
196
+ if (raw === null || typeof raw !== 'object') return fail('发送结果未知')
197
+ const row = raw as { status?: unknown; message?: unknown; ok?: unknown }
198
+ if (row.ok === true) return ok()
199
+ if (row.ok === false) return fail(typeof row.message === 'string' ? row.message : '发送失败')
200
+ const status = typeof row.status === 'string' ? row.status : ''
201
+ if (status === 'accepted' || status === 'submitted') return ok()
202
+ const detail = typeof row.message === 'string' && row.message ? ':' + row.message : ''
203
+ if (status === 'rejected') return fail('会话拒绝接收答复' + detail)
204
+ if (status === 'unavailable') return fail('对话输入不可用' + detail)
205
+ if (status === 'cancelled') return fail('发送已取消' + detail)
206
+ return fail('发送结果未知' + detail)
207
+ }
208
+
209
+ export function installHtmlPlanActions(ctx: PlanActionCtx, options: HtmlPlanActionOptions = {}): () => void {
210
+ const injectedAppend = options.appendText
211
+ const injectedSend = options.sendTask
212
+ const addToConversation = injectedAppend && injectedSend ? null : createAddToConversation(ctx as never)
213
+ const sendInjected = injectedSend
214
+ const conversations = addToConversation
215
+ host = {
216
+ ctx,
217
+ appendText: injectedAppend ?? ((sessionId, text) => conversations!.appendText(sessionId, text)),
218
+ sendTask: typeof sendInjected === 'function'
219
+ ? async (sessionId, text) => sendResultOf(await sendInjected(sessionId, text))
220
+ : async (sessionId, text) => {
221
+ const send = conversations?.sendTaskResult
222
+ if (typeof send !== 'function') return fail('当前 DSH 不支持直接发送,请用「填入对话输入框」')
223
+ return sendResultOf(await send.call(conversations, sessionId, text))
224
+ },
225
+ }
226
+ return () => {
227
+ host = null
228
+ }
229
+ }
230
+
231
+ /**
232
+ * 回答官方 plan-review:批准 = 选批准标签;不批准 = 选继续规划标签(若官方提供)。
233
+ * @author ddj 2026年11月21号
234
+ * @param sessionId 会话 id
235
+ * @param approve 是否批准
236
+ * @returns 动作结果
237
+ */
238
+ export async function answerPlanReview(sessionId: string, approve: boolean): Promise<PlanActionResult> {
239
+ if (!host) return fail('计划动作桥未就绪,请在对话审批卡片中操作')
240
+ if (!sessionId) return fail('当前没有活动会话')
241
+ const live = liveReviewOf(sessionId)
242
+ if (live) {
243
+ const label = approve ? live.labels.approveLabel : live.labels.keepLabel
244
+ if (!label) return fail(approve ? '该审批没有可用的批准选项' : '官方审批没有「继续规划」选项,请在对话中要求修改')
245
+ try {
246
+ await live.pending.answer({ answers: [{ id: live.labels.questionId, selected: [label] }] })
247
+ return ok()
248
+ } catch (error) {
249
+ return fail('提交审批失败:' + messageOf(error))
250
+ }
251
+ }
252
+ const review = readPendingReview(sessionId)
253
+ if (!review) return fail('没有待审批的计划(可能已在别处审批)')
254
+ const answer = reviewAnswerOf(review, approve)
255
+ if (!answer) return fail(approve ? '该审批没有可用的批准选项' : '官方审批没有「继续规划」选项,请在对话中要求修改')
256
+ const questions = serviceOf(host.ctx, 'remote.userQuestions') as { answer?: (id: string, callId: string, value: unknown) => Promise<unknown> } | undefined
257
+ if (!questions || typeof questions.answer !== 'function') {
258
+ return fail('当前 DSH 不支持在插件内作答,请在对话审批卡片中操作')
259
+ }
260
+ try {
261
+ return unwrap(await questions.answer(sessionId, review.callId, answer))
262
+ } catch (error) {
263
+ return fail('提交审批失败:' + messageOf(error))
264
+ }
265
+ }
266
+
267
+ /**
268
+ * 退出计划模式(等价 composer 计划徽标的 /plan off)。
269
+ * @author ddj 2026年11月21号
270
+ * @param sessionId 会话 id
271
+ * @returns 动作结果
272
+ */
273
+ export async function exitPlanMode(sessionId: string): Promise<PlanActionResult> {
274
+ if (!host) return fail('计划动作桥未就绪,请点 composer 计划徽标退出')
275
+ if (!sessionId) return fail('当前没有活动会话')
276
+ const commands = serviceOf(host.ctx, 'remote.commands') as { execute?: (id: string, line: string, attachments: unknown[]) => Promise<unknown> } | undefined
277
+ if (!commands || typeof commands.execute !== 'function') {
278
+ return fail('当前 DSH 不支持在插件内执行命令,请点 composer 计划徽标退出')
279
+ }
280
+ try {
281
+ return unwrap(await commands.execute(sessionId, '/plan off', []))
282
+ } catch (error) {
283
+ return fail('退出计划模式失败:' + messageOf(error))
284
+ }
285
+ }
286
+
287
+ /**
288
+ * 发送计划页答复给 agent:有待审批时先提交「继续规划」,再发送反馈正文。
289
+ * @author ddj 2026年11月21号
290
+ * @param sessionId 会话 id
291
+ * @param text 答复 markdown
292
+ * @returns 动作结果(失败带原因,答复文本不丢)
293
+ */
294
+ export async function submitPlanResponse(sessionId: string, text: string): Promise<PlanActionResult> {
295
+ if (!host) return fail('计划动作桥未就绪')
296
+ if (!sessionId) return fail('当前没有活动会话')
297
+ const body = String(text ?? '').trim()
298
+ if (!body) return fail('答复为空:先在页面里作答再点「回复」')
299
+ // 有待审批卡片:先结算为「同意执行」,再把答复作为用户消息送出;失败则不发,避免半截状态。
300
+ if (readPendingReview(sessionId)) {
301
+ const approved = await answerPlanReview(sessionId, true)
302
+ if (!approved.ok) return fail('先同意执行失败,答复未发送:' + String(approved.error ?? ''))
303
+ }
304
+ try {
305
+ return await host.sendTask(sessionId, body)
306
+ } catch (error) {
307
+ return fail('发送失败:' + messageOf(error))
308
+ }
309
+ }
310
+
311
+ /**
312
+ * 打开官方审批卡片(兜底入口;能力缺失返回 false)。
313
+ * @author ddj 2026年11月21号
314
+ * @param sessionId 会话 id
315
+ * @returns 是否已请求官方卡片
316
+ */
317
+ export function revealPlanReview(sessionId: string): boolean {
318
+ if (!host) return false
319
+ const review = readPendingReview(sessionId)
320
+ if (!review) return false
321
+ const panels = serviceOf(host.ctx, 'userQuestionPanels') as { reveal?: (id: string, callId: string) => unknown } | undefined
322
+ if (!panels || typeof panels.reveal !== 'function') return false
323
+ try {
324
+ return panels.reveal(sessionId, review.callId) !== false
325
+ } catch {
326
+ return false
327
+ }
328
+ }
329
+
330
+ /**
331
+ * 把页面答复填入对话输入框(复用既有引用/纯文本注入通道,不自动发送)。
332
+ * @author ddj 2026年11月21号
333
+ * @param sessionId 会话 id
334
+ * @param text 答复 markdown(纯文本写入)
335
+ * @returns 动作结果
336
+ */
337
+ export async function fillComposer(sessionId: string, text: string): Promise<PlanActionResult> {
338
+ if (!host) return fail('计划动作桥未就绪')
339
+ if (!sessionId) return fail('当前没有活动会话')
340
+ if (!String(text ?? '').trim()) return fail('没有可填入的答复:先在页面里点 Copy response')
341
+ try {
342
+ const outcome = await host.appendText(sessionId, String(text))
343
+ return outcome === 'ok' || outcome === 'busy' ? ok() : fail('写入输入框失败(' + outcome + ')')
344
+ } catch (error) {
345
+ return fail('写入输入框失败:' + messageOf(error))
346
+ }
347
+ }