@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.
- package/CHANGELOG.md +597 -0
- package/LICENSE +21 -0
- package/README.md +292 -2
- package/README.zh-CN.md +307 -0
- package/SKILL.md +261 -0
- package/cordis.patch.yml +9 -0
- package/demo-prompts.md +118 -0
- package/lib/assets/echarts-core.js +43 -0
- package/lib/assets/echarts-full.js +72 -0
- package/lib/assets/mermaid.js +3591 -0
- package/lib/assets/standalone-runtime.js +1506 -0
- package/lib/assets/three.js +3844 -0
- package/lib/client.js +405 -0
- package/lib/index.js +5187 -0
- package/lib/invariant.js +19 -0
- package/lib/types/client/EChartNode.d.ts +13 -0
- package/lib/types/client/ErrorBoundary.d.ts +30 -0
- package/lib/types/client/GenuiBlock.d.ts +9 -0
- package/lib/types/client/PlotBlock.d.ts +44 -0
- package/lib/types/client/TemplateDrawer.d.ts +7 -0
- package/lib/types/client/achievement-store.d.ts +35 -0
- package/lib/types/client/achievement-toast.d.ts +2 -0
- package/lib/types/client/achievements.d.ts +63 -0
- package/lib/types/client/action-context.d.ts +7 -0
- package/lib/types/client/artifact/ExportableGenuiBlock.d.ts +6 -0
- package/lib/types/client/artifact/create.d.ts +5 -0
- package/lib/types/client/artifact/download.d.ts +9 -0
- package/lib/types/client/artifact/html.d.ts +5 -0
- package/lib/types/client/artifact/index.d.ts +8 -0
- package/lib/types/client/artifact/json.d.ts +3 -0
- package/lib/types/client/artifact/parse.d.ts +3 -0
- package/lib/types/client/artifact/portability.d.ts +4 -0
- package/lib/types/client/artifact/standalone-theme.d.ts +2 -0
- package/lib/types/client/artifact/types.d.ts +33 -0
- package/lib/types/client/asset-echarts-core.d.ts +1 -0
- package/lib/types/client/asset-echarts.d.ts +17 -0
- package/lib/types/client/asset-loader.d.ts +33 -0
- package/lib/types/client/asset-mermaid.d.ts +1 -0
- package/lib/types/client/asset-three.d.ts +1 -0
- package/lib/types/client/blocks/advanced.d.ts +101 -0
- package/lib/types/client/blocks/basic.d.ts +22 -0
- package/lib/types/client/blocks/charts.d.ts +53 -0
- package/lib/types/client/blocks/checkbox.d.ts +17 -0
- package/lib/types/client/blocks/diagram/geometry.d.ts +73 -0
- package/lib/types/client/blocks/diagram/index.d.ts +5 -0
- package/lib/types/client/blocks/diagram/layout.d.ts +41 -0
- package/lib/types/client/blocks/diagram/theme.d.ts +37 -0
- package/lib/types/client/blocks/forms.d.ts +77 -0
- package/lib/types/client/blocks/image.d.ts +6 -0
- package/lib/types/client/blocks/render-node.d.ts +10 -0
- package/lib/types/client/blocks/state.d.ts +63 -0
- package/lib/types/client/blocks/svg.d.ts +4 -0
- package/lib/types/client/dom-fence.d.ts +30 -0
- package/lib/types/client/echarts-engine.d.ts +4 -0
- package/lib/types/client/echarts-lazy.d.ts +18 -0
- package/lib/types/client/embed.d.ts +10 -0
- package/lib/types/client/fence-render.d.ts +106 -0
- package/lib/types/client/gallery.d.ts +7 -0
- package/lib/types/client/genui-runtime/diagnostics.d.ts +18 -0
- package/lib/types/client/genui-runtime/index.d.ts +1 -0
- package/lib/types/client/genui-runtime/limits.d.ts +54 -0
- package/lib/types/client/genui-runtime/normalize.d.ts +15 -0
- package/lib/types/client/genui-runtime/schema.d.ts +87 -0
- package/lib/types/client/genui-runtime/value-utils.d.ts +18 -0
- package/lib/types/client/guard.d.ts +144 -0
- package/lib/types/client/i18n/en.d.ts +307 -0
- package/lib/types/client/i18n/index.d.ts +44 -0
- package/lib/types/client/i18n/runtime.d.ts +64 -0
- package/lib/types/client/i18n/zh.d.ts +8 -0
- package/lib/types/client/index.d.ts +36 -0
- package/lib/types/client/inline.d.ts +5 -0
- package/lib/types/client/interaction-store.d.ts +48 -0
- package/lib/types/client/mermaid-core.d.ts +8 -0
- package/lib/types/client/mermaid-lazy.d.ts +9 -0
- package/lib/types/client/mermaid-safe.d.ts +52 -0
- package/lib/types/client/panel-command.d.ts +34 -0
- package/lib/types/client/panel-store.d.ts +94 -0
- package/lib/types/client/panel.d.ts +18 -0
- package/lib/types/client/parse-partial.d.ts +63 -0
- package/lib/types/client/primitive-adapter.d.ts +4 -0
- package/lib/types/client/primitive-labels.d.ts +18 -0
- package/lib/types/client/safe-math.d.ts +43 -0
- package/lib/types/client/scene3d-core.d.ts +21 -0
- package/lib/types/client/scene3d-lazy.d.ts +8 -0
- package/lib/types/client/session-resolver.d.ts +8 -0
- package/lib/types/client/source-fence.d.ts +29 -0
- package/lib/types/client/spec.d.ts +709 -0
- package/lib/types/client/standalone/asset-loader.d.ts +2 -0
- package/lib/types/client/standalone/bootstrap-types.d.ts +9 -0
- package/lib/types/client/standalone/katex-style.d.ts +1 -0
- package/lib/types/client/standalone/primitive-adapter.d.ts +54 -0
- package/lib/types/client/standalone/runtime.d.ts +2 -0
- package/lib/types/client/submission-registry.d.ts +51 -0
- package/lib/types/client/svg-fence.d.ts +2 -0
- package/lib/types/client/table-details.d.ts +20 -0
- package/lib/types/client/templates.d.ts +41 -0
- package/lib/types/client/toolview.d.ts +7 -0
- package/lib/types/client/walk-spec.d.ts +3 -0
- package/lib/types/index.d.ts +1 -0
- package/lib/types/plugin/chart-contract.d.ts +9 -0
- package/lib/types/plugin/fence-feedback.d.ts +151 -0
- package/lib/types/plugin/genui-diagnostic.d.ts +13 -0
- package/lib/types/plugin/index.d.ts +35 -0
- package/lib/types/plugin/inline-content-diagnostic.d.ts +8 -0
- package/lib/types/plugin/invariant.d.ts +15 -0
- package/lib/types/plugin/tool.d.ts +27 -0
- package/lib/types/shared/fence-repair.d.ts +78 -0
- package/lib/types/shared/fence-resolve.d.ts +39 -0
- package/package.json +249 -4
- package/src/client/EChartNode.tsx +466 -0
- package/src/client/ErrorBoundary.tsx +67 -0
- package/src/client/GenuiBlock.module.css +2221 -0
- package/src/client/GenuiBlock.tsx +235 -0
- package/src/client/PlotBlock.module.css +171 -0
- package/src/client/PlotBlock.tsx +492 -0
- package/src/client/TemplateDrawer.module.css +152 -0
- package/src/client/TemplateDrawer.tsx +147 -0
- package/src/client/achievement-store.ts +151 -0
- package/src/client/achievement-toast.tsx +71 -0
- package/src/client/achievements.ts +160 -0
- package/src/client/action-context.ts +32 -0
- package/src/client/artifact/ArtifactExport.module.css +64 -0
- package/src/client/artifact/ExportableGenuiBlock.tsx +100 -0
- package/src/client/artifact/create.ts +69 -0
- package/src/client/artifact/download.ts +42 -0
- package/src/client/artifact/html.ts +157 -0
- package/src/client/artifact/index.ts +15 -0
- package/src/client/artifact/json.ts +6 -0
- package/src/client/artifact/parse.ts +32 -0
- package/src/client/artifact/portability.ts +47 -0
- package/src/client/artifact/standalone-theme.ts +94 -0
- package/src/client/artifact/types.ts +44 -0
- package/src/client/asset-echarts-core.ts +39 -0
- package/src/client/asset-echarts.ts +27 -0
- package/src/client/asset-loader.ts +96 -0
- package/src/client/asset-mermaid.ts +13 -0
- package/src/client/asset-three.ts +12 -0
- package/src/client/blocks/advanced.tsx +537 -0
- package/src/client/blocks/basic.tsx +121 -0
- package/src/client/blocks/charts.tsx +999 -0
- package/src/client/blocks/checkbox.tsx +61 -0
- package/src/client/blocks/diagram/geometry.ts +151 -0
- package/src/client/blocks/diagram/index.tsx +293 -0
- package/src/client/blocks/diagram/layout.ts +202 -0
- package/src/client/blocks/diagram/theme.ts +127 -0
- package/src/client/blocks/forms.tsx +531 -0
- package/src/client/blocks/image.tsx +28 -0
- package/src/client/blocks/render-node.tsx +494 -0
- package/src/client/blocks/state.ts +65 -0
- package/src/client/blocks/svg.tsx +66 -0
- package/src/client/dom-fence.tsx +1123 -0
- package/src/client/echarts-engine.ts +9 -0
- package/src/client/echarts-lazy.ts +41 -0
- package/src/client/embed.ts +19 -0
- package/src/client/fence-render.tsx +266 -0
- package/src/client/gallery.ts +215 -0
- package/src/client/genui-runtime/diagnostics.ts +165 -0
- package/src/client/genui-runtime/index.ts +1 -0
- package/src/client/genui-runtime/limits.ts +54 -0
- package/src/client/genui-runtime/normalize.ts +329 -0
- package/src/client/genui-runtime/schema.ts +352 -0
- package/src/client/genui-runtime/value-utils.ts +67 -0
- package/src/client/guard.ts +1965 -0
- package/src/client/i18n/en.ts +335 -0
- package/src/client/i18n/index.ts +125 -0
- package/src/client/i18n/runtime.ts +130 -0
- package/src/client/i18n/zh.ts +330 -0
- package/src/client/index.tsx +228 -0
- package/src/client/inline.ts +106 -0
- package/src/client/interaction-store.ts +127 -0
- package/src/client/mermaid-core.ts +158 -0
- package/src/client/mermaid-lazy.ts +31 -0
- package/src/client/mermaid-safe.ts +122 -0
- package/src/client/panel-command.ts +138 -0
- package/src/client/panel-store.ts +471 -0
- package/src/client/panel.tsx +287 -0
- package/src/client/parse-partial.ts +170 -0
- package/src/client/primitive-adapter.ts +13 -0
- package/src/client/primitive-labels.ts +55 -0
- package/src/client/safe-math.ts +298 -0
- package/src/client/scene3d-core.ts +195 -0
- package/src/client/scene3d-lazy.ts +26 -0
- package/src/client/session-resolver.ts +33 -0
- package/src/client/source-fence.ts +70 -0
- package/src/client/spec.ts +896 -0
- package/src/client/standalone/asset-loader.ts +9 -0
- package/src/client/standalone/bootstrap-types.ts +11 -0
- package/src/client/standalone/katex-style.ts +1 -0
- package/src/client/standalone/primitive-adapter.tsx +94 -0
- package/src/client/standalone/runtime.tsx +27 -0
- package/src/client/submission-registry.ts +150 -0
- package/src/client/svg-fence.tsx +39 -0
- package/src/client/table-details.ts +151 -0
- package/src/client/templates.ts +322 -0
- package/src/client/toolview.tsx +67 -0
- package/src/client/walk-spec.ts +43 -0
- package/src/css-modules.d.ts +5 -0
- package/src/index.ts +9 -0
- package/src/plugin/chart-contract.ts +13 -0
- package/src/plugin/fence-feedback.ts +655 -0
- package/src/plugin/genui-diagnostic.ts +112 -0
- package/src/plugin/index.ts +224 -0
- package/src/plugin/inline-content-diagnostic.ts +178 -0
- package/src/plugin/invariant.ts +30 -0
- package/src/plugin/node-shims.d.ts +31 -0
- package/src/plugin/tool.ts +424 -0
- package/src/shared/fence-repair.ts +536 -0
- package/src/shared/fence-resolve.ts +80 -0
- package/tsconfig.json +35 -0
- package/tsdown.config.ts +275 -0
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `render_ui` tool: a model-facing channel that renders a GenUI spec as
|
|
3
|
+
* an interactive card in the conversation TOOL ROW (route A of the design
|
|
4
|
+
* doc). The ```dsh-ui fence channel renders inline in the reply; this tool
|
|
5
|
+
* renders in the tool row and rides the harness's result `meta` projection:
|
|
6
|
+
* `presentationMeta` stores the repaired spec, the browser toolview
|
|
7
|
+
* (`src/client/toolview.tsx`) reads it from the result node and renders.
|
|
8
|
+
*
|
|
9
|
+
* Zero runtime harness imports, deliberately: an external plugin's node half
|
|
10
|
+
* must not depend on the harness module graph at runtime (the profile
|
|
11
|
+
* resolves only the plugin package itself). The definition is therefore a
|
|
12
|
+
* plain `ToolDefinition` object — the exact shape `defineTool` returns — with
|
|
13
|
+
* the arguments schema authored as JSON Schema (the harness validates args
|
|
14
|
+
* and output with the same JSON Schema validator defineTool uses). Deep
|
|
15
|
+
* validation, deterministic repair, and resource limits live in the shared
|
|
16
|
+
* guard (`src/client/guard.ts`), which the schema deliberately stays loose
|
|
17
|
+
* enough to reach.
|
|
18
|
+
* @module @changfenhuang/dsh-genui/plugin/tool
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
|
|
22
|
+
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
|
|
23
|
+
import type { GenericCallView, GenericResultView, JsonSchemaNode, ToolDefinition } from '@deepseek-ai/dsh-tools'
|
|
24
|
+
import {
|
|
25
|
+
isRenderableProcess, processGenuiSpec,
|
|
26
|
+
} from '../client/guard.ts'
|
|
27
|
+
import type { GenuiProcessResult } from '../client/guard.ts'
|
|
28
|
+
import { completeFenceJson } from '../shared/fence-repair.ts'
|
|
29
|
+
import { droppedNodeFailure } from './genui-diagnostic.ts'
|
|
30
|
+
import { collectInlineContentWarnings } from './inline-content-diagnostic.ts'
|
|
31
|
+
import type { GenuiSpec } from '../client/spec.ts'
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Arguments schema: an open `spec` slot. The schema must NOT reject anything
|
|
35
|
+
* the guard could repair — the model's component trees are imperfect by
|
|
36
|
+
* nature, and the guard heals them; argument validation would only strand
|
|
37
|
+
* them. `additionalProperties: false` keeps the call shape honest.
|
|
38
|
+
*
|
|
39
|
+
* `spec` IS typed `object` on purpose: the guard can only repair plain
|
|
40
|
+
* records (a serialized JSON string, array, or scalar root is unusable), so
|
|
41
|
+
* argument validation rejecting non-objects loses nothing repairable — and
|
|
42
|
+
* it stops the model from double-encoding the tree as a string (observed
|
|
43
|
+
* twice in the wild), failing fast with a clear schema error instead.
|
|
44
|
+
*/
|
|
45
|
+
const RENDER_UI_PARAMETERS: Record<string, unknown> = {
|
|
46
|
+
type: 'object',
|
|
47
|
+
properties: {
|
|
48
|
+
spec: {
|
|
49
|
+
type: 'object',
|
|
50
|
+
description: [
|
|
51
|
+
'Render structured UI for the user (tool-row card). USE THIS whenever the answer contains ≥3 parallel points, a comparison, numbers/metrics, a step sequence, a flow, or a status/report — do NOT write those as markdown bullets or a markdown table.',
|
|
52
|
+
'Same white-listed vocabulary as the ```dsh-ui fence (see the GenUI system-prompt section). Pick the fence when the UI belongs in the message body; pick this tool when the deliverable is a self-contained card.',
|
|
53
|
+
'Deep-validated and repaired by the renderer. Pass the spec as a JSON OBJECT — never as a serialized JSON string (a string fails argument validation).',
|
|
54
|
+
].join(' '),
|
|
55
|
+
// Structural hints for the tool-call bridge. A bare `object` here was
|
|
56
|
+
// observed to make some bridge layers stringify the whole spec into an
|
|
57
|
+
// OpenAI-style `{ arguments: "<JSON>" }` wrapper (and to corrupt long
|
|
58
|
+
// specs mid-stream). Declaring the known top-level fields gives the
|
|
59
|
+
// bridge a concrete shape to serialize directly, while the schema stays
|
|
60
|
+
// deliberately open (unknown keys tolerated, `items` elements are free
|
|
61
|
+
// objects) so the guard — not the schema — remains the repair authority.
|
|
62
|
+
properties: {
|
|
63
|
+
title: { type: 'string', description: 'Short title shown as the card banner.' },
|
|
64
|
+
gap: { type: 'number', description: 'Vertical gap between root items in px.' },
|
|
65
|
+
panel: { type: 'boolean', description: 'Panel-only: renders into the session panel dock instead of the message flow.' },
|
|
66
|
+
items: {
|
|
67
|
+
type: 'array',
|
|
68
|
+
description: 'Root component list (white-listed vocabulary).',
|
|
69
|
+
items: { type: 'object' },
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
required: ['spec'],
|
|
75
|
+
additionalProperties: false,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The tool's canonical value is a short model-facing summary string. */
|
|
79
|
+
const RENDER_UI_OUTPUT_SCHEMA: JsonSchemaNode = { type: 'string', description: 'One-line human-readable render summary for the model.' }
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Read the `spec` argument defensively (presenters run on replayed args).
|
|
83
|
+
*
|
|
84
|
+
* The harness tool-call bridge has been observed to deliver arguments in
|
|
85
|
+
* shapes other than the authored `{ spec: <object> }`:
|
|
86
|
+
* - `{ spec: "<JSON string>" }` — spec serialized to text;
|
|
87
|
+
* - `{ arguments: "<JSON string>" }` / `{ arguments: <object> }` — a
|
|
88
|
+
* double-encoded wrapper from the SDK tool-call bridge (seen live in the
|
|
89
|
+
* web GUI: small specs arrived wrapped this way, large specs arrived with
|
|
90
|
+
* their JSON corrupted mid-stream);
|
|
91
|
+
* - a bare JSON string (double-encoded root).
|
|
92
|
+
* Each shape is unwrapped here so the guard can repair the actual tree.
|
|
93
|
+
* Corrupted JSON cannot be recovered (bytes were lost in transit): it yields
|
|
94
|
+
* `undefined` plus a diagnostic log line for the transport-layer bug.
|
|
95
|
+
*/
|
|
96
|
+
function specOf(args: unknown): unknown {
|
|
97
|
+
if (typeof args === 'string') {
|
|
98
|
+
return parseSpecJson(args, 'bare-string')
|
|
99
|
+
}
|
|
100
|
+
if (typeof args !== 'object' || args === null) return undefined
|
|
101
|
+
const record = args as Record<string, unknown>
|
|
102
|
+
if ('spec' in record) {
|
|
103
|
+
const s = record.spec
|
|
104
|
+
if (typeof s === 'string') return parseSpecJson(s, 'spec-string')
|
|
105
|
+
return unwrapSpec(s, 'spec')
|
|
106
|
+
}
|
|
107
|
+
if ('arguments' in record) {
|
|
108
|
+
const a = record.arguments
|
|
109
|
+
if (typeof a === 'string') return parseSpecJson(a, 'arguments-string')
|
|
110
|
+
if (typeof a === 'object' && a !== null) return unwrapSpec(a, 'arguments')
|
|
111
|
+
}
|
|
112
|
+
return undefined
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Peel nested `{ spec: ... }` wrapper layers. Observed bridge shapes nest the
|
|
117
|
+
* authored `spec` object one or more levels deep (e.g. the serialized text
|
|
118
|
+
* inside `{ arguments: "..." }` is itself `{ spec: { title, gap, items } }`),
|
|
119
|
+
* so unwrapping stops only at a value that carries no `spec` key.
|
|
120
|
+
*/
|
|
121
|
+
function unwrapSpec(value: unknown, shape: string): unknown {
|
|
122
|
+
if (typeof value === 'object' && value !== null) {
|
|
123
|
+
const record = value as Record<string, unknown>
|
|
124
|
+
if ('spec' in record) {
|
|
125
|
+
const s = record.spec
|
|
126
|
+
if (typeof s === 'string') return parseSpecJson(s, `${shape}/spec-string`)
|
|
127
|
+
return unwrapSpec(s, `${shape}/spec`)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return value
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Try to decode a serialized spec; log a diagnostic when it is broken. */
|
|
134
|
+
function parseSpecJson(raw: string, shape: string): unknown {
|
|
135
|
+
try {
|
|
136
|
+
return unwrapSpec(JSON.parse(raw), shape)
|
|
137
|
+
} catch (error: unknown) {
|
|
138
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
139
|
+
const pos = /position (\d+)/.exec(detail)?.[1] ?? '?'
|
|
140
|
+
console.error(`[genui-tool] spec wrapped as ${shape} but its JSON is broken (${raw.length} bytes, error at ${pos}); cannot recover — bytes lost in transit`)
|
|
141
|
+
return undefined
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Process a raw tool value once for all render-time decisions. */
|
|
146
|
+
function processRenderableValue(value: unknown): GenuiProcessResult {
|
|
147
|
+
return processGenuiSpec(value)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Wrap model-facing validation fields in the stable GenUI protocol envelope. */
|
|
151
|
+
function validationProtocol(lines: string[]): string {
|
|
152
|
+
return ['[genui-validation]', ...lines, 'reply_language=conversation'].join('\n')
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Render process diagnostics as stable model-facing warning fields. */
|
|
156
|
+
function formatProcessWarnings(processed: GenuiProcessResult): string[] {
|
|
157
|
+
return processed.warnings.map(warning => {
|
|
158
|
+
if (warning.kind === 'alias' && warning.canonical !== undefined) {
|
|
159
|
+
const separator = warning.path.lastIndexOf('.')
|
|
160
|
+
const canonicalPath = `${separator < 0 ? '' : warning.path.slice(0, separator + 1)}${warning.canonical}`
|
|
161
|
+
return warning.message.includes('ignored')
|
|
162
|
+
? `warning=alias_ignored path=${warning.path} canonical=${canonicalPath}`
|
|
163
|
+
: `warning=alias_normalized path=${warning.path} canonical=${canonicalPath}`
|
|
164
|
+
}
|
|
165
|
+
return `warning=process detail=${JSON.stringify(warning.message)}`
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 将行内字段的块级 Markdown 诊断写入稳定的验证协议。 */
|
|
170
|
+
function formatInlineContentWarnings(spec: GenuiSpec): string[] {
|
|
171
|
+
return collectInlineContentWarnings(spec).map(warning =>
|
|
172
|
+
`warning=block_markdown path=${warning.path} kind=${warning.kind} replacement=${warning.replacement}`)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Format chart-specific process errors while keeping other schema errors generic. */
|
|
176
|
+
function formatProcessFailure(processed: GenuiProcessResult): string | undefined {
|
|
177
|
+
const chartErrors = processed.errors.filter(error => /(?:variant is unsupported|kind must be bars, line, or donut|requires data or series|(?:data|series) is required for|(?:\.data|\.series)(?:\[\d+\])?(?:\.(?:data|label|value|color))? must|series is only supported for bars)/.test(error))
|
|
178
|
+
return chartErrors.length === 0 ? undefined : validationProtocol([
|
|
179
|
+
'status=invalid',
|
|
180
|
+
'error=invalid_chart_fields',
|
|
181
|
+
...chartErrors.map(error => `diagnostic=${JSON.stringify(error)}`),
|
|
182
|
+
'next=fix_and_revalidate',
|
|
183
|
+
])
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Tool-call title shared by the pending and completed presentations. */
|
|
187
|
+
function cardTitle(args: unknown): string | undefined {
|
|
188
|
+
const processed = processRenderableValue(specOf(args))
|
|
189
|
+
if (!isRenderableProcess(processed) || processed.spec === null) return undefined
|
|
190
|
+
return `渲染 UI:${processed.spec.title ?? '未命名'}`
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Build the render_ui tool definition. Registered by the plugin node half;
|
|
195
|
+
* `ctx.tools.register` consumes it exactly like a `defineTool` result.
|
|
196
|
+
*/
|
|
197
|
+
export function createRenderUiTool(): ToolDefinition {
|
|
198
|
+
return {
|
|
199
|
+
name: 'render_ui',
|
|
200
|
+
description:
|
|
201
|
+
'Render an interactive UI card in the conversation tool row by passing a GenUI spec (a white-listed component tree; the same vocabulary as the ```dsh-ui fence, see the system prompt). '
|
|
202
|
+
+ 'Use it when the user asks for a structured panel, dashboard, or form that belongs in the tool row rather than inline in the reply. '
|
|
203
|
+
+ 'The card is interactive client-side (tabs, buttons, inputs, switches); components carrying an "action" field send [genui-action] back to you when the user interacts, and you should re-render the updated UI.',
|
|
204
|
+
parameters: RENDER_UI_PARAMETERS,
|
|
205
|
+
output: {
|
|
206
|
+
schema: RENDER_UI_OUTPUT_SCHEMA,
|
|
207
|
+
render(_args: unknown, value: JsonValue): ContentBlock[] {
|
|
208
|
+
return [{ type: 'text', text: String(value) }]
|
|
209
|
+
},
|
|
210
|
+
presentationMeta(args: unknown): JsonValue {
|
|
211
|
+
// The browser toolview reads the repaired spec from result meta. The
|
|
212
|
+
// spec is JSON-safe by construction (only string/number/boolean/array
|
|
213
|
+
// fields after repair), so the widening cast is lossless.
|
|
214
|
+
const processed = processRenderableValue(specOf(args))
|
|
215
|
+
return (isRenderableProcess(processed) ? processed.spec : null) as unknown as JsonValue
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
async execute(args: unknown): Promise<JsonValue> {
|
|
219
|
+
const processed = processRenderableValue(specOf(args))
|
|
220
|
+
if (processed.spec === null) {
|
|
221
|
+
return ['[genui-render]', 'status=invalid', 'error=invalid_spec', 'required=items', 'next=fix_and_retry', 'reply_language=conversation'].join('\n')
|
|
222
|
+
}
|
|
223
|
+
if (!isRenderableProcess(processed)) {
|
|
224
|
+
throw new Error('render_ui spec invalid: ' + processed.errors.join('; '))
|
|
225
|
+
}
|
|
226
|
+
const spec = processed.spec
|
|
227
|
+
const warnings = formatProcessWarnings(processed)
|
|
228
|
+
return [
|
|
229
|
+
'[genui-render]',
|
|
230
|
+
'status=rendered',
|
|
231
|
+
...(spec.title === undefined ? [] : [`title=${JSON.stringify(spec.title)}`]),
|
|
232
|
+
`rendered=${processed.renderedCount}`,
|
|
233
|
+
'action_feedback=[genui-action]',
|
|
234
|
+
...warnings,
|
|
235
|
+
'reply_language=conversation',
|
|
236
|
+
].join('\n')
|
|
237
|
+
},
|
|
238
|
+
presentCall(args: unknown): GenericCallView | undefined {
|
|
239
|
+
const title = cardTitle(args)
|
|
240
|
+
return title === undefined ? undefined : { card: 'generic', title, kind: 'other' }
|
|
241
|
+
},
|
|
242
|
+
presentResult(args: unknown): GenericResultView | undefined {
|
|
243
|
+
const title = cardTitle(args)
|
|
244
|
+
return title === undefined ? undefined : { card: 'generic', title }
|
|
245
|
+
},
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* The `validate_dsh_ui` tool: a model-facing pre-flight check for the
|
|
251
|
+
* ```dsh-ui fence channel. The model calls it with the JSON text it is about
|
|
252
|
+
* to put inside a fence; it reports whether the body parses as a valid GenUI
|
|
253
|
+
* spec, and when it does not, WHERE it breaks and WHAT is likely wrong
|
|
254
|
+
* (bracket counts, common typo classes) so the model can fix and re-validate
|
|
255
|
+
* before emitting — turning "render a red banner after the fact" into
|
|
256
|
+
* "verify before you send". Purely local: no LLM, no network, no DOM.
|
|
257
|
+
*/
|
|
258
|
+
const VALIDATE_DESCRIPTION =
|
|
259
|
+
'Validate the JSON body of a ```dsh-ui fence BEFORE emitting it — use for non-trivial specs (≥3 nodes or containing a table); skip for trivial ones (≤2 nodes). '
|
|
260
|
+
+ 'Pass the exact JSON text you are about to put inside the fence as the "spec" argument (a string). '
|
|
261
|
+
+ 'Returns a [genui-validation] protocol block with status, diagnostics, next action, and reply_language=conversation. '
|
|
262
|
+
+ 'When invalid JSON is repairable, repaired_json contains the fixed body; emit it only with next=emit_repaired_fence. '
|
|
263
|
+
+ 'A warning=block_markdown requires the indicated replacement node and another validation call.'
|
|
264
|
+
|
|
265
|
+
const VALIDATE_PARAMETERS: Record<string, unknown> = {
|
|
266
|
+
type: 'object',
|
|
267
|
+
properties: {
|
|
268
|
+
spec: {
|
|
269
|
+
oneOf: [
|
|
270
|
+
{ type: 'string', description: 'The exact JSON text of the fence body.' },
|
|
271
|
+
{ type: 'object', description: 'The spec object (serialized before validation).' },
|
|
272
|
+
],
|
|
273
|
+
description: 'The dsh-ui fence body to validate: pass the JSON as a string for an exact check, or as the spec object.',
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
required: ['spec'],
|
|
277
|
+
additionalProperties: false,
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Read the fence-body text from the call args (string preferred, object serialized). */
|
|
281
|
+
function fenceTextOf(args: unknown): string | null {
|
|
282
|
+
if (typeof args === 'string') return args
|
|
283
|
+
if (typeof args !== 'object' || args === null) return null
|
|
284
|
+
const record = args as Record<string, unknown>
|
|
285
|
+
const s = 'spec' in record ? record.spec : 'arguments' in record ? record.arguments : undefined
|
|
286
|
+
if (typeof s === 'string') return s
|
|
287
|
+
if (typeof s === 'object' && s !== null) return JSON.stringify(s)
|
|
288
|
+
return null
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Count structural brackets outside string literals. */
|
|
292
|
+
function bracketCounts(raw: string): { '{': number; '}': number; '[': number; ']': number } {
|
|
293
|
+
const counts = { '{': 0, '}': 0, '[': 0, ']': 0 }
|
|
294
|
+
let inString = false
|
|
295
|
+
let escaped = false
|
|
296
|
+
for (let i = 0; i < raw.length; i++) {
|
|
297
|
+
const ch = raw[i]!
|
|
298
|
+
if (escaped) {
|
|
299
|
+
escaped = false
|
|
300
|
+
continue
|
|
301
|
+
}
|
|
302
|
+
if (inString) {
|
|
303
|
+
if (ch === '\\') escaped = true
|
|
304
|
+
else if (ch === '"') inString = false
|
|
305
|
+
continue
|
|
306
|
+
}
|
|
307
|
+
if (ch === '"') {
|
|
308
|
+
inString = true
|
|
309
|
+
continue
|
|
310
|
+
}
|
|
311
|
+
if (ch === '{') counts['{'] += 1
|
|
312
|
+
else if (ch === '}') counts['}'] += 1
|
|
313
|
+
else if (ch === '[') counts['['] += 1
|
|
314
|
+
else if (ch === ']') counts[']'] += 1
|
|
315
|
+
}
|
|
316
|
+
return counts
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Return stable structural count fields for an invalid JSON body. */
|
|
320
|
+
function bracketDiagnostic(raw: string): string[] {
|
|
321
|
+
const c = bracketCounts(raw)
|
|
322
|
+
const fields = [`braces_open=${c['{']}`, `braces_close=${c['}']}`, `brackets_open=${c['[']}`, `brackets_close=${c[']']}`]
|
|
323
|
+
if (c['{'] !== c['}']) {
|
|
324
|
+
const d = c['{'] - c['}']
|
|
325
|
+
fields.push(`brace_delta=${d}`, `brace_action=${d > 0 ? `add:${d}` : `remove:${-d}`}`)
|
|
326
|
+
}
|
|
327
|
+
if (c['['] !== c[']']) {
|
|
328
|
+
const d = c['['] - c[']']
|
|
329
|
+
fields.push(`bracket_delta=${d}`, `bracket_action=${d > 0 ? `add:${d}` : `remove:${-d}`}`)
|
|
330
|
+
}
|
|
331
|
+
return fields
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const COMMON_CAUSES = 'likely_causes=unbalanced_delimiters,unescaped_quote,trailing_comma,unterminated_string'
|
|
335
|
+
|
|
336
|
+
/** Build the validate_dsh_ui tool definition (registered alongside render_ui). */
|
|
337
|
+
export function createValidateDshUiTool(): ToolDefinition {
|
|
338
|
+
return {
|
|
339
|
+
name: 'validate_dsh_ui',
|
|
340
|
+
description: VALIDATE_DESCRIPTION,
|
|
341
|
+
parameters: VALIDATE_PARAMETERS,
|
|
342
|
+
output: {
|
|
343
|
+
schema: { type: 'string', description: 'Validation verdict for the model.' },
|
|
344
|
+
render(_args: unknown, value: JsonValue): ContentBlock[] {
|
|
345
|
+
return [{ type: 'text', text: String(value) }]
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
async execute(args: unknown): Promise<JsonValue> {
|
|
349
|
+
const raw = fenceTextOf(args)
|
|
350
|
+
if (raw === null || raw.trim() === '') {
|
|
351
|
+
return validationProtocol(['status=invalid', 'error=missing_spec', 'next=provide_spec'])
|
|
352
|
+
}
|
|
353
|
+
let parsed: unknown
|
|
354
|
+
try {
|
|
355
|
+
parsed = JSON.parse(raw)
|
|
356
|
+
} catch (error: unknown) {
|
|
357
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
358
|
+
// Pre-emission, both repair tiers are safe (no streaming half exists
|
|
359
|
+
// in a validation call). When the repair succeeds, hand the model the
|
|
360
|
+
// FIXED JSON instead of asking it to re-author the fix — re-writing
|
|
361
|
+
// the whole fence by hand is where the next typo comes from.
|
|
362
|
+
const repaired = completeFenceJson(raw)
|
|
363
|
+
if (repaired !== null) {
|
|
364
|
+
const repairedValue = JSON.parse(repaired.text) as unknown
|
|
365
|
+
const processed = processRenderableValue(repairedValue)
|
|
366
|
+
const chartFailure = formatProcessFailure(processed)
|
|
367
|
+
if (chartFailure !== undefined) return chartFailure
|
|
368
|
+
if (processed.spec !== null && processed.errors.length === 0) {
|
|
369
|
+
const warnings = formatProcessWarnings(processed)
|
|
370
|
+
const inlineWarnings = formatInlineContentWarnings(processed.spec)
|
|
371
|
+
return `${validationProtocol([
|
|
372
|
+
'status=invalid',
|
|
373
|
+
'error=invalid_json',
|
|
374
|
+
`detail=${JSON.stringify(detail)}`,
|
|
375
|
+
...bracketDiagnostic(raw),
|
|
376
|
+
...warnings,
|
|
377
|
+
...inlineWarnings,
|
|
378
|
+
'repair=applied',
|
|
379
|
+
`repair_count=${repaired.repairs}`,
|
|
380
|
+
inlineWarnings.length === 0 ? 'next=emit_repaired_fence' : 'next=fix_and_revalidate',
|
|
381
|
+
])}\nrepaired_json:\n\`\`\`\n${repaired.text}\n\`\`\``
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return validationProtocol([
|
|
385
|
+
'status=invalid',
|
|
386
|
+
'error=invalid_json',
|
|
387
|
+
`detail=${JSON.stringify(detail)}`,
|
|
388
|
+
...bracketDiagnostic(raw),
|
|
389
|
+
'repair=failed',
|
|
390
|
+
COMMON_CAUSES,
|
|
391
|
+
'next=fix_and_revalidate',
|
|
392
|
+
])
|
|
393
|
+
}
|
|
394
|
+
const processed = processRenderableValue(parsed)
|
|
395
|
+
const chartFailure = formatProcessFailure(processed)
|
|
396
|
+
if (chartFailure !== undefined) return chartFailure
|
|
397
|
+
if (processed.spec === null || processed.errors.length > 0) {
|
|
398
|
+
const dropped = droppedNodeFailure(processed, parsed)
|
|
399
|
+
return dropped === undefined
|
|
400
|
+
? validationProtocol([
|
|
401
|
+
'status=invalid',
|
|
402
|
+
'error=invalid_spec',
|
|
403
|
+
...(processed.errors.length === 0
|
|
404
|
+
? ['required=items', 'node_types=whitelist']
|
|
405
|
+
: processed.errors.map(error => `diagnostic=${JSON.stringify(error)}`)),
|
|
406
|
+
'next=fix_and_revalidate',
|
|
407
|
+
])
|
|
408
|
+
: validationProtocol(['status=invalid', ...dropped, 'next=fix_and_revalidate'])
|
|
409
|
+
}
|
|
410
|
+
const warnings = formatProcessWarnings(processed)
|
|
411
|
+
const inlineWarnings = formatInlineContentWarnings(processed.spec)
|
|
412
|
+
return validationProtocol([
|
|
413
|
+
'status=valid', `rendered=${processed.renderedCount}`, ...warnings, ...inlineWarnings,
|
|
414
|
+
inlineWarnings.length === 0 ? 'next=emit_fence' : 'next=fix_and_revalidate',
|
|
415
|
+
])
|
|
416
|
+
},
|
|
417
|
+
presentCall(): GenericCallView | undefined {
|
|
418
|
+
return { card: 'generic', title: '验证 dsh-ui 围栏', kind: 'other' }
|
|
419
|
+
},
|
|
420
|
+
presentResult(): GenericResultView | undefined {
|
|
421
|
+
return { card: 'generic', title: '验证 dsh-ui 围栏' }
|
|
422
|
+
},
|
|
423
|
+
}
|
|
424
|
+
}
|