@sparkelf/dsh-genui 0.0.0-stage → 0.11.4-patch.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 (210) hide show
  1. package/CHANGELOG.md +597 -0
  2. package/LICENSE +21 -0
  3. package/README.md +292 -2
  4. package/README.zh-CN.md +307 -0
  5. package/SKILL.md +261 -0
  6. package/cordis.patch.yml +9 -0
  7. package/demo-prompts.md +118 -0
  8. package/lib/assets/echarts-core.js +43 -0
  9. package/lib/assets/echarts-full.js +72 -0
  10. package/lib/assets/mermaid.js +3591 -0
  11. package/lib/assets/standalone-runtime.js +1506 -0
  12. package/lib/assets/three.js +3844 -0
  13. package/lib/client.js +405 -0
  14. package/lib/index.js +5187 -0
  15. package/lib/invariant.js +19 -0
  16. package/lib/types/client/EChartNode.d.ts +13 -0
  17. package/lib/types/client/ErrorBoundary.d.ts +30 -0
  18. package/lib/types/client/GenuiBlock.d.ts +9 -0
  19. package/lib/types/client/PlotBlock.d.ts +44 -0
  20. package/lib/types/client/TemplateDrawer.d.ts +7 -0
  21. package/lib/types/client/achievement-store.d.ts +35 -0
  22. package/lib/types/client/achievement-toast.d.ts +2 -0
  23. package/lib/types/client/achievements.d.ts +63 -0
  24. package/lib/types/client/action-context.d.ts +7 -0
  25. package/lib/types/client/artifact/ExportableGenuiBlock.d.ts +6 -0
  26. package/lib/types/client/artifact/create.d.ts +5 -0
  27. package/lib/types/client/artifact/download.d.ts +9 -0
  28. package/lib/types/client/artifact/html.d.ts +5 -0
  29. package/lib/types/client/artifact/index.d.ts +8 -0
  30. package/lib/types/client/artifact/json.d.ts +3 -0
  31. package/lib/types/client/artifact/parse.d.ts +3 -0
  32. package/lib/types/client/artifact/portability.d.ts +4 -0
  33. package/lib/types/client/artifact/standalone-theme.d.ts +2 -0
  34. package/lib/types/client/artifact/types.d.ts +33 -0
  35. package/lib/types/client/asset-echarts-core.d.ts +1 -0
  36. package/lib/types/client/asset-echarts.d.ts +17 -0
  37. package/lib/types/client/asset-loader.d.ts +33 -0
  38. package/lib/types/client/asset-mermaid.d.ts +1 -0
  39. package/lib/types/client/asset-three.d.ts +1 -0
  40. package/lib/types/client/blocks/advanced.d.ts +101 -0
  41. package/lib/types/client/blocks/basic.d.ts +22 -0
  42. package/lib/types/client/blocks/charts.d.ts +53 -0
  43. package/lib/types/client/blocks/checkbox.d.ts +17 -0
  44. package/lib/types/client/blocks/diagram/geometry.d.ts +73 -0
  45. package/lib/types/client/blocks/diagram/index.d.ts +5 -0
  46. package/lib/types/client/blocks/diagram/layout.d.ts +41 -0
  47. package/lib/types/client/blocks/diagram/theme.d.ts +37 -0
  48. package/lib/types/client/blocks/forms.d.ts +77 -0
  49. package/lib/types/client/blocks/image.d.ts +6 -0
  50. package/lib/types/client/blocks/render-node.d.ts +10 -0
  51. package/lib/types/client/blocks/state.d.ts +63 -0
  52. package/lib/types/client/blocks/svg.d.ts +4 -0
  53. package/lib/types/client/dom-fence.d.ts +30 -0
  54. package/lib/types/client/echarts-engine.d.ts +4 -0
  55. package/lib/types/client/echarts-lazy.d.ts +18 -0
  56. package/lib/types/client/embed.d.ts +10 -0
  57. package/lib/types/client/fence-render.d.ts +106 -0
  58. package/lib/types/client/gallery.d.ts +7 -0
  59. package/lib/types/client/genui-runtime/diagnostics.d.ts +18 -0
  60. package/lib/types/client/genui-runtime/index.d.ts +1 -0
  61. package/lib/types/client/genui-runtime/limits.d.ts +54 -0
  62. package/lib/types/client/genui-runtime/normalize.d.ts +15 -0
  63. package/lib/types/client/genui-runtime/schema.d.ts +87 -0
  64. package/lib/types/client/genui-runtime/value-utils.d.ts +18 -0
  65. package/lib/types/client/guard.d.ts +144 -0
  66. package/lib/types/client/i18n/en.d.ts +307 -0
  67. package/lib/types/client/i18n/index.d.ts +44 -0
  68. package/lib/types/client/i18n/runtime.d.ts +64 -0
  69. package/lib/types/client/i18n/zh.d.ts +8 -0
  70. package/lib/types/client/index.d.ts +36 -0
  71. package/lib/types/client/inline.d.ts +5 -0
  72. package/lib/types/client/interaction-store.d.ts +48 -0
  73. package/lib/types/client/mermaid-core.d.ts +8 -0
  74. package/lib/types/client/mermaid-lazy.d.ts +9 -0
  75. package/lib/types/client/mermaid-safe.d.ts +52 -0
  76. package/lib/types/client/panel-command.d.ts +34 -0
  77. package/lib/types/client/panel-store.d.ts +94 -0
  78. package/lib/types/client/panel.d.ts +18 -0
  79. package/lib/types/client/parse-partial.d.ts +63 -0
  80. package/lib/types/client/primitive-adapter.d.ts +4 -0
  81. package/lib/types/client/primitive-labels.d.ts +18 -0
  82. package/lib/types/client/safe-math.d.ts +43 -0
  83. package/lib/types/client/scene3d-core.d.ts +21 -0
  84. package/lib/types/client/scene3d-lazy.d.ts +8 -0
  85. package/lib/types/client/session-resolver.d.ts +8 -0
  86. package/lib/types/client/source-fence.d.ts +29 -0
  87. package/lib/types/client/spec.d.ts +709 -0
  88. package/lib/types/client/standalone/asset-loader.d.ts +2 -0
  89. package/lib/types/client/standalone/bootstrap-types.d.ts +9 -0
  90. package/lib/types/client/standalone/katex-style.d.ts +1 -0
  91. package/lib/types/client/standalone/primitive-adapter.d.ts +54 -0
  92. package/lib/types/client/standalone/runtime.d.ts +2 -0
  93. package/lib/types/client/submission-registry.d.ts +51 -0
  94. package/lib/types/client/svg-fence.d.ts +2 -0
  95. package/lib/types/client/table-details.d.ts +20 -0
  96. package/lib/types/client/templates.d.ts +41 -0
  97. package/lib/types/client/toolview.d.ts +7 -0
  98. package/lib/types/client/walk-spec.d.ts +3 -0
  99. package/lib/types/index.d.ts +1 -0
  100. package/lib/types/plugin/chart-contract.d.ts +9 -0
  101. package/lib/types/plugin/fence-feedback.d.ts +151 -0
  102. package/lib/types/plugin/genui-diagnostic.d.ts +13 -0
  103. package/lib/types/plugin/index.d.ts +35 -0
  104. package/lib/types/plugin/inline-content-diagnostic.d.ts +8 -0
  105. package/lib/types/plugin/invariant.d.ts +15 -0
  106. package/lib/types/plugin/tool.d.ts +27 -0
  107. package/lib/types/shared/fence-repair.d.ts +78 -0
  108. package/lib/types/shared/fence-resolve.d.ts +39 -0
  109. package/package.json +249 -4
  110. package/src/client/EChartNode.tsx +466 -0
  111. package/src/client/ErrorBoundary.tsx +67 -0
  112. package/src/client/GenuiBlock.module.css +2221 -0
  113. package/src/client/GenuiBlock.tsx +235 -0
  114. package/src/client/PlotBlock.module.css +171 -0
  115. package/src/client/PlotBlock.tsx +492 -0
  116. package/src/client/TemplateDrawer.module.css +152 -0
  117. package/src/client/TemplateDrawer.tsx +147 -0
  118. package/src/client/achievement-store.ts +151 -0
  119. package/src/client/achievement-toast.tsx +71 -0
  120. package/src/client/achievements.ts +160 -0
  121. package/src/client/action-context.ts +32 -0
  122. package/src/client/artifact/ArtifactExport.module.css +64 -0
  123. package/src/client/artifact/ExportableGenuiBlock.tsx +100 -0
  124. package/src/client/artifact/create.ts +69 -0
  125. package/src/client/artifact/download.ts +42 -0
  126. package/src/client/artifact/html.ts +157 -0
  127. package/src/client/artifact/index.ts +15 -0
  128. package/src/client/artifact/json.ts +6 -0
  129. package/src/client/artifact/parse.ts +32 -0
  130. package/src/client/artifact/portability.ts +47 -0
  131. package/src/client/artifact/standalone-theme.ts +94 -0
  132. package/src/client/artifact/types.ts +44 -0
  133. package/src/client/asset-echarts-core.ts +39 -0
  134. package/src/client/asset-echarts.ts +27 -0
  135. package/src/client/asset-loader.ts +96 -0
  136. package/src/client/asset-mermaid.ts +13 -0
  137. package/src/client/asset-three.ts +12 -0
  138. package/src/client/blocks/advanced.tsx +537 -0
  139. package/src/client/blocks/basic.tsx +121 -0
  140. package/src/client/blocks/charts.tsx +999 -0
  141. package/src/client/blocks/checkbox.tsx +61 -0
  142. package/src/client/blocks/diagram/geometry.ts +151 -0
  143. package/src/client/blocks/diagram/index.tsx +293 -0
  144. package/src/client/blocks/diagram/layout.ts +202 -0
  145. package/src/client/blocks/diagram/theme.ts +127 -0
  146. package/src/client/blocks/forms.tsx +531 -0
  147. package/src/client/blocks/image.tsx +28 -0
  148. package/src/client/blocks/render-node.tsx +494 -0
  149. package/src/client/blocks/state.ts +65 -0
  150. package/src/client/blocks/svg.tsx +66 -0
  151. package/src/client/dom-fence.tsx +1123 -0
  152. package/src/client/echarts-engine.ts +9 -0
  153. package/src/client/echarts-lazy.ts +41 -0
  154. package/src/client/embed.ts +19 -0
  155. package/src/client/fence-render.tsx +266 -0
  156. package/src/client/gallery.ts +215 -0
  157. package/src/client/genui-runtime/diagnostics.ts +165 -0
  158. package/src/client/genui-runtime/index.ts +1 -0
  159. package/src/client/genui-runtime/limits.ts +54 -0
  160. package/src/client/genui-runtime/normalize.ts +329 -0
  161. package/src/client/genui-runtime/schema.ts +352 -0
  162. package/src/client/genui-runtime/value-utils.ts +67 -0
  163. package/src/client/guard.ts +1965 -0
  164. package/src/client/i18n/en.ts +335 -0
  165. package/src/client/i18n/index.ts +125 -0
  166. package/src/client/i18n/runtime.ts +130 -0
  167. package/src/client/i18n/zh.ts +330 -0
  168. package/src/client/index.tsx +228 -0
  169. package/src/client/inline.ts +106 -0
  170. package/src/client/interaction-store.ts +127 -0
  171. package/src/client/mermaid-core.ts +158 -0
  172. package/src/client/mermaid-lazy.ts +31 -0
  173. package/src/client/mermaid-safe.ts +122 -0
  174. package/src/client/panel-command.ts +138 -0
  175. package/src/client/panel-store.ts +471 -0
  176. package/src/client/panel.tsx +287 -0
  177. package/src/client/parse-partial.ts +170 -0
  178. package/src/client/primitive-adapter.ts +13 -0
  179. package/src/client/primitive-labels.ts +55 -0
  180. package/src/client/safe-math.ts +298 -0
  181. package/src/client/scene3d-core.ts +195 -0
  182. package/src/client/scene3d-lazy.ts +26 -0
  183. package/src/client/session-resolver.ts +33 -0
  184. package/src/client/source-fence.ts +70 -0
  185. package/src/client/spec.ts +896 -0
  186. package/src/client/standalone/asset-loader.ts +9 -0
  187. package/src/client/standalone/bootstrap-types.ts +11 -0
  188. package/src/client/standalone/katex-style.ts +1 -0
  189. package/src/client/standalone/primitive-adapter.tsx +94 -0
  190. package/src/client/standalone/runtime.tsx +27 -0
  191. package/src/client/submission-registry.ts +150 -0
  192. package/src/client/svg-fence.tsx +39 -0
  193. package/src/client/table-details.ts +151 -0
  194. package/src/client/templates.ts +322 -0
  195. package/src/client/toolview.tsx +67 -0
  196. package/src/client/walk-spec.ts +43 -0
  197. package/src/css-modules.d.ts +5 -0
  198. package/src/index.ts +9 -0
  199. package/src/plugin/chart-contract.ts +13 -0
  200. package/src/plugin/fence-feedback.ts +655 -0
  201. package/src/plugin/genui-diagnostic.ts +112 -0
  202. package/src/plugin/index.ts +224 -0
  203. package/src/plugin/inline-content-diagnostic.ts +178 -0
  204. package/src/plugin/invariant.ts +30 -0
  205. package/src/plugin/node-shims.d.ts +31 -0
  206. package/src/plugin/tool.ts +424 -0
  207. package/src/shared/fence-repair.ts +536 -0
  208. package/src/shared/fence-resolve.ts +80 -0
  209. package/tsconfig.json +35 -0
  210. package/tsdown.config.ts +275 -0
@@ -0,0 +1,655 @@
1
+ /**
2
+ * Fence feedback loop (issue #160): a reply whose ```dsh-ui fence the guard
3
+ * cannot render should not stay broken for the reader. The host's
4
+ * `agent/turn-stopping` boundary lets a plugin steer input into the SAME turn —
5
+ * the machine re-reads its inbox and runs another step instead of closing
6
+ * (see the `dsh-agent` runtime contract) — so the model can resend a corrected
7
+ * fence while the user is still looking at the raw JSON.
8
+ *
9
+ * The loop is deliberately narrow, matching the contract agreed on the issue:
10
+ * - **默认开启。** 插件配置中的 `fenceFeedback: false` 可以关闭回合转向。
11
+ * - **修正上限。** 每个 turn 最多发送两条 correction;render failure 和 delivery reminder 共用上限,
12
+ * 每个 fence body 在当前回合中最多修正一次,新回合可重新修正。
13
+ * - **仅含 reasoning 的恢复。** 已验证的 GenUI 回合若只以 reasoning block 结束,使用宿主的
14
+ * `EMPTY_RESPONSE` retry policy。
15
+ * - **Never for subagents.** A child session's fence belongs to a parent reply.
16
+ * - **Exact fence matching.** Only an info string of exactly `dsh-ui` opens a
17
+ * fence, so ` ```dsh-ui-dark `, indented prose, or a mention of the name is
18
+ * never rewritten.
19
+ * - **Accounted before sending.** The fingerprint is recorded before `steer`,
20
+ * so a re-entrant boundary cannot deliver the same correction twice.
21
+ * - **Cancellation-aware.** An aborted turn or a missing session is left alone.
22
+ *
23
+ * 检查会复用 renderer 在回合结束后的流程,包括 JSON 修复和坏节点清理;
24
+ * 已经可以渲染的最终回复不会收到修正请求。
25
+ * @module @changfenhuang/dsh-genui/plugin/fence-feedback
26
+ */
27
+
28
+ import type { Context } from '@deepseek-ai/cordis'
29
+ import type {} from '@deepseek-ai/dsh-agent'
30
+ import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
31
+ import type { Session, SessionEvent, SessionStore, UserMessage } from '@deepseek-ai/dsh-session'
32
+ import { createHash, randomUUID } from 'node:crypto'
33
+ import { droppedNodeFailure } from './genui-diagnostic.ts'
34
+ import { resolveFence } from '../shared/fence-resolve.ts'
35
+
36
+ /** Plugin name recorded on every message this loop steers. */
37
+ export const FEEDBACK_PLUGIN_NAME = '@changfenhuang/dsh-genui'
38
+ /** Source kind persisted by this plugin in Session format v4. */
39
+ export const FEEDBACK_SOURCE_KIND = `plugin:${FEEDBACK_PLUGIN_NAME}` as const
40
+
41
+ /** Marker prefix inside the correction text: `[genui-fence-repair #<fingerprint>]`. */
42
+ const MARKER_PREFIX = '[genui-fence-repair #'
43
+ /**
44
+ * 同一个 turn 内 fence-feedback correction 的共享上限。
45
+ * Render failure 和 nothing-delivered reminder 共用该 budget;各自的 ledger 独立阻止重复修正。
46
+ */
47
+ export const MAX_CORRECTIONS_PER_TURN = 2
48
+
49
+ /** Marker prefix written by older plugin versions. */
50
+ const LEGACY_MARKER_PREFIX = '[genui 自修 #'
51
+
52
+ /** A fence opener is an info string of exactly `dsh-ui` (≤3 spaces indent). */
53
+ const FENCE_OPEN = /^ {0,3}```[ \t]*dsh-ui[ \t]*$/u
54
+ /** Any fence closer (the renderer never nests fences in one body). */
55
+ const FENCE_CLOSE = /^ {0,3}```[ \t]*$/u
56
+ /** Upper bound on fences inspected per reply — a reply is text, not a corpus. */
57
+ const MAX_FENCES = 40
58
+
59
+ /** One ```dsh-ui fence found in an assistant reply. */
60
+ export interface ExtractedFence {
61
+ /** Raw body between the fences (no delimiters). */
62
+ readonly raw: string
63
+ /** False when the reply ended before the closing fence. */
64
+ readonly closed: boolean
65
+ /** 1-based position among this reply's fences. */
66
+ readonly index: number
67
+ }
68
+
69
+ /**
70
+ * Extract every ```dsh-ui fence from one assistant reply.
71
+ *
72
+ * @param text - the assistant message text.
73
+ * @returns the fences in document order (at most {@link MAX_FENCES}).
74
+ */
75
+ export function extractDshUiFences(text: string): ExtractedFence[] {
76
+ const lines = text.split('\n')
77
+ const fences: ExtractedFence[] = []
78
+ let open: { start: number; index: number } | null = null
79
+ for (let line = 0; line < lines.length; line++) {
80
+ const current = lines[line] ?? ''
81
+ if (open === null) {
82
+ if (FENCE_OPEN.test(current)) open = { start: line + 1, index: fences.length + 1 }
83
+ continue
84
+ }
85
+ if (!FENCE_CLOSE.test(current)) continue
86
+ fences.push({ raw: lines.slice(open.start, line).join('\n'), closed: true, index: open.index })
87
+ open = null
88
+ if (fences.length >= MAX_FENCES) return fences
89
+ }
90
+ if (open !== null && fences.length < MAX_FENCES) {
91
+ fences.push({ raw: lines.slice(open.start).join('\n'), closed: false, index: open.index })
92
+ }
93
+ return fences
94
+ }
95
+
96
+ /** Stable, log-safe identity of one fence body (same body → same fingerprint). */
97
+ export function fenceFingerprint(raw: string): string {
98
+ return createHash('sha256').update(raw.trim()).digest('hex').slice(0, 12)
99
+ }
100
+
101
+ /** One fence the guard refuses to render, with its model-facing reason. */
102
+ export interface FenceFailure {
103
+ readonly index: number
104
+ readonly fingerprint: string
105
+ /** Actionable diagnosis, in the same wording the validator tool uses. */
106
+ readonly detail: string
107
+ }
108
+
109
+ /**
110
+ * Validate every fence in a reply the way the DOM channel would render it.
111
+ *
112
+ * @param text - the assistant message text.
113
+ * @returns the fences that would stay a raw code block, in document order.
114
+ */
115
+ export function fenceFailures(text: string): FenceFailure[] {
116
+ const failures: FenceFailure[] = []
117
+ for (const fence of extractDshUiFences(text)) {
118
+ const detail = fenceFailureDetail(fence)
119
+ if (detail !== null) failures.push({ index: fence.index, fingerprint: fenceFingerprint(fence.raw), detail })
120
+ }
121
+ return failures
122
+ }
123
+
124
+ /** `null` when this fence renders; otherwise the reason it does not. */
125
+ function fenceFailureDetail(fence: ExtractedFence): string | null {
126
+ if (!fence.closed) return 'error=unterminated_fence\nrequired=closing_fence'
127
+ const resolution = resolveFence(fence.raw, { settled: true })
128
+ if (resolution.spec !== null) return null
129
+ if (resolution.processed !== null) {
130
+ const dropped = droppedNodeFailure(resolution.processed, resolution.value)
131
+ return dropped?.join('\n')
132
+ ?? ['error=invalid_spec', ...resolution.processed.errors.map(error => `diagnostic=${JSON.stringify(error)}`)].join('\n')
133
+ }
134
+ return 'error=invalid_json\nrepair=failed'
135
+ }
136
+
137
+ /**
138
+ * Build the correction input for a reply with unrenderable fences.
139
+ *
140
+ * @param failures - fences {@link fenceFailures} rejected.
141
+ * @returns the message text to steer into the running turn.
142
+ */
143
+ export function fenceCorrectionText(failures: readonly FenceFailure[]): string {
144
+ const body = failures
145
+ .map(failure => `fence=${failure.index}\nfingerprint=${failure.fingerprint}\n${failure.detail}`)
146
+ .join('\n\n')
147
+ const marker = failures.map(failure => `${MARKER_PREFIX}${failure.fingerprint}]`).join(' ')
148
+ return `${marker}\n\n[genui-fence-repair]\nstatus=render_failed\nfences=${failures.length}\nnext=resend_corrected_fence_only\nrepeat_rendered_content=false\nreply_language=conversation\n\n${body}\n`
149
+ }
150
+
151
+ /**
152
+ * Create the identified user-role message this loop steers.
153
+ *
154
+ * Mirrors `createUserMessage` from `@deepseek-ai/dsh-llm` (id + role + frozen)
155
+ * without a runtime dependency on that package: the node half of this plugin
156
+ * deliberately imports no `@deepseek-ai/*` values, so a linked or npm-installed
157
+ * copy resolves identically on every host.
158
+ *
159
+ * @param text - the correction text.
160
+ * @param sessionFormatVersion - the format recorded by the active session.
161
+ * @returns a frozen user message attributed to this plugin as a notice.
162
+ */
163
+ export function createFeedbackMessage(text: string, sessionFormatVersion: number): UserMessage {
164
+ const source = sessionFormatVersion >= 4
165
+ ? {
166
+ kind: FEEDBACK_SOURCE_KIND,
167
+ form: 'notice' as const,
168
+ summary: 'genui fence repair requested',
169
+ }
170
+ : {
171
+ kind: 'plugin' as const,
172
+ plugin: FEEDBACK_PLUGIN_NAME,
173
+ form: 'notice' as const,
174
+ summary: 'genui fence repair requested',
175
+ }
176
+ const message = {
177
+ id: randomUUID(),
178
+ role: 'user',
179
+ content: [{ type: 'text', text }],
180
+ source,
181
+ }
182
+ Object.freeze(message.content)
183
+ return Object.freeze(message) as unknown as UserMessage
184
+ }
185
+
186
+ /** Per-session bookkeeping for the loop (process lifetime). */
187
+ interface SessionFeedback {
188
+ /** Latest assistant reply text of the current turn (fences are read from here). */
189
+ text: string
190
+ /**
191
+ * A `validate_dsh_ui` call happened in this turn. This is the FORMAL signal
192
+ * that the turn is GenUI-related — the loop never guesses intent by scanning
193
+ * the reasoning block.
194
+ */
195
+ validatedThisTurn: boolean
196
+ /** 子代理会话的输出不会直接交给用户。 */
197
+ isSubagent: boolean
198
+ /**
199
+ * The turn delivered something formal: a non-empty body text, or a
200
+ * `render_ui` call whose RESULT reports success. A failed render is not an
201
+ * answer, and a call whose result has not arrived yet proves nothing.
202
+ */
203
+ deliveredThisTurn: boolean
204
+ /**
205
+ * `render_ui` calls of this turn whose result has not arrived yet. The
206
+ * result — not the call — decides delivery, so an outstanding call blocks
207
+ * steering at the boundary instead of being guessed about.
208
+ */
209
+ pendingRenders: Set<string>
210
+ /** Fence fingerprints already corrected for a RENDER failure in the current turn. */
211
+ correctedSpec: Set<string>
212
+ /**
213
+ * Turns already given the "nothing was delivered" reminder. Kept separate from
214
+ * {@link correctedSpec}: a missing delivery must not consume the render-failure
215
+ * ledger (nor the other way round).
216
+ */
217
+ deliveryRemindedTurns: Set<number>
218
+ /** Corrections already steered in {@link correctionsTurn}. */
219
+ correctionsThisTurn: number
220
+ /** Turn {@link correctionsThisTurn} counts. */
221
+ correctionsTurn: number | undefined
222
+ /** 从 session event 中恢复的当前 turn。 */
223
+ currentTurn: number | undefined
224
+ /** 已计入 correction budget 的 message ID。 */
225
+ accountedCorrectionMessageIds: Set<string>
226
+ }
227
+
228
+ /** What the pure planner needs to decide whether a correction may be sent. */
229
+ export interface FenceFeedbackPlanInput {
230
+ /** Latest assistant reply text of the current turn. */
231
+ readonly text: string
232
+ readonly turn: number
233
+ /** Fence bodies already corrected for a render failure in the current turn. */
234
+ readonly correctedSpec: ReadonlySet<string>
235
+ /** Turns already given the delivery reminder. */
236
+ readonly deliveryRemindedTurns?: ReadonlySet<number> | undefined
237
+ /** A `validate_dsh_ui` call happened this turn (formal GenUI signal). */
238
+ readonly validatedThisTurn?: boolean | undefined
239
+ /** The turn already delivered a body or a successful `render_ui` result. */
240
+ readonly deliveredThisTurn?: boolean | undefined
241
+ readonly aborted: boolean
242
+ /** Corrections already steered in this turn (shared hard cap). */
243
+ readonly correctionsThisTurn?: number | undefined
244
+ /** Turn {@link correctionsThisTurn} counts (stale counts are ignored). */
245
+ readonly correctionsTurn?: number | undefined
246
+ }
247
+
248
+ /** A correction the caller must account for before steering. */
249
+ export interface FenceFeedbackPlan {
250
+ readonly text: string
251
+ readonly fingerprints: readonly string[]
252
+ readonly turn: number
253
+ /**
254
+ * `render` corrects a fence that failed to resolve; `delivery` reminds the
255
+ * model that the turn produced nothing formal. They share the per-turn budget
256
+ * but keep separate ledgers.
257
+ */
258
+ readonly kind: 'render' | 'delivery'
259
+ }
260
+
261
+ /**
262
+ * Decide whether this turn boundary should steer a correction — the pure core of
263
+ * the loop, so every bound (per-turn cap, per-fence ledger, cancellation) is
264
+ * testable without a host.
265
+ *
266
+ * The decision is driven by FORMAL events only: fences in the reply body, a
267
+ * `validate_dsh_ui` call, a delivered body text or a successful `render_ui`
268
+ * result. The reasoning block is
269
+ * never read here — a draft inside the thinking block is not proof that the model
270
+ * chose to deliver it, so it must not change any decision.
271
+ *
272
+ * @param input - reply text, turn identity, formal signals, and the accounting.
273
+ * @returns the correction to send, or null when the loop must stay silent.
274
+ */
275
+ export function planFenceFeedback(input: FenceFeedbackPlanInput): FenceFeedbackPlan | null {
276
+ if (input.aborted) return null
277
+ const used = input.correctionsTurn === input.turn ? (input.correctionsThisTurn ?? 0) : 0
278
+ if (used >= MAX_CORRECTIONS_PER_TURN) return null
279
+ const failures = fenceFailures(input.text).filter(failure => !input.correctedSpec.has(failure.fingerprint))
280
+ if (failures.length > 0) {
281
+ return {
282
+ text: fenceCorrectionText(failures),
283
+ fingerprints: failures.map(failure => failure.fingerprint),
284
+ turn: input.turn,
285
+ kind: 'render',
286
+ }
287
+ }
288
+ // No un-corrected render failure. If the turn formally validated a spec and
289
+ // then delivered nothing, remind the model once for this turn.
290
+ if (input.validatedThisTurn !== true || input.deliveredThisTurn === true) return null
291
+ if (input.deliveryRemindedTurns?.has(input.turn) === true) return null
292
+ return { text: missingBodyCorrectionText(input.turn, used + 1), fingerprints: [], turn: input.turn, kind: 'delivery' }
293
+ }
294
+
295
+ /**
296
+ * Correction for a validated GenUI turn that reached the boundary without any
297
+ * formal delivery.
298
+ *
299
+ * @param turn - turn that reached the boundary.
300
+ * @param attempt - correction number within the shared turn budget.
301
+ * @returns the message text to steer into the running turn.
302
+ */
303
+ export function missingBodyCorrectionText(turn: number, attempt = 1): string {
304
+ const head = `${MARKER_PREFIX}turn-${turn}]\n\n[genui-fence-repair]\nstatus=nothing_delivered\nfences=0\nnext=emit_fence_in_body\nrepeat_rendered_content=false\nreply_language=conversation\n\n`
305
+ const emphasis = attempt <= 1 ? '' : `(第 ${attempt} 次提醒)`
306
+ return `${head}本轮尚未产生正式回答,也没有通过支持的通道交付结果${emphasis}。请根据用户当前请求完成正式答复;需要 UI 时,在回答正文输出你最终选定的 dsh-ui 围栏,或明确调用 render_ui。可以修改或放弃此前候选;不能完成时,请在正文说明原因。\n`
307
+ }
308
+
309
+ /**
310
+ * 将 GenUI 回合中仅含 reasoning 的完整响应转换为宿主已有的可重试空响应错误。
311
+ *
312
+ * @param options - LLM stream waterfall 拦截的请求。
313
+ * @param source - 本次请求的 provider stream。
314
+ * @returns 原始 stream;仅符合条件的终止 stop 会被改写。
315
+ */
316
+ async function* retryReasoningOnlyGenuiStream(
317
+ options: GenerateOptions,
318
+ source: AsyncIterable<StreamChunk>,
319
+ ): AsyncGenerator<StreamChunk> {
320
+ const { EMPTY_RESPONSE_CODE, isAgentLoopRequest } = await import('@deepseek-ai/dsh-llm')
321
+ if (!isAgentLoopRequest(options)) {
322
+ yield* source
323
+ return
324
+ }
325
+
326
+ let hasReasoningBlock = false
327
+ let hasOtherBlock = false
328
+ for await (const chunk of source) {
329
+ if (chunk.type === 'block-end') {
330
+ if (chunk.block.type === 'reasoning') hasReasoningBlock = true
331
+ else hasOtherBlock = true
332
+ }
333
+ if (chunk.type === 'finish' && chunk.reason.kind === 'stop' && hasReasoningBlock && !hasOtherBlock) {
334
+ yield {
335
+ type: 'finish',
336
+ reason: {
337
+ kind: 'error',
338
+ failure: {
339
+ message: 'GenUI turn completed with reasoning only and no deliverable response',
340
+ code: EMPTY_RESPONSE_CODE,
341
+ },
342
+ },
343
+ }
344
+ } else {
345
+ yield chunk
346
+ }
347
+ }
348
+ }
349
+
350
+ /** Text of one assistant message's text blocks, in order. */
351
+ function textOfContent(content: unknown): string {
352
+ if (!Array.isArray(content)) return ''
353
+ return content
354
+ .map(block => {
355
+ if (typeof block !== 'object' || block === null) return ''
356
+ const record = block as { type?: unknown; text?: unknown }
357
+ return record.type === 'text' && typeof record.text === 'string' ? record.text : ''
358
+ })
359
+ .filter(part => part !== '')
360
+ .join('\n')
361
+ }
362
+
363
+ type RenderResultStatus = 'rendered' | 'invalid'
364
+
365
+ /** 读取 render_ui result protocol 中明确返回的 status。 */
366
+ function renderResultStatus(content: unknown): RenderResultStatus | undefined {
367
+ const lines = textOfContent(content).split(/\r?\n/u)
368
+ if (lines[0]?.trim() !== '[genui-render]') return undefined
369
+ for (const line of lines.slice(1)) {
370
+ if (line === 'status=rendered') return 'rendered'
371
+ if (line === 'status=invalid') return 'invalid'
372
+ }
373
+ return undefined
374
+ }
375
+
376
+ interface ObservedToolResult {
377
+ readonly callId: string
378
+ readonly isError: boolean
379
+ readonly content: unknown
380
+ }
381
+
382
+ /** 从 legacy wrapper 与 Session format v4 中提取 tool result 数据。 */
383
+ function observedToolResult(message: unknown): ObservedToolResult | null {
384
+ if (typeof message !== 'object' || message === null) return null
385
+ const record = message as { toolCallId?: unknown; isError?: unknown; content?: unknown }
386
+ if (typeof record.toolCallId === 'string') {
387
+ return { callId: record.toolCallId, isError: record.isError === true, content: record.content }
388
+ }
389
+ if (!Array.isArray(record.content)) return null
390
+ const block = record.content.find(part => typeof part === 'object' && part !== null
391
+ && (part as { type?: unknown }).type === 'tool-result') as {
392
+ toolCallId?: unknown
393
+ isError?: unknown
394
+ content?: unknown
395
+ } | undefined
396
+ if (typeof block?.toolCallId !== 'string') return null
397
+ return { callId: block.toolCallId, isError: block.isError === true, content: block.content }
398
+ }
399
+
400
+ /** Tool whose SUCCESSFUL result is a formal delivery. */
401
+ const DELIVERY_TOOL = 'render_ui'
402
+
403
+ /**
404
+ * Whether one assistant message delivered a non-empty body text.
405
+ *
406
+ * Deliberately narrow: a non-empty text block. A `render_ui` call is decided
407
+ * by its `tool/result`, not by the call appearing in a message — a call that
408
+ * failed (or whose result has not arrived) is not a delivery. Other tools
409
+ * (validate_dsh_ui, bash, …) may succeed without producing any answer, so
410
+ * they are NOT counted as delivery.
411
+ *
412
+ * @param content - assistant content blocks.
413
+ * @returns true when this message delivered a body text.
414
+ */
415
+ function deliveredBodyText(content: unknown): boolean {
416
+ if (!Array.isArray(content)) return false
417
+ return content.some(block => {
418
+ if (typeof block !== 'object' || block === null) return false
419
+ const record = block as { type?: unknown; text?: unknown }
420
+ return record.type === 'text' && typeof record.text === 'string' && record.text.trim() !== ''
421
+ })
422
+ }
423
+
424
+
425
+ interface FeedbackMarkers {
426
+ readonly renderFingerprints: string[]
427
+ readonly deliveryTurns: number[]
428
+ }
429
+
430
+ /** 分类当前与 legacy correction message 中的 marker。 */
431
+ function feedbackMarkersIn(text: string): FeedbackMarkers {
432
+ const renderFingerprints: string[] = []
433
+ const deliveryTurns: number[] = []
434
+ let cursor = 0
435
+ while (cursor < text.length) {
436
+ const current = text.indexOf(MARKER_PREFIX, cursor)
437
+ const legacy = text.indexOf(LEGACY_MARKER_PREFIX, cursor)
438
+ if (current < 0 && legacy < 0) break
439
+ const useLegacy = legacy >= 0 && (current < 0 || legacy < current)
440
+ const prefix = useLegacy ? LEGACY_MARKER_PREFIX : MARKER_PREFIX
441
+ const index = useLegacy ? legacy : current
442
+ const end = text.indexOf(']', index + prefix.length)
443
+ if (end < 0) break
444
+ const marker = text.slice(index + prefix.length, end)
445
+ const turn = /^turn-(\d+)$/u.exec(marker)
446
+ if (turn !== null) deliveryTurns.push(Number(turn[1]))
447
+ else renderFingerprints.push(marker)
448
+ cursor = end + 1
449
+ }
450
+ return { renderFingerprints, deliveryTurns }
451
+ }
452
+
453
+ /** 恢复一条持久化 correction 消耗的 turn budget。 */
454
+ function accountReplayedCorrection(state: SessionFeedback, turn: number): void {
455
+ if (state.correctionsTurn !== turn) {
456
+ state.correctionsTurn = turn
457
+ state.correctionsThisTurn = 1
458
+ return
459
+ }
460
+ state.correctionsThisTurn = Math.min(MAX_CORRECTIONS_PER_TURN, state.correctionsThisTurn + 1)
461
+ }
462
+
463
+ /** Identify this plugin's source across current and migrated session shapes. */
464
+ function isFeedbackSource(source: { kind?: unknown; plugin?: unknown } | undefined): boolean {
465
+ return source?.kind === FEEDBACK_SOURCE_KIND
466
+ || (source?.kind === 'plugin' && source.plugin === FEEDBACK_PLUGIN_NAME)
467
+ }
468
+
469
+ /**
470
+ * 注册 GenUI 回合跟踪、宿主重试判定和可选的围栏修正流程。
471
+ *
472
+ * @param ctx - 宿主 Context。
473
+ * @param enabled - 是否启用同回合围栏修正。
474
+ */
475
+ export function installFenceFeedback(ctx: Context, enabled: boolean): void {
476
+ const sessions = new Map<string, SessionFeedback>()
477
+ const stateOf = (sessionId: string): SessionFeedback => {
478
+ let state = sessions.get(sessionId)
479
+ if (state === undefined) {
480
+ state = {
481
+ text: '',
482
+ validatedThisTurn: false,
483
+ isSubagent: false,
484
+ deliveredThisTurn: false,
485
+ pendingRenders: new Set(),
486
+ correctedSpec: new Set(),
487
+ deliveryRemindedTurns: new Set(),
488
+ correctionsThisTurn: 0,
489
+ correctionsTurn: undefined,
490
+ currentTurn: undefined,
491
+ accountedCorrectionMessageIds: new Set(),
492
+ }
493
+ sessions.set(sessionId, state)
494
+ }
495
+ return state
496
+ }
497
+
498
+ ctx.on('session/disposed', (session): void => {
499
+ sessions.delete(String(session.id))
500
+ })
501
+
502
+ const resetTurnState = (state: SessionFeedback, turn: number | undefined): void => {
503
+ state.text = ''
504
+ state.validatedThisTurn = false
505
+ state.deliveredThisTurn = false
506
+ state.pendingRenders.clear()
507
+ state.currentTurn = turn
508
+ }
509
+
510
+ const observeEvent = (session: Session, event: SessionEvent): void => {
511
+ const sessionId = String(session.id)
512
+ if (event.type === 'turn/start') {
513
+ // The formal turn boundary: whatever happened in the previous turn is
514
+ // settled and this turn starts clean. The `user/message` reset below is
515
+ // only a fallback for direct prompts.
516
+ const state = stateOf(sessionId)
517
+ state.isSubagent = session.header.parentSession !== undefined
518
+ // 去重只约束当前回合,新一轮仍可修正相同错误。
519
+ state.correctedSpec.clear()
520
+ resetTurnState(state, (event.data as { turn?: number }).turn)
521
+ return
522
+ }
523
+ if (event.type === 'assistant/message') {
524
+ const content = (event.data as { message?: { content?: unknown } }).message?.content
525
+ const text = textOfContent(content)
526
+ const state = stateOf(sessionId)
527
+ state.isSubagent = session.header.parentSession !== undefined
528
+ // Fences are read from the BODY only: a draft in the reasoning block is not
529
+ // a delivery and must not become one.
530
+ state.text = extractDshUiFences(text).length > 0 ? text : ''
531
+ // Delivery is sticky for the turn: once a body text exists, the turn has
532
+ // answered and must never be corrected into publishing again. A
533
+ // `render_ui` call in the content proves nothing here — its result does.
534
+ state.deliveredThisTurn = state.deliveredThisTurn || deliveredBodyText(content)
535
+ return
536
+ }
537
+ if (event.type === 'tool/call') {
538
+ const data = event.data as { name?: unknown; callId?: unknown }
539
+ const state = stateOf(sessionId)
540
+ state.isSubagent = session.header.parentSession !== undefined
541
+ // validate_dsh_ui is the FORMAL signal that this turn is GenUI-related.
542
+ if (data.name === 'validate_dsh_ui') state.validatedThisTurn = true
543
+ // The result — not the call — decides whether render_ui delivered.
544
+ if (data.name === DELIVERY_TOOL && typeof data.callId === 'string') {
545
+ state.pendingRenders.add(data.callId)
546
+ }
547
+ return
548
+ }
549
+ if (event.type === 'tool/result') {
550
+ const data = event.data as { message?: unknown; error?: unknown }
551
+ const result = observedToolResult(data.message)
552
+ if (result === null) return
553
+ const state = stateOf(sessionId)
554
+ state.isSubagent = session.header.parentSession !== undefined
555
+ if (!state.pendingRenders.delete(result.callId)) return
556
+ if (data.error === undefined && result.isError !== true && renderResultStatus(result.content) === 'rendered') {
557
+ state.deliveredThisTurn = true
558
+ }
559
+ return
560
+ }
561
+ if (event.type !== 'user/message') return
562
+ const data = event.data as { id?: unknown; content?: unknown; source?: { kind?: unknown; plugin?: unknown } }
563
+ if (isFeedbackSource(data.source)) {
564
+ const markers = feedbackMarkersIn(textOfContent(data.content))
565
+ if (markers.renderFingerprints.length === 0 && markers.deliveryTurns.length === 0) return
566
+ const state = stateOf(sessionId)
567
+ state.isSubagent = session.header.parentSession !== undefined
568
+ for (const fingerprint of markers.renderFingerprints) state.correctedSpec.add(fingerprint)
569
+ for (const turn of markers.deliveryTurns) state.deliveryRemindedTurns.add(turn)
570
+ if (typeof data.id === 'string' && !state.accountedCorrectionMessageIds.has(data.id)) {
571
+ state.accountedCorrectionMessageIds.add(data.id)
572
+ const turn = markers.deliveryTurns[0] ?? state.currentTurn
573
+ if (turn !== undefined) accountReplayedCorrection(state, turn)
574
+ }
575
+ return
576
+ }
577
+ // A DIRECT human prompt starts a new turn: the previous reply is settled.
578
+ // Synthetic context that rides the same user surface — `agent.inject()`
579
+ // notices, team member messages — carries a different source kind and
580
+ // arrives MID-TURN: resetting here used to wipe the turn's validation and
581
+ // delivery state before the boundary could use it.
582
+ if (data.source?.kind !== 'user') return
583
+ const state = sessions.get(sessionId)
584
+ if (state !== undefined) {
585
+ state.isSubagent = session.header.parentSession !== undefined
586
+ // turn/start 先于用户消息;清掉正文状态时保留正式回合身份。
587
+ resetTurnState(state, state.currentTurn)
588
+ }
589
+ }
590
+
591
+ const restoreHistory = (session: Session): void => {
592
+ if (sessions.has(String(session.id))) return
593
+ for (const event of session.snapshotEvents()) observeEvent(session, event)
594
+ }
595
+ ctx.on('session/event', (session, event) => {
596
+ // 服务注入是异步的;首条实时事件也先接管历史,避免丢失旧纠错次数。
597
+ restoreHistory(session)
598
+ observeEvent(session, event)
599
+ })
600
+ ctx.on('session/created', restoreHistory)
601
+ const restoreSessions = (sessionCtx: Context): void => {
602
+ const store = sessionCtx.reflect.get('sessions') as SessionStore | undefined
603
+ if (store === undefined) return
604
+ for (const session of store.list()) restoreHistory(session)
605
+ }
606
+ // 宿主不重播历史;安装时同步接管已有会话,异步注入负责晚到的服务。
607
+ restoreSessions(ctx)
608
+ ctx.inject(['sessions'], restoreSessions)
609
+
610
+ ctx.on('llm/stream', (options, next) => {
611
+ if (options.sessionId === undefined || options.purpose !== undefined) return next()
612
+ const state = sessions.get(String(options.sessionId))
613
+ if (state?.validatedThisTurn !== true || state.isSubagent) return next()
614
+ return retryReasoningOnlyGenuiStream(options, next())
615
+ }, { global: true })
616
+
617
+ ctx.on('agent/turn-stopping', ({ agent, turn, signal }): void => {
618
+ if (!enabled) return
619
+ // A child session's fence belongs to a parent reply, and an aborted turn is
620
+ // on its way out: never steer into either.
621
+ if (agent.session.header.parentSession !== undefined) return
622
+ const state = sessions.get(String(agent.session.id))
623
+ if (state === undefined) return
624
+ state.currentTurn = turn
625
+ // A render_ui result still outstanding could deliver (or fail) after this
626
+ // boundary fires: steering now would race the late result, so stay silent
627
+ // and let the next boundary decide on settled facts.
628
+ if (state.pendingRenders.size > 0) return
629
+ const usedThisTurn = state.correctionsTurn === turn ? state.correctionsThisTurn : 0
630
+ const plan = planFenceFeedback({
631
+ text: state.text,
632
+ turn,
633
+ correctedSpec: state.correctedSpec,
634
+ deliveryRemindedTurns: state.deliveryRemindedTurns,
635
+ validatedThisTurn: state.validatedThisTurn,
636
+ deliveredThisTurn: state.deliveredThisTurn,
637
+ aborted: signal.aborted,
638
+ correctionsThisTurn: usedThisTurn,
639
+ correctionsTurn: state.correctionsTurn,
640
+ })
641
+ if (plan === null) return
642
+ // Account BEFORE sending: a re-entrant boundary must not deliver twice.
643
+ for (const fingerprint of plan.fingerprints) state.correctedSpec.add(fingerprint)
644
+ if (plan.kind === 'delivery') state.deliveryRemindedTurns.add(plan.turn)
645
+ state.correctionsTurn = plan.turn
646
+ state.correctionsThisTurn = usedThisTurn + 1
647
+ try {
648
+ const message = createFeedbackMessage(plan.text, agent.session.header.version)
649
+ state.accountedCorrectionMessageIds.add(message.id)
650
+ agent.steer(message)
651
+ } catch (error) {
652
+ ctx.logger?.warn?.(`dsh-genui: fence feedback steering failed (${error instanceof Error ? error.message : String(error)})`)
653
+ }
654
+ })
655
+ }