@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,536 @@
1
+ /**
2
+ * Shared fence-body JSON repair — pure string functions, no DOM, no I/O.
3
+ * Used by BOTH the client fence renderer (tier-1/tier-2 auto-repair before
4
+ * rendering) and the node-side validate_dsh_ui tool (which returns the
5
+ * repaired JSON to the model instead of making it re-author the fix).
6
+ *
7
+ * Two tiers, deliberately gated differently by the callers:
8
+ * - Tier-1 (`repairFenceJson`): heals the most common model JSON typos that
9
+ * do NOT change the body's structure — unescaped half-width quotes inside
10
+ * string values and trailing commas. Safe at any time (streaming included),
11
+ * adopted only when the WHOLE body parses afterwards.
12
+ * - Tier-2 (`completeFenceJson`): heals structural incompleteness — missing
13
+ * closing quotes/brackets — by appending the missing terminators, and
14
+ * skips mismatched closers (a `]` mistyped as `}`, duplicated terminators).
15
+ * SETTLED MESSAGES ONLY: a streaming half must never be adopted as a
16
+ * finished prefix.
17
+ * @module @changfenhuang/dsh-genui/shared/fence-repair
18
+ */
19
+
20
+ /** A fence body counts as complete when it parses as a whole JSON value. */
21
+ export function isCompleteJson(raw: string): boolean {
22
+ try {
23
+ JSON.parse(raw)
24
+ return true
25
+ } catch {
26
+ return false
27
+ }
28
+ }
29
+
30
+ /** Short human-readable reason for a body that fails whole-JSON parsing, or
31
+ * null when it parses. Positions come from the host's JSON.parse error. */
32
+ export function describeJsonFailure(raw: string): string | null {
33
+ try {
34
+ JSON.parse(raw)
35
+ return null
36
+ } catch (err) {
37
+ const msg = err instanceof Error ? err.message : String(err)
38
+ const pos = msg.match(/position (\d+)/i)
39
+ const where = pos !== null ? `(字符 ${pos[1]} 附近)` : ''
40
+ return `${where}${msg.slice(0, 140)}`
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Tier-1 repair — SAFE AT ANY TIME (streaming included): heals the most
46
+ * common model JSON typos that do NOT change the body's structure, and only
47
+ * when the whole body parses afterwards (so a still-growing streaming half
48
+ * can never be adopted):
49
+ *
50
+ * 1. Unescaped half-width `"` inside a string value — Chinese text quoted
51
+ * with ASCII quotes (e.g. `对"别名路径"判定失败`), which makes JSON.parse
52
+ * fail near that quote with "Expected ',' or ']'...".
53
+ * 2. Trailing commas before `}` / `]` or at end of input.
54
+ *
55
+ * A shared grammar-aware scan distinguishes object keys from values and
56
+ * checks the continuation after a potential string terminator. Ambiguous
57
+ * value quotes use bounded backtracking; trailing commas are dropped only
58
+ * outside strings.
59
+ *
60
+ * Returns `{ text, repairs }` on success, or null when nothing needed fixing
61
+ * or the body still does not parse (callers fall through to tier-2 / banner).
62
+ */
63
+ export function repairFenceJson(raw: string): { text: string; repairs: number } | null {
64
+ try {
65
+ JSON.parse(raw)
66
+ return null
67
+ } catch {
68
+ // fall through to the repair scan
69
+ }
70
+ return scanFenceJson(raw, false)
71
+ }
72
+
73
+ /** A fixed search budget prevents quote ambiguity from becoming exponential. */
74
+ const MAX_QUOTE_ATTEMPTS = 32
75
+ const MAX_QUOTE_LOOKAHEAD = 4096
76
+
77
+ type JsonScope = {
78
+ closer: '}' | ']'
79
+ expecting: 'key' | 'colon' | 'value' | 'comma'
80
+ }
81
+ type RepairScan = {
82
+ text: string
83
+ repairs: number
84
+ rootEnd: number
85
+ rawRootEnd: number
86
+ choices: number[]
87
+ unfinishedString: boolean
88
+ invalidValue: boolean
89
+ }
90
+
91
+ function isJsonSpace(ch: string | undefined): boolean {
92
+ return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r'
93
+ }
94
+
95
+ /**
96
+ * Quote closure is contextual: only keys may be followed by `:`, and a comma
97
+ * must introduce the next member of the enclosing object/array. Walk closing
98
+ * delimiters too, so a bracket in a quoted code example cannot end a value
99
+ * when prose immediately follows it inside the enclosing JSON structure.
100
+ * Lookahead has a fixed bound; inconclusive long continuations keep the
101
+ * terminator interpretation and leave the final JSON.parse as the arbiter.
102
+ */
103
+ function quoteCanClose(raw: string, index: number, key: boolean, scopes: JsonScope[], complete: boolean): boolean {
104
+ const limit = Math.min(raw.length, index + MAX_QUOTE_LOOKAHEAD)
105
+ let cursor = index + 1
106
+ const skipSpace = (): void => { while (cursor < limit && isJsonSpace(raw[cursor])) cursor++ }
107
+ skipSpace()
108
+ if (cursor >= limit) return true
109
+ if (key) return raw[cursor] === ':'
110
+ let scopeIndex = scopes.length - 1
111
+ if (raw[cursor] === ':') return false
112
+ while (raw[cursor] === '}' || raw[cursor] === ']') {
113
+ const scope = scopes[scopeIndex]
114
+ if (scope === undefined) return false
115
+ if (raw[cursor] === scope.closer) scopeIndex--
116
+ else if (!complete) return false
117
+ cursor++
118
+ skipSpace()
119
+ if (cursor >= limit) return true
120
+ // Tier-2 can retain a complete root prefix followed by junk. It tries
121
+ // whole-body quote alternatives before actually adopting that prefix.
122
+ if (scopeIndex < 0) return complete
123
+ }
124
+ if (raw[cursor] !== ',') return false
125
+ const scope = scopes[scopeIndex]
126
+ if (scope === undefined) return false
127
+ cursor++
128
+ skipSpace()
129
+ if (cursor >= limit) return true
130
+ if (raw[cursor] === scope.closer) return true // a removable trailing comma
131
+ if (scope.closer === ']') return /["[{tfn\-0-9]/.test(raw[cursor]!)
132
+ if (raw[cursor] !== '"') return false
133
+ // An object comma must be followed by a quoted key and its colon. Escapes
134
+ // in that key are skipped without changing them.
135
+ cursor++
136
+ while (cursor < limit) {
137
+ if (raw[cursor] === '\\') { cursor += 2; continue }
138
+ if (raw[cursor] === '"') {
139
+ cursor++
140
+ skipSpace()
141
+ return cursor >= limit || raw[cursor] === ':'
142
+ }
143
+ if (raw[cursor]!.charCodeAt(0) < 0x20) return false
144
+ cursor++
145
+ }
146
+ return true
147
+ }
148
+
149
+ /** Both tiers share the same string-aware scan and quote decisions. */
150
+ function scanFenceCandidate(raw: string, complete: boolean, contentQuotes: ReadonlySet<number>): RepairScan {
151
+ let out = ''
152
+ const scopes: JsonScope[] = []
153
+ let inString = false
154
+ let key = false
155
+ let interiorQuote = false
156
+ let escaped = false
157
+ let repairs = 0
158
+ let rootEnd = 0
159
+ let rawRootEnd = 0
160
+ let invalidValue = false
161
+ const choices: number[] = []
162
+ const finishValue = (): void => {
163
+ const scope = scopes[scopes.length - 1]
164
+ if (scope !== undefined) scope.expecting = 'comma'
165
+ }
166
+ for (let i = 0; i < raw.length; i++) {
167
+ const ch = raw[i]!
168
+ if (escaped) {
169
+ if (inString && ch === '"') interiorQuote = true
170
+ out += ch
171
+ escaped = false
172
+ continue
173
+ }
174
+ if (inString) {
175
+ if (ch === '\\') { out += ch; escaped = true; continue }
176
+ if (ch !== '"') { out += ch; continue }
177
+ let next = i + 1
178
+ while (next < raw.length && isJsonSpace(raw[next])) next++
179
+ // Without any interior quote, a delimiter-looking quote is a normal
180
+ // terminator even if its sibling is malformed. Do not absorb a broken
181
+ // bare value merely to make structural completion succeed.
182
+ const ordinaryEnd = !key && ((!interiorQuote && ',}]:'.includes(raw[next] ?? '\0'))
183
+ || (scopes[scopes.length - 1]?.closer === ']' && raw[next] === ','))
184
+ if (!contentQuotes.has(i) && (ordinaryEnd || quoteCanClose(raw, i, key, scopes, complete))) {
185
+ inString = false
186
+ out += ch
187
+ const scope = scopes[scopes.length - 1]
188
+ if (key) {
189
+ if (scope !== undefined) scope.expecting = 'colon'
190
+ } else {
191
+ finishValue()
192
+ // Only value terminators create alternatives. Retaining at most
193
+ // 32 recent decisions bounds the pending search and its memory.
194
+ if (scope !== undefined && interiorQuote) {
195
+ if (choices.length === MAX_QUOTE_ATTEMPTS) choices.shift()
196
+ choices.push(i)
197
+ }
198
+ }
199
+ } else {
200
+ out += '\\"'
201
+ interiorQuote = true
202
+ repairs++
203
+ }
204
+ continue
205
+ }
206
+ if (ch === '"') {
207
+ key = scopes[scopes.length - 1]?.expecting === 'key'
208
+ interiorQuote = false
209
+ inString = true
210
+ out += ch
211
+ continue
212
+ }
213
+ if (ch === '{' || ch === '[') {
214
+ finishValue()
215
+ scopes.push({ closer: ch === '{' ? '}' : ']', expecting: ch === '{' ? 'key' : 'value' })
216
+ out += ch
217
+ continue
218
+ }
219
+ if (ch === '}' || ch === ']') {
220
+ if (scopes[scopes.length - 1]?.closer === ch) {
221
+ scopes.pop()
222
+ out += ch
223
+ if (scopes.length === 0 && rootEnd === 0) {
224
+ rootEnd = out.length
225
+ rawRootEnd = i + 1
226
+ }
227
+ } else if (complete) repairs++
228
+ else out += ch
229
+ continue
230
+ }
231
+ if (ch === ',') {
232
+ let j = i + 1
233
+ while (j < raw.length && isJsonSpace(raw[j])) j++
234
+ if (j === raw.length || raw[j] === '}' || raw[j] === ']') {
235
+ repairs++
236
+ continue
237
+ }
238
+ const scope = scopes[scopes.length - 1]
239
+ if (scope !== undefined) scope.expecting = scope.closer === '}' ? 'key' : 'value'
240
+ } else if (ch === ':') {
241
+ const scope = scopes[scopes.length - 1]
242
+ if (scope !== undefined) scope.expecting = 'value'
243
+ } else if (!isJsonSpace(ch) && scopes[scopes.length - 1]?.expecting === 'value') {
244
+ // Invalid bare values are not quote ambiguity: do not turn an earlier
245
+ // finished string into a container for `broken` / `undefined` tokens.
246
+ let j = i + 1
247
+ while (j < raw.length && !isJsonSpace(raw[j]) && !'{}[],:"'.includes(raw[j]!)) j++
248
+ const token = raw.slice(i, j)
249
+ if (!/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/.test(token)) invalidValue = true
250
+ finishValue()
251
+ out += token
252
+ i = j - 1
253
+ continue
254
+ }
255
+ out += ch
256
+ }
257
+ const unfinishedString = inString
258
+ if (complete) {
259
+ if (inString) { out += '"'; repairs++ }
260
+ while (scopes.length > 0) { out += scopes.pop()!.closer; repairs++ }
261
+ }
262
+ return { text: out, repairs, rootEnd, rawRootEnd, choices, unfinishedString, invalidValue }
263
+ }
264
+
265
+ /** Find an authoritative, already-valid object/array prefix without repair. */
266
+ function originalJsonPrefix(raw: string): string | null {
267
+ const scopes: string[] = []
268
+ let inString = false
269
+ let escaped = false
270
+ let started = false
271
+ for (let i = 0; i < raw.length; i++) {
272
+ const ch = raw[i]!
273
+ if (escaped) { escaped = false; continue }
274
+ if (inString) {
275
+ if (ch === '\\') escaped = true
276
+ else if (ch === '"') inString = false
277
+ continue
278
+ }
279
+ if (!started) {
280
+ if (isJsonSpace(ch)) continue
281
+ if (ch !== '{' && ch !== '[') return null
282
+ started = true
283
+ }
284
+ if (ch === '"') { inString = true; continue }
285
+ if (ch === '{' || ch === '[') scopes.push(ch === '{' ? '}' : ']')
286
+ else if (ch === '}' || ch === ']') {
287
+ if (scopes.pop() !== ch) return null
288
+ if (scopes.length === 0) {
289
+ const text = raw.slice(0, i + 1).trimEnd()
290
+ try { JSON.parse(text); return text } catch { return null }
291
+ }
292
+ }
293
+ }
294
+ return null
295
+ }
296
+
297
+ /**
298
+ * Prefer real terminators; if the resulting whole body fails, try interpreting
299
+ * a bounded number of ambiguous value quotes as content. Each attempt is an
300
+ * iterative scan, not a recursive parser; no engine-specific error offset is
301
+ * needed. Fixed attempts/lookahead give O(n) time and O(n) working storage.
302
+ */
303
+ function scanFenceJson(raw: string, complete: boolean): { text: string; repairs: number } | null {
304
+ // A genuine original root is authoritative. Never reinterpret its closing
305
+ // quote to absorb a second object or prose, even during speculative repair.
306
+ const original = originalJsonPrefix(raw)
307
+ if (original !== null) return complete ? { text: original, repairs: 1 } : null
308
+ const pending: number[][] = [[]]
309
+ let prefix: { text: string; repairs: number; rawEnd: number } | null = null
310
+ for (let attempt = 0; attempt < MAX_QUOTE_ATTEMPTS && pending.length > 0; attempt++) {
311
+ const forced = pending.pop()!
312
+ const scanned = scanFenceCandidate(raw, complete, new Set(forced))
313
+ // A speculative branch must find a real closing quote. Appending one to
314
+ // that branch could swallow malformed sibling fields into invented text.
315
+ if (scanned.repairs > 0 && !(forced.length > 0 && scanned.unfinishedString)) {
316
+ try {
317
+ JSON.parse(scanned.text)
318
+ return { text: scanned.text, repairs: scanned.repairs }
319
+ } catch { /* try a different bounded quote interpretation */ }
320
+ }
321
+ // Validate possible prefixes now, but do not adopt one until all whole-
322
+ // body alternatives have failed. Prefer the one that retains the most
323
+ // source text, rather than an earlier quote mistaken for a root end.
324
+ if (complete && scanned.rootEnd > 0 && (prefix === null || scanned.rawRootEnd > prefix.rawEnd)) {
325
+ const text = scanned.text.slice(0, scanned.rootEnd).trimEnd()
326
+ try {
327
+ JSON.parse(text)
328
+ prefix = { text, repairs: scanned.repairs + 1, rawEnd: scanned.rawRootEnd }
329
+ } catch { /* a balanced but invalid prefix cannot be adopted */ }
330
+ }
331
+ if (scanned.invalidValue) continue
332
+ const last = forced[forced.length - 1] ?? -1
333
+ for (const quote of scanned.choices) {
334
+ if (quote > last) pending.push([...forced, quote])
335
+ }
336
+ // Newer decisions are tried first. Discard older pending branches when
337
+ // the fixed budget is full instead of accumulating an exponential tree.
338
+ if (pending.length > MAX_QUOTE_ATTEMPTS) pending.splice(0, pending.length - MAX_QUOTE_ATTEMPTS)
339
+ }
340
+ // Balanced-prefix adoption remains strictly tier-2 / settled-only, and only
341
+ // after whole-body repair attempts have failed.
342
+ if (prefix !== null) return { text: prefix.text, repairs: prefix.repairs }
343
+ return null
344
+ }
345
+
346
+ /**
347
+ * 取**第一个平衡根值**的文本(丢弃其后的杂字符);没有平衡根时返回 null。
348
+ *
349
+ * 与 {@link completeFenceJson} 里的前缀回退同源,但**只做裁剪、不做结构补全**:
350
+ * 内容识别用它来容忍「合法 JSON + 尾部泄漏文本」(真实样本:模型把自己的工具调用
351
+ * 模板泄漏在 JSON 之后,且围栏没闭合)。根值正好结束在末尾时返回 null —— 那种情况
352
+ * `JSON.parse` 本来就会成功。
353
+ *
354
+ * @param text - 候选正文。
355
+ * @returns 平衡根前缀;无可裁剪内容时 null。
356
+ */
357
+ export function trimToBalancedRoot(text: string): string | null {
358
+ const stack: Array<'}' | ']'> = []
359
+ let inString = false
360
+ let escaped = false
361
+ let started = false
362
+ for (let i = 0; i < text.length; i += 1) {
363
+ const ch = text[i]
364
+ if (escaped) {
365
+ escaped = false
366
+ continue
367
+ }
368
+ if (inString) {
369
+ if (ch === '\\') escaped = true
370
+ else if (ch === '"') inString = false
371
+ continue
372
+ }
373
+ if (ch === '"') {
374
+ inString = true
375
+ started = true
376
+ continue
377
+ }
378
+ if (ch === '{') {
379
+ stack.push('}')
380
+ started = true
381
+ continue
382
+ }
383
+ if (ch === '[') {
384
+ stack.push(']')
385
+ started = true
386
+ continue
387
+ }
388
+ if (ch === '}' || ch === ']') {
389
+ // 不匹配的闭括号 ⇒ 这份正文结构上已经坏了,不做"裁剪"式的猜测。
390
+ if (stack[stack.length - 1] !== ch) return null
391
+ stack.pop()
392
+ if (stack.length === 0 && started) {
393
+ if (i + 1 >= text.length) return null
394
+ return text.slice(0, i + 1).trim()
395
+ }
396
+ }
397
+ }
398
+ return null
399
+ }
400
+
401
+ /**
402
+ * Rewrite the "Tetris table" shape into legal JSON: the model closed the
403
+ * `columns` array after the header cells and then wrote the row matrix as a
404
+ * SIBLING array element —
405
+ *
406
+ * "columns":["a","b"],["rows":[["1","2"],["3","4"]]]
407
+ *
408
+ * The element after `columns` is a `rows` field wearing the wrong hat, so
409
+ * restore the key (`"rows":[…]`) and drop the closer the mis-nesting left
410
+ * over (the final bracket-depth rescan removes every unmatched closer). Safe
411
+ * by construction: only applied to a body that does not parse, and the caller
412
+ * adopts the result only when the WHOLE body then parses.
413
+ *
414
+ * @param raw - the raw fence body.
415
+ * @returns the rewritten body plus the edit count, or null when the shape is
416
+ * not present (or the columns array never closes).
417
+ */
418
+ function rewriteTetrisTableColumns(raw: string): { text: string; repairs: number } | null {
419
+ if (!/"columns"\s*:\s*\[/.test(raw)) return null
420
+ let text = ''
421
+ let rest = raw
422
+ let edits = 0
423
+ while (true) {
424
+ const match = /"columns"\s*:\s*\[/.exec(rest)
425
+ if (match === null) { text += rest; break }
426
+ const start = match.index + match[0]!.length
427
+ // Walk to the matching `]` of this columns array, string-aware.
428
+ let depth = 1
429
+ let inString = false
430
+ let escaped = false
431
+ let end = -1
432
+ for (let i = start; i < rest.length; i++) {
433
+ const ch = rest[i]!
434
+ if (escaped) { escaped = false; continue }
435
+ if (inString) {
436
+ if (ch === '\\') escaped = true
437
+ else if (ch === '"') inString = false
438
+ continue
439
+ }
440
+ if (ch === '"') { inString = true; continue }
441
+ if (ch === '[') depth++
442
+ else if (ch === ']') { depth--; if (depth === 0) { end = i; break } }
443
+ }
444
+ if (end < 0) return null
445
+ const after = rest.slice(end + 1)
446
+ // Two Tetris spellings, both meaning "the rows matrix is a sibling array
447
+ // of `columns`": with the key already inside the array (`[ "rows": […]`)
448
+ // or as a bare matrix (`[ […], […] ]`).
449
+ const keyed = /^\s*,\s*\[\s*"rows"\s*:\s*\[/.exec(after)
450
+ if (keyed !== null) {
451
+ const through = end + 1 + keyed[0]!.length
452
+ text += `${rest.slice(0, end + 1)},"rows":[`
453
+ rest = rest.slice(through)
454
+ edits += 1
455
+ continue
456
+ }
457
+ const nextArray = /^\s*,\s*\[/.exec(after)
458
+ if (nextArray === null) {
459
+ text += rest.slice(0, end + 1)
460
+ rest = after
461
+ continue
462
+ }
463
+ const throughBracket = end + 1 + nextArray[0]!.length
464
+ text += rest.slice(0, throughBracket).replace(/,\s*\[$/, ', "rows": [')
465
+ rest = rest.slice(throughBracket)
466
+ edits += 1
467
+ }
468
+ if (edits === 0) return null
469
+ // Drop the closers the mis-nesting left without a partner.
470
+ const stack: string[] = []
471
+ let out = ''
472
+ let inString = false
473
+ let escaped = false
474
+ for (const ch of text) {
475
+ if (escaped) { out += ch; escaped = false; continue }
476
+ if (inString) {
477
+ out += ch
478
+ if (ch === '\\') escaped = true
479
+ else if (ch === '"') inString = false
480
+ continue
481
+ }
482
+ if (ch === '"') { inString = true; out += ch; continue }
483
+ if (ch === '{' || ch === '[') { stack.push(ch); out += ch; continue }
484
+ if (ch === '}' || ch === ']') {
485
+ const open = stack[stack.length - 1]
486
+ if ((ch === '}' && open === '{') || (ch === ']' && open === '[')) {
487
+ stack.pop()
488
+ out += ch
489
+ } else edits += 1 // stray closer → drop it
490
+ continue
491
+ }
492
+ out += ch
493
+ }
494
+ return { text: out, repairs: edits }
495
+ }
496
+
497
+ /**
498
+ * Tier-2 repair — SETTLED MESSAGES ONLY (never while streaming): heals
499
+ * structural incompleteness — missing closing quotes/brackets — by appending
500
+ * the missing terminators, and heals stray closers — a `]` mistyped as `}` or
501
+ * a duplicated terminator — by skipping closers that do not match the open
502
+ * stack (they cannot be legal JSON). Callers gate it on settled messages (the
503
+ * client uses the host-provided fence source; the validate tool is by
504
+ * definition pre-emission), so a streaming half can never flash premature UI.
505
+ *
506
+ * One shared scan implementation folds the tier-1 fixes (quote escaping +
507
+ * trailing-comma drops) into structural completion, so bodies with BOTH defects
508
+ * (a trailing comma AND a missing closer) heal in one shot — the old
509
+ * two-phase chain lost tier-1's partial work when its whole-body parse
510
+ * failed, and re-scanning the raw text could not compose the repairs.
511
+ * Adopted only when the completed body parses as whole JSON.
512
+ */
513
+ export function completeFenceJson(raw: string): { text: string; repairs: number } | null {
514
+ try {
515
+ JSON.parse(raw)
516
+ return null
517
+ } catch {
518
+ // fall through to the unified repair scan
519
+ }
520
+ // Shape defect first: the "Tetris table" nesting cannot be healed by the
521
+ // closer-appending scan below (its brackets are balanced — just nested
522
+ // wrongly), so rewrite the shape, then let the scan run on the result.
523
+ const tetris = rewriteTetrisTableColumns(raw)
524
+ if (tetris !== null) {
525
+ try {
526
+ JSON.parse(tetris.text)
527
+ return tetris
528
+ } catch {
529
+ // Tetris 形状修复可能暴露需要 tier-2 继续处理的结构问题。
530
+ }
531
+ const scanned = completeFenceJson(tetris.text)
532
+ if (scanned === null) return null
533
+ return { text: scanned.text, repairs: scanned.repairs + tetris.repairs }
534
+ }
535
+ return scanFenceJson(raw, true)
536
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 使用浏览器 renderer 与 Node 侧最终回复反馈守卫共用的流程解析 dsh-ui 围栏正文。
3
+ * @module @changfenhuang/dsh-genui/shared/fence-resolve
4
+ */
5
+
6
+ import { partialRepairGenuiSpec, processGenuiSpec, type GenuiProcessResult } from '../client/guard.ts'
7
+ import { parsePartialGenuiSpec } from '../client/parse-partial.ts'
8
+ import type { GenuiSpec } from '../client/spec.ts'
9
+ import { completeFenceJson, repairFenceJson } from './fence-repair.ts'
10
+
11
+ /** 控制是否允许采用结构化 JSON 修复的选项。 */
12
+ export interface FenceResolveOptions {
13
+ /** 回合结束后的回复允许使用 tier-2 补全修复。 */
14
+ readonly settled: boolean
15
+ }
16
+
17
+ /** 一次围栏候选正文经过规格守卫后的结果。 */
18
+ export interface FenceResolution {
19
+ /** 参与本次规格处理的解析值;没有可解析值时为 null。 */
20
+ readonly value: unknown | null
21
+ /** 规格守卫输出的诊断;没有可解析值时为 null。 */
22
+ readonly processed: GenuiProcessResult | null
23
+ /** 可渲染的 spec;无法渲染时为 null。 */
24
+ readonly spec: GenuiSpec | null
25
+ }
26
+
27
+ /**
28
+ * 对已经解析的值执行规格守卫和坏节点清理。
29
+ *
30
+ * @param value - 已解析或部分解析的围栏值。
31
+ * @returns 当前候选正文的规格处理结果。
32
+ */
33
+ function resolveParsedFence(value: unknown): FenceResolution {
34
+ const processed = processGenuiSpec(value)
35
+ return { value, processed, spec: partialRepairGenuiSpec(processed) }
36
+ }
37
+
38
+ /** 返回没有可解析正文的围栏处理结果。 */
39
+ function unresolvedFence(): FenceResolution {
40
+ return { value: null, processed: null, spec: null }
41
+ }
42
+
43
+ /**
44
+ * 使用 renderer 的统一流程解析原始 dsh-ui 正文。
45
+ *
46
+ * 流式生成期间可以使用 tier-1 修复。tier-2 补全修复只允许用于回合结束后的回复,
47
+ * 防止未完成的正文提前渲染。
48
+ *
49
+ * @param raw - dsh-ui 围栏标记之间的原始正文。
50
+ * @param options - 流式或回合结束后的解析策略。
51
+ * @returns 通过规格守卫的渲染 spec;正文无法渲染时返回 null。
52
+ */
53
+ export function resolveFence(raw: string, options: FenceResolveOptions): FenceResolution {
54
+ const parsed = parsePartialGenuiSpec(raw)
55
+ let resolution = parsed === null ? unresolvedFence() : resolveParsedFence(parsed)
56
+ if (resolution.spec !== null) return resolution
57
+
58
+ const repaired = repairFenceJson(raw)
59
+ if (repaired !== null) {
60
+ const reparsed = parsePartialGenuiSpec(repaired.text)
61
+ resolution = reparsed === null ? unresolvedFence() : resolveParsedFence(reparsed)
62
+ }
63
+ if (resolution.spec !== null || !options.settled) return resolution
64
+
65
+ const completed = completeFenceJson(raw)
66
+ if (completed === null) return resolution
67
+ const reparsed = parsePartialGenuiSpec(completed.text)
68
+ return reparsed === null ? unresolvedFence() : resolveParsedFence(reparsed)
69
+ }
70
+
71
+ /**
72
+ * 只返回统一围栏解析流程的可渲染 spec。
73
+ *
74
+ * @param raw - dsh-ui 围栏标记之间的原始正文。
75
+ * @param options - 流式或回合结束后的解析策略。
76
+ * @returns 通过规格守卫的渲染 spec;正文无法渲染时返回 null。
77
+ */
78
+ export function resolveFenceSpec(raw: string, options: FenceResolveOptions): GenuiSpec | null {
79
+ return resolveFence(raw, options).spec
80
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2024",
4
+ "module": "esnext",
5
+ "moduleResolution": "bundler",
6
+ "jsx": "react-jsx",
7
+ "lib": [
8
+ "ES2024",
9
+ "DOM",
10
+ "DOM.Iterable"
11
+ ],
12
+ "types": [
13
+ "node"
14
+ ],
15
+ "declaration": true,
16
+ "skipLibCheck": true,
17
+ "esModuleInterop": true,
18
+ "allowImportingTsExtensions": true,
19
+ "rewriteRelativeImportExtensions": true,
20
+ "strict": true,
21
+ "noUncheckedIndexedAccess": true,
22
+ "exactOptionalPropertyTypes": true,
23
+ "noImplicitOverride": true,
24
+ "noFallthroughCasesInSwitch": true,
25
+ "noUnusedLocals": true,
26
+ "noUnusedParameters": true,
27
+ "rootDir": "src",
28
+ "outDir": "lib",
29
+ "emitDeclarationOnly": true,
30
+ "declarationDir": "lib/types"
31
+ },
32
+ "include": [
33
+ "src"
34
+ ]
35
+ }