dsh-motion-ui 0.5.6 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +76 -4
  3. package/VERIFICATION.md +109 -0
  4. package/client.js +3764 -22300
  5. package/index.js +107 -81
  6. package/lib/assets/echarts-core.js +47 -0
  7. package/lib/assets/echarts-full.js +78 -0
  8. package/lib/assets/katex-fonts/KaTeX_AMS-Regular.woff2 +0 -0
  9. package/lib/assets/katex-fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  10. package/lib/assets/katex-fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  11. package/lib/assets/katex-fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  12. package/lib/assets/katex-fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  13. package/lib/assets/katex-fonts/KaTeX_Main-Bold.woff2 +0 -0
  14. package/lib/assets/katex-fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  15. package/lib/assets/katex-fonts/KaTeX_Main-Italic.woff2 +0 -0
  16. package/lib/assets/katex-fonts/KaTeX_Main-Regular.woff2 +0 -0
  17. package/lib/assets/katex-fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  18. package/lib/assets/katex-fonts/KaTeX_Math-Italic.woff2 +0 -0
  19. package/lib/assets/katex-fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  20. package/lib/assets/katex-fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  21. package/lib/assets/katex-fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  22. package/lib/assets/katex-fonts/KaTeX_Script-Regular.woff2 +0 -0
  23. package/lib/assets/katex-fonts/KaTeX_Size1-Regular.woff2 +0 -0
  24. package/lib/assets/katex-fonts/KaTeX_Size2-Regular.woff2 +0 -0
  25. package/lib/assets/katex-fonts/KaTeX_Size3-Regular.woff2 +0 -0
  26. package/lib/assets/katex-fonts/KaTeX_Size4-Regular.woff2 +0 -0
  27. package/lib/assets/katex-fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  28. package/lib/assets/katex.css +1 -0
  29. package/lib/assets/mermaid.js +3644 -0
  30. package/lib/assets/standalone-runtime.css +1 -0
  31. package/lib/assets/standalone-runtime.js +328 -0
  32. package/lib/assets/three.js +3842 -0
  33. package/lib/assets/visual.css +1 -0
  34. package/lib/assets/visual.js +414 -0
  35. package/lib/authoring-guide.js +2 -2
  36. package/lib/build-info.js +1 -1
  37. package/lib/canvas-system.js +3 -3
  38. package/lib/catalog.js +94 -92
  39. package/lib/components.js +9 -4
  40. package/lib/delivery.js +18 -0
  41. package/lib/diagnostics-route.js +6 -0
  42. package/lib/document-update.js +27 -0
  43. package/lib/export-runtime-bundle.js +1 -1
  44. package/lib/fence-feedback.js +61 -0
  45. package/lib/fence-route.js +14 -0
  46. package/lib/fences.js +9 -0
  47. package/lib/freeform.js +1 -1
  48. package/lib/inspection.js +3 -2
  49. package/lib/links.js +13 -0
  50. package/lib/normalize-authoring.js +46 -1
  51. package/lib/normalize-visual.js +36 -0
  52. package/lib/presentation.js +1 -1
  53. package/lib/protocol.js +348 -320
  54. package/lib/scene-library.js +13 -0
  55. package/lib/store.js +17 -2
  56. package/lib/stream.js +12 -0
  57. package/lib/text-document.js +25 -0
  58. package/lib/text-guide.js +13 -0
  59. package/lib/third-party/bundled/@braintree_sanitize-url-LICENSE +21 -0
  60. package/lib/third-party/bundled/@iconify_utils-license.txt +21 -0
  61. package/lib/third-party/bundled/@mermaid-js_parser-LICENSE +21 -0
  62. package/lib/third-party/bundled/@upsetjs_venn.js-LICENSE +22 -0
  63. package/lib/third-party/bundled/cose-base-LICENSE +21 -0
  64. package/lib/third-party/bundled/cytoscape-LICENSE +19 -0
  65. package/lib/third-party/bundled/cytoscape-cose-bilkent-LICENSE +21 -0
  66. package/lib/third-party/bundled/cytoscape-fcose-LICENSE +19 -0
  67. package/lib/third-party/bundled/cytoscape-license-update.mjs +32 -0
  68. package/lib/third-party/bundled/d3-LICENSE +13 -0
  69. package/lib/third-party/bundled/d3-array-LICENSE +27 -0
  70. package/lib/third-party/bundled/d3-axis-LICENSE +13 -0
  71. package/lib/third-party/bundled/d3-brush-LICENSE +13 -0
  72. package/lib/third-party/bundled/d3-chord-LICENSE +13 -0
  73. package/lib/third-party/bundled/d3-color-LICENSE +13 -0
  74. package/lib/third-party/bundled/d3-contour-LICENSE +13 -0
  75. package/lib/third-party/bundled/d3-delaunay-LICENSE +14 -0
  76. package/lib/third-party/bundled/d3-dispatch-LICENSE +13 -0
  77. package/lib/third-party/bundled/d3-drag-LICENSE +13 -0
  78. package/lib/third-party/bundled/d3-dsv-LICENSE +13 -0
  79. package/lib/third-party/bundled/d3-ease-LICENSE +28 -0
  80. package/lib/third-party/bundled/d3-fetch-LICENSE +13 -0
  81. package/lib/third-party/bundled/d3-force-LICENSE +13 -0
  82. package/lib/third-party/bundled/d3-format-LICENSE +13 -0
  83. package/lib/third-party/bundled/d3-geo-LICENSE +34 -0
  84. package/lib/third-party/bundled/d3-hierarchy-LICENSE +13 -0
  85. package/lib/third-party/bundled/d3-interpolate-LICENSE +13 -0
  86. package/lib/third-party/bundled/d3-path-LICENSE +27 -0
  87. package/lib/third-party/bundled/d3-polygon-LICENSE +13 -0
  88. package/lib/third-party/bundled/d3-quadtree-LICENSE +13 -0
  89. package/lib/third-party/bundled/d3-random-LICENSE +13 -0
  90. package/lib/third-party/bundled/d3-sankey-LICENSE +27 -0
  91. package/lib/third-party/bundled/d3-scale-LICENSE +13 -0
  92. package/lib/third-party/bundled/d3-scale-chromatic-LICENSE +28 -0
  93. package/lib/third-party/bundled/d3-selection-LICENSE +13 -0
  94. package/lib/third-party/bundled/d3-shape-LICENSE +13 -0
  95. package/lib/third-party/bundled/d3-time-LICENSE +13 -0
  96. package/lib/third-party/bundled/d3-time-format-LICENSE +13 -0
  97. package/lib/third-party/bundled/d3-timer-LICENSE +13 -0
  98. package/lib/third-party/bundled/d3-transition-LICENSE +13 -0
  99. package/lib/third-party/bundled/d3-zoom-LICENSE +13 -0
  100. package/lib/third-party/bundled/dagre-d3-es-LICENSE.md +23 -0
  101. package/lib/third-party/bundled/dayjs-LICENSE +21 -0
  102. package/lib/third-party/bundled/delaunator-LICENSE +15 -0
  103. package/lib/third-party/bundled/dompurify-LICENSE +202 -0
  104. package/lib/third-party/bundled/dompurify-LICENSE-MPL +373 -0
  105. package/lib/third-party/bundled/echarts-LICENSE +222 -0
  106. package/lib/third-party/bundled/echarts-NOTICE +5 -0
  107. package/lib/third-party/bundled/es-toolkit-LICENSE +21 -0
  108. package/lib/third-party/bundled/es-toolkit-NOTICE +39 -0
  109. package/lib/third-party/bundled/internmap-LICENSE +13 -0
  110. package/lib/third-party/bundled/katex-LICENSE +21 -0
  111. package/lib/third-party/bundled/khroma-license +21 -0
  112. package/lib/third-party/bundled/layout-base-LICENSE +21 -0
  113. package/lib/third-party/bundled/lodash-es-LICENSE +47 -0
  114. package/lib/third-party/bundled/marked-LICENSE.md +44 -0
  115. package/lib/third-party/bundled/mermaid-LICENSE +21 -0
  116. package/lib/third-party/bundled/react-LICENSE +21 -0
  117. package/lib/third-party/bundled/react-dom-LICENSE +21 -0
  118. package/lib/third-party/bundled/robust-predicates-LICENSE +24 -0
  119. package/lib/third-party/bundled/roughjs-LICENSE +21 -0
  120. package/lib/third-party/bundled/scheduler-LICENSE +21 -0
  121. package/lib/third-party/bundled/stylis-LICENSE +21 -0
  122. package/lib/third-party/bundled/three-LICENSE +21 -0
  123. package/lib/third-party/bundled/ts-dedent-LICENSE +21 -0
  124. package/lib/third-party/bundled/tslib-LICENSE.txt +12 -0
  125. package/lib/third-party/bundled/uuid-LICENSE.md +9 -0
  126. package/lib/third-party/bundled/zrender-LICENSE +29 -0
  127. package/lib/third-party/dsh-genui-LICENSE.txt +21 -0
  128. package/lib/third-party/dsh-genui-NOTICE.md +26 -0
  129. package/lib/third-party/echarts-LICENSE.txt +222 -0
  130. package/lib/third-party/echarts-NOTICE.txt +5 -0
  131. package/lib/third-party/katex-LICENSE.txt +21 -0
  132. package/lib/third-party/mermaid-LICENSE.txt +21 -0
  133. package/lib/third-party/three-LICENSE.txt +21 -0
  134. package/lib/tool-schema.js +17 -6
  135. package/lib/typography.js +16 -0
  136. package/lib/ui-intent.js +15 -14
  137. package/lib/ui-skill.js +53 -47
  138. package/lib/visual-assets.js +7 -0
  139. package/lib/visual-defaults.js +2 -0
  140. package/lib/visual-guard.js +2 -0
  141. package/lib/visual-styles.js +30 -0
  142. package/lib/visual.js +40 -0
  143. package/package.json +92 -77
  144. package/skills/intelligent-ui/SKILL.md +103 -96
@@ -0,0 +1,61 @@
1
+ import {randomUUID,createHash} from 'node:crypto';
2
+ import {extractUiFences} from './fences.js';
3
+ import {resolveSourceFence} from './delivery.js';
4
+ const fingerprint=raw=>createHash('sha256').update(raw).digest('hex').slice(0,16);
5
+ const textOf=content=>Array.isArray(content)?content.filter(x=>x.type==='text').map(x=>x.text??'').join('\n'):'';
6
+ export function isUiDeliveryAnnouncement(text,request=''){
7
+ const value=text.trim();
8
+ // Only short visible delivery announcements, never private reasoning or
9
+ // substantive answers, source fences, lists, or questions about UI concepts.
10
+ if(!value||value.length>240||/```|(?:^|\n)\s*(?:[-*]|\d+[.)、])\s*/.test(value))return false;
11
+ if(/(?:什么是|何时|什么时候|为什么|为何|区别|能做什么|有哪些能力).{0,20}(?:UI|界面|组件|流程图|图表|可视化)/i.test(request))return false;
12
+ if(!/(?:UI\b|界面|组件|流程图|图表|可视化|(?:一张|这张)图|render_(?:text|ui|canvas))/i.test(value))return false;
13
+ return /(?:现在|接下来|马上|我会|我来|我将|准备|这就).{0,40}(?:补上|生成|展示|绘制|画|做|调用|制作|呈现)|(?:用|通过).{0,12}(?:流程图|图表|可视化|界面).{0,16}(?:看|展示|呈现|说明|讲|清楚|直观)|我把.{0,70}(?:图上|图中).{0,20}(?:看|展示|呈现)|I(?:'ll| will| am going to).{0,40}(?:render|create|draw|show)/i.test(value);
14
+ }
15
+ export function registerFenceFeedback(ctx,enabled=()=>true){
16
+ if(typeof ctx.on!=='function')return {available:false};
17
+ const sessions=new Map();
18
+ const fresh=turn=>({turn,blocks:new Map(),corrected:new Set(),notices:new Set(),calls:new Map(),toolFailures:new Map(),seenToolCall:false,silentRequested:false,request:'',delivered:false,lastText:'',count:0});
19
+ function observe(session,event){
20
+ const id=String(session.id);if(event.type==='turn/start'){sessions.set(id,fresh(event.data.turn));return}
21
+ let state=sessions.get(id);if(!state){state=fresh(event.data?.turn);sessions.set(id,state)}
22
+ if(event.type==='assistant/message'){state.lastText=textOf(event.data.message?.content).slice(0,262144);state.blocks.set(event.data.step??0,state.lastText)}
23
+ if(event.type==='tool/call')state.seenToolCall=true;
24
+ if(event.type==='user/message'&&event.data.source?.kind==='user'){state.request=textOf(event.data.content).slice(0,8192);state.silentRequested=/(?:不用|不必|无需|不要)回复|do not (?:respond|reply)|no (?:response|reply) (?:needed|required)/i.test(state.request)}
25
+ if(event.type==='tool/call'&&['render_text','render_ui','render_canvas','update_ui','patch_ui'].includes(event.data.name))state.calls.set(event.data.callId,event.data.name);
26
+ if(event.type==='tool/result'){
27
+ const message=event.data.message,name=state.calls.get(message?.toolCallId);
28
+ if(name){if(message.isError){const diagnostic=name+': '+textOf(message.content).slice(0,1200);state.toolFailures.set(fingerprint(diagnostic),diagnostic)}else state.delivered=true}
29
+ }
30
+ if(event.type==='user/message'&&(event.data.source?.kind==='plugin:motion-ui'||event.data.source?.plugin==='motion-ui')&&!state.notices.has(event.data.id)){
31
+ state.notices.add(event.data.id);state.count++;
32
+ for(const match of textOf(event.data.content).matchAll(/\[motion-repair:([a-f0-9]{16})\]/g))state.corrected.add(match[1]);
33
+ }
34
+ }
35
+ const restore=session=>{if(!sessions.has(String(session.id)))for(const event of session.snapshotEvents?.()??[])observe(session,event)};
36
+ ctx.on('session/event',(session,event)=>{restore(session);observe(session,event)});
37
+ ctx.on('session/disposed',session=>sessions.delete(String(session.id)));
38
+ ctx.on('agent/turn-stopping',({agent,turn,signal})=>{
39
+ if(!enabled()||signal?.aborted||agent.session.header?.parentSession!==undefined||typeof agent.steer!=='function')return;
40
+ restore(agent.session);const state=sessions.get(String(agent.session.id));if(!state||state.turn!==turn||state.count>=2)return;
41
+ const failures=[];
42
+ for(const text of state.blocks.values())for(const fence of extractUiFences(text)){
43
+ const key=fingerprint(fence.raw);if(state.corrected.has(key))continue;
44
+ const result=resolveSourceFence(fence.raw,{svg:fence.language==='svg'});if(result.marker||result.valid&&result.complete)continue;
45
+ failures.push({key,diagnostic:result.diagnostics?.map(x=>x.message).join('; ').slice(0,1200)});
46
+ }
47
+ // A failed UI tool followed by a reasoning-only stop is unfinished work.
48
+ // Do not infer intent from private reasoning or interrupt useful text answers.
49
+ if(!state.delivered&&!state.lastText.trim())for(const[key,diagnostic]of state.toolFailures)if(!state.corrected.has(key))failures.push({key,diagnostic,tool:true});
50
+ const emptyKey=fingerprint('empty-visible-turn');
51
+ if(!state.silentRequested&&!state.seenToolCall&&state.blocks.size&&[...state.blocks.values()].every(text=>!text.trim())&&!state.corrected.has(emptyKey))failures.push({key:emptyKey,empty:true,diagnostic:'The turn is ending with no visible answer and no tool call. No requested work has been delivered.'});
52
+ const visible=[...state.blocks.values()].join('\n').trim(),promiseKey=fingerprint('announcement:'+visible);
53
+ if(!state.silentRequested&&!state.delivered&&isUiDeliveryAnnouncement(visible,state.request)&&!state.corrected.has(promiseKey))failures.push({key:promiseKey,empty:true,diagnostic:'The visible answer only announces a UI, but no UI was delivered. Complete the promised work instead of ending with a delivery announcement.'});
54
+ if(!failures.length)return;
55
+ const chosen=failures.slice(0,4);state.count++;chosen.forEach(f=>state.corrected.add(f.key));
56
+ const text=chosen.map(f=>'[motion-repair:'+f.key+'] '+f.diagnostic).join('\n')+'\n'+(chosen.some(f=>f.empty)?'Complete the user task with an actual visible answer. If a UI helps, submit it through the appropriate rendering tool or a complete source fence; otherwise answer in plain text. Do not finish with only a plan or promise. This notice does not require a UI, limit reasoning or stop generation.':'Motion UI delivery is incomplete. '+(chosen.some(f=>f.tool)?'A rendering tool failed and your last response contained no visible answer. Correct the actual failed tool arguments and submit a complete UI, or provide a useful text fallback. A promise to render later is not delivery. ':'Correct only the failed source fence(s), retaining their intended content. ')+'Do not repeat successful UIs or call render_ui for an already rendered fence. Use ui_catalog or validate_ui for exact syntax. If the same defect cannot be corrected, give a useful text fallback. This notice does not limit your reasoning or stop generation.');
57
+ const source=(agent.session.header?.version??4)>=4?{kind:'plugin:motion-ui',form:'notice',summary:'Motion UI delivery repair'}:{kind:'plugin',plugin:'motion-ui',form:'notice',summary:'Motion UI delivery repair'};
58
+ const id=randomUUID();state.notices.add(id);
59
+ try{agent.steer({id,role:'user',content:[{type:'text',text}],source})}catch(e){ctx.logger?.warn?.('Motion UI correction could not be queued: '+e.message)}
60
+ });return {available:true};
61
+ }
@@ -0,0 +1,14 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {validateDocument} from './protocol.js';
3
+ export function fenceRoute(store){return async request=>{
4
+ try{
5
+ if(request.method!=='POST')return Response.json({error:'POST required'},{status:405});
6
+ if(!request.headers.get('content-type')?.startsWith('application/json'))return Response.json({error:'JSON required'},{status:415});
7
+ const body=await request.text();if(Buffer.byteLength(body)>150000)return Response.json({error:'Fence too large'},{status:413});
8
+ const input=JSON.parse(body);if(!input||typeof input.sessionId!=='string'||!input.sessionId.trim()||input.sessionId.length>256||typeof input.source!=='string'||!/^[\w:.-]{1,128}$/.test(input.source)||Object.keys(input).some(k=>!['sessionId','source','document'].includes(k)))throw Error('Invalid fence identity');
9
+ const document=validateDocument(input.document),hash=createHash('sha256').update(input.sessionId+'\0'+input.source+'\0'+JSON.stringify(document)).digest('hex');
10
+ const id=hash.slice(0,8)+'-'+hash.slice(8,12)+'-4'+hash.slice(13,16)+'-a'+hash.slice(17,20)+'-'+hash.slice(20,32);
11
+ let record;try{record=await store.owned(id,input.sessionId)}catch(e){if(e.status!==404)throw e;record=await store.create(document,{documentId:id,sessionId:input.sessionId,callId:'fence:'+input.source})}
12
+ return Response.json(record,{headers:{'Cache-Control':'no-store'}});
13
+ }catch(e){return Response.json({error:e.message},{status:e.status??400})}
14
+ }}
package/lib/fences.js ADDED
@@ -0,0 +1,9 @@
1
+ // Only assistant text projection supplies these candidates. Never infer UI
2
+ // ownership from an arbitrary JSON code block or a user/tool message.
3
+ export function extractUiFences(text){
4
+ if(typeof text!=='string'||new TextEncoder().encode(text).length>262144)return[];
5
+ const lines=text.split('\n'),out=[];let fence=null;
6
+ for(const line of lines){if(!fence){const m=line.match(/^ {0,3}(`{3,}|~{3,})(dsh-ui|motion-ui|svg)\s*$/i);if(m)fence={delimiter:m[1][0],count:m[1].length,language:m[2].toLowerCase(),lines:[]};continue}
7
+ if(new RegExp('^ {0,3}'+(fence.delimiter==='`'?'`':'~')+'{'+fence.count+',}\\s*$').test(line)){out.push({language:fence.language,raw:fence.lines.join('\n'),complete:true});fence=null;if(out.length>=24)break}else fence.lines.push(line);
8
+ }if(fence&&out.length<24)out.push({language:fence.language,raw:fence.lines.join('\n'),complete:false});return out;
9
+ }
package/lib/freeform.js CHANGED
@@ -7,7 +7,7 @@ export function canvasDocument({title,fallback,html,css,script,height,state,data
7
7
  return validateDocument({version:1,title,fallback,...values,nodes:[{id:'canvas',type:'sandbox',title,fallback,html,...(css===undefined?{}:{css}),...(script===undefined?{}:{script}),...(height===undefined?{}:{height}),stateKeys:Object.keys(values.state),dataKeys:Object.keys(values.data),derivedKeys:Object.keys(values.derived)}]});
8
8
  }
9
9
  export const FREE_UI_CONTRACT=AUTHORING_GUIDE+`\nYou have a freeform visual UI surface (static or interactive) in the conversation. Choose the graphics, structure, typography, colors, layout and animation yourself to suit the user's intent. No design template, card composition, accent palette, example UI or dashboard convention is prescribed. Use ordinary text when a UI would not help.
10
- Call render_canvas({title,fallback,html,css?,script?,height?,state?,data?,derived?}) directly, not inside PTC/run_code. The UI is displayed after the whole assistant turn ends, then parameter restoration enables controls; do not claim it is already visible merely because the tool succeeded. Source field order does not affect validation. Optional host .ui-* primitives exist but no composition is required. html is a body fragment supporting HTML/SVG; put all CSS in css and JavaScript in script, use addEventListener rather than HTML event attributes. Each source field max 49152 characters, whole document max128KiB, height160..1000. Code runs only after commit and parameter restoration. No external resources, imports, eval or host APIs; the isolated frame is not a CPU/memory hard limit. The existing frame is updated with inspect_ui/patch_ui, never arbitrary host access.
10
+ Call render_canvas({title,fallback,html,css?,script?,height?,state?,data?,derived?}) directly, not inside PTC/run_code. A stable inert HTML/SVG preview appears progressively during generation; after the whole assistant turn ends, parameter restoration enables controls. Prefer title/fallback/css before html for early styled previews. Do not claim interaction is active merely because the tool succeeded. Source field order does not affect validation. Optional host .ui-* primitives exist but no composition is required. html is a body fragment supporting HTML/SVG; put all CSS in css and JavaScript in script, use addEventListener rather than HTML event attributes. Each source field max 49152 characters, whole document max128KiB, height160..1000. Code runs only after commit and parameter restoration. No external resources, imports, eval or host APIs; the isolated frame is not a CPU/memory hard limit. The existing frame is updated with inspect_ui/patch_ui, never arbitrary host access.
11
11
  The user-facing content and all controls may be authored inside your canvas. State important to the user belongs in state, e.g. {speed:{type:"number",default:1,min:0.5,max:3,step:0.5},running:{type:"boolean",default:false}}. Strings require type:"string",default; options:[string,...] is optional. Structured lists/objects use type:"json",default:[]/{} (16KiB per value). Bind custom controls through DSHUI.setState({speed:2}); use DSHUI.subscribe(snapshot=>...) to draw snapshot.state/data/derived. Do not write state from each animation frame or echo subscribe updates back into setState. State updates are validated and persisted. Reload may reset transient animation phase.
12
12
  Prefer DSHUI.animate(({time,delta,reducedMotion,visible})=>...) for motion; seconds, delta capped0.05, returns unsubscribe. Integrate delta only while running; reducedMotion needs a meaningful static view. Stop/replacement disposes the frame. DSHUI.formatNumber(value, decimals=2) formats finite numbers with 0..6 decimal places and comma grouping, exactly matching native metrics and fallback; use it for shared readouts instead of mixing toFixed rounding. Theme is in snapshot.theme and CSS variables --canvas-bg/soft/ink/muted/line/accent. Use readable text and named keyboard-operable controls, adapt to narrow and wide widths; ensure information remains available in a useful fallback. Be truthful about data, assumptions and simulation accuracy.
13
13
  If native controls or mixed component layouts would help, render_ui and ui_catalog remain available; query the catalog for their exact contract when needed. They are optional, not the default layout.
package/lib/inspection.js CHANGED
@@ -3,11 +3,12 @@ export function inspectRecord(record,state,derived,audits,{detail='summary',node
3
3
  if(!['summary','nodes','full'].includes(detail))throw new Error('DSH UI: invalid inspection detail');
4
4
  const flat=list=>list.flatMap(n=>[n,...flat(n.children??[])]),nodes=flat(record.document.nodes);
5
5
  if(!Array.isArray(nodeIds)||nodeIds.length>16||nodeIds.some(id=>typeof id!=='string'||!nodes.some(n=>n.id===id)))throw new Error('DSH UI: nodeIds requires up to 16 existing IDs');
6
- if(detail==='nodes'&&!nodeIds.length)throw new Error('DSH UI: choose nodeIds for nodes inspection');
6
+ const inferred=detail==='nodes'&&!nodeIds.length;
7
+ if(inferred)nodeIds=nodes.slice(0,16).map(n=>n.id);
7
8
  const bounded=value=>Buffer.byteLength(JSON.stringify(value??{}))<=8192?value:{omitted:true,reason:'Value exceeds 8KiB summary budget; request full inspection.',keys:Object.keys(value??{})};
8
9
  const result={documentId:record.documentId,documentRevision:record.documentRevision??0,title:record.document.title,state:detail==='full'?state:bounded(state),derived:detail==='full'?derived:bounded(derived),audits,detail};
9
10
  if(detail==='full')result.document=record.document;
10
- else if(detail==='nodes')result.nodes=nodes.filter(n=>nodeIds.includes(n.id));
11
+ else if(detail==='nodes'){result.nodes=nodes.filter(n=>nodeIds.includes(n.id));if(inferred&&nodes.length>16)result.selection={returned:16,total:nodes.length,remainingIds:nodes.slice(16).map(n=>n.id),hint:'Pass nodeIds to inspect additional nodes.'};}
11
12
  else result.nodes=nodes.map(n=>({id:n.id,type:n.type,...Object.fromEntries(['title','label','text','bind'].filter(k=>typeof n[k]==='string').map(k=>[k,n[k].slice(0,160)])),...(n.type==='sandbox'?{sourceCharacters:{html:n.html.length,css:n.css?.length??0,script:n.script?.length??0}}:{})}));
12
13
  return result;
13
14
  }
package/lib/links.js ADDED
@@ -0,0 +1,13 @@
1
+ export function validateLink(node){
2
+ const fail=message=>{throw Error('DSH UI: '+message)};
3
+ if([node.href,node.path,node.action].filter(v=>v!==undefined).length!==1)fail(`node.${node.id}: choose exactly one href (http/https), path (file), or action (Agent follow-up)`);
4
+ if(node.variant!==undefined&&!['primary','secondary','text'].includes(node.variant))fail('link/button variant must be primary/secondary/text');
5
+ if(node.href!==undefined){
6
+ if(typeof node.href!=='string'||node.href.length>8192||/[\u0000-\u0020\u007f]/.test(node.href)||!/^https?:\/\//i.test(node.href))fail('href must be an absolute http/https URL; encode spaces');
7
+ let url;try{url=new URL(node.href)}catch{fail('invalid href URL')}
8
+ if(!url.hostname||url.username||url.password)fail('href must have a host and must not contain credentials');
9
+ }
10
+ if(node.path!==undefined){
11
+ if(typeof node.path!=='string'||!node.path.trim()||node.path.length>8192||/[\u0000-\u001f\u007f]/.test(node.path)||/^\s*(?:[a-z][a-z\d+.-]*:|[\\/]{2})/i.test(node.path)&&!/^\s*[a-z]:[\\/]/i.test(node.path))fail('path must be a local file path, not a URL, network path or command');
12
+ }
13
+ }
@@ -1,9 +1,11 @@
1
1
  // Lossless transport repairs only at protocol-typed positions. Never traverse
2
2
  // arbitrary data/state payloads or rewrite labels, HTML, CSS or JavaScript.
3
3
  const object = v => v !== null && typeof v === 'object' && !Array.isArray(v);
4
+ import {visualDocument,VISUAL_TYPES} from './visual.js';
5
+ import {COMPONENTS} from './components.js';
4
6
  const own = (v,k) => Object.hasOwn(v,k);
5
7
  const singleItem = v => object(v) && Object.keys(v).length === 1 && own(v,'item');
6
- const array = v => singleItem(v) && Array.isArray(v.item) ? v.item : v;
8
+ const array = v => {let candidate=v;for(let i=0;i<8&&singleItem(candidate);i++)candidate=candidate.item;return Array.isArray(candidate)?candidate:v};
7
9
  const numericOps = new Set(['add','sub','mul','div','min','max','round','abs','lt','lte','gt','gte']);
8
10
  function number(v) {
9
11
  if (typeof v !== 'string' || !/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(v.trim())) return v;
@@ -23,6 +25,8 @@ function expression(e, numeric = false, logical = false) {
23
25
  return e;
24
26
  }
25
27
  export function normalizeAuthoring(doc) {
28
+ if (Array.isArray(doc)) doc=visualDocument(doc);
29
+ if (object(doc)&&!own(doc,'nodes')&&(own(doc,'items')||typeof doc.type==='string')) doc=visualDocument(doc);
26
30
  if (!object(doc)) return doc;
27
31
  if (own(doc,'version')) doc.version = number(doc.version);
28
32
  if (object(doc.state)) for (const k of Object.keys(doc.state)) {
@@ -50,6 +54,39 @@ export function normalizeAuthoring(doc) {
50
54
  if (!Array.isArray(list)) return list;
51
55
  for (const node of list) {
52
56
  if (!object(node)) continue;
57
+ if(['text','heading','callout'].includes(node.type)&&own(node,'content')){
58
+ // Collapse aliases only when no conflicting content would be lost.
59
+ if(!own(node,'text')){node.text=node.content;delete node.content}
60
+ else if(node.text===node.content)delete node.content;
61
+ }
62
+ if(['text','heading','callout'].includes(node.type)&&typeof node.text==='string'){
63
+ const spans=array(node.spans);
64
+ if(Array.isArray(spans)&&spans.every(s=>object(s)&&typeof s.text==='string')&&spans.map(s=>s.text).join('')===node.text)delete node.text;
65
+ }
66
+ if(node.type==='table'&&own(node,'types')){
67
+ const columns=array(node.columns),rows=array(node.rows),types=array(node.types);
68
+ const allowed=['id','type','label','columns','rows','types'];
69
+ if(Object.keys(node).every(k=>allowed.includes(k))&&Array.isArray(columns)&&columns.length&&columns.every(c=>object(c)&&typeof c.key==='string'&&typeof c.label==='string'&&Object.keys(c).every(k=>['key','label','unit'].includes(k)))&&new Set(columns.map(c=>c.key)).size===columns.length&&Array.isArray(rows)&&rows.every(object)&&Array.isArray(types)&&types.length===columns.length&&types.every(t=>['text','num','delta','bar','badge'].includes(t))){
70
+ const spec={...(node.label?{title:node.label}:{}),items:[{type:'table',columns:columns.map(c=>c.label+(c.unit?` (${c.unit})`:'')),rows:rows.map(row=>columns.map(c=>row[c.key]??null)),types}]},id=node.id;
71
+ for(const k of Object.keys(node))delete node[k];
72
+ Object.assign(node,{...(id!==undefined?{id}:{}),type:'visual',spec});
73
+ }
74
+ }
75
+ // Extended-only nodes have an unambiguous native visual wrapper. Keep
76
+ // the author's ID so mixed documents need no extra repair round.
77
+ if(typeof node.id==='string'&&VISUAL_TYPES.includes(node.type)&&!own(COMPONENTS,node.type)){
78
+ const spec={items:[{...node}]},id=node.id;
79
+ for(const k of Object.keys(node))delete node[k];
80
+ Object.assign(node,{id,type:'visual',spec});
81
+ }
82
+ if(node.type==='table'&&Array.isArray(node.columns)&&node.columns.length&&Array.isArray(node.rows)&&node.rows.every(Array.isArray)&&node.columns.every(c=>object(c)&&Number.isInteger(c.key)&&c.key>=0)&&new Set(node.columns.map(c=>c.key)).size===node.columns.length){
83
+ const columns=node.columns.map(c=>({...c,key:'col_'+c.key}));
84
+ node.rows=node.rows.map(row=>Object.fromEntries(node.columns.map(c=>['col_'+c.key,row[c.key]??null])));node.columns=columns;
85
+ }
86
+ if(node.type==='visual'&&typeof node.id==='string'){
87
+ node.stateKey??='visual_'+node.id;doc.state??={};
88
+ if(!own(doc.state,node.stateKey))doc.state[node.stateKey]={type:'json',default:{}};
89
+ }
53
90
  if (node.type === 'sandbox') {
54
91
  if (!own(node,'title')) node.title = doc.title;
55
92
  if (!own(node,'fallback')) node.fallback = doc.fallback;
@@ -57,7 +94,15 @@ export function normalizeAuthoring(doc) {
57
94
  for (const field of ['children','items','columns','stateKeys','dataKeys','derivedKeys']) if (own(node,field)) node[field] = array(node[field]);
58
95
  if (['table','chart'].includes(node.type) && own(node,'rows')) node.rows = array(node.rows);
59
96
  for (const field of ['decimals','height']) if (own(node,field)) node[field] = number(node[field]);
97
+ if(['row','column'].includes(node.type)){if(own(node,'gap'))node.gap=number(node.gap);if(node.type==='row'&&own(node,'columns'))node.columns=number(node.columns)}
98
+ if(['text','heading','callout'].includes(node.type)){
99
+ for(const field of ['size','weight','lineHeight'])if(own(node,field))node[field]=number(node[field]);
100
+ if(own(node,'spans'))node.spans=array(node.spans);
101
+ if(Array.isArray(node.spans))for(const span of node.spans)if(object(span))for(const field of ['size','weight','lineHeight'])if(own(span,field))span[field]=number(span[field]);
102
+ }
60
103
  if (node.type === 'details' && own(node,'open')) node.open = boolean(node.open);
104
+ if(node.type==='text'&&own(node,'copyable'))node.copyable=boolean(node.copyable);
105
+ if(node.type==='code'&&own(node,'wrap'))node.wrap=boolean(node.wrap);
61
106
  for (const field of ['text','value','max','rows']) if (own(node,field)) expression(node[field],node.type === 'progress');
62
107
  if (['row','column','card','details'].includes(node.type) && own(node,'children')) node.children = nodes(node.children);
63
108
  }
@@ -0,0 +1,36 @@
1
+ // Repair transport encodings only where the component schema declares a type.
2
+ // Opaque JSON, ECharts options, source code and user data retain their contents.
3
+ export function normalizeVisual(value, schemas) {
4
+ const unwrap=v=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).length===1&&Array.isArray(v.item)?v.item:v;
5
+ const scalar=(v,kind)=>kind==='number'&&typeof v==='string'&&v.trim()!==''&&Number.isFinite(Number(v))?Number(v):kind==='boolean'&&(v==='true'||v==='false')?v==='true':v;
6
+ function record(input,schema,depth=0){
7
+ if(!input||typeof input!=='object'||Array.isArray(input)||depth>32)return input;
8
+ const out={...input};
9
+ for(const [key,v]of Object.entries(input)){
10
+ const target=schema.aliases?.[key]??key,kind=schema.fields?.[target];
11
+ if(kind==='array'||kind==='nodes'){
12
+ let array=unwrap(v);
13
+ if(Array.isArray(array))array=array.map(x=>kind==='nodes'?node(x,depth+1):schema.nested?.[target]?record(x,schema.nested[target],depth+1):x);
14
+ out[key]=array;
15
+ }else out[key]=scalar(v,kind);
16
+ }
17
+ return out;
18
+ }
19
+ function node(v,depth){
20
+ if(!v||typeof v!=='object'||Array.isArray(v))return v;
21
+ // Native v1 uses heading, while the extended vocabulary calls it text.
22
+ // This spelling has an unambiguous equivalent and should not cost a retry.
23
+ if(v.type==='heading'){v={...v,type:'text',content:v.content??v.text??v.title,size:v.size??'h3'};delete v.text;delete v.title}
24
+ if(['card','row','col','grid'].includes(v.type)&&v.items===undefined&&Array.isArray(unwrap(v.children))){v={...v,items:unwrap(v.children)};delete v.children}
25
+ const out=record(v,schemas[v.type]??{},depth);
26
+ if(v.type==='quiz'&&Array.isArray(out.options))out.options=out.options.map(x=>record(x,{fields:{correct:'boolean'}}));
27
+ if(v.type==='table')for(const key of ['rows','data','items','details'])if(Array.isArray(out[key]))out[key]=out[key].map(row=>{row=unwrap(row);return key==='details'&&Array.isArray(row)?row.map(x=>node(x,depth+1)):row});
28
+ if(v.type==='echart')for(const key of ['data','series','links'])if(Array.isArray(out[key]))out[key]=out[key].map(x=>record(x,{fields:{value:'number',data:'array'},nested:{data:{fields:{value:'number'}}}}));
29
+ return out;
30
+ }
31
+ if(Array.isArray(value))return {items:value.map(x=>node(x,0))};
32
+ if(!value||typeof value!=='object')return value;
33
+ const out={...value},items=unwrap(value.items);
34
+ if(Array.isArray(items))out.items=items.map(x=>node(x,0));
35
+ return out;
36
+ }
@@ -1,5 +1,5 @@
1
1
  // Public, bounded presentation vocabulary. Never accept arbitrary CSS or SVG from the model.
2
- export const UI_ICONS = Object.freeze(['sparkles', 'sliders', 'layers', 'chart', 'gauge', 'cpu', 'database', 'info', 'check', 'warning', 'arrow', 'target']);
2
+ export const UI_ICONS = Object.freeze(['sparkles', 'sliders', 'layers', 'chart', 'gauge', 'cpu', 'database', 'info', 'check', 'warning', 'arrow', 'target','external','file','globe']);
3
3
  export const UI_TONES = Object.freeze(['neutral', 'accent', 'success', 'warning', 'danger']);
4
4
  export const UI_LAYOUTS = Object.freeze(['dashboard', 'workbench', 'comparison', 'guide', 'status', 'report']);
5
5
  export const UI_ACCENTS = Object.freeze(['blue', 'teal', 'violet', 'amber', 'rose']);