@sparkelf/dsh-genui 0.0.0-stage → 0.11.4-patch.2

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,112 @@
1
+ /**
2
+ * GenUI 节点诊断共享逻辑。
3
+ * @module @changfenhuang/dsh-genui/plugin/genui-diagnostic
4
+ */
5
+
6
+ import type { GenuiProcessResult } from '../client/guard.ts'
7
+ import { COMPONENT_SCHEMAS } from '../client/genui-runtime/schema.ts'
8
+
9
+ /** 获取指定组件类型已知字段,保持提示顺序稳定。 */
10
+ function knownFieldsOf(type: string): string[] {
11
+ const schema = COMPONENT_SCHEMAS[type]
12
+ if (schema === undefined) return []
13
+ return [...schema.required, ...Object.keys(schema.optional)]
14
+ }
15
+
16
+ /** 获取校验错误对应的节点路径。 */
17
+ function nodePathOf(error: string): string | null {
18
+ const match = /^(items\[\d+\](?:\.items\[\d+\])*)(?=:|\.items\[|$)/.exec(error)
19
+ return match === null ? null : match[1]!
20
+ }
21
+
22
+ /** 根据节点路径读取模型声明的节点对象。 */
23
+ function declaredNodeAt(value: unknown, path: string): Record<string, unknown> | undefined {
24
+ if (typeof value !== 'object' || value === null) return undefined
25
+ const root = value as Record<string, unknown>
26
+ const normalized = path.replace(/^items/, '')
27
+ let current: unknown = normalized === '' ? root : root.items
28
+ for (const step of normalized.replace(/^\./, '').split('.').filter(part => part !== '')) {
29
+ const matched = /(?:items)?\[(\d+)\]/.exec(step)
30
+ const index = matched === null ? Number.NaN : Number(matched[1])
31
+ if (!Number.isInteger(index) || !Array.isArray(current)) return undefined
32
+ current = current[index]
33
+ }
34
+ return typeof current === 'object' && current !== null && !Array.isArray(current)
35
+ ? current as Record<string, unknown>
36
+ : undefined
37
+ }
38
+
39
+ /** 将校验错误转换为固定协议字段。 */
40
+ function fieldSymptom(error: string, path: string, type: string): string {
41
+ const rest = error.slice(path.length)
42
+ const unknown = /^\.([A-Za-z0-9_-]+): unknown field\b/.exec(rest)
43
+ if (unknown !== null) {
44
+ const known = knownFieldsOf(type)
45
+ return [`error=unknown_field`, `field=${unknown[1]}`, ...(known.length === 0 ? [] : [`allowed=${known.join(',')}`])].join('\n')
46
+ }
47
+ const missing = /requires ([A-Za-z0-9_-]+)/.exec(rest)
48
+ if (missing !== null) return `error=missing_required_field\nfield=${missing[1]}`
49
+ return `error=validation_error\ndetail=${JSON.stringify(rest.replace(/^:\s*/, '').slice(0, 120))}`
50
+ }
51
+
52
+ /** 获取校验错误中声明的组件类型。 */
53
+ function errorTypeOf(error: string): string | undefined {
54
+ return /type '([^']+)'/.exec(error)?.[1]
55
+ }
56
+
57
+ /** 生成被丢弃节点的路径、类型和字段诊断。 */
58
+ function droppedNodeDiagnosis(processed: GenuiProcessResult, raw: unknown): string[] {
59
+ const byPath = new Map<string, string[]>()
60
+ for (const error of processed.errors) {
61
+ const path = nodePathOf(error)
62
+ if (path === null) continue
63
+ const bucket = byPath.get(path)
64
+ if (bucket === undefined) byPath.set(path, [error])
65
+ else bucket.push(error)
66
+ }
67
+ const lines: string[] = []
68
+ for (const [path, errors] of byPath) {
69
+ const node = declaredNodeAt(raw, path)
70
+ const type = (typeof node?.type === 'string' ? node.type : undefined)
71
+ ?? errors.map(errorTypeOf).find(candidate => candidate !== undefined)
72
+ if (type !== undefined && repairedContainsType(processed.repaired, type)) continue
73
+ const emitted = node === undefined ? [] : Object.keys(node).filter(key => key !== 'type')
74
+ const symptoms = [...new Set(errors.map(error => fieldSymptom(error, path, type ?? 'unknown')))]
75
+ lines.push([
76
+ `node=${path}`,
77
+ `type=${type ?? 'unknown'}`,
78
+ ...symptoms,
79
+ ...(emitted.length === 0 ? [] : [`written=${emitted.join(',')}`]),
80
+ ].join('\n'))
81
+ }
82
+ return lines
83
+ }
84
+
85
+ /** 检查修复后的组件树中是否仍然存在指定类型的原生节点。 */
86
+ function repairedContainsType(node: unknown, type: string): boolean {
87
+ if (Array.isArray(node)) return node.some(child => repairedContainsType(child, type))
88
+ if (typeof node !== 'object' || node === null) return false
89
+ const record = node as Record<string, unknown>
90
+ if (record.type === type) return true
91
+ return Object.values(record).some(child => repairedContainsType(child, type))
92
+ }
93
+
94
+ /**
95
+ * 报告被丢弃的组件,并保留模型可以直接修正的字段信息。
96
+ *
97
+ * @param processed - 节点处理结果。
98
+ * @param raw - 节点处理使用的原始值。
99
+ * @returns 可嵌入调用方协议的诊断字段;没有节点被丢弃时返回 undefined。
100
+ */
101
+ export function droppedNodeFailure(processed: GenuiProcessResult, raw: unknown): string[] | undefined {
102
+ if (!processed.errors.some(error => error.startsWith('repair dropped '))) return undefined
103
+ const dropped = processed.declaredNativeCount - processed.renderedNativeCount
104
+ const diagnosis = droppedNodeDiagnosis(processed, raw)
105
+ return [
106
+ `declared=${processed.declaredNativeCount}`,
107
+ `rendered=${processed.renderedNativeCount}`,
108
+ `dropped=${dropped}`,
109
+ ...diagnosis.flatMap(line => [line, '']),
110
+ ...processed.errors.map(error => `diagnostic=${JSON.stringify(error)}`),
111
+ ]
112
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * GenUI plugin: teaches the model the ```dsh-ui fence syntax for emitting
3
+ * declarative UI components inline in its reply. The browser half renders the
4
+ * fence through GenuiBlock (ui-primitives); this host half only tells the
5
+ * model the language exists, so a session without the plugin simply never
6
+ * emits fences and nothing changes.
7
+ *
8
+ * The section uses the host's centrally allocated structured-output placement.
9
+ * @module @changfenhuang/dsh-genui
10
+ */
11
+
12
+ import { Context } from '@deepseek-ai/cordis'
13
+ import type {} from '@deepseek-ai/dsh-system-prompt'
14
+ import type {} from '@deepseek-ai/dsh-tools'
15
+ import type { SkillProvider } from '@deepseek-ai/dsh-skill'
16
+ import type { IncomingMessage, ServerResponse } from 'node:http'
17
+ import { readFileSync } from 'node:fs'
18
+ import { readFile } from 'node:fs/promises'
19
+ import { basename, dirname, join, resolve } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+ import { createRenderUiTool, createValidateDshUiTool } from './tool.ts'
22
+ import { installFenceFeedback } from './fence-feedback.ts'
23
+
24
+ /* ---------------- lazy engine asset route ---------------- */
25
+
26
+ /**
27
+ * The mermaid/three engines ship as standalone IIFE bundles under
28
+ * `lib/assets/` and are fetched by the client ONLY when a spec needs them.
29
+ * This route serves them from the plugin's own package directory through the
30
+ * host webserver service — the longest-prefix rule lets it win over the
31
+ * generic `/plugins` bundle route, and no host source change is needed. The
32
+ * service is optional at this plugin's start time, so a dependency fiber owns
33
+ * the registration and follows the webserver through late binding, replacement,
34
+ * and plugin reloads.
35
+ */
36
+
37
+ /** Route prefix under /plugins; anything under it is this plugin's asset. */
38
+ const ASSET_ROUTE_PATH = '/plugins/@changfenhuang/dsh-genui/assets'
39
+
40
+ /** Safe flat file names only: no slashes, no traversal, js assets only. */
41
+ const ASSET_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.js$/
42
+
43
+ /** The handler itself (registered via the optional webServer probe). */
44
+ async function serveGenuiAsset(req: IncomingMessage, res: ServerResponse): Promise<void> {
45
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
46
+ res.writeHead(405)
47
+ res.end()
48
+ return
49
+ }
50
+ let pathname: string
51
+ try {
52
+ pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname)
53
+ } catch {
54
+ res.writeHead(400)
55
+ res.end()
56
+ return
57
+ }
58
+ const rel = pathname.startsWith(`${ASSET_ROUTE_PATH}/`) ? pathname.slice(ASSET_ROUTE_PATH.length) : null
59
+ if (rel === null) {
60
+ res.writeHead(404)
61
+ res.end()
62
+ return
63
+ }
64
+ const file = rel.slice(1)
65
+ if (!ASSET_FILE_RE.test(file)) {
66
+ res.writeHead(404)
67
+ res.end()
68
+ return
69
+ }
70
+ try {
71
+ // lib/index.js → ./assets/ = <pkg>/lib/assets/ (the tsdown asset outDir).
72
+ const dir = fileURLToPath(new URL('./assets/', import.meta.url))
73
+ const body = await readFile(join(dir, file))
74
+ res.writeHead(200, {
75
+ 'content-type': 'text/javascript; charset=utf-8',
76
+ 'cache-control': 'no-cache',
77
+ })
78
+ res.end(body)
79
+ } catch {
80
+ // Missing asset (old build) — a loud 404; the client shows its fallback.
81
+ res.writeHead(404)
82
+ res.end()
83
+ }
84
+ }
85
+
86
+ /** The fence language description injected into every assembled system prompt.
87
+ * Deliberately slim: the `genui` skill carries the full component→field
88
+ * mapping; this section keeps only the contract that must always be
89
+ * present (fence syntax, type whitelist, and critical behavioral rules). */
90
+ export const GENUI_SECTION_TEXT = `You can render interactive UI components INSIDE your reply — between paragraphs — by emitting a fenced block with the language tag \`dsh-ui\` containing a JSON spec:
91
+
92
+ \`\`\`dsh-ui
93
+ {"title":"<user-language text>","gap":14,"items":[...]}
94
+ \`\`\`
95
+
96
+ Allowed \`type\` values; the \`genui\` skill, when available, carries the full content→component mapping and per-component field details:
97
+
98
+ - 布局: text · row · col · grid · card · divider · spacer · hero(封面块,一条回答最多一个)
99
+ - 展示: badge · stat · progress · list · table · keyvalue · timeline · file-tree · breadcrumb · callout · steps · diff · json · code · copy · avatar · audio · video
100
+ - 图表: chart {"kind":"bars|line|donut","data":[{"label":"...","value":n}],"series":[{"label":"...","data":[...]}]?,"horizontal":true?,"stacked":true?}(series:bars 分组/堆叠 / line 多序列;horizontal 横向柱) · echart (preset 名或 option 直通,预设清单见 skill) · plot (函数图)
101
+ - 交互: button · input · textarea · select · checkbox · switch · slider · radio · submit · quiz · link · tabs · accordion
102
+ - 高级: mermaid (流程图/时序/甘特/ER 等,关键字见 skill) · diagram (架构/流程图,27 种 kind) · scene3d (3D WebGL)
103
+
104
+ **默认就该出 UI**:出现下列情况至少出一个围栏:
105
+ - ≥3 条并列要点 → \`list\`;数字对比 → \`table\`;指标/进度/状态 → \`stat\`/\`progress\`/\`badge\`
106
+ - 步骤/时间线 → \`steps\`/\`timeline\`/\`mermaid\`;架构/流程 → \`diagram\` 或 \`mermaid\`;风险/结论 → \`callout\`;代码/改动 → \`code\`/\`diff\`/\`json\`
107
+ - 行内富文本:支持公式、\`code\`、加粗、高亮、链接;禁用 Markdown table / fenced code,改用 table / code / diff / json。
108
+ - 默认无卡:按触发条件使用组件,每个组件承载不同信息;卡片只用于并排项与数据对象,单段文字用标题、正文与间距。
109
+
110
+ **发回答前最后自检一次**:这段内容里有没有 ≥3 条并列要点、任何对比、任何数字/指标、任何步骤或流程?有就先转成组件再开口。**状态汇报、进度说明、提交与改动清单同样算**。
111
+ - 趋势/占比 → \`chart\`(≤8 点)或 \`echart\`(多序列/要交互时);配色默认跟随主题,只有语义需要时才用 \`palette\`/\`card.accent\`;grid 子节点用 \`"span":2\` 跨列做宽窄混排;数据多时给 \`table\`/\`chart\`/\`list\` 配一个 \`input\`(id) + \`filter\` 绑定,读者能就地筛选。
112
+
113
+ **字段速查**(完整见 genui skill):\`stat\` \`{"label","value","delta"?}\` · \`table\` \`{"columns":[...],"rows":[[...]],"types"?,"details"?,"filter"?,"export"?}\` · \`progress\` \`{"value":0-100,"label"?,"variant"?,"target"?}\` · \`keyvalue\` \`{"pairs":[{"key","value"}]}\` · \`steps\` \`{"steps":[{"title","desc"?}]}\` · \`file-tree\` \`{"items":[{"name","type":"file|dir","children"?}]}\` · \`callout\` \`{"content","tone"?,"title"?}\`
114
+
115
+ **字段名写错 = 该组件被丢弃**(其余组件照常渲染):\`callout\` 正文是 \`content\` 不是 text/desc;\`table\` 要 \`columns\`+\`rows\` 不是 items;\`keyvalue\` 记录是 \`{key,value}\` 不是 \`{label,value}\`;\`file-tree\` 记录是 \`{name,type}\` 不是 \`{label}\`;callout tone 是 info/success/warning/error(无 danger)。不确定就调 \`validate_dsh_ui\`。
116
+
117
+ Rules:
118
+ - LANGUAGE: reply+UI=conversation language; schema fixed. NEVER infer it from prompt/skill/examples/tools. Replace \`<user-language ...>\`; never emit these placeholders literally.
119
+ - JSON 严格:坏组件被丢弃,坏围栏变代码块;≥3 节点或含 table 时调 validate_dsh_ui,按诊断修改并重验;小围栏字段存疑也先验证。
120
+ - warning=block_markdown:按 replacement 改写并重验。
121
+ - 规模: ≤200 节点、嵌套≤8 层(超出被截断);一条回答 3–8 个组件,一个主题一个主组件;3D mesh 1–5;plot 给合理 xMin/xMax。
122
+ - LOCAL-FIRST + actions: UI 能自己做的状态变化(判卷、判题、重置、展开、选中)就地完成,零往返;action 只用于必须模型参与的事。交互以 [genui-action] name + 组件数据回传,届时重渲染更新 UI;无 action 的按钮禁用。
123
+ - Durable state: 交互状态按「会话+内容指纹」持久化——刷新/重放恢复;相同内容保留,新内容重置。
124
+ - 卷子模式: 每题一个 radio(group+answer+explanation)+ 一个 submit(groups 全列),本地判分。
125
+ - Secrets ban: 不索取密码、API Key、Token、恢复码;需要时拒绝并解释。
126
+ - Tool channel: render_ui 工具把同一 spec 渲染为工具行卡片;围栏用于回答内联 UI。
127
+ - 围栏位置:\`dsh-ui\` 只写在**回答正文**;写在 reasoning/思考块里不渲染、用户看不到——思考里验证好 spec,正文再输出同一份。
128
+ - Panel: "panel":true 只渲染进会话面板 dock 并原地更新;"append":true 追加合并;上限 200 节点/200 次追加,满了发 replace 重建。面板来的 [genui-action] 只回一个 panel:true 围栏 + 至多一行 10 字内确认。`
129
+
130
+ /**
131
+ * Register the GenUI output-language section and the render_ui tool.
132
+ * @param ctx - cordis context.
133
+ */
134
+ // `tools` is intentionally NOT injected: the service is optional for this
135
+ // plugin — hosts without tool access keep the fence channel working. Cordis
136
+ // inject entries are hard requirements, so the registry is probed at runtime
137
+ // instead (see apply).
138
+ export const name = '@changfenhuang/dsh-genui'
139
+ export const inject = ['systemPrompt']
140
+
141
+ const BUNDLED_SKILL_RANK = 600
142
+ const BUNDLED_SKILL_PROVIDER = 'dsh-genui'
143
+ const BUNDLED_SKILL_DESCRIPTION = 'GenUI dsh-ui component/schema reference. Preserve conversation language for all user-visible text.'
144
+ const BUNDLED_SKILL_INVOCATION = { modelInvocable: true, userInvocable: true } as const
145
+
146
+ /** Register through the provider path so source=bundled also gets bundled precedence. */
147
+ function bundledSkillProvider(): SkillProvider {
148
+ const moduleDirectory = dirname(fileURLToPath(new URL(import.meta.url)))
149
+ const path = basename(moduleDirectory) === 'plugin'
150
+ ? resolve(moduleDirectory, '../../SKILL.md')
151
+ : resolve(moduleDirectory, '../SKILL.md')
152
+ const raw = readFileSync(path, 'utf8')
153
+ const end = raw.indexOf('\n---\n', 4)
154
+ if (!raw.startsWith('---\n') || end < 0) throw new Error('genui SKILL.md has invalid frontmatter')
155
+ return {
156
+ name: BUNDLED_SKILL_PROVIDER,
157
+ list: () => Promise.resolve([{
158
+ name: 'genui',
159
+ description: BUNDLED_SKILL_DESCRIPTION,
160
+ invocation: BUNDLED_SKILL_INVOCATION,
161
+ source: 'bundled',
162
+ provider: BUNDLED_SKILL_PROVIDER,
163
+ path,
164
+ resourceBase: { kind: 'directory', path: dirname(path) },
165
+ rank: BUNDLED_SKILL_RANK,
166
+ locator: path,
167
+ }]),
168
+ get: () => Promise.resolve({
169
+ name: 'genui',
170
+ description: BUNDLED_SKILL_DESCRIPTION,
171
+ invocation: BUNDLED_SKILL_INVOCATION,
172
+ source: 'bundled',
173
+ provider: BUNDLED_SKILL_PROVIDER,
174
+ path,
175
+ resourceBase: { kind: 'directory', path: dirname(path) },
176
+ content: raw.slice(end + 5),
177
+ }),
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Plugin config as the host passes it (unvalidated: the node half deliberately
183
+ * imports no schema library, so a profile can set these keys directly).
184
+ */
185
+ export interface GenuiPluginConfig {
186
+ /**
187
+ * 在最终 dsh-ui 围栏无法渲染的回合中请求模型发送一次修正版(issue #160)。
188
+ * 默认开启,设置为 false 可以关闭同回合围栏修正。GenUI 回合的 reasoning-only 响应仍会交给宿主重试策略处理。
189
+ * 每回合和每个围栏正文最多请求一次,子代理不触发,每次修正请求会消耗模型步数。
190
+ */
191
+ fenceFeedback?: boolean
192
+ }
193
+
194
+ export function apply(ctx: Context, config?: GenuiPluginConfig): void {
195
+ ctx.systemPrompt.section({
196
+ name: 'genui:fence',
197
+ order: ctx.systemPrompt.getSectionOrder('STRUCTURED_OUTPUT'),
198
+ text: GENUI_SECTION_TEXT,
199
+ })
200
+ installFenceFeedback(ctx, config?.fenceFeedback !== false)
201
+ // Hosts without tool access keep the fence channel. The dependency fiber
202
+ // starts whenever tools becomes available and unloads its registrations
203
+ // before either the service or this plugin is replaced.
204
+ ctx.inject(['tools'], (toolsCtx) => {
205
+ toolsCtx.effect(function* () {
206
+ yield toolsCtx.tools.register(createRenderUiTool())
207
+ yield toolsCtx.tools.register(createValidateDshUiTool())
208
+ }, 'dsh-genui: model tools')
209
+ })
210
+
211
+ ctx.inject(['skills'], (skillCtx) => {
212
+ skillCtx.skills.registerProvider(() => bundledSkillProvider())
213
+ })
214
+
215
+ // webServer.register returns a raw disposer, so an explicit effect binds the
216
+ // route to the dependency fiber instead of leaving it in the host route table.
217
+ ctx.inject(['webServer'], (webCtx) => {
218
+ const webServer = webCtx.reflect.get('webServer') as { register(route: unknown): () => void }
219
+ webCtx.effect(
220
+ () => webServer.register({ kind: 'prefix', path: ASSET_ROUTE_PATH, handler: serveGenuiAsset }),
221
+ 'dsh-genui: asset route',
222
+ )
223
+ })
224
+ }
@@ -0,0 +1,178 @@
1
+ import type { GenuiNode, GenuiSpec } from '../client/spec.ts'
2
+
3
+ export interface InlineContentWarning {
4
+ path: string
5
+ kind: 'fenced_code' | 'markdown_table'
6
+ replacement: 'code' | 'table'
7
+ }
8
+
9
+ /** 识别文字字段中的连续代码围栏标记。 */
10
+ function hasFencedCode(value: string): boolean {
11
+ return /`{3,}|~{3,}/.test(value)
12
+ }
13
+
14
+ /** 判断相邻表头下方的 Markdown 表格分隔行。 */
15
+ function isMarkdownTableSeparator(line: string): boolean {
16
+ let value = line.trim()
17
+ if (value.startsWith('|')) value = value.slice(1)
18
+ if (value.endsWith('|')) value = value.slice(0, -1)
19
+ const cells = value.split('|').map(cell => cell.trim())
20
+ return cells.length >= 2 && cells.every(cell => /^:?-{2,}:?$/.test(cell))
21
+ }
22
+
23
+ /** 仅在相邻表头和分隔行构成表格时报告。 */
24
+ function hasMarkdownTable(value: string): boolean {
25
+ const lines = value.split(/\r?\n/)
26
+ for (let i = 0; i + 1 < lines.length; i++) {
27
+ if (lines[i]!.includes('|') && isMarkdownTableSeparator(lines[i + 1]!)) return true
28
+ }
29
+ return false
30
+ }
31
+
32
+ /** 按组件结构检查需要块级内容诊断的 canonical 显示字段。 */
33
+ export function collectInlineContentWarnings(spec: GenuiSpec): InlineContentWarning[] {
34
+ const warnings: InlineContentWarning[] = []
35
+
36
+ /** 将一个可见文字字段中的块级 Markdown 记录为稳定诊断。 */
37
+ function check(value: string | undefined, path: string): void {
38
+ if (value === undefined) return
39
+ if (hasFencedCode(value)) warnings.push({ path, kind: 'fenced_code', replacement: 'code' })
40
+ if (hasMarkdownTable(value)) warnings.push({ path, kind: 'markdown_table', replacement: 'table' })
41
+ }
42
+
43
+ /** 只沿 GenUI 组件的子节点字段访问下一层。 */
44
+ function visit(node: GenuiNode, path: string): void {
45
+ switch (node.type) {
46
+ case 'text': check(node.content, `${path}.content`); break
47
+ case 'card':
48
+ check(node.title, `${path}.title`)
49
+ node.items.forEach((child, i) => visit(child, `${path}.items[${i}]`))
50
+ break
51
+ case 'row':
52
+ case 'col':
53
+ case 'grid':
54
+ node.items.forEach((child, i) => visit(child, `${path}.items[${i}]`))
55
+ break
56
+ case 'button':
57
+ case 'checkbox':
58
+ case 'link':
59
+ case 'badge':
60
+ case 'switch':
61
+ case 'submit':
62
+ check(node.label, `${path}.label`)
63
+ break
64
+ case 'input':
65
+ case 'select':
66
+ case 'slider':
67
+ case 'textarea':
68
+ check(node.label, `${path}.label`)
69
+ break
70
+ case 'radio':
71
+ check(node.label, `${path}.label`)
72
+ node.options.forEach((option, i) => check(option, `${path}.options[${i}]`))
73
+ if (typeof node.answer === 'string') check(node.answer, `${path}.answer`)
74
+ check(node.explanation, `${path}.explanation`)
75
+ break
76
+ case 'image':
77
+ case 'audio':
78
+ case 'video':
79
+ check(node.alt, `${path}.alt`)
80
+ break
81
+ case 'hero':
82
+ for (const field of ['label', 'value', 'delta', 'title', 'subtitle'] as const) check(node[field], `${path}.${field}`)
83
+ break
84
+ case 'stat':
85
+ for (const field of ['label', 'value', 'delta'] as const) check(node[field], `${path}.${field}`)
86
+ break
87
+ case 'progress':
88
+ check(node.label, `${path}.label`)
89
+ check(node.valueLabel, `${path}.valueLabel`)
90
+ break
91
+ case 'list':
92
+ node.items.forEach((item, i) => {
93
+ const itemPath = `${path}.items[${i}]`
94
+ if (typeof item === 'string') check(item, itemPath)
95
+ else if ('type' in item && typeof item.type === 'string') visit(item as GenuiNode, itemPath)
96
+ else {
97
+ check(item.title, `${itemPath}.title`)
98
+ check(item.desc, `${itemPath}.desc`)
99
+ }
100
+ })
101
+ break
102
+ case 'table':
103
+ node.columns.forEach((column, i) => check(column, `${path}.columns[${i}]`))
104
+ node.rows.forEach((row, i) => {
105
+ const detail = node.details?.[i] ?? null
106
+ row.forEach((cell, j) => {
107
+ if (node.types?.[j] === 'index' && (j !== 0 || detail === null)) return
108
+ if (typeof cell === 'string') check(cell, `${path}.rows[${i}][${j}]`)
109
+ })
110
+ })
111
+ node.details?.forEach((detail, i) => detail?.forEach((child, j) => visit(child, `${path}.details[${i}][${j}]`)))
112
+ break
113
+ case 'chart':
114
+ node.series?.forEach((series, i) => check(series.label, `${path}.series[${i}].label`))
115
+ break
116
+ case 'tabs':
117
+ node.tabs.forEach((tab, i) => {
118
+ check(tab.label, `${path}.tabs[${i}].label`)
119
+ tab.items.forEach((child, j) => visit(child, `${path}.tabs[${i}].items[${j}]`))
120
+ })
121
+ break
122
+ case 'accordion':
123
+ node.items.forEach((item, i) => {
124
+ check(item.title, `${path}.items[${i}].title`)
125
+ item.items.forEach((child, j) => visit(child, `${path}.items[${i}].items[${j}]`))
126
+ })
127
+ break
128
+ case 'callout':
129
+ check(node.title, `${path}.title`)
130
+ check(node.content, `${path}.content`)
131
+ break
132
+ case 'steps':
133
+ node.steps.forEach((step, i) => {
134
+ check(step.title, `${path}.steps[${i}].title`)
135
+ check(step.desc, `${path}.steps[${i}].desc`)
136
+ })
137
+ break
138
+ case 'keyvalue':
139
+ node.pairs.forEach((pair, i) => {
140
+ check(pair.key, `${path}.pairs[${i}].key`)
141
+ check(pair.value, `${path}.pairs[${i}].value`)
142
+ })
143
+ break
144
+ case 'timeline':
145
+ node.items.forEach((item, i) => {
146
+ check(item.title, `${path}.items[${i}].title`)
147
+ check(item.time, `${path}.items[${i}].time`)
148
+ check(item.desc, `${path}.items[${i}].desc`)
149
+ })
150
+ break
151
+ case 'breadcrumb':
152
+ node.items.forEach((item, i) => check(item, `${path}.items[${i}]`))
153
+ break
154
+ case 'quiz':
155
+ check(node.question, `${path}.question`)
156
+ node.options.forEach((option, i) => {
157
+ check(option.label, `${path}.options[${i}].label`)
158
+ check(option.feedback, `${path}.options[${i}].feedback`)
159
+ })
160
+ check(node.explanation, `${path}.explanation`)
161
+ break
162
+ case 'plot':
163
+ case 'echart':
164
+ case 'diagram':
165
+ case 'scene3d':
166
+ case 'svg':
167
+ check(node.title, `${path}.title`)
168
+ break
169
+ case 'copy':
170
+ check(node.label, `${path}.label`)
171
+ break
172
+ }
173
+ }
174
+
175
+ check(spec.title, 'title')
176
+ spec.items.forEach((node, i) => visit(node, `items[${i}]`))
177
+ return warnings
178
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Package-owned invariant companion for `@changfenhuang/dsh-genui`.
3
+ * @module @changfenhuang/dsh-genui/invariant
4
+ */
5
+
6
+ /* jscpd:ignore-start */
7
+ import type { Context } from '@deepseek-ai/cordis'
8
+ import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
9
+
10
+ const PACKAGE_NAME = '@changfenhuang/dsh-genui'
11
+
12
+ /** Cordis companion plugin name. */
13
+ export const name = 'genui-invariant'
14
+ /** Service required before the companion can reserve package ownership. */
15
+ export const inject = ['invariants']
16
+
17
+ /**
18
+ * No runtime invariant: this host plugin only registers a static prompt
19
+ * section; the section text is pinned by its own tests.
20
+ */
21
+ const install: InvariantInstaller = () => {}
22
+
23
+ /**
24
+ * Register this package's invariant companion.
25
+ * @param ctx - Cordis context carrying the invariant service.
26
+ * @returns the installed registration's disposer after setup succeeds.
27
+ */
28
+ export const apply = (ctx: Context): Promise<() => void> =>
29
+ Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
30
+ /* jscpd:ignore-end */
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Minimal ambient declarations for the node: builtins the plugin node half
3
+ * uses (asset route: http/fs/path/url). The package compiles with
4
+ * `"types": []` and ships no @types/node devDependency, so these shims are
5
+ * the typecheck surface; tsdown bundles the real node modules at build time
6
+ * (platform: node). Declarations cover exactly the members in use.
7
+ * @module @changfenhuang/dsh-genui/plugin/node-shims
8
+ */
9
+
10
+ declare module 'node:http' {
11
+ export interface IncomingMessage {
12
+ method?: string
13
+ url?: string
14
+ }
15
+ export interface ServerResponse {
16
+ writeHead(statusCode: number, headers?: Record<string, string>): ServerResponse
17
+ end(data?: string | Buffer): void
18
+ }
19
+ }
20
+
21
+ declare module 'node:fs/promises' {
22
+ export function readFile(path: string): Promise<Buffer>
23
+ }
24
+
25
+ declare module 'node:path' {
26
+ export function join(...paths: string[]): string
27
+ }
28
+
29
+ declare module 'node:url' {
30
+ export function fileURLToPath(url: URL): string
31
+ }