deepseek-harness-intelligent-ui 0.2.8 → 0.2.9

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 CHANGED
@@ -6,6 +6,21 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.2.9]
10
+
11
+ ### Fixed
12
+
13
+ - `ui_render` and `ui_compose` catalog blocks: the tool schema and description now say that the top-level `root` field is required, and a call without it gets an error that says how to fix it. In real-model runs DeepSeek models often named the first component `"root"` but left out the `root` field, so the first call was refused and had to be retried ([#62](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/pull/62)).
14
+ - Release publication verification: wait up to 10 minutes (30 attempts) for npm registry propagation to avoid false-alarm verification failures ([#56](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/pull/56)).
15
+ - Evaluation routing: guard against missing chart properties and empty block lists, accept local OpenAI-compatible HTTP endpoints via `DEEPSEEK_EVAL_ENDPOINT`, and judge delivery on inline widgets instead of workspace tool calls ([#59](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/pull/59), [#61](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/pull/61)).
16
+
17
+ ### Added
18
+
19
+ - [docs/presentation-routing.md](docs/presentation-routing.md) records the presentation-routing study for [#58](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/issues/58): rule overlaps, four comparable projects, and a real-model A/B (DeepSeek V4.1 Flash, 3 runs × 39 cases) in which a rewritten decision-order guidance did not route better than the current one (114/117 vs. 111/117 routed correctly), so the current guidance is kept ([#64](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/pull/64)).
20
+ - Real-model evaluation group F: paired presentation-routing cases for [#58](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/issues/58). Each pair keeps the topic and changes only the task, so a prompt cannot score well by always or never drawing UI; the whole answer is judged (explanation, code, interaction, the user's own data), not just the tool name. Categories `no-ui`, `needs-ui` and `update` report the unnecessary-UI rate, the missed-UI rate and follow-up edits separately. API cases also record prompt and completion tokens ([#59](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/pull/59)).
21
+ - Storefront screenshots manifest: `screenshots.json` declares the showcase screenshots and order for plugin markets like `dshmarket`.
22
+ - [CONTRIBUTING.md](CONTRIBUTING.md) guide covering development setup, the committed-bundle rule, test layout, required CI checks, translations, PR automation, and release integrity rules ([#57](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/pull/57)).
23
+
9
24
  ## [0.2.8]
10
25
 
11
26
  ### Added
@@ -178,7 +193,8 @@ All notable changes to this project are documented here. The format follows
178
193
  - The declarative component catalog (`ui_render`) and sandboxed streaming HTML widgets (`ui_render_widget`).
179
194
  - The `/ui` command and the guidance system-prompt section.
180
195
 
181
- [Unreleased]: https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/compare/v0.2.8...HEAD
196
+ [Unreleased]: https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/compare/v0.2.9...HEAD
197
+ [0.2.9]: https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/compare/v0.2.8...v0.2.9
182
198
  [0.2.8]: https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/compare/v0.2.7...v0.2.8
183
199
  [0.2.7]: https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/compare/v0.2.6...v0.2.7
184
200
  [0.2.6]: https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/compare/v0.2.5...v0.2.6
package/README.md CHANGED
@@ -171,6 +171,8 @@ The plugin injects a system-prompt section ([`src/guidance.js`](src/guidance.js)
171
171
  - **`ui_render_widget`** for what the catalog cannot draw: 3D, simulations, animations, games, custom tools.
172
172
  - **Local first:** anything computable in the browser must update instantly without a message to the model.
173
173
 
174
+ Why these rules were kept after a real-model A/B against a rewritten decision order, and how routing is measured: [docs/presentation-routing.md](docs/presentation-routing.md).
175
+
174
176
  `/ui <request>` forces a UI answer.
175
177
 
176
178
  | Tool | Use it for | Rendering |
@@ -316,11 +318,12 @@ npm run eval:real -- --record && npm run eval:demo # record and cut the demo vi
316
318
 
317
319
  | Option | Effect |
318
320
  | --- | --- |
319
- | `--stage mock,api,browser` | Run only some layers (`all` by default); `A`/`B`/`C`/`D` selects API categories |
321
+ | `--stage mock,api,browser` | Run only some layers (`all` by default); `A`–`F` selects API categories (`F`: paired presentation-routing cases, [#58](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/issues/58)) |
320
322
  | `--only B3,R-chart` | Run only these cases |
321
323
  | `--keep-other-layers` | Keep the layers or cases this run did not execute, each with its own date |
322
324
  | `--append` | With `--only`: add the rerun as extra samples; a failure is never replaced by a lucky retry |
323
325
  | `--rescore` | Re-judge the last API run from its saved transcripts with the current assertions, no model calls |
326
+ | `--report <file.json>` | Write the report elsewhere, e.g. one file per prompt version to compare a baseline with a candidate |
324
327
  | `DEEPSEEK_EVAL_MODEL` | Model id (default `deepseek-flash`) |
325
328
 
326
329
  The **Real-model eval** workflow runs the same command on demand with the `DEEPSEEK_API_KEY` secret; a full run costs about ¥1.5 with `deepseek-flash`.
@@ -339,6 +342,7 @@ The **Real-model eval** workflow runs the same command on demand with the `DEEPS
339
342
  - **Math Plot (C2):** three sliders, every one used in the expression, an `exp(…)·sin/cos(…)` shape.
340
343
  - **Three.js and widgets (C1, C3, C4):** `UI.three()` or `import("three")`, animation, lights, start/pause and parameter controls.
341
344
  - **Multi-turn edits (D2, D3):** a new column with every value correct and old values kept; bar → line, then a third series with exact values.
345
+ - **Presentation routing (F, not yet in the recorded run):** 21 cases in pairs that keep the topic and change only the task (explain vs. drag a parameter, explain Three.js vs. a rotatable scene here, code to copy vs. a repo change, Markdown table vs. a searchable grid of the user's rows, a formula vs. a derivation with a plot between the steps, a closing Choice vs. a chart after each section), plus a patch that must leave a filtered table untouched, a text-only restriction after a 3D turn and live data without a source. `no-ui` failures are unnecessary UI, `needs-ui` failures missed UI. Details: [#58](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/issues/58).
342
346
 
343
347
  **Browser stage** (`scripts/eval/browser-stage.mjs`, 11 cases, each in a new conversation): plain text creates no card; chart legend, Q1–Q4 and local hover; table re-sorts without a model call; a form filled and submitted with real mouse and keyboard; Plot slider redraws; Three.js canvas drawn (pixel statistics) and draggable, with "Ask to fix" on failure; stop → preview → Regenerate; two in-place edits; Fast 3G; CDN blocked; 390 px phone width. Console errors are recorded per case, and every screenshot is reviewed by hand.
344
348
 
package/README.zh-CN.md CHANGED
@@ -171,6 +171,8 @@ npx deepseek-harness-intelligent-ui doctor # 只诊断,不做修改
171
171
  - **`ui_render_widget`**:组件目录画不出的东西,例如三维、模拟、动画、游戏、自定义工具。
172
172
  - **本地优先**:凡是能在浏览器里算出来的,都必须即时更新,不调用模型。
173
173
 
174
+ 这些规则为什么在与重写版决策顺序做真实模型 A/B 后被保留,以及路由如何评测,见 [docs/presentation-routing.md](docs/presentation-routing.md)。
175
+
174
176
  `/ui <需求>` 可强制以 UI 作答。
175
177
 
176
178
  | 工具 | 适用场景 | 渲染方式 |
@@ -316,11 +318,12 @@ npm run eval:real -- --record && npm run eval:demo # 录制并剪辑演示视
316
318
 
317
319
  | 选项 | 作用 |
318
320
  | --- | --- |
319
- | `--stage mock,api,browser` | 只运行部分层(默认 `all`);`A`/`B`/`C`/`D` 选择 API 类别 |
321
+ | `--stage mock,api,browser` | 只运行部分层(默认 `all`);`A`–`F` 选择 API 类别(`F`:成对的呈现方式决策用例,[#58](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/issues/58)) |
320
322
  | `--only B3,R-chart` | 只运行这些用例 |
321
323
  | `--keep-other-layers` | 保留本次没有运行的层或用例,各自保留原来的日期 |
322
324
  | `--append` | 配合 `--only`:把重跑结果作为额外样本加入,绝不用一次侥幸成功覆盖失败 |
323
325
  | `--rescore` | 用当前断言、基于已保存的对话记录重新判定上一次 API 运行,不调用模型 |
326
+ | `--report <file.json>` | 把报告写到其他文件,例如每个提示词版本一份,用来对比基线与候选提示词 |
324
327
  | `DEEPSEEK_EVAL_MODEL` | 模型 id(默认 `deepseek-flash`) |
325
328
 
326
329
  GitHub 上的 **Real-model eval** 工作流可按需手动触发,使用仓库密钥 `DEEPSEEK_API_KEY` 运行同一条命令;用 `deepseek-flash` 完整跑一遍约花费 ¥1.5。
@@ -339,6 +342,7 @@ GitHub 上的 **Real-model eval** 工作流可按需手动触发,使用仓库
339
342
  - **数学 Plot(C2):** 三个滑块且都出现在表达式中,函数形状为 `exp(…)·sin/cos(…)`。
340
343
  - **Three.js 与组件(C1、C3、C4):** 使用 `UI.three()` 或 `import("three")`,有动画、光照、启动/暂停和参数控件。
341
344
  - **多轮修改(D2、D3):** 新增一列且每个值都正确、旧值保留;柱状 → 折线,再按准确数值加入第三个系列。
345
+ - **呈现方式决策(F,尚未进入已记录的运行):** 21 个成对用例,主题不变、只改变任务(解释 vs. 拖动参数、解释 Three.js vs. 对话内可旋转场景、可复制代码 vs. 修改仓库、Markdown 表格 vs. 用户数据的可搜索表格、写公式 vs. 推导中插入曲线、结尾 Choice vs. 每节一张图),另有必须保持已筛选表格不变的 patch、3D 回合之后的纯文本限制,以及没有数据源的实时数据请求。`no-ui` 失败表示不必要的 UI,`needs-ui` 失败表示漏掉了 UI。详见 [#58](https://github.com/dreamfarer-space/deepseek-harness-intelligent-ui/issues/58)。
342
346
 
343
347
  **浏览器阶段**(`scripts/eval/browser-stage.mjs`,11 个用例,每个都在新会话中):纯文本不创建卡片;图表有图例、Q1–Q4 和本地悬停;数据表重新排序不调用模型;用真实鼠标键盘填写并提交表单;Plot 滑块重绘;Three.js 画布确有内容(像素统计)且可拖动,失败时尝试「让模型修复」;停止 → 预览 → 重新生成;两轮原位修改;Fast 3G;屏蔽 CDN;390 px 手机宽度。每个用例都记录控制台错误,每张截图都经过人工复核。
344
348
 
package/client/client.js CHANGED
@@ -1,9 +1,9 @@
1
- /* deepseek-harness-intelligent-ui 0.2.8 — generated by scripts/build-client.mjs; do not edit. */
1
+ /* deepseek-harness-intelligent-ui 0.2.9 — generated by scripts/build-client.mjs; do not edit. */
2
2
  window.__ModuleLoader__.load({ id: "deepseek-harness-intelligent-ui", factory: (require) => {
3
3
  var module = { exports: {} }; var exports = module.exports;
4
4
  "use strict";var df=Object.create;var Yn=Object.defineProperty;var ff=Object.getOwnPropertyDescriptor;var pf=Object.getOwnPropertyNames;var mf=Object.getPrototypeOf,hf=Object.prototype.hasOwnProperty;var gf=(e,t,n)=>t in e?Yn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Xn=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Bi=(e,t)=>{for(var n in t)Yn(e,n,{get:t[n],enumerable:!0})},Is=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of pf(t))!hf.call(e,i)&&i!==n&&Yn(e,i,{get:()=>t[i],enumerable:!(r=ff(t,i))||r.enumerable});return e};var Ns=(e,t,n)=>(n=e!=null?df(mf(e)):{},Is(t||!e||!e.__esModule?Yn(n,"default",{value:e,enumerable:!0}):n,e)),yf=e=>Is(Yn({},"__esModule",{value:!0}),e);var be=(e,t,n)=>gf(e,typeof t!="symbol"?t+"":t,n);var mu=Xn((Av,pu)=>{"use strict";var uu=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,im=/\n/g,om=/^\s*/,am=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,sm=/^:\s*/,lm=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,um=/^[;\s]*/,cm=/^\s+|\s+$/g,dm=`
5
5
  `,cu="/",du="*",tn="",fm="comment",pm="declaration";function mm(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var n=1,r=1;function i(m){var h=m.match(im);h&&(n+=h.length);var b=m.lastIndexOf(dm);r=~b?m.length-b:r+m.length}function o(){var m={line:n,column:r};return function(h){return h.position=new a(m),u(),h}}function a(m){this.start=m,this.end={line:n,column:r},this.source=t.source}a.prototype.content=e;function s(m){var h=new Error(t.source+":"+n+":"+r+": "+m);if(h.reason=m,h.filename=t.source,h.line=n,h.column=r,h.source=e,!t.silent)throw h}function l(m){var h=m.exec(e);if(h){var b=h[0];return i(b),e=e.slice(b.length),h}}function u(){l(om)}function c(m){var h;for(m=m||[];h=d();)h!==!1&&m.push(h);return m}function d(){var m=o();if(!(cu!=e.charAt(0)||du!=e.charAt(1))){for(var h=2;tn!=e.charAt(h)&&(du!=e.charAt(h)||cu!=e.charAt(h+1));)++h;if(h+=2,tn===e.charAt(h-1))return s("End of comment missing");var b=e.slice(2,h-2);return r+=2,i(b),e=e.slice(h),r+=2,m({type:fm,comment:b})}}function p(){var m=o(),h=l(am);if(h){if(d(),!l(sm))return s("property missing ':'");var b=l(lm),g=m({type:pm,property:fu(h[0].replace(uu,tn)),value:b?fu(b[0].replace(uu,tn)):tn});return l(um),g}}function f(){var m=[];c(m);for(var h;h=p();)h!==!1&&(m.push(h),c(m));return m}return u(),f()}function fu(e){return e?e.replace(cm,tn):tn}pu.exports=mm});var hu=Xn(cr=>{"use strict";var hm=cr&&cr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(cr,"__esModule",{value:!0});cr.default=ym;var gm=hm(mu());function ym(e,t){let n=null;if(!e||typeof e!="string")return n;let r=(0,gm.default)(e),i=typeof t=="function";return r.forEach(o=>{if(o.type!=="declaration")return;let{property:a,value:s}=o;i?t(a,s,o):s&&(n=n||{},n[a]=s)}),n}});var yu=Xn(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.camelCase=void 0;var bm=/^--[a-zA-Z0-9_-]+$/,xm=/-([a-z])/g,wm=/^[^-]+$/,km=/^-(webkit|moz|ms|o|khtml)-/,vm=/^-(ms)-/,Sm=function(e){return!e||wm.test(e)||bm.test(e)},Cm=function(e,t){return t.toUpperCase()},gu=function(e,t){return"".concat(t,"-")},Em=function(e,t){return t===void 0&&(t={}),Sm(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(vm,gu):e=e.replace(km,gu),e.replace(xm,Cm))};ri.camelCase=Em});var xu=Xn((Yo,bu)=>{"use strict";var Im=Yo&&Yo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},Nm=Im(hu()),Tm=yu();function Go(e,t){var n={};return!e||typeof e!="string"||(0,Nm.default)(e,function(r,i){r&&i&&(n[(0,Tm.camelCase)(r,t)]=i)}),n}Go.default=Go;bu.exports=Go});var qc=Xn((dI,Hc)=>{"use strict";var Ni=Object.prototype.hasOwnProperty,Bc=Object.prototype.toString,jc=Object.defineProperty,Fc=Object.getOwnPropertyDescriptor,Dc=function(t){return typeof Array.isArray=="function"?Array.isArray(t):Bc.call(t)==="[object Array]"},zc=function(t){if(!t||Bc.call(t)!=="[object Object]")return!1;var n=Ni.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&Ni.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var i;for(i in t);return typeof i>"u"||Ni.call(t,i)},_c=function(t,n){jc&&n.name==="__proto__"?jc(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},Uc=function(t,n){if(n==="__proto__")if(Ni.call(t,n)){if(Fc)return Fc(t,n).value}else return;return t[n]};Hc.exports=function e(){var t,n,r,i,o,a,s=arguments[0],l=1,u=arguments.length,c=!1;for(typeof s=="boolean"&&(c=s,s=arguments[1]||{},l=2),(s==null||typeof s!="object"&&typeof s!="function")&&(s={});l<u;++l)if(t=arguments[l],t!=null)for(n in t)r=Uc(s,n),i=Uc(t,n),s!==i&&(c&&i&&(zc(i)||(o=Dc(i)))?(o?(o=!1,a=r&&Dc(r)?r:[]):a=r&&zc(r)?r:{},_c(s,{name:n,newValue:e(c,a,i)})):typeof i<"u"&&_c(s,{name:n,newValue:i}));return s}});var jb={};Bi(jb,{CATALOG_API_VERSION:()=>Zn,apply:()=>Lb,createControlledRuntime:()=>$s,inject:()=>Rb,promptSession:()=>tf,registerComponentExtension:()=>bl});module.exports=yf(jb);var Ir=Object.freeze({sin:[1,Math.sin],cos:[1,Math.cos],tan:[1,Math.tan],asin:[1,Math.asin],acos:[1,Math.acos],atan:[1,Math.atan],atan2:[2,Math.atan2],sinh:[1,Math.sinh],cosh:[1,Math.cosh],tanh:[1,Math.tanh],exp:[1,Math.exp],ln:[1,Math.log],log:[1,Math.log10],log10:[1,Math.log10],log2:[1,Math.log2],sqrt:[1,Math.sqrt],cbrt:[1,Math.cbrt],abs:[1,Math.abs],sign:[1,Math.sign],floor:[1,Math.floor],ceil:[1,Math.ceil],round:[1,Math.round],min:[-1,Math.min],max:[-1,Math.max],pow:[2,Math.pow],hypot:[-1,Math.hypot]}),Ts=Object.freeze({pi:Math.PI,e:Math.E,tau:2*Math.PI}),As=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,Ps=500;function bf(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===" "||r===" "||r===`
6
- `){n++;continue}let i=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(e.slice(n));if(i){t.push({t:"num",v:Number(i[0]),at:n}),n+=i[0].length;continue}let o=/^[A-Za-z_][A-Za-z_0-9]*/.exec(e.slice(n));if(o){t.push({t:"id",v:o[0],at:n}),n+=o[0].length;continue}if(e.startsWith("**",n)){t.push({t:"op",v:"^",at:n}),n+=2;continue}if("+-*/%^".includes(r)){t.push({t:"op",v:r,at:n}),n++;continue}if(r==="("||r===")"||r===","){t.push({t:r,v:r,at:n}),n++;continue}if(r==="·"||r==="×"){t.push({t:"op",v:"*",at:n}),n++;continue}throw new SyntaxError(`unexpected character ${JSON.stringify(r)} at ${n}`)}return t}function Hi(e,t){if(typeof e!="string"||!e.trim())throw new SyntaxError("empty expression");if(e.length>Ps)throw new SyntaxError(`longer than ${Ps} characters`);let n=new Set(t),r=bf(e),i=0,o=()=>r[i],a=m=>{throw new SyntaxError(m)},s=m=>{let h=r[i];(!h||h.t!==m)&&a(`expected "${m}" ${h?`at ${h.at}`:"at end"}`),i++};function l(){let m=u();for(;o()?.t==="op"&&(o().v==="+"||o().v==="-");){let h=r[i++].v,b=m,g=u();m=h==="+"?v=>b(v)+g(v):v=>b(v)-g(v)}return m}function u(){let m=c();for(;;){let h=o();if(h?.t==="op"&&(h.v==="*"||h.v==="/"||h.v==="%")){i++;let g=m,v=c();m=h.v==="*"?S=>g(S)*v(S):h.v==="/"?S=>g(S)/v(S):S=>g(S)%v(S);continue}let b=r[i-1];if(h&&(h.t==="id"||h.t==="("||h.t==="num")&&b&&(b.t==="num"||b.t===")")&&!(h.t==="num"&&b.t==="num")){let g=m,v=c();m=S=>g(S)*v(S);continue}return m}}function c(){let m=o();if(m?.t==="op"&&(m.v==="-"||m.v==="+")){i++;let h=c();return m.v==="-"?b=>-h(b):h}return d()}function d(){let m=p();if(o()?.t==="op"&&o().v==="^"){i++;let h=c();return b=>m(b)**h(b)}return m}function p(){let m=r[i++];if(m||a("unexpected end of expression"),m.t==="num"){let h=m.v;return()=>h}if(m.t==="("){let h=l();return s(")"),h}if(m.t==="id"){let h=String(m.v);if(o()?.t==="("){let g=As(Ir,h);g||a(`unknown function "${h}"; allowed: ${Object.keys(Ir).join(", ")}`),i++;let v=[];if(o()?.t!==")")for(v.push(l());o()?.t===",";)i++,v.push(l());s(")");let[S,O]=g;if(S>=0&&v.length!==S&&a(`${h}() takes ${S} argument(s), got ${v.length}`),S<0&&v.length===0&&a(`${h}() needs at least one argument`),v.length===1){let E=v[0];return C=>O(E(C))}if(v.length===2){let[E,C]=v;return P=>O(E(P),C(P))}return E=>O(...v.map(C=>C(E)))}if(n.has(h))return g=>g[h];let b=As(Ts,h);if(b!==void 0)return()=>b;a(`unknown variable "${h}"; available: ${[...n,...Object.keys(Ts)].join(", ")}`)}a(`unexpected "${m.v}" at ${m.at}`)}let f=l();return i<r.length&&a(`unexpected "${r[i].v}" at ${r[i].at}`),f}function Os(e,t){try{Hi(e,t);return}catch(n){return n instanceof Error?n.message:String(n)}}var kn=Object.freeze({dataBytes:512e3,argsBytes:16e3,resultBytes:64e3,resources:64,receipts:128}),qi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ht=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Y(e){throw new Error(e)}function Qn(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function vn(e,t){let n=(i,o=0)=>{if(o>20&&Y("JSON nesting exceeds limit"),!(i===null||typeof i=="string"||typeof i=="boolean")&&!(typeof i=="number"&&Number.isFinite(i))){!Ht(i)&&!Array.isArray(i)&&Y("Payload must be finite JSON");for(let a of Object.values(i))n(a,o+1)}};n(e);let r=JSON.stringify(e);return(r===void 0||new TextEncoder().encode(r).length>t)&&Y("Payload exceeds limit or is not JSON"),JSON.parse(r)}function ut(e){return e&&typeof e=="object"&&(Object.values(e).forEach(ut),Object.freeze(e)),e}function Je(e,t,n=!1,r=0){(r>12||!Ht(e))&&Y("Invalid schema");let i={object:["type","properties","required","additionalProperties"],array:["type","items","maxItems"],string:["type","maxLength","enum"],number:["type","minimum","maximum","enum"],integer:["type","minimum","maximum","enum"],boolean:["type"],null:["type"]}[e.type];(!i||Object.keys(e).some(o=>!i.includes(o)))&&Y("Unsupported schema keyword/type"),e.enum!==void 0&&(!Array.isArray(e.enum)||e.enum.length>100)&&Y("Invalid enum");for(let o of["maxLength","maxItems"])e[o]!==void 0&&(!Number.isSafeInteger(e[o])||e[o]<0)&&Y("Invalid schema bound");for(let o of["minimum","maximum"])e[o]!==void 0&&!Number.isFinite(e[o])&&Y("Invalid schema bound");if(e.type==="object"){(!Ht(e.properties)||e.additionalProperties!==!1||!Array.isArray(e.required??[])||(e.required??[]).some(o=>!qi(e.properties,o)))&&Y("Object schema requires properties and additionalProperties:false");for(let o of Object.values(e.properties))Je(o,void 0,!0,r+1)}if(e.type==="array"&&Je(e.items,void 0,!0,r+1),!n){if(e.type==="object"){(!Ht(t)||Object.keys(t).some(o=>!qi(e.properties,o))||(e.required??[]).some(o=>!qi(t,o)))&&Y("Arguments do not match schema");for(let[o,a]of Object.entries(t))Je(e.properties[o],a,!1,r+1)}else e.type==="array"?((!Array.isArray(t)||t.length>(e.maxItems??1e3))&&Y("Invalid array"),t.forEach(o=>Je(e.items,o,!1,r+1))):e.type==="null"?t!==null&&Y("Expected null"):typeof t!==(e.type==="integer"?"number":e.type)&&Y("Arguments do not match schema");typeof t=="number"&&(!Number.isFinite(t)||e.type==="integer"&&!Number.isSafeInteger(t)||t<(e.minimum??-1/0)||t>(e.maximum??1/0))&&Y("Invalid number"),typeof t=="string"&&t.length>(e.maxLength??16e3)&&Y("String exceeds limit"),e.enum&&!e.enum.includes(t)&&Y("Value is outside enum")}}function $s(e){(typeof e!="string"||!e)&&Y("Session id required");let t=new Map,n=new Map,r=new Map,i=new Set,o=!1,a=0,s=()=>{a++;for(let m of i)m()},l=()=>{o&&Y("Session disposed")},u=(m,h)=>JSON.stringify([m,h]),c=m=>(l(),(!m||m.sessionId!==e||typeof m.uiId!="string"||!m.uiId)&&Y("Scope denied"),m.uiId),d=(m,h)=>{(typeof m!="string"||!m||m.length>200||typeof h!="string"||!h||h.length>100)&&Y("Invalid resource id/scope")},p=()=>{l(),t.size+n.size>=kn.resources&&Y("Resource limit")},f={sessionId:e,subscribe(m){return o?()=>{}:(i.add(m),()=>i.delete(m))},getRevision(){return a},registerData(m,h,b){p(),d(m,h);let g=ut(vn(b,kn.dataBytes));(!Array.isArray(g.columns)||g.columns.length<1||g.columns.length>24||g.columns.some(O=>typeof O!="string")||!Array.isArray(g.rows)||g.rows.length>500||g.rows.some(O=>!Array.isArray(O)||O.length!==g.columns.length||O.some(E=>!(E===null||["string","boolean","number"].includes(typeof E)))))&&Y("Invalid dataset");let v=u(m,h);t.has(v)&&Y("Duplicate data id");let S={value:g,view:ut({search:"",filterColumn:-1,filterValue:"",sortColumn:-1,descending:!1,page:0})};return t.set(v,S),s(),()=>{t.get(v)===S&&(t.delete(v),s())}},readData(m,h){let b=c(m);(!Ht(h)||h.scope!==b||typeof h.id!="string")&&Y("Data scope denied");let g=t.get(u(b,h.id));return g||Y("Data unavailable (expired or unregistered)"),Object.freeze({value:g.value,view:g.view})},setView(m,h,b){let g=f.readData(m,h),v={...g.view,...vn(b,4e3)};(Object.keys(v).some(S=>!["search","filterColumn","filterValue","sortColumn","descending","page"].includes(S))||typeof v.search!="string"||typeof v.filterValue!="string"||typeof v.descending!="boolean"||![v.filterColumn,v.sortColumn].every(S=>Number.isInteger(S)&&S>=-1&&S<g.value.columns.length)||!Number.isSafeInteger(v.page)||v.page<0)&&Y("Invalid local query"),t.get(u(m.uiId,h.id)).view=ut(v),s()},registerAction(m,h,b){p(),d(m,h),Je(b.schema,void 0,!0),(!["read","write"].includes(b.effect)||typeof b.run!="function"||typeof b.authorize!="function"||b.effect==="write"&&typeof b.confirm!="function")&&Y("Action needs effect, authorize, run and write confirmation");let g=u(m,h);n.has(g)&&Y("Duplicate action id");let v={...b,schema:ut(vn(b.schema,16e3))};return n.set(g,v),()=>{n.get(g)===v&&n.delete(g)}},prepareAction(m,h){let b=c(m),g=vn(h,kn.argsBytes);(!Ht(g)||typeof g.actionId!="string"||g.requestId!==void 0&&(typeof g.requestId!="string"||!g.requestId||g.requestId.length>100))&&Y("Invalid action request");let v=n.get(u(b,g.actionId));return v||Y("Unregistered action"),Je(v.schema,g.args),ut({actionId:g.actionId,args:g.args,requestId:typeof g.requestId=="string"?g.requestId:Qn()})},async invokeAction(m,h,b){let g=c(m);(!(b instanceof Event)||!b.isTrusted||b.type!=="click")&&Y("Explicit trusted user click required"),(!Ht(h)||typeof h.actionId!="string"||typeof h.requestId!="string"||!h.requestId||h.requestId.length>100)&&Y("Invalid action request");let v=n.get(u(g,h.actionId));v||Y("Unregistered action"),h=ut(vn(h,kn.argsBytes)),m=ut({sessionId:m.sessionId,uiId:g});let S=h.args;Je(v.schema,S);let O=u(g,h.requestId),E=JSON.stringify([h.actionId,S]),C=r.get(O);if(C)return C.fingerprint!==E&&Y("Idempotency key reused with different arguments"),C.promise;r.size>=kn.receipts&&Y("Receipt limit reached; start a new surface/session");let P=ut({sessionId:e,uiId:g,requestId:h.requestId}),R=()=>{c(m),n.get(u(g,h.actionId))!==v&&Y("Action revoked")},F=!1,y=Promise.resolve().then(async()=>(R(),await v.authorize(P,S)!==!0&&Y("Action permission denied"),R(),v.effect==="write"&&await v.confirm(P,S)!==!0&&Y("Action cancelled"),R(),await v.authorize(P,S)!==!0&&Y("Action permission denied"),R(),F=!0,vn(await v.run(S,P),kn.resultBytes))).catch(x=>{throw!F&&r.get(O)?.promise===y&&r.delete(O),x});return r.set(O,{fingerprint:E,promise:y}),y},releaseScope(m){for(let h of[t,n,r])for(let b of h.keys())JSON.parse(b)[0]===m&&h.delete(b);s()},dispose(){o||(o=!0,t.clear(),n.clear(),r.clear(),s(),i.clear())}};return f}function Ms(e){let{value:t,view:n}=e,r=t.rows.filter(i=>(!n.search||i.some(o=>String(o??"").toLowerCase().includes(n.search.toLowerCase())))&&(n.filterColumn<0||String(i[n.filterColumn]??"")===n.filterValue));return n.sortColumn>=0&&(r=[...r].sort((i,o)=>{let a=i[n.sortColumn],s=o[n.sortColumn];return(typeof a=="number"&&typeof s=="number"?a-s:String(a??"").localeCompare(String(s??""),void 0,{numeric:!0}))*(n.descending?-1:1)})),{columns:t.columns,rows:r}}var Zn=1,Nr=new Map,Sn=new Map,Wi=new Set,xf=0,wf=0;function Ls(e){return Wi.add(e),()=>Wi.delete(e)}function Vi(){xf++;for(let e of Wi)e()}var js=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),kf=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function ce(e){throw new Error(`Catalog extension: ${e}`)}function Ji(e){return e&&typeof e=="object"&&(Object.values(e).forEach(Ji),Object.freeze(e)),e}function Ki(e,t=0){if(t>16&&ce("manifest nesting exceeds limit"),e===null||typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map(r=>Ki(r,t+1));(!js(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))&&ce("manifest must be plain JSON");let n=Object.create(null);for(let[r,i]of Object.entries(e))["__proto__","prototype","constructor"].includes(r)&&ce(`reserved key ${r}`),n[r]=Ki(i,t+1);return n}function Rs(e,t){(!js(e)||Object.keys(e).some(n=>!t.includes(n)))&&ce("unknown manifest field")}function Fs(e){let t=Ki(e);JSON.stringify(t).length>64e3&&ce("manifest exceeds limit"),Rs(t,["apiVersion","namespace","version","components"]),t.apiVersion!==Zn&&ce(`unsupported apiVersion; expected ${Zn}`),(typeof t.namespace!="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(t.namespace))&&ce("invalid namespace"),(typeof t.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(t.version))&&ce("version must be major.minor.patch"),Nr.has(t.namespace)&&ce(`namespace ${t.namespace} already registered`),(!Array.isArray(t.components)||!t.components.length||t.components.length>32)&&ce("expected 1-32 components"),Nr.size>=32&&ce("too many extensions");let n=new Map;for(let a of t.components){Rs(a,["name","description","propsSchema","children","actions"]),(typeof a.name!="string"||!/^[A-Z][A-Za-z0-9]{0,63}$/.test(a.name))&&ce("invalid component name");let s=`${t.namespace}/${a.name}`;n.has(s)&&ce(`duplicate type ${s}`),(typeof a.description!="string"||!a.description||a.description.length>2e3)&&ce("description required (max 2000 characters)"),a.children!==void 0&&typeof a.children!="boolean"&&ce("children must be boolean"),a.actions!==void 0&&(!Array.isArray(a.actions)||a.actions.length>32||a.actions.some(l=>typeof l!="string"||!l||l.length>100)||new Set(a.actions).size!==a.actions.length)&&ce("invalid actions"),a.propsSchema?.type!=="object"&&ce("propsSchema must be an object schema");try{Je(a.propsSchema,void 0,!0)}catch(l){ce(`invalid propsSchema for ${s}: ${l.message}`)}kf(a.propsSchema.properties,"children")&&ce("children belongs on the node, not in propsSchema"),n.set(s,Ji({...a,children:a.children??!1,generation:++wf,version:t.version,actions:a.actions??[]}))}Ji(t);let r=!0,i=!1,o={manifest:t};Nr.set(t.namespace,o);for(let[a,s]of n)Sn.set(a,s);return Vi(),Object.freeze({manifest:t,setEnabled(a){if(i&&ce("extension disposed"),typeof a!="boolean"&&ce("enabled must be boolean"),r!==a){r=a;for(let[s,l]of n)r?Sn.set(s,l):Sn.delete(s);Vi()}},dispose(){if(!i){i=!0,Nr.delete(t.namespace);for(let a of n.keys())Sn.delete(a);Vi()}}})}var Tt=e=>typeof e=="string"?Sn.get(e):void 0,Ds=()=>[...Sn.keys()];var zs={type:"object",props:{id:{type:"string",required:!0,max:100},scope:{type:"string",required:!0,max:200}}},vf={type:"object",props:{actionId:{type:"string",required:!0,max:100},args:{type:"any",required:!0}}},er=["default","muted","info","success","warning","error"],Sf=["text","number","range","select","checkbox","date","textarea"],Cf=["text","number","date","boolean","string"],Ef=["bar","line","area","pie"],K=Object.freeze({components:300,depth:24,tableRows:500,tableColumns:24,chartPoints:500,chartSeries:12,formFields:40,text:2e4,plotFunctions:8,plotParams:8,timelineItems:100,choiceOptions:8,scatterPoints:2e3,heatmapAxis:60,diffFiles:20,diffChars:2e5,treeEntries:2e3,jsonChars:1e5,jsonDepth:32}),tr=Object.freeze({Card:{description:"Bordered container with optional title/subtitle/footer; children stack vertically.",children:!0,props:{title:{type:"string"},subtitle:{type:"string"},footer:{type:"string"}}},Stack:{description:"Lays out children vertically (default) or horizontally.",children:!0,props:{direction:{type:"enum",values:["vertical","horizontal"]},gap:{type:"number",min:0,max:64},wrap:{type:"boolean"},align:{type:"enum",values:["start","center","end","stretch"]}}},Grid:{description:"Responsive grid; `columns` is the column count on wide screens (1-6).",children:!0,props:{columns:{type:"number",required:!0,min:1,max:6}}},Tabs:{description:"Tabbed panels: labels[i] titles children[i].",children:!0,props:{labels:{type:"array",required:!0,items:{type:"string"},max:12}}},Text:{description:"Text with a markdown subset (**bold**, *italic*, `code`, [link](https://...), line breaks).",children:!1,props:{text:{type:"string",required:!0,max:K.text},variant:{type:"enum",values:["body","title","heading","caption"]},tone:{type:"enum",values:er}}},Code:{description:"Monospaced code block.",children:!1,props:{code:{type:"string",required:!0,max:K.text},language:{type:"string"}}},Alert:{description:"Callout box with a tone.",children:!1,props:{title:{type:"string"},text:{type:"string",required:!0},tone:{type:"enum",values:er}}},Badge:{description:"Small inline label.",children:!1,props:{text:{type:"string",required:!0},tone:{type:"enum",values:er}}},Divider:{description:"Horizontal rule.",children:!1,props:{}},Stat:{description:"KPI tile: label, big value, optional delta with trend.",children:!1,props:{label:{type:"string",required:!0},value:{type:"scalar",required:!0},delta:{type:"string"},trend:{type:"enum",values:["up","down","flat"]},hint:{type:"string"}}},Progress:{description:"Progress bar; value out of max (default 100).",children:!1,props:{value:{type:"number",required:!0},max:{type:"number",min:0},label:{type:"string"},tone:{type:"enum",values:er}}},List:{description:"Bulleted or numbered list of short markdown-subset strings.",children:!1,props:{items:{type:"array",required:!0,items:{type:"string"},max:200},ordered:{type:"boolean"}}},Table:{description:"Data table / data grid. rows[i][j] belongs to columns[j]. Optional local, model-free interactions: sortable (typed: numbers, ISO 8601 dates `YYYY-MM-DD[THH:mm]`, booleans; empty values last), searchable, filterable (per-column contains / min-max range), pageSize, exportable (CSV/Markdown of the filtered rows). columnTypes overrides inferred types. Or use a host-registered dataRef for shared local search/filter/sort/paging.",children:!1,props:{dataRef:zs,pageSize:{type:"number",min:1,max:100},columnTypes:{type:"array",max:K.tableColumns,items:{type:"enum",values:Cf}},searchable:{type:"boolean"},filterable:{type:"boolean"},exportable:{type:"boolean"},columns:{type:"array",items:{type:"string"},max:K.tableColumns},rows:{type:"array",max:K.tableRows,items:{type:"array",items:{type:"scalar"},max:K.tableColumns}},caption:{type:"string"},sortable:{type:"boolean"}}},Chart:{description:"SVG chart. Use dataRef with labelColumn and valueColumns (zero-based) for local linked data; otherwise labels are the x categories (pie: slice names); each series has one value per label.",children:!1,props:{kind:{type:"enum",required:!0,values:Ef},dataRef:zs,labelColumn:{type:"number",min:0,max:23},valueColumns:{type:"array",max:12,items:{type:"number",min:0,max:23}},labels:{type:"array",items:{type:"scalar"},max:K.chartPoints},series:{type:"array",max:K.chartSeries,items:{type:"object",props:{name:{type:"string",required:!0},values:{type:"array",required:!0,items:{type:"number"},max:K.chartPoints}}}},title:{type:"string"},unit:{type:"string"},stacked:{type:"boolean"},height:{type:"number",min:120,max:600},exportable:{type:"boolean"}}},Scatter:{description:"Scatter plot of real numeric observations: each point has continuous x and y (not category indexes). Use for correlation/distribution between two measures. Points with a null coordinate are hidden and counted. Hover, tap or arrow keys show a point; legend toggles series.",children:!1,props:{series:{type:"array",required:!0,max:K.chartSeries,items:{type:"object",props:{name:{type:"string",required:!0},points:{type:"array",required:!0,max:K.scatterPoints,items:{type:"object",props:{x:{type:"scalar",required:!0},y:{type:"scalar",required:!0},label:{type:"string",max:200}}}}}}},title:{type:"string"},xLabel:{type:"string"},yLabel:{type:"string"},xUnit:{type:"string"},yUnit:{type:"string"},height:{type:"number",min:160,max:600}}},Heatmap:{description:'Matrix heatmap: values[r][c] belongs to yLabels[r] × xLabels[c]. Use null for missing data (drawn hatched, never as 0). scale "diverging" centres on 0 (negative red, positive blue); default "sequential". Optional fixed min/max.',children:!1,props:{xLabels:{type:"array",required:!0,items:{type:"scalar"},max:K.heatmapAxis},yLabels:{type:"array",required:!0,items:{type:"scalar"},max:K.heatmapAxis},values:{type:"array",required:!0,max:K.heatmapAxis,items:{type:"array",items:{type:"scalar"},max:K.heatmapAxis}},title:{type:"string"},unit:{type:"string"},scale:{type:"enum",values:["sequential","diverging"]},min:{type:"number"},max:{type:"number"},showValues:{type:"boolean"}}},CodeDiff:{description:"Read-only code diff viewer for one or more files: give each file before/after full text (the diff is computed, unchanged runs collapse to expandable context) or a unified diff `patch`. Shows line numbers and +/- counts; large files start collapsed. Content is shown as text, never executed. For displaying changes, not applying them.",children:!1,props:{title:{type:"string"},context:{type:"number",min:0,max:20},files:{type:"array",required:!0,max:K.diffFiles,items:{type:"object",props:{path:{type:"string",required:!0,max:500},before:{type:"string",max:K.diffChars},after:{type:"string",max:K.diffChars},patch:{type:"string",max:K.diffChars},language:{type:"string",max:40}}}}}},FileTree:{description:"Collapsible file/directory tree built from slash-separated paths (a trailing / marks an empty directory), with optional per-entry status (added/modified/deleted/renamed) and short note. Labels only: nothing is read from disk.",children:!1,props:{title:{type:"string"},expandDepth:{type:"number",min:0,max:32},entries:{type:"array",required:!0,max:K.treeEntries,items:{type:"object",props:{path:{type:"string",required:!0,max:500},status:{type:"enum",values:["added","modified","deleted","renamed"]},note:{type:"string",max:200}}}}}},JsonView:{description:"Collapsible JSON tree for any JSON value (`data`), with per-node path ($.a[0].b) and copy path / copy value. Use to inspect API responses, configs or tool output.",children:!1,props:{data:{type:"any",required:!0},title:{type:"string"},expandDepth:{type:"number",min:0,max:32}}},Button:{description:"Button sends prompt on explicit user click: sessionTarget defaults to current; new starts an independent Agent session in the same workspace. Or invokes a host-registered action {actionId,args}. Never invent action ids.",children:!1,props:{label:{type:"string",required:!0},prompt:{type:"string"},sessionTarget:{type:"enum",values:["current","new"]},action:vf,variant:{type:"enum",values:["primary","secondary"]}}},Choice:{description:"Single-choice decision card with 2-8 options. Selection is local; the primary action continues in the current session and an optional secondary action starts a new session. Set sessionTarget only for an explicitly chosen fixed destination. Give options stable ids; recommended marks an id without selecting it. Every prompt must preserve user constraints and be self-contained for a new session. New-session retries retain the first confirmed task. No registered actions.",children:!1,props:{question:{type:"string",required:!0,max:300},submitLabel:{type:"string",max:200},sessionTarget:{type:"enum",values:["current","new"]},recommended:{type:"string",max:100},options:{type:"array",required:!0,max:K.choiceOptions,items:{type:"object",props:{id:{type:"string",max:100},label:{type:"string",required:!0,max:200},description:{type:"string",max:1200},prompt:{type:"string",required:!0,max:K.text}}}}}},Form:{description:"Input form. Submit sends all field values prefixed by prompt. sessionTarget defaults to current; new creates an independent session in the same workspace and submits automatically. For new, prompt must contain complete task context and user constraints; conversation history is not copied.",children:!1,props:{title:{type:"string"},submitLabel:{type:"string"},prompt:{type:"string"},sessionTarget:{type:"enum",values:["current","new"]},fields:{type:"array",required:!0,max:K.formFields,items:{type:"object",props:{name:{type:"string",required:!0},label:{type:"string",required:!0},type:{type:"enum",required:!0,values:Sf},options:{type:"array",items:{type:"string"},max:100},required:{type:"boolean"},placeholder:{type:"string"},default:{type:"scalar"},min:{type:"number"},max:{type:"number"},step:{type:"number",min:0}}}}}},Timeline:{description:"Vertical timeline of events/steps in order.",children:!1,props:{items:{type:"array",required:!0,max:K.timelineItems,items:{type:"object",props:{title:{type:"string",required:!0},time:{type:"string"},text:{type:"string"},tone:{type:"enum",values:er}}}}}},Plot:{description:"Function plot y = f(x) drawn natively. `params` become sliders the user drags; the curves update instantly in the browser (no message to you). Expressions use x, the param names, pi, e, + - * / ^, and functions like sin, cos, exp, ln, sqrt, abs.",children:!1,props:{functions:{type:"array",required:!0,max:K.plotFunctions,items:{type:"object",props:{expr:{type:"string",required:!0,max:500},label:{type:"string"}}}},xMin:{type:"number"},xMax:{type:"number"},yMin:{type:"number"},yMax:{type:"number"},params:{type:"array",max:K.plotParams,items:{type:"object",props:{name:{type:"string",required:!0},label:{type:"string"},min:{type:"number",required:!0},max:{type:"number",required:!0},step:{type:"number",min:0},value:{type:"number",required:!0}}}},title:{type:"string"},xLabel:{type:"string"},yLabel:{type:"string"},height:{type:"number",min:160,max:600}}},Math:{description:"LaTeX math typeset with KaTeX (block by default). Put related equations in one node (e.g. \\begin{aligned}...\\end{aligned}). In JSON, escape each backslash (\\\\frac).",children:!1,props:{tex:{type:"string",required:!0,max:5e3},display:{type:"boolean"}}},Mermaid:{description:"Diagram from Mermaid source (flowchart, sequenceDiagram, classDiagram, stateDiagram, erDiagram, gantt, timeline, mindmap, pie).",children:!1,props:{code:{type:"string",required:!0,max:K.text}}}}),If=Object.freeze(Object.keys(tr));function nr(e){return Object.hasOwn(tr,e)?tr[e]:Tt(e)}function Gi(){return[...If,...Ds()]}function Yi(e,t){let n=Tt(e);return n&&t!==n.version?[`componentVersion: ${e} requires ${n.version}`]:!n&&t!==void 0?["componentVersion: only registered extensions accept a version"]:[]}function $e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function _s(e,t,n,r){switch(t.type){case"any":return;case"string":if(typeof e!="string"){r.push(`${n}: expected string, got ${qt(e)}`);return}t.max!==void 0&&e.length>t.max&&r.push(`${n}: longer than ${t.max} characters`);return;case"number":if(typeof e!="number"||!Number.isFinite(e)){r.push(`${n}: expected finite number, got ${qt(e)}`);return}t.min!==void 0&&e<t.min&&r.push(`${n}: must be >= ${t.min}`),t.max!==void 0&&e>t.max&&r.push(`${n}: must be <= ${t.max}`);return;case"boolean":typeof e!="boolean"&&r.push(`${n}: expected boolean, got ${qt(e)}`);return;case"scalar":e===null||["string","number","boolean"].includes(typeof e)||r.push(`${n}: expected string, number, boolean or null, got ${qt(e)}`);return;case"enum":t.values.includes(e)||r.push(`${n}: expected one of ${t.values.join(" | ")}, got ${JSON.stringify(e)}`);return;case"array":if(!Array.isArray(e)){r.push(`${n}: expected array, got ${qt(e)}`);return}if(t.max!==void 0&&e.length>t.max){r.push(`${n}: more than ${t.max} items`);return}t.items&&e.forEach((i,o)=>_s(i,t.items,`${n}[${o}]`,r));return;case"object":if(!$e(e)){r.push(`${n}: expected object, got ${qt(e)}`);return}Us(e,t.props||{},n,r);return;default:r.push(`${n}: unknown spec type ${t.type}`)}}function Us(e,t,n,r){for(let[i,o]of Object.entries(t)){let a=e[i];if(a===void 0){o.required&&r.push(`${n}.${i}: required`);continue}_s(a,o,`${n}.${i}`,r)}for(let i of Object.keys(e))i in t||r.push(`${n}.${i}: unknown prop`)}function Nf(e,t,n,r){if(e==="Table"||e==="Chart"){let i=e==="Table"?["columns","rows"]:["labels","series"];t.dataRef!==void 0?(i.some(o=>t[o]!==void 0)&&r.push(`${n}: dataRef cannot be mixed with inline data`),e==="Chart"&&(!Number.isInteger(t.labelColumn)||!Array.isArray(t.valueColumns)||!t.valueColumns.length||t.valueColumns.some(o=>!Number.isInteger(o)))&&r.push(`${n}: bound Chart needs integer labelColumn and valueColumns`),e==="Chart"&&t.kind==="pie"&&Array.isArray(t.valueColumns)&&t.valueColumns.length!==1&&r.push(`${n}: bound pie chart needs exactly one value column`)):i.some(o=>t[o]===void 0)&&r.push(`${n}: needs ${i.join(" and ")} or dataRef`),t.pageSize!==void 0&&!Number.isInteger(t.pageSize)&&r.push(`${n}.pageSize: expected integer`),Array.isArray(t.columnTypes)&&Array.isArray(t.columns)&&t.columnTypes.length>t.columns.length&&r.push(`${n}.columnTypes: has ${t.columnTypes.length} entries but columns has ${t.columns.length}`),e==="Table"&&t.dataRef!==void 0&&(t.searchable||t.filterable)&&r.push(`${n}: searchable/filterable apply to inline rows; a dataRef table already has shared search and filter`)}if(e==="Button"&&t.prompt===void 0==(t.action===void 0)&&r.push(`${n}: needs exactly one of prompt or action`),e==="Button"&&t.sessionTarget!==void 0&&t.action!==void 0&&r.push(`${n}.sessionTarget: only supported with prompt`),e==="Form"&&t.sessionTarget==="new"&&(typeof t.prompt!="string"||!t.prompt.trim())&&r.push(`${n}.prompt: new session needs a non-empty task prompt`),e==="Choice"){for(let i of["question","submitLabel"])typeof t[i]=="string"&&!t[i].trim()&&r.push(`${n}.${i}: must not be blank`);if(Array.isArray(t.options)){t.options.length<2&&r.push(`${n}.options: needs at least 2 options`);let i=new Set;t.options.forEach((o,a)=>{if($e(o)){for(let s of["id","label","prompt"])typeof o[s]=="string"&&!o[s].trim()&&r.push(`${n}.options[${a}].${s}: must not be blank`);o.id!==void 0&&i.has(o.id)&&r.push(`${n}.options[${a}].id: duplicate option id`),o.id!==void 0&&i.add(o.id)}}),t.recommended!==void 0&&!i.has(t.recommended)&&r.push(`${n}.recommended: must reference an option id`)}}if(e==="Chart"&&Array.isArray(t.labels)&&Array.isArray(t.series)&&(t.series.forEach((i,o)=>{$e(i)&&Array.isArray(i.values)&&i.values.length!==t.labels.length&&r.push(`${n}.series[${o}].values: has ${i.values.length} values but labels has ${t.labels.length}`)}),t.kind==="pie"&&t.series.length>1&&r.push(`${n}.series: a pie chart takes exactly one series`)),e==="Form"&&Array.isArray(t.fields)){let i=new Set;t.fields.forEach((o,a)=>{$e(o)&&(i.has(o.name)&&r.push(`${n}.fields[${a}].name: duplicate field name ${JSON.stringify(o.name)}`),i.add(o.name),o.type==="select"&&(!Array.isArray(o.options)||o.options.length===0)&&r.push(`${n}.fields[${a}].options: a select field needs options`),o.type==="range"&&!(typeof o.min=="number"&&typeof o.max=="number"&&o.min<o.max)&&r.push(`${n}.fields[${a}]: a range field needs numeric min < max`))})}if(e==="Plot"&&Pf(t,n,r),e==="Scatter"&&Array.isArray(t.series)){let i=0;t.series.forEach((o,a)=>{!$e(o)||!Array.isArray(o.points)||(i+=o.points.length,o.points.forEach((s,l)=>{if($e(s))for(let u of["x","y"]){let c=s[u];c!==null&&!(typeof c=="number"&&Number.isFinite(c))&&r.push(`${n}.series[${a}].points[${l}].${u}: expected a finite number or null`)}}))}),i>K.scatterPoints&&r.push(`${n}.series: ${i} points in total; at most ${K.scatterPoints}`)}if(e==="CodeDiff"&&Array.isArray(t.files)){let i=0;t.files.forEach((o,a)=>{if(!$e(o))return;let s=o.patch!==void 0;s&&(o.before!==void 0||o.after!==void 0)&&r.push(`${n}.files[${a}]: use either patch or before/after, not both`),!s&&o.before===void 0&&o.after===void 0&&r.push(`${n}.files[${a}]: needs before/after text or a patch`);for(let l of["before","after","patch"])typeof o[l]=="string"&&(i+=o[l].length)}),i>K.diffChars&&r.push(`${n}.files: ${i} characters in total; at most ${K.diffChars}`)}if(e==="JsonView"&&t.data!==void 0){let i;try{i=JSON.stringify(t.data)}catch{i=void 0}i===void 0?r.push(`${n}.data: must be a JSON value`):i.length>K.jsonChars?r.push(`${n}.data: ${i.length} characters; at most ${K.jsonChars}`):Bs(t.data)>K.jsonDepth&&r.push(`${n}.data: nested deeper than ${K.jsonDepth} levels`)}e==="Heatmap"&&Array.isArray(t.values)&&Array.isArray(t.xLabels)&&Array.isArray(t.yLabels)&&(t.values.length!==t.yLabels.length&&r.push(`${n}.values: has ${t.values.length} rows but yLabels has ${t.yLabels.length}`),t.values.forEach((i,o)=>{Array.isArray(i)&&(i.length!==t.xLabels.length&&r.push(`${n}.values[${o}]: has ${i.length} values but xLabels has ${t.xLabels.length}`),i.forEach((a,s)=>{a!==null&&!(typeof a=="number"&&Number.isFinite(a))&&r.push(`${n}.values[${o}][${s}]: expected a finite number or null`)}))}),typeof t.min=="number"&&typeof t.max=="number"&&!(t.min<t.max)&&r.push(`${n}: min must be less than max`))}function Bs(e,t=0){if(t>K.jsonDepth||e===null||typeof e!="object")return t;let n=t+1;for(let r of Array.isArray(e)?e:Object.values(e))n=Math.max(n,Bs(r,t+1));return n}var Tf=/^[A-Za-z_][A-Za-z_0-9]*$/,Af=new Set(["x","pi","e","tau",...Object.keys(Ir)]);function Pf(e,t,n){let r=typeof e.xMin=="number"?e.xMin:-10,i=typeof e.xMax=="number"?e.xMax:10;r<i||n.push(`${t}: xMin must be less than xMax`),typeof e.yMin=="number"&&typeof e.yMax=="number"&&!(e.yMin<e.yMax)&&n.push(`${t}: yMin must be less than yMax`);let o=[];Array.isArray(e.params)&&e.params.forEach((a,s)=>{if(!$e(a)||typeof a.name!="string")return;let l=`${t}.params[${s}]`;Tf.test(a.name)?Af.has(a.name)?n.push(`${l}.name: "${a.name}" is reserved`):o.includes(a.name)&&n.push(`${l}.name: duplicate parameter "${a.name}"`):n.push(`${l}.name: must be an identifier like "a" or "omega"`),o.push(a.name),typeof a.min=="number"&&typeof a.max=="number"&&(a.min<a.max?typeof a.value=="number"&&(a.value<a.min||a.value>a.max)&&n.push(`${l}.value: must lie within [min, max]`):n.push(`${l}: min must be less than max`))}),Array.isArray(e.functions)&&e.functions.forEach((a,s)=>{if(!$e(a)||typeof a.expr!="string")return;let l=Os(a.expr,["x",...o]);l&&n.push(`${t}.functions[${s}].expr: ${l}`)})}function Xi(e,t,n="props"){let r=nr(e);if(!r)return[`${n}: unknown component type ${JSON.stringify(e)}; use one of ${Gi().join(", ")}`];let i=t===void 0?{}:t;if(!$e(i))return[`${n}: expected object, got ${qt(i)}`];let o=[];if(r.propsSchema){try{Je(r.propsSchema,i)}catch(a){o.push(`${n}: ${a.message}`)}return o}return Us(i,r.props,n,o),Nf(e,i,n,o),o}function Tr(e){let t=[],n=[],r={};if(!$e(e))return{ok:!1,errors:["arguments: expected object"],warnings:n,types:r,count:0};let{root:i,components:o}=e;if(e.title!==void 0&&typeof e.title!="string"&&t.push("title: expected string"),(typeof i!="string"||i==="")&&t.push("root: expected the id of the top-level component"),!Array.isArray(o)||o.length===0)return t.push("components: expected a non-empty array"),{ok:!1,errors:t,warnings:n,types:r,count:0};o.length>K.components&&t.push(`components: more than ${K.components} nodes`);let a=new Map;o.forEach((l,u)=>{let c=`components[${u}]`;if(!$e(l)){t.push(`${c}: expected object`);return}if(typeof l.id!="string"||l.id===""){t.push(`${c}.id: expected non-empty string`);return}if(a.has(l.id)){t.push(`${c}.id: duplicate id ${JSON.stringify(l.id)}`);return}a.set(l.id,l),Object.hasOwn(tr,l.type)&&$e(l.props)&&"children"in l.props&&(l.children===void 0&&Array.isArray(l.props.children)&&(l.children=l.props.children),delete l.props.children);let d=nr(l.type);r[l.type]=(r[l.type]||0)+1,t.push(...Xi(l.type,l.props,`${c}(${l.id}).props`)),t.push(...Yi(l.type,l.componentVersion).map(p=>`${c}(${l.id}).${p}`)),l.children!==void 0&&(!Array.isArray(l.children)||l.children.some(p=>typeof p!="string")?t.push(`${c}(${l.id}).children: expected array of component ids`):d&&!d.children&&l.children.length>0&&t.push(`${c}(${l.id}).children: ${l.type} cannot have children`));for(let p of Object.keys(l))["id","type","componentVersion","props","children"].includes(p)||t.push(`${c}(${l.id}).${p}: unknown field`)});let s=new Map;for(let l of a.values())if(Array.isArray(l.children))for(let u of l.children){if(!a.has(u)){t.push(`${l.id}.children: unknown id ${JSON.stringify(u)}`);continue}if(u===i){t.push(`${l.id}.children: the root ${JSON.stringify(i)} cannot be a child`);continue}if(s.has(u)){t.push(`${u}: has two parents (${s.get(u)} and ${l.id})`);continue}s.set(u,l.id)}if(typeof i=="string"&&i!==""&&!a.has(i)&&t.push(`root: unknown id ${JSON.stringify(i)}`),a.has(i)){let l=new Set,u=(d,p,f)=>{if(f.has(d)){t.push(`cycle through ${JSON.stringify(d)}`);return}if(p>K.depth){t.push(`nesting deeper than ${K.depth} at ${JSON.stringify(d)}`);return}if(l.has(d))return;l.add(d);let m=a.get(d);if(!(!m||!Array.isArray(m.children))){f.add(d);for(let h of m.children)a.has(h)&&u(h,p+1,f);f.delete(d)}};u(i,0,new Set);let c=[...a.keys()].filter(d=>!l.has(d));c.length>0&&n.push(`not reachable from root (not rendered): ${c.join(", ")}`)}for(let l of a.values()){if(l.type!=="Tabs"||!$e(l.props)||!Array.isArray(l.props.labels))continue;let u=Array.isArray(l.children)?l.children.length:0;u!==l.props.labels.length&&t.push(`${l.id}: Tabs has ${l.props.labels.length} labels but ${u} children`)}return{ok:t.length===0,errors:t,warnings:n,types:r,count:a.size}}function Me(e){return e==null}function Pr(e){return e&&typeof e=="object"&&!Array.isArray(e)}function qs(e,t){return Object.fromEntries(Object.entries(e).filter(([n,r])=>t(n,r)))}function ct(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,t(r,n)]))}function Vs(e,t,n){if(!t)return{...e};let r={};for(let i of t)(n||e[i]!==void 0)&&(r[i]=e[i]);return r}var Ws=Symbol.for("cosmokit.volatile.write");function Qi(e,t=new Set){if(typeof e=="function")throw new TypeError("volatile config cannot contain functions");if(e===null||typeof e!="object")return e;if(t.has(e))throw new TypeError("volatile config cannot contain cycles");t.add(e);try{if(Array.isArray(e))return Object.freeze(e.map(n=>Qi(n,t)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("volatile config objects must be plain objects or arrays");return Object.freeze(Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Qi(r,t)])))}finally{t.delete(e)}}function Zi(e){let t=Qi(e);return Object.freeze({get:()=>t,[Ws]:n=>{t=n}})}function Cn(e){return typeof e=="object"&&e!==null&&Ws in e}function At(e,t){return arguments.length===1?n=>At(e,n):e in globalThis&&t instanceof globalThis[e]||Object.prototype.toString.call(t).slice(8,-1)===e}function Or(e){return At("ArrayBuffer",e)||At("SharedArrayBuffer",e)}function Of(e){return Or(e)||ArrayBuffer.isView(e)}var Ke;(function(e){e.is=Or,e.isSource=Of;function t(a){return ArrayBuffer.isView(a)?a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength):a}e.fromSource=t;function n(a){if(a=t(a),typeof Buffer<"u")return Buffer.from(a).toString("base64");let s="",l=new Uint8Array(a);for(let u=0;u<l.byteLength;u++)s+=String.fromCharCode(l[u]);return btoa(s)}e.toBase64=n;function r(a){return typeof Buffer<"u"?t(Buffer.from(a,"base64")):Uint8Array.from(atob(a),s=>s.charCodeAt(0))}e.fromBase64=r;function i(a){return a=t(a),typeof Buffer<"u"?Buffer.from(a).toString("hex"):Array.from(new Uint8Array(a),s=>s.toString(16).padStart(2,"0")).join("")}e.toHex=i;function o(a){if(typeof Buffer<"u")return t(Buffer.from(a,"hex"));let s=a.length%2===0?a:a.slice(0,a.length-1),l=[];for(let u=0;u<s.length;u+=2)l.push(parseInt(`${s[u]}${s[u+1]}`,16));return Uint8Array.from(l).buffer}e.fromHex=o})(Ke||(Ke={}));var Jb=Ke.fromBase64,Kb=Ke.toBase64,Gb=Ke.fromHex,Yb=Ke.toHex;function Ar(e,t=new Map){if(!e||typeof e!="object")return e;if(At("Date",e))return new Date(e.valueOf());if(At("RegExp",e))return new RegExp(e.source,e.flags);if(Or(e))return e.slice(0);if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);let n=t.get(e);if(n)return n;if(Array.isArray(e)){let i=[];return t.set(e,i),e.forEach((o,a)=>{i[a]=Reflect.apply(Ar,null,[o,t])}),i}let r=Object.create(Object.getPrototypeOf(e));t.set(e,r);for(let i of Reflect.ownKeys(e)){let o={...Reflect.getOwnPropertyDescriptor(e,i)};"value"in o&&(o.value=Reflect.apply(Ar,null,[o.value,t])),Reflect.defineProperty(r,i,o)}return r}function $r(e,t,n){let r=new Set;function i(o,a){if(o===a)return!0;if(Cn(o)||Cn(a))return Cn(o)&&Cn(a);if(!n&&Me(o)&&Me(a))return!0;if(typeof o!=typeof a||typeof o!="object"||!o||!a||r.has(o))return!1;function s(l,u){return l(o)?l(a)?u(o,a):!1:l(a)?!1:void 0}r.add(o);try{return s(Array.isArray,(l,u)=>{if(l.length!==u.length)return!1;for(let c=0;c<l.length;c++)if(!i(l[c],u[c]))return!1;return!0})??s(At("Date"),(l,u)=>l.valueOf()===u.valueOf())??s(At("URL"),(l,u)=>l.href===u.href)??s(At("RegExp"),(l,u)=>l.source===u.source&&l.flags===u.flags)??s(Or,(l,u)=>{if(l.byteLength!==u.byteLength)return!1;let c=new Uint8Array(l),d=new Uint8Array(u);for(let p=0;p<c.length;p++)if(c[p]!==d[p])return!1;return!0})??((!n||[o,a].every(l=>Object.getPrototypeOf(l)===Object.prototype||Object.getPrototypeOf(l)===null))&&Object.keys({...o,...a}).every(l=>i(o[l],a[l])))}finally{r.delete(o)}}return i(e,t)}var Hs;(function(e){e.millisecond=1,e.second=1e3,e.minute=e.second*60,e.hour=e.minute*60,e.day=e.hour*24,e.week=e.day*7;let t=new Date().getTimezoneOffset();function n(f){t=f}e.setTimezoneOffset=n;function r(){return t}e.getTimezoneOffset=r;function i(f=new Date,m){return typeof f=="number"&&(f=new Date(f)),m===void 0&&(m=t),Math.floor((f.valueOf()/e.minute-m)/1440)}e.getDateNumber=i;function o(f,m){let h=new Date(f*e.day);return m===void 0&&(m=t),new Date(+h+m*e.minute)}e.fromDateNumber=o;let a=/\d+(?:\.\d+)?/.source,s=new RegExp(`^${["w(?:eek(?:s)?)?","d(?:ay(?:s)?)?","h(?:our(?:s)?)?","m(?:in(?:ute)?(?:s)?)?","s(?:ec(?:ond)?(?:s)?)?"].map(f=>`(${a}${f})?`).join("")}$`);function l(f){let m=s.exec(f);return m?(parseFloat(m[1])*e.week||0)+(parseFloat(m[2])*e.day||0)+(parseFloat(m[3])*e.hour||0)+(parseFloat(m[4])*e.minute||0)+(parseFloat(m[5])*e.second||0):0}e.parseTime=l;function u(f){let m=l(f);return m?f=Date.now()+m:/^\d{1,2}(:\d{1,2}){1,2}$/.test(f)?f=`${new Date().toLocaleDateString()}-${f}`:/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(f)&&(f=`${new Date().getFullYear()}-${f}`),f?new Date(f):new Date}e.parseDate=u;function c(f){let m=Math.abs(f);return m>=e.day-e.hour/2?Math.round(f/e.day)+"d":m>=e.hour-e.minute/2?Math.round(f/e.hour)+"h":m>=e.minute-e.second/2?Math.round(f/e.minute)+"m":m>=e.second?Math.round(f/e.second)+"s":f+"ms"}e.format=c;function d(f,m=2){return f.toString().padStart(m,"0")}e.toDigits=d;function p(f,m=new Date){return f.replace("yyyy",m.getFullYear().toString()).replace("yy",m.getFullYear().toString().slice(2)).replace("MM",d(m.getMonth()+1)).replace("dd",d(m.getDate())).replace("hh",d(m.getHours())).replace("mm",d(m.getMinutes())).replace("ss",d(m.getSeconds())).replace("SSS",d(m.getMilliseconds(),3))}e.template=p})(Hs||(Hs={}));var ir=Symbol.for("schemastery"),Gs=Symbol.for("ValidationError");globalThis.__schemastery_index__??(globalThis.__schemastery_index__=0);globalThis.__schemastery_refs__=void 0;var ee=class extends TypeError{constructor(t,n){let r="$";for(let i of n.path||[])typeof i=="string"?r+="."+i:typeof i=="number"?r+="["+i+"]":typeof i=="symbol"&&(r+=`[Symbol(${i.toString()})]`);r.startsWith(".")&&(r=r.slice(1));super((r==="$"?"":`${r} `)+t);be(this,"options");be(this,"name","ValidationError");this.options=n}static is(t){return!!t?.[Gs]}};Object.defineProperty(ee.prototype,Gs,{value:!0});var $=function(e){let t=function(n,r={}){return $.resolve(n,t,r)[0]};if(e.refs){let n=ct(e.refs,i=>new $(i)),r=i=>n[i];for(let i in n){let o=n[i];o.sKey=r(o.sKey),o.inner=r(o.inner),o.list=o.list&&o.list.map(r),o.dict=o.dict&&ct(o.dict,r)}return n[e.uid]}if(Object.assign(t,e),typeof t.callback=="string")try{t.callback=new Function("return "+t.callback)()}catch{}return Object.defineProperty(t,"uid",{value:globalThis.__schemastery_index__++}),Object.setPrototypeOf(t,$.prototype),t.meta||(t.meta={}),t.toString=t.toString.bind(t),t};$.prototype=Object.create(Function.prototype);$.prototype[ir]=!0;Object.defineProperty($.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:e=>{try{return{value:$.resolve(e,this,{})[0]}}catch(t){if(ee.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}}}}});$.ValidationError=ee;$.prototype.toJSON=function(){var n,r;if(globalThis.__schemastery_refs__)return(n=globalThis.__schemastery_refs__)[r=this.uid]??(n[r]=JSON.parse(JSON.stringify({...this}))),this.uid;globalThis.__schemastery_refs__={[this.uid]:{...this}},globalThis.__schemastery_refs__[this.uid]=JSON.parse(JSON.stringify({...this}));let t={uid:this.uid,refs:globalThis.__schemastery_refs__};return globalThis.__schemastery_refs__=void 0,t};$.prototype.set=function(t,n){return this.dict[t]=n,this};$.prototype.push=function(t){return this.list.push(t),this};function $f(e,t){let n=typeof e=="string"?{"":e}:{...e};for(let r in t){let i=t[r];i?.$description||i?.$desc?n[r]=i.$description||i.$desc:typeof i=="string"&&(n[r]=i)}return n}function rr(e){return e?.$value??e?.$inner}function Js(e){return qs(e??{},t=>!t.startsWith("$"))}$.prototype.i18n=function(t){let n=$(this),r=$f(n.meta.description,t);return Object.keys(r).length&&(n.meta.description=r),n.dict&&(n.dict=ct(n.dict,(i,o)=>i.i18n(ct(t,a=>rr(a)?.[o]??a?.[o])))),n.list&&(n.list=n.list.map((i,o)=>i.i18n(ct(t,(a={})=>Array.isArray(rr(a))?rr(a)[o]:Array.isArray(a)?a[o]:Js(a))))),n.inner&&(n.inner=n.inner.i18n(ct(t,i=>rr(i)?rr(i):Js(i)))),n.sKey&&(n.sKey=n.sKey.i18n(ct(t,i=>i?.$key))),n};$.prototype.extra=function(t,n){let r=$(this);return r.meta={...r.meta,[t]:n},r};for(let e of["required","disabled","collapse","hidden","loose"])Object.assign($.prototype,{[e](t=!0){let n=$(this);return n.meta={...n.meta,[e]:t},n}});$.prototype.deprecated=function(){var n;let t=$(this);return(n=t.meta).badges||(n.badges=[]),t.meta.badges.push({text:"deprecated",type:"danger"}),t};$.prototype.experimental=function(){var n;let t=$(this);return(n=t.meta).badges||(n.badges=[]),t.meta.badges.push({text:"experimental",type:"warning"}),t};$.prototype.pattern=function(t){let n=$(this),r=Vs(t,["source","flags"]);return n.meta={...n.meta,pattern:r},n};$.prototype.simplify=function(t){if(Cn(t)&&(t=t.get()),$r(t,this.meta.default,this.type==="dict"))return null;if(Me(t))return t;if(this.type==="object"||this.type==="dict"){let n={};for(let r in t){let i=(this.type==="object"?this.dict[r]:this.inner)?.simplify(t[r]);(this.type==="dict"||!Me(i))&&(n[r]=i)}return $r(n,this.meta.default,this.type==="dict")?null:n}else if(this.type==="array"||this.type==="tuple"){let n=[];return t.forEach((r,i)=>{let o=this.type==="array"?this.inner:this.list[i],a=o?o.simplify(r):r;n.push(a)}),n}else if(this.type==="intersect"){let n={};for(let r of this.list)Object.assign(n,r.simplify(t));return n}else if(this.type==="union")for(let n of this.list)try{return $.resolve(t,n,{}),n.simplify(t)}catch{}return t};$.prototype.toString=function(t){return Xs[this.type]?.(this,t)??`Schema<${this.type}>`};$.prototype.role=function(e,t){let n=$(this);return n.meta={...n.meta,role:e,extra:t},n};for(let e of["default","link","comment","description","max","min","step"])Object.assign($.prototype,{[e](t){let n=$(this);return n.meta={...n.meta,[e]:t},n}});$.prototype.volatile=function(){if(this.meta.volatile)throw new TypeError("volatile schema is already wrapped");return this.extra("volatile",!0)};var Ys={},Ks=Symbol("checked-volatile-schema");function En(e,t=[],n=!1,r=new Map){let i=r.get(e)??new Set;if(i.has(n))return;if(i.add(n),r.set(e,i),e.meta?.volatile&&n)throw new ee("volatile fields require a fixed object path without an enclosing volatile field",{path:t});let o=n||!!e.meta?.volatile;if(e.dict)for(let[a,s]of Object.entries(e.dict))En(s,[...t,a],o,r);if(e.sKey&&En(e.sKey,[...t,"<key>"],!0,r),e.inner&&(e.type!=="lazy"||e.inner[ir])&&En(e.inner,[...t,"*"],!0,r),e.list)for(let a=0;a<e.list.length;a++)En(e.list[a],[...t,String(a)],!0,r)}$.extend=function(t,n){Ys[t]=n};$.resolve=function(t,n,r={},i=!1){if(!n)return[t];if(r[Ks]||(En(n,r.path),r={...r,[Ks]:!0}),n.meta?.volatile){let a=$(n);a.meta={...n.meta,volatile:!1};let[s,l]=$.resolve(t,a,r,i);try{return[Zi(s),l]}catch(u){throw new ee(u instanceof Error?u.message:String(u),r)}}if(r.ignore?.(t,n))return[t];if(Me(t)&&n.type!=="lazy"){if(n.meta.required)throw new ee("missing required value",r);let a=n,s=n.meta.default;for(;a?.type==="intersect"&&Me(s);)a=a.list[0],s=a?.meta.default;if(Me(s))return[t];t=Ar(s)}let o=Ys[n.type];if(!o)throw new ee(`unsupported type "${n.type}"`,r);try{return o(t,n,r,i)}catch(a){if(!n.meta.loose)throw a;return[n.meta.default]}};$.from=function(t){if(Me(t))return $.any();if(["string","number","boolean"].includes(typeof t))return $.const(t).required();if(t[ir])return t;if(typeof t=="function")switch(t){case String:return $.string().required();case Number:return $.number().required();case Boolean:return $.boolean().required();case Function:return $.function().required();default:return $.is(t).required()}else throw new TypeError(`cannot infer schema from ${t}`)};$.lazy=function(t){let n=()=>(r.inner[ir]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),r=new $({type:"lazy",builder:t,inner:{toJSON:n}});return r};$.natural=function(){return $.number().step(1).min(0)};$.percent=function(){return $.number().step(.01).min(0).max(1).role("slider")};$.date=function(){return $.union([$.is(Date),$.transform($.string().role("datetime"),(t,n)=>{let r=new Date(t);if(isNaN(+r))throw new ee(`invalid date "${t}"`,n);return r},!0)])};$.regExp=function(t=""){return $.union([$.is(RegExp),$.transform($.string().role("regexp",{flag:t}),(n,r)=>{try{return new RegExp(n,t)}catch(i){throw new ee(i.message,r)}},!0)])};$.arrayBuffer=function(t){return $.union([$.is(ArrayBuffer),$.is(SharedArrayBuffer),$.transform($.any(),(n,r)=>{if(Ke.isSource(n))return Ke.fromSource(n);throw new ee(`expected ArrayBufferSource but got ${n}`,r)},!0),...t?[$.transform($.string(),(n,r)=>{try{return t==="base64"?Ke.fromBase64(n):Ke.fromHex(n)}catch(i){throw new ee(i.message,r)}},!0)]:[]])};$.extend("lazy",(e,t,n,r)=>(t.inner[ir]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta},En(t.inner,n.path,!0)),$.resolve(e,t.inner,n,r)));$.extend("any",e=>[e]);$.extend("never",(e,t,n)=>{throw new ee(`expected nullable but got ${e}`,n)});$.extend("const",(e,{value:t},n)=>{if($r(e,t))return[t];throw new ee(`expected ${t} but got ${e}`,n)});function no(e,t,n,r,i=!1){let{max:o=1/0,min:a=-1/0}=t;if(e>o)throw new ee(`expected ${n} <= ${o} but got ${e}`,r);if(e<a&&!i)throw new ee(`expected ${n} >= ${a} but got ${e}`,r)}$.extend("string",(e,{meta:t},n)=>{if(typeof e!="string")throw new ee(`expected string but got ${e}`,n);if(t.pattern){let r=new RegExp(t.pattern.source,t.pattern.flags);if(!r.test(e))throw new ee(`expect string to match regexp ${r}`,n)}return no(e.length,t,"string length",n),[e]});function eo(e,t){let n=e.toString();if(n.includes("e"))return e*Math.pow(10,t);let r=n.indexOf(".");if(r===-1)return e*Math.pow(10,t);let i=n.slice(r+1),o=n.slice(0,r);return i.length<=t?+(o+i.padEnd(t,"0")):+(o+i.slice(0,t)+"."+i.slice(t))}function Mf(e,t,n){if(n=Math.abs(n),!/^\d+\.\d+$/.test(n.toString()))return(e-t)%n===0;let r=n.toString().indexOf("."),i=n.toString().slice(r+1).length;return Math.abs(eo(e,i)-eo(t,i))%eo(n,i)===0}$.extend("number",(e,{meta:t},n)=>{if(typeof e!="number")throw new ee(`expected number but got ${e}`,n);no(e,t,"number",n);let{step:r}=t;if(r&&!Mf(e,t.min??0,r))throw new ee(`expected number multiple of ${r} but got ${e}`,n);return[e]});$.extend("boolean",(e,t,n)=>{if(typeof e=="boolean")return[e];throw new ee(`expected boolean but got ${e}`,n)});$.extend("bitset",(e,{bits:t,meta:n},r)=>{let i=0,o=[];if(typeof e=="number"){i=e;for(let a in t)e&t[a]&&o.push(a)}else if(Array.isArray(e)){o=e;for(let a of o){if(typeof a!="string")throw new ee(`expected string but got ${a}`,r);a in t&&(i|=t[a])}}else throw new ee(`expected number or array but got ${e}`,r);return i===n.default?[i]:[i,o]});$.extend("function",(e,t,n)=>{if(typeof e=="function")return[e];throw new ee(`expected function but got ${e}`,n)});$.extend("is",(e,{constructor:t},n)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new ee(`expected ${t.name} but got ${e}`,n)}else{if(Me(e))throw new ee(`expected ${t} but got ${e}`,n);let r=Object.getPrototypeOf(e);for(;r;){if(r.constructor?.name===t)return[e];r=Object.getPrototypeOf(r)}throw new ee(`expected ${t} but got ${e}`,n)}});function Mr(e,t,n,r){try{let[i,o]=$.resolve(e[t],n,{...r,path:[...r.path||[],t]});return o!==void 0&&(e[t]=o),i}catch(i){if(!r?.autofix)throw i;return delete e[t],n.meta.volatile?Zi(n.meta.default):n.meta.default}}$.extend("array",(e,{inner:t,meta:n},r)=>{if(!Array.isArray(e))throw new ee(`expected array but got ${e}`,r);return no(e.length,n,"array length",r,!Me(t.meta.default)),[e.map((i,o)=>Mr(e,o,t,r))]});$.extend("dict",(e,{inner:t,sKey:n},r,i)=>{if(!Pr(e))throw new ee(`expected object but got ${e}`,r);let o={};for(let a in e){let s;try{s=$.resolve(a,n,r)[0]}catch(l){if(i)continue;throw l}o[s]=Mr(e,a,t,r),e[s]=e[a],a!==s&&delete e[a]}return[o]});$.extend("tuple",(e,{list:t},n,r)=>{if(!Array.isArray(e))throw new ee(`expected array but got ${e}`,n);let i=t.map((o,a)=>Mr(e,a,o,n));return r?[i]:(i.push(...e.slice(t.length)),[i])});function to(e,t){for(let n in t)n in e||(e[n]=t[n])}$.extend("object",(e,{dict:t},n,r)=>{if(!Pr(e))throw new ee(`expected object but got ${e}`,n);let i={};for(let o in t){let a=Mr(e,o,t[o],n);(!Me(a)||o in e)&&(i[o]=a)}return r||to(i,e),[i]});$.extend("union",(e,{list:t,toString:n},r,i)=>{let o=[];for(let a of t)try{return $.resolve(e,a,r,i)}catch(s){o.push(s)}throw new ee(`expected ${n()} but got ${JSON.stringify(e)}`,r)});$.extend("intersect",(e,{list:t,toString:n},r,i)=>{if(!t.length)return[e];let o;for(let a of t){let s=$.resolve(e,a,r,!0)[0];if(!Me(s))if(Me(o))o=s;else{if(typeof o!=typeof s)throw new ee(`expected ${n()} but got ${JSON.stringify(e)}`,r);if(typeof s=="object")to(o??(o={}),s);else if(o!==s)throw new ee(`expected ${n()} but got ${JSON.stringify(e)}`,r)}}return!i&&Pr(e)&&to(o,e),[o]});$.extend("transform",(e,{inner:t,callback:n,preserve:r},i)=>{let[o,a=e]=$.resolve(e,t,i,!0);return r?[n(o)]:[n(o),n(a)]});var Xs={};function Ce(e,t,n){Xs[e]=n,Object.assign($,{[e](...r){let i=new $({type:e});return t.forEach((o,a)=>{switch(o){case"sKey":i.sKey=r[a]??$.string();break;case"inner":i.inner=$.from(r[a]);break;case"list":i.list=r[a].map($.from);break;case"dict":i.dict=ct(r[a],$.from);break;case"bits":i.bits={};for(let s in r[a])typeof r[a][s]=="number"&&(i.bits[s]=r[a][s]);break;case"callback":{let s=i.callback=r[a];s.toJSON||(s.toJSON=()=>s.toString());break}case"constructor":{let s=i.constructor=r[a];typeof s=="function"&&(s.toJSON||(s.toJSON=()=>s.name));break}default:i[o]=r[a]}}),e==="object"||e==="dict"?i.meta.default={}:e==="array"||e==="tuple"?i.meta.default=[]:e==="bitset"&&(i.meta.default=0),i}})}Ce("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);Ce("any",[],()=>"any");Ce("never",[],()=>"never");Ce("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);Ce("string",[],()=>"string");Ce("number",[],()=>"number");Ce("boolean",[],()=>"boolean");Ce("bitset",["bits"],()=>"bitset");Ce("function",[],()=>"function");Ce("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);Ce("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);Ce("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);Ce("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,n])=>`${t}${n.meta.required?"":"?"}: ${n.toString()}`).join(", ")} }`);Ce("union",["list"],({list:e},t)=>{let n=e.map(({toString:r})=>r()).join(" | ");return t?`(${n})`:n});Ce("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);Ce("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t));var dt=Object.freeze({enableCatalog:!0,enableWidget:!0,enableCompose:!0,injectGuidance:!0,cdnAllowlist:["https://esm.sh","https://cdn.jsdelivr.net","https://unpkg.com"],allowNetwork:!1,maxWidgetHeight:2400,maxWidgetBytes:4e5,sendPromptMaxChars:4e3,openLinkAllowedOrigins:[]}),ix=$.object({enableCatalog:$.boolean().default(dt.enableCatalog).description("Register `ui_render` (declarative cards, tables, charts, forms)."),enableWidget:$.boolean().default(dt.enableWidget).description("Register `ui_render_widget` (sandboxed streaming HTML/CSS/JS widgets)."),enableCompose:$.boolean().default(dt.enableCompose).description("Register `ui_compose` (one answer that interleaves markdown, native components and widgets). Needs at least one UI capability."),injectGuidance:$.boolean().default(dt.injectGuidance).description("Add a system-prompt section telling the model when and how to answer with UI."),cdnAllowlist:$.array($.string()).default([...dt.cdnAllowlist]).description("Origins widgets may load scripts, styles, fonts and images from (CSP)."),allowNetwork:$.boolean().default(dt.allowNetwork).description("Allow widgets to fetch()/WebSocket to the CDN allowlist (CSP connect-src). Off: no network calls."),maxWidgetHeight:$.natural().min(200).max(8e3).default(dt.maxWidgetHeight).description("Maximum widget frame height in pixels."),maxWidgetBytes:$.natural().min(1e4).default(dt.maxWidgetBytes).description("Reject widgets whose html+css+js exceed this many characters."),sendPromptMaxChars:$.natural().min(100).max(2e4).default(dt.sendPromptMaxChars).description("Longest message a widget, button or form may send back to the conversation."),openLinkAllowedOrigins:$.array($.string()).default([]).description("If non-empty, widgets may only open https links on these origins.")});var Vt="ui_render_widget";function Zs(e,t){let n=[];if(typeof e!="object"||e===null)return["arguments: expected object"];let r=(o,a)=>{let s=e[o];if(s===void 0){a&&n.push(`${o}: required`);return}typeof s!="string"&&n.push(`${o}: expected string`)};r("title"),r("css"),r("html",!0),r("jsFunctions"),typeof e.html=="string"&&e.html.trim()===""&&n.push("html: must not be empty");for(let o of["placeholderMessages","jsExpressions"]){let a=e[o];a!==void 0&&(!Array.isArray(a)||a.some(s=>typeof s!="string"))&&n.push(`${o}: expected array of strings`)}e.initialHeight!==void 0&&(typeof e.initialHeight!="number"||!Number.isFinite(e.initialHeight)||e.initialHeight<=0)&&n.push("initialHeight: expected positive number"),typeof e.html=="string"&&/<script[\s>]/i.test(e.html)&&n.push("html: must not contain <script>; put code in jsFunctions/jsExpressions");let i=["css","html","jsFunctions"].reduce((o,a)=>o+(typeof e[a]=="string"?e[a].length:0),0)+(Array.isArray(e.jsExpressions)?e.jsExpressions.join("").length:0);return i>t.maxWidgetBytes&&n.push(`widget is ${i} characters; the limit is ${t.maxWidgetBytes}`),n}var ft="ui_compose";var pt=Object.freeze({blocks:24,markdownChars:6e4,totalChars:2e5,titleChars:200,idChars:64}),el=Object.freeze(["markdown","catalog","widget"]),tl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ro(e,t){return`${e}#${t}`}var Lf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,nl=Object.freeze({markdown:["id","type","text"],catalog:["id","type","title","root","components"],widget:["id","type","title","initialHeight","placeholderMessages","css","html","jsFunctions","jsExpressions"]});function io(e,t,n={}){let r=[],i=[],o={markdown:0,catalog:0,widget:0,components:0,markdownChars:0};if(!tl(e))return{ok:!1,errors:["arguments: expected object"],warnings:i,blocks:[],stats:o};for(let u of Object.keys(e))u!=="title"&&u!=="blocks"&&r.push(`${u}: unknown field`);if(e.title!==void 0&&(typeof e.title!="string"?r.push("title: expected string"):e.title.length>pt.titleChars&&r.push(`title: longer than ${pt.titleChars} characters`)),!Array.isArray(e.blocks)||e.blocks.length===0)return r.push("blocks: expected a non-empty ordered array"),{ok:!1,errors:r,warnings:i,blocks:[],stats:o};e.blocks.length>pt.blocks&&r.push(`blocks: more than ${pt.blocks} blocks`);let a=new Set,s=[],l=0;return e.blocks.forEach((u,c)=>{let d=`blocks[${c}]`;if(!tl(u)){r.push(`${d}: expected object`);return}if(typeof u.id!="string"||u.id===""){r.push(`${d}.id: expected a non-empty string`);return}if(!Lf.test(u.id)){r.push(`${d}.id: ${JSON.stringify(u.id)} must start with a letter and use only letters, digits, "_" or "-" (max ${pt.idChars})`);return}if(a.has(u.id)){r.push(`${d}.id: duplicate block id ${JSON.stringify(u.id)}`);return}if(a.add(u.id),!el.includes(u.type)){r.push(`${d}.type: expected one of ${el.join(" | ")}, got ${JSON.stringify(u.type)}`);return}let p=nl[u.type];for(let m of Object.keys(u))p.includes(m)||r.push(`${d}(${u.id}).${m}: unknown field for a ${u.type} block`);if(u.type==="catalog"&&n.requireCatalog===!1){r.push(`${d}(${u.id}): catalog blocks are disabled on this host`);return}if(u.type==="widget"&&n.requireWidget===!1){r.push(`${d}(${u.id}): widget blocks are disabled on this host`);return}let f={id:u.id,type:u.type};if(u.type==="markdown"){if(typeof u.text!="string"){r.push(`${d}(${u.id}).text: expected string`);return}if(!u.text.trim()){r.push(`${d}(${u.id}).text: must not be blank`);return}if(u.text.length>pt.markdownChars){r.push(`${d}(${u.id}).text: ${u.text.length} characters; a markdown block holds at most ${pt.markdownChars}`);return}o.markdown++,o.markdownChars+=u.text.length,l+=u.text.length,f.text=u.text}else if(u.type==="catalog"){let m={root:u.root,components:u.components,...u.title!==void 0?{title:u.title}:{}},h=Tr(m);for(let b of h.errors)r.push(`${d}(${u.id}).${b}`);for(let b of h.warnings)i.push(`${u.id}: ${b}`);o.catalog++,o.components+=h.count,l+=JSON.stringify(m).length,f.title=typeof u.title=="string"?u.title:void 0,f.root=u.root,f.components=u.components}else{let m={};for(let h of nl.widget)h!=="type"&&u[h]!==void 0&&(m[h]=u[h]);for(let h of Zs(m,t))r.push(`${d}(${u.id}).${h}`);o.widget++,l+=["css","html","jsFunctions"].reduce((h,b)=>h+(typeof u[b]=="string"?u[b].length:0),0)+(Array.isArray(u.jsExpressions)?u.jsExpressions.join("").length:0);for(let h of["title","initialHeight","placeholderMessages","css","html","jsFunctions","jsExpressions"])u[h]!==void 0&&(f[h]=u[h])}s.push(f)}),!o.markdown&&!o.catalog&&!o.widget&&r.length===0&&r.push("blocks: a composition needs at least one block"),l>pt.totalChars&&r.push(`blocks: the composition is ${l} characters; the limit is ${pt.totalChars}`),{ok:r.length===0,errors:r,warnings:i,blocks:r.length?[]:s,stats:o}}var jf=Object.freeze(["setProps","replaceNode","insertChild","removeNode"]),Ff=Object.freeze({ops:50,nodesPerOp:K.components}),gx=Object.freeze({setProps:["id","props","unset"],replaceNode:["id","node","nodes"],insertChild:["parent","id","index","nodes"],removeNode:["id"]});var Wt="ui_render";var Jt="ui_patch";var jn=require("react");var Be=class extends Error{constructor(n,r){super(r);be(this,"code",n)}},He=class{constructor(t){be(this,"opts",t);be(this,"armedAt");be(this,"lastSend",-1/0);be(this,"now");be(this,"minInterval");this.now=t.now??(()=>Date.now()),this.armedAt=this.now()+(t.armDelayMs??1e3),this.minInterval=t.minIntervalMs??2e3}admitPrompt(t){let n=typeof t=="string"?t.trim():"";if(!n)throw new Be("empty","sendPrompt needs non-empty text");if(n.length>this.opts.policy.sendPromptMaxChars)throw new Be("too-long",`sendPrompt text exceeds ${this.opts.policy.sendPromptMaxChars} characters`);let r=this.now();if(r<this.armedAt)throw new Be("not-armed","sendPrompt is only allowed in response to a user action, not on load");if(r-this.lastSend<this.minInterval)throw new Be("rate-limited","sendPrompt called too often");return this.lastSend=r,n}admitLink(t){let n;try{n=new URL(String(t))}catch{throw new Be("bad-url","openLink needs an absolute https URL")}if(n.protocol!=="https:")throw new Be("bad-url","openLink only opens https URLs");let r=this.opts.policy.openLinkOrigins;if(r.length>0&&!r.some(i=>{try{return new URL(i).origin===n.origin}catch{return!1}}))throw new Be("origin",`openLink: ${n.origin} is not an allowed origin`);return n.href}};function rl(e,t,n){return`${t?.trim()||(e?`Form "${e}" submitted:`:"Form submitted:")}
6
+ `){n++;continue}let i=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(e.slice(n));if(i){t.push({t:"num",v:Number(i[0]),at:n}),n+=i[0].length;continue}let o=/^[A-Za-z_][A-Za-z_0-9]*/.exec(e.slice(n));if(o){t.push({t:"id",v:o[0],at:n}),n+=o[0].length;continue}if(e.startsWith("**",n)){t.push({t:"op",v:"^",at:n}),n+=2;continue}if("+-*/%^".includes(r)){t.push({t:"op",v:r,at:n}),n++;continue}if(r==="("||r===")"||r===","){t.push({t:r,v:r,at:n}),n++;continue}if(r==="·"||r==="×"){t.push({t:"op",v:"*",at:n}),n++;continue}throw new SyntaxError(`unexpected character ${JSON.stringify(r)} at ${n}`)}return t}function Hi(e,t){if(typeof e!="string"||!e.trim())throw new SyntaxError("empty expression");if(e.length>Ps)throw new SyntaxError(`longer than ${Ps} characters`);let n=new Set(t),r=bf(e),i=0,o=()=>r[i],a=m=>{throw new SyntaxError(m)},s=m=>{let h=r[i];(!h||h.t!==m)&&a(`expected "${m}" ${h?`at ${h.at}`:"at end"}`),i++};function l(){let m=u();for(;o()?.t==="op"&&(o().v==="+"||o().v==="-");){let h=r[i++].v,b=m,g=u();m=h==="+"?v=>b(v)+g(v):v=>b(v)-g(v)}return m}function u(){let m=c();for(;;){let h=o();if(h?.t==="op"&&(h.v==="*"||h.v==="/"||h.v==="%")){i++;let g=m,v=c();m=h.v==="*"?S=>g(S)*v(S):h.v==="/"?S=>g(S)/v(S):S=>g(S)%v(S);continue}let b=r[i-1];if(h&&(h.t==="id"||h.t==="("||h.t==="num")&&b&&(b.t==="num"||b.t===")")&&!(h.t==="num"&&b.t==="num")){let g=m,v=c();m=S=>g(S)*v(S);continue}return m}}function c(){let m=o();if(m?.t==="op"&&(m.v==="-"||m.v==="+")){i++;let h=c();return m.v==="-"?b=>-h(b):h}return d()}function d(){let m=p();if(o()?.t==="op"&&o().v==="^"){i++;let h=c();return b=>m(b)**h(b)}return m}function p(){let m=r[i++];if(m||a("unexpected end of expression"),m.t==="num"){let h=m.v;return()=>h}if(m.t==="("){let h=l();return s(")"),h}if(m.t==="id"){let h=String(m.v);if(o()?.t==="("){let g=As(Ir,h);g||a(`unknown function "${h}"; allowed: ${Object.keys(Ir).join(", ")}`),i++;let v=[];if(o()?.t!==")")for(v.push(l());o()?.t===",";)i++,v.push(l());s(")");let[S,O]=g;if(S>=0&&v.length!==S&&a(`${h}() takes ${S} argument(s), got ${v.length}`),S<0&&v.length===0&&a(`${h}() needs at least one argument`),v.length===1){let E=v[0];return C=>O(E(C))}if(v.length===2){let[E,C]=v;return P=>O(E(P),C(P))}return E=>O(...v.map(C=>C(E)))}if(n.has(h))return g=>g[h];let b=As(Ts,h);if(b!==void 0)return()=>b;a(`unknown variable "${h}"; available: ${[...n,...Object.keys(Ts)].join(", ")}`)}a(`unexpected "${m.v}" at ${m.at}`)}let f=l();return i<r.length&&a(`unexpected "${r[i].v}" at ${r[i].at}`),f}function Os(e,t){try{Hi(e,t);return}catch(n){return n instanceof Error?n.message:String(n)}}var kn=Object.freeze({dataBytes:512e3,argsBytes:16e3,resultBytes:64e3,resources:64,receipts:128}),qi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ht=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Y(e){throw new Error(e)}function Qn(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function vn(e,t){let n=(i,o=0)=>{if(o>20&&Y("JSON nesting exceeds limit"),!(i===null||typeof i=="string"||typeof i=="boolean")&&!(typeof i=="number"&&Number.isFinite(i))){!Ht(i)&&!Array.isArray(i)&&Y("Payload must be finite JSON");for(let a of Object.values(i))n(a,o+1)}};n(e);let r=JSON.stringify(e);return(r===void 0||new TextEncoder().encode(r).length>t)&&Y("Payload exceeds limit or is not JSON"),JSON.parse(r)}function ut(e){return e&&typeof e=="object"&&(Object.values(e).forEach(ut),Object.freeze(e)),e}function Je(e,t,n=!1,r=0){(r>12||!Ht(e))&&Y("Invalid schema");let i={object:["type","properties","required","additionalProperties"],array:["type","items","maxItems"],string:["type","maxLength","enum"],number:["type","minimum","maximum","enum"],integer:["type","minimum","maximum","enum"],boolean:["type"],null:["type"]}[e.type];(!i||Object.keys(e).some(o=>!i.includes(o)))&&Y("Unsupported schema keyword/type"),e.enum!==void 0&&(!Array.isArray(e.enum)||e.enum.length>100)&&Y("Invalid enum");for(let o of["maxLength","maxItems"])e[o]!==void 0&&(!Number.isSafeInteger(e[o])||e[o]<0)&&Y("Invalid schema bound");for(let o of["minimum","maximum"])e[o]!==void 0&&!Number.isFinite(e[o])&&Y("Invalid schema bound");if(e.type==="object"){(!Ht(e.properties)||e.additionalProperties!==!1||!Array.isArray(e.required??[])||(e.required??[]).some(o=>!qi(e.properties,o)))&&Y("Object schema requires properties and additionalProperties:false");for(let o of Object.values(e.properties))Je(o,void 0,!0,r+1)}if(e.type==="array"&&Je(e.items,void 0,!0,r+1),!n){if(e.type==="object"){(!Ht(t)||Object.keys(t).some(o=>!qi(e.properties,o))||(e.required??[]).some(o=>!qi(t,o)))&&Y("Arguments do not match schema");for(let[o,a]of Object.entries(t))Je(e.properties[o],a,!1,r+1)}else e.type==="array"?((!Array.isArray(t)||t.length>(e.maxItems??1e3))&&Y("Invalid array"),t.forEach(o=>Je(e.items,o,!1,r+1))):e.type==="null"?t!==null&&Y("Expected null"):typeof t!==(e.type==="integer"?"number":e.type)&&Y("Arguments do not match schema");typeof t=="number"&&(!Number.isFinite(t)||e.type==="integer"&&!Number.isSafeInteger(t)||t<(e.minimum??-1/0)||t>(e.maximum??1/0))&&Y("Invalid number"),typeof t=="string"&&t.length>(e.maxLength??16e3)&&Y("String exceeds limit"),e.enum&&!e.enum.includes(t)&&Y("Value is outside enum")}}function $s(e){(typeof e!="string"||!e)&&Y("Session id required");let t=new Map,n=new Map,r=new Map,i=new Set,o=!1,a=0,s=()=>{a++;for(let m of i)m()},l=()=>{o&&Y("Session disposed")},u=(m,h)=>JSON.stringify([m,h]),c=m=>(l(),(!m||m.sessionId!==e||typeof m.uiId!="string"||!m.uiId)&&Y("Scope denied"),m.uiId),d=(m,h)=>{(typeof m!="string"||!m||m.length>200||typeof h!="string"||!h||h.length>100)&&Y("Invalid resource id/scope")},p=()=>{l(),t.size+n.size>=kn.resources&&Y("Resource limit")},f={sessionId:e,subscribe(m){return o?()=>{}:(i.add(m),()=>i.delete(m))},getRevision(){return a},registerData(m,h,b){p(),d(m,h);let g=ut(vn(b,kn.dataBytes));(!Array.isArray(g.columns)||g.columns.length<1||g.columns.length>24||g.columns.some(O=>typeof O!="string")||!Array.isArray(g.rows)||g.rows.length>500||g.rows.some(O=>!Array.isArray(O)||O.length!==g.columns.length||O.some(E=>!(E===null||["string","boolean","number"].includes(typeof E)))))&&Y("Invalid dataset");let v=u(m,h);t.has(v)&&Y("Duplicate data id");let S={value:g,view:ut({search:"",filterColumn:-1,filterValue:"",sortColumn:-1,descending:!1,page:0})};return t.set(v,S),s(),()=>{t.get(v)===S&&(t.delete(v),s())}},readData(m,h){let b=c(m);(!Ht(h)||h.scope!==b||typeof h.id!="string")&&Y("Data scope denied");let g=t.get(u(b,h.id));return g||Y("Data unavailable (expired or unregistered)"),Object.freeze({value:g.value,view:g.view})},setView(m,h,b){let g=f.readData(m,h),v={...g.view,...vn(b,4e3)};(Object.keys(v).some(S=>!["search","filterColumn","filterValue","sortColumn","descending","page"].includes(S))||typeof v.search!="string"||typeof v.filterValue!="string"||typeof v.descending!="boolean"||![v.filterColumn,v.sortColumn].every(S=>Number.isInteger(S)&&S>=-1&&S<g.value.columns.length)||!Number.isSafeInteger(v.page)||v.page<0)&&Y("Invalid local query"),t.get(u(m.uiId,h.id)).view=ut(v),s()},registerAction(m,h,b){p(),d(m,h),Je(b.schema,void 0,!0),(!["read","write"].includes(b.effect)||typeof b.run!="function"||typeof b.authorize!="function"||b.effect==="write"&&typeof b.confirm!="function")&&Y("Action needs effect, authorize, run and write confirmation");let g=u(m,h);n.has(g)&&Y("Duplicate action id");let v={...b,schema:ut(vn(b.schema,16e3))};return n.set(g,v),()=>{n.get(g)===v&&n.delete(g)}},prepareAction(m,h){let b=c(m),g=vn(h,kn.argsBytes);(!Ht(g)||typeof g.actionId!="string"||g.requestId!==void 0&&(typeof g.requestId!="string"||!g.requestId||g.requestId.length>100))&&Y("Invalid action request");let v=n.get(u(b,g.actionId));return v||Y("Unregistered action"),Je(v.schema,g.args),ut({actionId:g.actionId,args:g.args,requestId:typeof g.requestId=="string"?g.requestId:Qn()})},async invokeAction(m,h,b){let g=c(m);(!(b instanceof Event)||!b.isTrusted||b.type!=="click")&&Y("Explicit trusted user click required"),(!Ht(h)||typeof h.actionId!="string"||typeof h.requestId!="string"||!h.requestId||h.requestId.length>100)&&Y("Invalid action request");let v=n.get(u(g,h.actionId));v||Y("Unregistered action"),h=ut(vn(h,kn.argsBytes)),m=ut({sessionId:m.sessionId,uiId:g});let S=h.args;Je(v.schema,S);let O=u(g,h.requestId),E=JSON.stringify([h.actionId,S]),C=r.get(O);if(C)return C.fingerprint!==E&&Y("Idempotency key reused with different arguments"),C.promise;r.size>=kn.receipts&&Y("Receipt limit reached; start a new surface/session");let P=ut({sessionId:e,uiId:g,requestId:h.requestId}),R=()=>{c(m),n.get(u(g,h.actionId))!==v&&Y("Action revoked")},F=!1,y=Promise.resolve().then(async()=>(R(),await v.authorize(P,S)!==!0&&Y("Action permission denied"),R(),v.effect==="write"&&await v.confirm(P,S)!==!0&&Y("Action cancelled"),R(),await v.authorize(P,S)!==!0&&Y("Action permission denied"),R(),F=!0,vn(await v.run(S,P),kn.resultBytes))).catch(x=>{throw!F&&r.get(O)?.promise===y&&r.delete(O),x});return r.set(O,{fingerprint:E,promise:y}),y},releaseScope(m){for(let h of[t,n,r])for(let b of h.keys())JSON.parse(b)[0]===m&&h.delete(b);s()},dispose(){o||(o=!0,t.clear(),n.clear(),r.clear(),s(),i.clear())}};return f}function Ms(e){let{value:t,view:n}=e,r=t.rows.filter(i=>(!n.search||i.some(o=>String(o??"").toLowerCase().includes(n.search.toLowerCase())))&&(n.filterColumn<0||String(i[n.filterColumn]??"")===n.filterValue));return n.sortColumn>=0&&(r=[...r].sort((i,o)=>{let a=i[n.sortColumn],s=o[n.sortColumn];return(typeof a=="number"&&typeof s=="number"?a-s:String(a??"").localeCompare(String(s??""),void 0,{numeric:!0}))*(n.descending?-1:1)})),{columns:t.columns,rows:r}}var Zn=1,Nr=new Map,Sn=new Map,Wi=new Set,xf=0,wf=0;function Ls(e){return Wi.add(e),()=>Wi.delete(e)}function Vi(){xf++;for(let e of Wi)e()}var js=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),kf=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function ce(e){throw new Error(`Catalog extension: ${e}`)}function Ji(e){return e&&typeof e=="object"&&(Object.values(e).forEach(Ji),Object.freeze(e)),e}function Ki(e,t=0){if(t>16&&ce("manifest nesting exceeds limit"),e===null||typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map(r=>Ki(r,t+1));(!js(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))&&ce("manifest must be plain JSON");let n=Object.create(null);for(let[r,i]of Object.entries(e))["__proto__","prototype","constructor"].includes(r)&&ce(`reserved key ${r}`),n[r]=Ki(i,t+1);return n}function Rs(e,t){(!js(e)||Object.keys(e).some(n=>!t.includes(n)))&&ce("unknown manifest field")}function Fs(e){let t=Ki(e);JSON.stringify(t).length>64e3&&ce("manifest exceeds limit"),Rs(t,["apiVersion","namespace","version","components"]),t.apiVersion!==Zn&&ce(`unsupported apiVersion; expected ${Zn}`),(typeof t.namespace!="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(t.namespace))&&ce("invalid namespace"),(typeof t.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(t.version))&&ce("version must be major.minor.patch"),Nr.has(t.namespace)&&ce(`namespace ${t.namespace} already registered`),(!Array.isArray(t.components)||!t.components.length||t.components.length>32)&&ce("expected 1-32 components"),Nr.size>=32&&ce("too many extensions");let n=new Map;for(let a of t.components){Rs(a,["name","description","propsSchema","children","actions"]),(typeof a.name!="string"||!/^[A-Z][A-Za-z0-9]{0,63}$/.test(a.name))&&ce("invalid component name");let s=`${t.namespace}/${a.name}`;n.has(s)&&ce(`duplicate type ${s}`),(typeof a.description!="string"||!a.description||a.description.length>2e3)&&ce("description required (max 2000 characters)"),a.children!==void 0&&typeof a.children!="boolean"&&ce("children must be boolean"),a.actions!==void 0&&(!Array.isArray(a.actions)||a.actions.length>32||a.actions.some(l=>typeof l!="string"||!l||l.length>100)||new Set(a.actions).size!==a.actions.length)&&ce("invalid actions"),a.propsSchema?.type!=="object"&&ce("propsSchema must be an object schema");try{Je(a.propsSchema,void 0,!0)}catch(l){ce(`invalid propsSchema for ${s}: ${l.message}`)}kf(a.propsSchema.properties,"children")&&ce("children belongs on the node, not in propsSchema"),n.set(s,Ji({...a,children:a.children??!1,generation:++wf,version:t.version,actions:a.actions??[]}))}Ji(t);let r=!0,i=!1,o={manifest:t};Nr.set(t.namespace,o);for(let[a,s]of n)Sn.set(a,s);return Vi(),Object.freeze({manifest:t,setEnabled(a){if(i&&ce("extension disposed"),typeof a!="boolean"&&ce("enabled must be boolean"),r!==a){r=a;for(let[s,l]of n)r?Sn.set(s,l):Sn.delete(s);Vi()}},dispose(){if(!i){i=!0,Nr.delete(t.namespace);for(let a of n.keys())Sn.delete(a);Vi()}}})}var Tt=e=>typeof e=="string"?Sn.get(e):void 0,Ds=()=>[...Sn.keys()];var zs={type:"object",props:{id:{type:"string",required:!0,max:100},scope:{type:"string",required:!0,max:200}}},vf={type:"object",props:{actionId:{type:"string",required:!0,max:100},args:{type:"any",required:!0}}},er=["default","muted","info","success","warning","error"],Sf=["text","number","range","select","checkbox","date","textarea"],Cf=["text","number","date","boolean","string"],Ef=["bar","line","area","pie"],K=Object.freeze({components:300,depth:24,tableRows:500,tableColumns:24,chartPoints:500,chartSeries:12,formFields:40,text:2e4,plotFunctions:8,plotParams:8,timelineItems:100,choiceOptions:8,scatterPoints:2e3,heatmapAxis:60,diffFiles:20,diffChars:2e5,treeEntries:2e3,jsonChars:1e5,jsonDepth:32}),tr=Object.freeze({Card:{description:"Bordered container with optional title/subtitle/footer; children stack vertically.",children:!0,props:{title:{type:"string"},subtitle:{type:"string"},footer:{type:"string"}}},Stack:{description:"Lays out children vertically (default) or horizontally.",children:!0,props:{direction:{type:"enum",values:["vertical","horizontal"]},gap:{type:"number",min:0,max:64},wrap:{type:"boolean"},align:{type:"enum",values:["start","center","end","stretch"]}}},Grid:{description:"Responsive grid; `columns` is the column count on wide screens (1-6).",children:!0,props:{columns:{type:"number",required:!0,min:1,max:6}}},Tabs:{description:"Tabbed panels: labels[i] titles children[i].",children:!0,props:{labels:{type:"array",required:!0,items:{type:"string"},max:12}}},Text:{description:"Text with a markdown subset (**bold**, *italic*, `code`, [link](https://...), line breaks).",children:!1,props:{text:{type:"string",required:!0,max:K.text},variant:{type:"enum",values:["body","title","heading","caption"]},tone:{type:"enum",values:er}}},Code:{description:"Monospaced code block.",children:!1,props:{code:{type:"string",required:!0,max:K.text},language:{type:"string"}}},Alert:{description:"Callout box with a tone.",children:!1,props:{title:{type:"string"},text:{type:"string",required:!0},tone:{type:"enum",values:er}}},Badge:{description:"Small inline label.",children:!1,props:{text:{type:"string",required:!0},tone:{type:"enum",values:er}}},Divider:{description:"Horizontal rule.",children:!1,props:{}},Stat:{description:"KPI tile: label, big value, optional delta with trend.",children:!1,props:{label:{type:"string",required:!0},value:{type:"scalar",required:!0},delta:{type:"string"},trend:{type:"enum",values:["up","down","flat"]},hint:{type:"string"}}},Progress:{description:"Progress bar; value out of max (default 100).",children:!1,props:{value:{type:"number",required:!0},max:{type:"number",min:0},label:{type:"string"},tone:{type:"enum",values:er}}},List:{description:"Bulleted or numbered list of short markdown-subset strings.",children:!1,props:{items:{type:"array",required:!0,items:{type:"string"},max:200},ordered:{type:"boolean"}}},Table:{description:"Data table / data grid. rows[i][j] belongs to columns[j]. Optional local, model-free interactions: sortable (typed: numbers, ISO 8601 dates `YYYY-MM-DD[THH:mm]`, booleans; empty values last), searchable, filterable (per-column contains / min-max range), pageSize, exportable (CSV/Markdown of the filtered rows). columnTypes overrides inferred types. Or use a host-registered dataRef for shared local search/filter/sort/paging.",children:!1,props:{dataRef:zs,pageSize:{type:"number",min:1,max:100},columnTypes:{type:"array",max:K.tableColumns,items:{type:"enum",values:Cf}},searchable:{type:"boolean"},filterable:{type:"boolean"},exportable:{type:"boolean"},columns:{type:"array",items:{type:"string"},max:K.tableColumns},rows:{type:"array",max:K.tableRows,items:{type:"array",items:{type:"scalar"},max:K.tableColumns}},caption:{type:"string"},sortable:{type:"boolean"}}},Chart:{description:"SVG chart. Use dataRef with labelColumn and valueColumns (zero-based) for local linked data; otherwise labels are the x categories (pie: slice names); each series has one value per label.",children:!1,props:{kind:{type:"enum",required:!0,values:Ef},dataRef:zs,labelColumn:{type:"number",min:0,max:23},valueColumns:{type:"array",max:12,items:{type:"number",min:0,max:23}},labels:{type:"array",items:{type:"scalar"},max:K.chartPoints},series:{type:"array",max:K.chartSeries,items:{type:"object",props:{name:{type:"string",required:!0},values:{type:"array",required:!0,items:{type:"number"},max:K.chartPoints}}}},title:{type:"string"},unit:{type:"string"},stacked:{type:"boolean"},height:{type:"number",min:120,max:600},exportable:{type:"boolean"}}},Scatter:{description:"Scatter plot of real numeric observations: each point has continuous x and y (not category indexes). Use for correlation/distribution between two measures. Points with a null coordinate are hidden and counted. Hover, tap or arrow keys show a point; legend toggles series.",children:!1,props:{series:{type:"array",required:!0,max:K.chartSeries,items:{type:"object",props:{name:{type:"string",required:!0},points:{type:"array",required:!0,max:K.scatterPoints,items:{type:"object",props:{x:{type:"scalar",required:!0},y:{type:"scalar",required:!0},label:{type:"string",max:200}}}}}}},title:{type:"string"},xLabel:{type:"string"},yLabel:{type:"string"},xUnit:{type:"string"},yUnit:{type:"string"},height:{type:"number",min:160,max:600}}},Heatmap:{description:'Matrix heatmap: values[r][c] belongs to yLabels[r] × xLabels[c]. Use null for missing data (drawn hatched, never as 0). scale "diverging" centres on 0 (negative red, positive blue); default "sequential". Optional fixed min/max.',children:!1,props:{xLabels:{type:"array",required:!0,items:{type:"scalar"},max:K.heatmapAxis},yLabels:{type:"array",required:!0,items:{type:"scalar"},max:K.heatmapAxis},values:{type:"array",required:!0,max:K.heatmapAxis,items:{type:"array",items:{type:"scalar"},max:K.heatmapAxis}},title:{type:"string"},unit:{type:"string"},scale:{type:"enum",values:["sequential","diverging"]},min:{type:"number"},max:{type:"number"},showValues:{type:"boolean"}}},CodeDiff:{description:"Read-only code diff viewer for one or more files: give each file before/after full text (the diff is computed, unchanged runs collapse to expandable context) or a unified diff `patch`. Shows line numbers and +/- counts; large files start collapsed. Content is shown as text, never executed. For displaying changes, not applying them.",children:!1,props:{title:{type:"string"},context:{type:"number",min:0,max:20},files:{type:"array",required:!0,max:K.diffFiles,items:{type:"object",props:{path:{type:"string",required:!0,max:500},before:{type:"string",max:K.diffChars},after:{type:"string",max:K.diffChars},patch:{type:"string",max:K.diffChars},language:{type:"string",max:40}}}}}},FileTree:{description:"Collapsible file/directory tree built from slash-separated paths (a trailing / marks an empty directory), with optional per-entry status (added/modified/deleted/renamed) and short note. Labels only: nothing is read from disk.",children:!1,props:{title:{type:"string"},expandDepth:{type:"number",min:0,max:32},entries:{type:"array",required:!0,max:K.treeEntries,items:{type:"object",props:{path:{type:"string",required:!0,max:500},status:{type:"enum",values:["added","modified","deleted","renamed"]},note:{type:"string",max:200}}}}}},JsonView:{description:"Collapsible JSON tree for any JSON value (`data`), with per-node path ($.a[0].b) and copy path / copy value. Use to inspect API responses, configs or tool output.",children:!1,props:{data:{type:"any",required:!0},title:{type:"string"},expandDepth:{type:"number",min:0,max:32}}},Button:{description:"Button sends prompt on explicit user click: sessionTarget defaults to current; new starts an independent Agent session in the same workspace. Or invokes a host-registered action {actionId,args}. Never invent action ids.",children:!1,props:{label:{type:"string",required:!0},prompt:{type:"string"},sessionTarget:{type:"enum",values:["current","new"]},action:vf,variant:{type:"enum",values:["primary","secondary"]}}},Choice:{description:"Single-choice decision card with 2-8 options. Selection is local; the primary action continues in the current session and an optional secondary action starts a new session. Set sessionTarget only for an explicitly chosen fixed destination. Give options stable ids; recommended marks an id without selecting it. Every prompt must preserve user constraints and be self-contained for a new session. New-session retries retain the first confirmed task. No registered actions.",children:!1,props:{question:{type:"string",required:!0,max:300},submitLabel:{type:"string",max:200},sessionTarget:{type:"enum",values:["current","new"]},recommended:{type:"string",max:100},options:{type:"array",required:!0,max:K.choiceOptions,items:{type:"object",props:{id:{type:"string",max:100},label:{type:"string",required:!0,max:200},description:{type:"string",max:1200},prompt:{type:"string",required:!0,max:K.text}}}}}},Form:{description:"Input form. Submit sends all field values prefixed by prompt. sessionTarget defaults to current; new creates an independent session in the same workspace and submits automatically. For new, prompt must contain complete task context and user constraints; conversation history is not copied.",children:!1,props:{title:{type:"string"},submitLabel:{type:"string"},prompt:{type:"string"},sessionTarget:{type:"enum",values:["current","new"]},fields:{type:"array",required:!0,max:K.formFields,items:{type:"object",props:{name:{type:"string",required:!0},label:{type:"string",required:!0},type:{type:"enum",required:!0,values:Sf},options:{type:"array",items:{type:"string"},max:100},required:{type:"boolean"},placeholder:{type:"string"},default:{type:"scalar"},min:{type:"number"},max:{type:"number"},step:{type:"number",min:0}}}}}},Timeline:{description:"Vertical timeline of events/steps in order.",children:!1,props:{items:{type:"array",required:!0,max:K.timelineItems,items:{type:"object",props:{title:{type:"string",required:!0},time:{type:"string"},text:{type:"string"},tone:{type:"enum",values:er}}}}}},Plot:{description:"Function plot y = f(x) drawn natively. `params` become sliders the user drags; the curves update instantly in the browser (no message to you). Expressions use x, the param names, pi, e, + - * / ^, and functions like sin, cos, exp, ln, sqrt, abs.",children:!1,props:{functions:{type:"array",required:!0,max:K.plotFunctions,items:{type:"object",props:{expr:{type:"string",required:!0,max:500},label:{type:"string"}}}},xMin:{type:"number"},xMax:{type:"number"},yMin:{type:"number"},yMax:{type:"number"},params:{type:"array",max:K.plotParams,items:{type:"object",props:{name:{type:"string",required:!0},label:{type:"string"},min:{type:"number",required:!0},max:{type:"number",required:!0},step:{type:"number",min:0},value:{type:"number",required:!0}}}},title:{type:"string"},xLabel:{type:"string"},yLabel:{type:"string"},height:{type:"number",min:160,max:600}}},Math:{description:"LaTeX math typeset with KaTeX (block by default). Put related equations in one node (e.g. \\begin{aligned}...\\end{aligned}). In JSON, escape each backslash (\\\\frac).",children:!1,props:{tex:{type:"string",required:!0,max:5e3},display:{type:"boolean"}}},Mermaid:{description:"Diagram from Mermaid source (flowchart, sequenceDiagram, classDiagram, stateDiagram, erDiagram, gantt, timeline, mindmap, pie).",children:!1,props:{code:{type:"string",required:!0,max:K.text}}}}),If=Object.freeze(Object.keys(tr));function nr(e){return Object.hasOwn(tr,e)?tr[e]:Tt(e)}function Gi(){return[...If,...Ds()]}function Yi(e,t){let n=Tt(e);return n&&t!==n.version?[`componentVersion: ${e} requires ${n.version}`]:!n&&t!==void 0?["componentVersion: only registered extensions accept a version"]:[]}function $e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function _s(e,t,n,r){switch(t.type){case"any":return;case"string":if(typeof e!="string"){r.push(`${n}: expected string, got ${qt(e)}`);return}t.max!==void 0&&e.length>t.max&&r.push(`${n}: longer than ${t.max} characters`);return;case"number":if(typeof e!="number"||!Number.isFinite(e)){r.push(`${n}: expected finite number, got ${qt(e)}`);return}t.min!==void 0&&e<t.min&&r.push(`${n}: must be >= ${t.min}`),t.max!==void 0&&e>t.max&&r.push(`${n}: must be <= ${t.max}`);return;case"boolean":typeof e!="boolean"&&r.push(`${n}: expected boolean, got ${qt(e)}`);return;case"scalar":e===null||["string","number","boolean"].includes(typeof e)||r.push(`${n}: expected string, number, boolean or null, got ${qt(e)}`);return;case"enum":t.values.includes(e)||r.push(`${n}: expected one of ${t.values.join(" | ")}, got ${JSON.stringify(e)}`);return;case"array":if(!Array.isArray(e)){r.push(`${n}: expected array, got ${qt(e)}`);return}if(t.max!==void 0&&e.length>t.max){r.push(`${n}: more than ${t.max} items`);return}t.items&&e.forEach((i,o)=>_s(i,t.items,`${n}[${o}]`,r));return;case"object":if(!$e(e)){r.push(`${n}: expected object, got ${qt(e)}`);return}Us(e,t.props||{},n,r);return;default:r.push(`${n}: unknown spec type ${t.type}`)}}function Us(e,t,n,r){for(let[i,o]of Object.entries(t)){let a=e[i];if(a===void 0){o.required&&r.push(`${n}.${i}: required`);continue}_s(a,o,`${n}.${i}`,r)}for(let i of Object.keys(e))i in t||r.push(`${n}.${i}: unknown prop`)}function Nf(e,t,n,r){if(e==="Table"||e==="Chart"){let i=e==="Table"?["columns","rows"]:["labels","series"];t.dataRef!==void 0?(i.some(o=>t[o]!==void 0)&&r.push(`${n}: dataRef cannot be mixed with inline data`),e==="Chart"&&(!Number.isInteger(t.labelColumn)||!Array.isArray(t.valueColumns)||!t.valueColumns.length||t.valueColumns.some(o=>!Number.isInteger(o)))&&r.push(`${n}: bound Chart needs integer labelColumn and valueColumns`),e==="Chart"&&t.kind==="pie"&&Array.isArray(t.valueColumns)&&t.valueColumns.length!==1&&r.push(`${n}: bound pie chart needs exactly one value column`)):i.some(o=>t[o]===void 0)&&r.push(`${n}: needs ${i.join(" and ")} or dataRef`),t.pageSize!==void 0&&!Number.isInteger(t.pageSize)&&r.push(`${n}.pageSize: expected integer`),Array.isArray(t.columnTypes)&&Array.isArray(t.columns)&&t.columnTypes.length>t.columns.length&&r.push(`${n}.columnTypes: has ${t.columnTypes.length} entries but columns has ${t.columns.length}`),e==="Table"&&t.dataRef!==void 0&&(t.searchable||t.filterable)&&r.push(`${n}: searchable/filterable apply to inline rows; a dataRef table already has shared search and filter`)}if(e==="Button"&&t.prompt===void 0==(t.action===void 0)&&r.push(`${n}: needs exactly one of prompt or action`),e==="Button"&&t.sessionTarget!==void 0&&t.action!==void 0&&r.push(`${n}.sessionTarget: only supported with prompt`),e==="Form"&&t.sessionTarget==="new"&&(typeof t.prompt!="string"||!t.prompt.trim())&&r.push(`${n}.prompt: new session needs a non-empty task prompt`),e==="Choice"){for(let i of["question","submitLabel"])typeof t[i]=="string"&&!t[i].trim()&&r.push(`${n}.${i}: must not be blank`);if(Array.isArray(t.options)){t.options.length<2&&r.push(`${n}.options: needs at least 2 options`);let i=new Set;t.options.forEach((o,a)=>{if($e(o)){for(let s of["id","label","prompt"])typeof o[s]=="string"&&!o[s].trim()&&r.push(`${n}.options[${a}].${s}: must not be blank`);o.id!==void 0&&i.has(o.id)&&r.push(`${n}.options[${a}].id: duplicate option id`),o.id!==void 0&&i.add(o.id)}}),t.recommended!==void 0&&!i.has(t.recommended)&&r.push(`${n}.recommended: must reference an option id`)}}if(e==="Chart"&&Array.isArray(t.labels)&&Array.isArray(t.series)&&(t.series.forEach((i,o)=>{$e(i)&&Array.isArray(i.values)&&i.values.length!==t.labels.length&&r.push(`${n}.series[${o}].values: has ${i.values.length} values but labels has ${t.labels.length}`)}),t.kind==="pie"&&t.series.length>1&&r.push(`${n}.series: a pie chart takes exactly one series`)),e==="Form"&&Array.isArray(t.fields)){let i=new Set;t.fields.forEach((o,a)=>{$e(o)&&(i.has(o.name)&&r.push(`${n}.fields[${a}].name: duplicate field name ${JSON.stringify(o.name)}`),i.add(o.name),o.type==="select"&&(!Array.isArray(o.options)||o.options.length===0)&&r.push(`${n}.fields[${a}].options: a select field needs options`),o.type==="range"&&!(typeof o.min=="number"&&typeof o.max=="number"&&o.min<o.max)&&r.push(`${n}.fields[${a}]: a range field needs numeric min < max`))})}if(e==="Plot"&&Pf(t,n,r),e==="Scatter"&&Array.isArray(t.series)){let i=0;t.series.forEach((o,a)=>{!$e(o)||!Array.isArray(o.points)||(i+=o.points.length,o.points.forEach((s,l)=>{if($e(s))for(let u of["x","y"]){let c=s[u];c!==null&&!(typeof c=="number"&&Number.isFinite(c))&&r.push(`${n}.series[${a}].points[${l}].${u}: expected a finite number or null`)}}))}),i>K.scatterPoints&&r.push(`${n}.series: ${i} points in total; at most ${K.scatterPoints}`)}if(e==="CodeDiff"&&Array.isArray(t.files)){let i=0;t.files.forEach((o,a)=>{if(!$e(o))return;let s=o.patch!==void 0;s&&(o.before!==void 0||o.after!==void 0)&&r.push(`${n}.files[${a}]: use either patch or before/after, not both`),!s&&o.before===void 0&&o.after===void 0&&r.push(`${n}.files[${a}]: needs before/after text or a patch`);for(let l of["before","after","patch"])typeof o[l]=="string"&&(i+=o[l].length)}),i>K.diffChars&&r.push(`${n}.files: ${i} characters in total; at most ${K.diffChars}`)}if(e==="JsonView"&&t.data!==void 0){let i;try{i=JSON.stringify(t.data)}catch{i=void 0}i===void 0?r.push(`${n}.data: must be a JSON value`):i.length>K.jsonChars?r.push(`${n}.data: ${i.length} characters; at most ${K.jsonChars}`):Bs(t.data)>K.jsonDepth&&r.push(`${n}.data: nested deeper than ${K.jsonDepth} levels`)}e==="Heatmap"&&Array.isArray(t.values)&&Array.isArray(t.xLabels)&&Array.isArray(t.yLabels)&&(t.values.length!==t.yLabels.length&&r.push(`${n}.values: has ${t.values.length} rows but yLabels has ${t.yLabels.length}`),t.values.forEach((i,o)=>{Array.isArray(i)&&(i.length!==t.xLabels.length&&r.push(`${n}.values[${o}]: has ${i.length} values but xLabels has ${t.xLabels.length}`),i.forEach((a,s)=>{a!==null&&!(typeof a=="number"&&Number.isFinite(a))&&r.push(`${n}.values[${o}][${s}]: expected a finite number or null`)}))}),typeof t.min=="number"&&typeof t.max=="number"&&!(t.min<t.max)&&r.push(`${n}: min must be less than max`))}function Bs(e,t=0){if(t>K.jsonDepth||e===null||typeof e!="object")return t;let n=t+1;for(let r of Array.isArray(e)?e:Object.values(e))n=Math.max(n,Bs(r,t+1));return n}var Tf=/^[A-Za-z_][A-Za-z_0-9]*$/,Af=new Set(["x","pi","e","tau",...Object.keys(Ir)]);function Pf(e,t,n){let r=typeof e.xMin=="number"?e.xMin:-10,i=typeof e.xMax=="number"?e.xMax:10;r<i||n.push(`${t}: xMin must be less than xMax`),typeof e.yMin=="number"&&typeof e.yMax=="number"&&!(e.yMin<e.yMax)&&n.push(`${t}: yMin must be less than yMax`);let o=[];Array.isArray(e.params)&&e.params.forEach((a,s)=>{if(!$e(a)||typeof a.name!="string")return;let l=`${t}.params[${s}]`;Tf.test(a.name)?Af.has(a.name)?n.push(`${l}.name: "${a.name}" is reserved`):o.includes(a.name)&&n.push(`${l}.name: duplicate parameter "${a.name}"`):n.push(`${l}.name: must be an identifier like "a" or "omega"`),o.push(a.name),typeof a.min=="number"&&typeof a.max=="number"&&(a.min<a.max?typeof a.value=="number"&&(a.value<a.min||a.value>a.max)&&n.push(`${l}.value: must lie within [min, max]`):n.push(`${l}: min must be less than max`))}),Array.isArray(e.functions)&&e.functions.forEach((a,s)=>{if(!$e(a)||typeof a.expr!="string")return;let l=Os(a.expr,["x",...o]);l&&n.push(`${t}.functions[${s}].expr: ${l}`)})}function Xi(e,t,n="props"){let r=nr(e);if(!r)return[`${n}: unknown component type ${JSON.stringify(e)}; use one of ${Gi().join(", ")}`];let i=t===void 0?{}:t;if(!$e(i))return[`${n}: expected object, got ${qt(i)}`];let o=[];if(r.propsSchema){try{Je(r.propsSchema,i)}catch(a){o.push(`${n}: ${a.message}`)}return o}return Us(i,r.props,n,o),Nf(e,i,n,o),o}function Tr(e){let t=[],n=[],r={};if(!$e(e))return{ok:!1,errors:["arguments: expected object"],warnings:n,types:r,count:0};let{root:i,components:o}=e;if(e.title!==void 0&&typeof e.title!="string"&&t.push("title: expected string"),i===void 0?t.push('root: missing. Add the top-level field "root" next to "components", set to the id of the top component (a component named "root" does not replace it)'):(typeof i!="string"||i==="")&&t.push("root: expected the id of the top-level component"),!Array.isArray(o)||o.length===0)return t.push("components: expected a non-empty array"),{ok:!1,errors:t,warnings:n,types:r,count:0};o.length>K.components&&t.push(`components: more than ${K.components} nodes`);let a=new Map;o.forEach((l,u)=>{let c=`components[${u}]`;if(!$e(l)){t.push(`${c}: expected object`);return}if(typeof l.id!="string"||l.id===""){t.push(`${c}.id: expected non-empty string`);return}if(a.has(l.id)){t.push(`${c}.id: duplicate id ${JSON.stringify(l.id)}`);return}a.set(l.id,l),Object.hasOwn(tr,l.type)&&$e(l.props)&&"children"in l.props&&(l.children===void 0&&Array.isArray(l.props.children)&&(l.children=l.props.children),delete l.props.children);let d=nr(l.type);r[l.type]=(r[l.type]||0)+1,t.push(...Xi(l.type,l.props,`${c}(${l.id}).props`)),t.push(...Yi(l.type,l.componentVersion).map(p=>`${c}(${l.id}).${p}`)),l.children!==void 0&&(!Array.isArray(l.children)||l.children.some(p=>typeof p!="string")?t.push(`${c}(${l.id}).children: expected array of component ids`):d&&!d.children&&l.children.length>0&&t.push(`${c}(${l.id}).children: ${l.type} cannot have children`));for(let p of Object.keys(l))["id","type","componentVersion","props","children"].includes(p)||t.push(`${c}(${l.id}).${p}: unknown field`)});let s=new Map;for(let l of a.values())if(Array.isArray(l.children))for(let u of l.children){if(!a.has(u)){t.push(`${l.id}.children: unknown id ${JSON.stringify(u)}`);continue}if(u===i){t.push(`${l.id}.children: the root ${JSON.stringify(i)} cannot be a child`);continue}if(s.has(u)){t.push(`${u}: has two parents (${s.get(u)} and ${l.id})`);continue}s.set(u,l.id)}if(typeof i=="string"&&i!==""&&!a.has(i)&&t.push(`root: unknown id ${JSON.stringify(i)}`),a.has(i)){let l=new Set,u=(d,p,f)=>{if(f.has(d)){t.push(`cycle through ${JSON.stringify(d)}`);return}if(p>K.depth){t.push(`nesting deeper than ${K.depth} at ${JSON.stringify(d)}`);return}if(l.has(d))return;l.add(d);let m=a.get(d);if(!(!m||!Array.isArray(m.children))){f.add(d);for(let h of m.children)a.has(h)&&u(h,p+1,f);f.delete(d)}};u(i,0,new Set);let c=[...a.keys()].filter(d=>!l.has(d));c.length>0&&n.push(`not reachable from root (not rendered): ${c.join(", ")}`)}for(let l of a.values()){if(l.type!=="Tabs"||!$e(l.props)||!Array.isArray(l.props.labels))continue;let u=Array.isArray(l.children)?l.children.length:0;u!==l.props.labels.length&&t.push(`${l.id}: Tabs has ${l.props.labels.length} labels but ${u} children`)}return{ok:t.length===0,errors:t,warnings:n,types:r,count:a.size}}function Me(e){return e==null}function Pr(e){return e&&typeof e=="object"&&!Array.isArray(e)}function qs(e,t){return Object.fromEntries(Object.entries(e).filter(([n,r])=>t(n,r)))}function ct(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,t(r,n)]))}function Vs(e,t,n){if(!t)return{...e};let r={};for(let i of t)(n||e[i]!==void 0)&&(r[i]=e[i]);return r}var Ws=Symbol.for("cosmokit.volatile.write");function Qi(e,t=new Set){if(typeof e=="function")throw new TypeError("volatile config cannot contain functions");if(e===null||typeof e!="object")return e;if(t.has(e))throw new TypeError("volatile config cannot contain cycles");t.add(e);try{if(Array.isArray(e))return Object.freeze(e.map(n=>Qi(n,t)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("volatile config objects must be plain objects or arrays");return Object.freeze(Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Qi(r,t)])))}finally{t.delete(e)}}function Zi(e){let t=Qi(e);return Object.freeze({get:()=>t,[Ws]:n=>{t=n}})}function Cn(e){return typeof e=="object"&&e!==null&&Ws in e}function At(e,t){return arguments.length===1?n=>At(e,n):e in globalThis&&t instanceof globalThis[e]||Object.prototype.toString.call(t).slice(8,-1)===e}function Or(e){return At("ArrayBuffer",e)||At("SharedArrayBuffer",e)}function Of(e){return Or(e)||ArrayBuffer.isView(e)}var Ke;(function(e){e.is=Or,e.isSource=Of;function t(a){return ArrayBuffer.isView(a)?a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength):a}e.fromSource=t;function n(a){if(a=t(a),typeof Buffer<"u")return Buffer.from(a).toString("base64");let s="",l=new Uint8Array(a);for(let u=0;u<l.byteLength;u++)s+=String.fromCharCode(l[u]);return btoa(s)}e.toBase64=n;function r(a){return typeof Buffer<"u"?t(Buffer.from(a,"base64")):Uint8Array.from(atob(a),s=>s.charCodeAt(0))}e.fromBase64=r;function i(a){return a=t(a),typeof Buffer<"u"?Buffer.from(a).toString("hex"):Array.from(new Uint8Array(a),s=>s.toString(16).padStart(2,"0")).join("")}e.toHex=i;function o(a){if(typeof Buffer<"u")return t(Buffer.from(a,"hex"));let s=a.length%2===0?a:a.slice(0,a.length-1),l=[];for(let u=0;u<s.length;u+=2)l.push(parseInt(`${s[u]}${s[u+1]}`,16));return Uint8Array.from(l).buffer}e.fromHex=o})(Ke||(Ke={}));var Jb=Ke.fromBase64,Kb=Ke.toBase64,Gb=Ke.fromHex,Yb=Ke.toHex;function Ar(e,t=new Map){if(!e||typeof e!="object")return e;if(At("Date",e))return new Date(e.valueOf());if(At("RegExp",e))return new RegExp(e.source,e.flags);if(Or(e))return e.slice(0);if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);let n=t.get(e);if(n)return n;if(Array.isArray(e)){let i=[];return t.set(e,i),e.forEach((o,a)=>{i[a]=Reflect.apply(Ar,null,[o,t])}),i}let r=Object.create(Object.getPrototypeOf(e));t.set(e,r);for(let i of Reflect.ownKeys(e)){let o={...Reflect.getOwnPropertyDescriptor(e,i)};"value"in o&&(o.value=Reflect.apply(Ar,null,[o.value,t])),Reflect.defineProperty(r,i,o)}return r}function $r(e,t,n){let r=new Set;function i(o,a){if(o===a)return!0;if(Cn(o)||Cn(a))return Cn(o)&&Cn(a);if(!n&&Me(o)&&Me(a))return!0;if(typeof o!=typeof a||typeof o!="object"||!o||!a||r.has(o))return!1;function s(l,u){return l(o)?l(a)?u(o,a):!1:l(a)?!1:void 0}r.add(o);try{return s(Array.isArray,(l,u)=>{if(l.length!==u.length)return!1;for(let c=0;c<l.length;c++)if(!i(l[c],u[c]))return!1;return!0})??s(At("Date"),(l,u)=>l.valueOf()===u.valueOf())??s(At("URL"),(l,u)=>l.href===u.href)??s(At("RegExp"),(l,u)=>l.source===u.source&&l.flags===u.flags)??s(Or,(l,u)=>{if(l.byteLength!==u.byteLength)return!1;let c=new Uint8Array(l),d=new Uint8Array(u);for(let p=0;p<c.length;p++)if(c[p]!==d[p])return!1;return!0})??((!n||[o,a].every(l=>Object.getPrototypeOf(l)===Object.prototype||Object.getPrototypeOf(l)===null))&&Object.keys({...o,...a}).every(l=>i(o[l],a[l])))}finally{r.delete(o)}}return i(e,t)}var Hs;(function(e){e.millisecond=1,e.second=1e3,e.minute=e.second*60,e.hour=e.minute*60,e.day=e.hour*24,e.week=e.day*7;let t=new Date().getTimezoneOffset();function n(f){t=f}e.setTimezoneOffset=n;function r(){return t}e.getTimezoneOffset=r;function i(f=new Date,m){return typeof f=="number"&&(f=new Date(f)),m===void 0&&(m=t),Math.floor((f.valueOf()/e.minute-m)/1440)}e.getDateNumber=i;function o(f,m){let h=new Date(f*e.day);return m===void 0&&(m=t),new Date(+h+m*e.minute)}e.fromDateNumber=o;let a=/\d+(?:\.\d+)?/.source,s=new RegExp(`^${["w(?:eek(?:s)?)?","d(?:ay(?:s)?)?","h(?:our(?:s)?)?","m(?:in(?:ute)?(?:s)?)?","s(?:ec(?:ond)?(?:s)?)?"].map(f=>`(${a}${f})?`).join("")}$`);function l(f){let m=s.exec(f);return m?(parseFloat(m[1])*e.week||0)+(parseFloat(m[2])*e.day||0)+(parseFloat(m[3])*e.hour||0)+(parseFloat(m[4])*e.minute||0)+(parseFloat(m[5])*e.second||0):0}e.parseTime=l;function u(f){let m=l(f);return m?f=Date.now()+m:/^\d{1,2}(:\d{1,2}){1,2}$/.test(f)?f=`${new Date().toLocaleDateString()}-${f}`:/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(f)&&(f=`${new Date().getFullYear()}-${f}`),f?new Date(f):new Date}e.parseDate=u;function c(f){let m=Math.abs(f);return m>=e.day-e.hour/2?Math.round(f/e.day)+"d":m>=e.hour-e.minute/2?Math.round(f/e.hour)+"h":m>=e.minute-e.second/2?Math.round(f/e.minute)+"m":m>=e.second?Math.round(f/e.second)+"s":f+"ms"}e.format=c;function d(f,m=2){return f.toString().padStart(m,"0")}e.toDigits=d;function p(f,m=new Date){return f.replace("yyyy",m.getFullYear().toString()).replace("yy",m.getFullYear().toString().slice(2)).replace("MM",d(m.getMonth()+1)).replace("dd",d(m.getDate())).replace("hh",d(m.getHours())).replace("mm",d(m.getMinutes())).replace("ss",d(m.getSeconds())).replace("SSS",d(m.getMilliseconds(),3))}e.template=p})(Hs||(Hs={}));var ir=Symbol.for("schemastery"),Gs=Symbol.for("ValidationError");globalThis.__schemastery_index__??(globalThis.__schemastery_index__=0);globalThis.__schemastery_refs__=void 0;var ee=class extends TypeError{constructor(t,n){let r="$";for(let i of n.path||[])typeof i=="string"?r+="."+i:typeof i=="number"?r+="["+i+"]":typeof i=="symbol"&&(r+=`[Symbol(${i.toString()})]`);r.startsWith(".")&&(r=r.slice(1));super((r==="$"?"":`${r} `)+t);be(this,"options");be(this,"name","ValidationError");this.options=n}static is(t){return!!t?.[Gs]}};Object.defineProperty(ee.prototype,Gs,{value:!0});var $=function(e){let t=function(n,r={}){return $.resolve(n,t,r)[0]};if(e.refs){let n=ct(e.refs,i=>new $(i)),r=i=>n[i];for(let i in n){let o=n[i];o.sKey=r(o.sKey),o.inner=r(o.inner),o.list=o.list&&o.list.map(r),o.dict=o.dict&&ct(o.dict,r)}return n[e.uid]}if(Object.assign(t,e),typeof t.callback=="string")try{t.callback=new Function("return "+t.callback)()}catch{}return Object.defineProperty(t,"uid",{value:globalThis.__schemastery_index__++}),Object.setPrototypeOf(t,$.prototype),t.meta||(t.meta={}),t.toString=t.toString.bind(t),t};$.prototype=Object.create(Function.prototype);$.prototype[ir]=!0;Object.defineProperty($.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:e=>{try{return{value:$.resolve(e,this,{})[0]}}catch(t){if(ee.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}}}}});$.ValidationError=ee;$.prototype.toJSON=function(){var n,r;if(globalThis.__schemastery_refs__)return(n=globalThis.__schemastery_refs__)[r=this.uid]??(n[r]=JSON.parse(JSON.stringify({...this}))),this.uid;globalThis.__schemastery_refs__={[this.uid]:{...this}},globalThis.__schemastery_refs__[this.uid]=JSON.parse(JSON.stringify({...this}));let t={uid:this.uid,refs:globalThis.__schemastery_refs__};return globalThis.__schemastery_refs__=void 0,t};$.prototype.set=function(t,n){return this.dict[t]=n,this};$.prototype.push=function(t){return this.list.push(t),this};function $f(e,t){let n=typeof e=="string"?{"":e}:{...e};for(let r in t){let i=t[r];i?.$description||i?.$desc?n[r]=i.$description||i.$desc:typeof i=="string"&&(n[r]=i)}return n}function rr(e){return e?.$value??e?.$inner}function Js(e){return qs(e??{},t=>!t.startsWith("$"))}$.prototype.i18n=function(t){let n=$(this),r=$f(n.meta.description,t);return Object.keys(r).length&&(n.meta.description=r),n.dict&&(n.dict=ct(n.dict,(i,o)=>i.i18n(ct(t,a=>rr(a)?.[o]??a?.[o])))),n.list&&(n.list=n.list.map((i,o)=>i.i18n(ct(t,(a={})=>Array.isArray(rr(a))?rr(a)[o]:Array.isArray(a)?a[o]:Js(a))))),n.inner&&(n.inner=n.inner.i18n(ct(t,i=>rr(i)?rr(i):Js(i)))),n.sKey&&(n.sKey=n.sKey.i18n(ct(t,i=>i?.$key))),n};$.prototype.extra=function(t,n){let r=$(this);return r.meta={...r.meta,[t]:n},r};for(let e of["required","disabled","collapse","hidden","loose"])Object.assign($.prototype,{[e](t=!0){let n=$(this);return n.meta={...n.meta,[e]:t},n}});$.prototype.deprecated=function(){var n;let t=$(this);return(n=t.meta).badges||(n.badges=[]),t.meta.badges.push({text:"deprecated",type:"danger"}),t};$.prototype.experimental=function(){var n;let t=$(this);return(n=t.meta).badges||(n.badges=[]),t.meta.badges.push({text:"experimental",type:"warning"}),t};$.prototype.pattern=function(t){let n=$(this),r=Vs(t,["source","flags"]);return n.meta={...n.meta,pattern:r},n};$.prototype.simplify=function(t){if(Cn(t)&&(t=t.get()),$r(t,this.meta.default,this.type==="dict"))return null;if(Me(t))return t;if(this.type==="object"||this.type==="dict"){let n={};for(let r in t){let i=(this.type==="object"?this.dict[r]:this.inner)?.simplify(t[r]);(this.type==="dict"||!Me(i))&&(n[r]=i)}return $r(n,this.meta.default,this.type==="dict")?null:n}else if(this.type==="array"||this.type==="tuple"){let n=[];return t.forEach((r,i)=>{let o=this.type==="array"?this.inner:this.list[i],a=o?o.simplify(r):r;n.push(a)}),n}else if(this.type==="intersect"){let n={};for(let r of this.list)Object.assign(n,r.simplify(t));return n}else if(this.type==="union")for(let n of this.list)try{return $.resolve(t,n,{}),n.simplify(t)}catch{}return t};$.prototype.toString=function(t){return Xs[this.type]?.(this,t)??`Schema<${this.type}>`};$.prototype.role=function(e,t){let n=$(this);return n.meta={...n.meta,role:e,extra:t},n};for(let e of["default","link","comment","description","max","min","step"])Object.assign($.prototype,{[e](t){let n=$(this);return n.meta={...n.meta,[e]:t},n}});$.prototype.volatile=function(){if(this.meta.volatile)throw new TypeError("volatile schema is already wrapped");return this.extra("volatile",!0)};var Ys={},Ks=Symbol("checked-volatile-schema");function En(e,t=[],n=!1,r=new Map){let i=r.get(e)??new Set;if(i.has(n))return;if(i.add(n),r.set(e,i),e.meta?.volatile&&n)throw new ee("volatile fields require a fixed object path without an enclosing volatile field",{path:t});let o=n||!!e.meta?.volatile;if(e.dict)for(let[a,s]of Object.entries(e.dict))En(s,[...t,a],o,r);if(e.sKey&&En(e.sKey,[...t,"<key>"],!0,r),e.inner&&(e.type!=="lazy"||e.inner[ir])&&En(e.inner,[...t,"*"],!0,r),e.list)for(let a=0;a<e.list.length;a++)En(e.list[a],[...t,String(a)],!0,r)}$.extend=function(t,n){Ys[t]=n};$.resolve=function(t,n,r={},i=!1){if(!n)return[t];if(r[Ks]||(En(n,r.path),r={...r,[Ks]:!0}),n.meta?.volatile){let a=$(n);a.meta={...n.meta,volatile:!1};let[s,l]=$.resolve(t,a,r,i);try{return[Zi(s),l]}catch(u){throw new ee(u instanceof Error?u.message:String(u),r)}}if(r.ignore?.(t,n))return[t];if(Me(t)&&n.type!=="lazy"){if(n.meta.required)throw new ee("missing required value",r);let a=n,s=n.meta.default;for(;a?.type==="intersect"&&Me(s);)a=a.list[0],s=a?.meta.default;if(Me(s))return[t];t=Ar(s)}let o=Ys[n.type];if(!o)throw new ee(`unsupported type "${n.type}"`,r);try{return o(t,n,r,i)}catch(a){if(!n.meta.loose)throw a;return[n.meta.default]}};$.from=function(t){if(Me(t))return $.any();if(["string","number","boolean"].includes(typeof t))return $.const(t).required();if(t[ir])return t;if(typeof t=="function")switch(t){case String:return $.string().required();case Number:return $.number().required();case Boolean:return $.boolean().required();case Function:return $.function().required();default:return $.is(t).required()}else throw new TypeError(`cannot infer schema from ${t}`)};$.lazy=function(t){let n=()=>(r.inner[ir]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),r=new $({type:"lazy",builder:t,inner:{toJSON:n}});return r};$.natural=function(){return $.number().step(1).min(0)};$.percent=function(){return $.number().step(.01).min(0).max(1).role("slider")};$.date=function(){return $.union([$.is(Date),$.transform($.string().role("datetime"),(t,n)=>{let r=new Date(t);if(isNaN(+r))throw new ee(`invalid date "${t}"`,n);return r},!0)])};$.regExp=function(t=""){return $.union([$.is(RegExp),$.transform($.string().role("regexp",{flag:t}),(n,r)=>{try{return new RegExp(n,t)}catch(i){throw new ee(i.message,r)}},!0)])};$.arrayBuffer=function(t){return $.union([$.is(ArrayBuffer),$.is(SharedArrayBuffer),$.transform($.any(),(n,r)=>{if(Ke.isSource(n))return Ke.fromSource(n);throw new ee(`expected ArrayBufferSource but got ${n}`,r)},!0),...t?[$.transform($.string(),(n,r)=>{try{return t==="base64"?Ke.fromBase64(n):Ke.fromHex(n)}catch(i){throw new ee(i.message,r)}},!0)]:[]])};$.extend("lazy",(e,t,n,r)=>(t.inner[ir]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta},En(t.inner,n.path,!0)),$.resolve(e,t.inner,n,r)));$.extend("any",e=>[e]);$.extend("never",(e,t,n)=>{throw new ee(`expected nullable but got ${e}`,n)});$.extend("const",(e,{value:t},n)=>{if($r(e,t))return[t];throw new ee(`expected ${t} but got ${e}`,n)});function no(e,t,n,r,i=!1){let{max:o=1/0,min:a=-1/0}=t;if(e>o)throw new ee(`expected ${n} <= ${o} but got ${e}`,r);if(e<a&&!i)throw new ee(`expected ${n} >= ${a} but got ${e}`,r)}$.extend("string",(e,{meta:t},n)=>{if(typeof e!="string")throw new ee(`expected string but got ${e}`,n);if(t.pattern){let r=new RegExp(t.pattern.source,t.pattern.flags);if(!r.test(e))throw new ee(`expect string to match regexp ${r}`,n)}return no(e.length,t,"string length",n),[e]});function eo(e,t){let n=e.toString();if(n.includes("e"))return e*Math.pow(10,t);let r=n.indexOf(".");if(r===-1)return e*Math.pow(10,t);let i=n.slice(r+1),o=n.slice(0,r);return i.length<=t?+(o+i.padEnd(t,"0")):+(o+i.slice(0,t)+"."+i.slice(t))}function Mf(e,t,n){if(n=Math.abs(n),!/^\d+\.\d+$/.test(n.toString()))return(e-t)%n===0;let r=n.toString().indexOf("."),i=n.toString().slice(r+1).length;return Math.abs(eo(e,i)-eo(t,i))%eo(n,i)===0}$.extend("number",(e,{meta:t},n)=>{if(typeof e!="number")throw new ee(`expected number but got ${e}`,n);no(e,t,"number",n);let{step:r}=t;if(r&&!Mf(e,t.min??0,r))throw new ee(`expected number multiple of ${r} but got ${e}`,n);return[e]});$.extend("boolean",(e,t,n)=>{if(typeof e=="boolean")return[e];throw new ee(`expected boolean but got ${e}`,n)});$.extend("bitset",(e,{bits:t,meta:n},r)=>{let i=0,o=[];if(typeof e=="number"){i=e;for(let a in t)e&t[a]&&o.push(a)}else if(Array.isArray(e)){o=e;for(let a of o){if(typeof a!="string")throw new ee(`expected string but got ${a}`,r);a in t&&(i|=t[a])}}else throw new ee(`expected number or array but got ${e}`,r);return i===n.default?[i]:[i,o]});$.extend("function",(e,t,n)=>{if(typeof e=="function")return[e];throw new ee(`expected function but got ${e}`,n)});$.extend("is",(e,{constructor:t},n)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new ee(`expected ${t.name} but got ${e}`,n)}else{if(Me(e))throw new ee(`expected ${t} but got ${e}`,n);let r=Object.getPrototypeOf(e);for(;r;){if(r.constructor?.name===t)return[e];r=Object.getPrototypeOf(r)}throw new ee(`expected ${t} but got ${e}`,n)}});function Mr(e,t,n,r){try{let[i,o]=$.resolve(e[t],n,{...r,path:[...r.path||[],t]});return o!==void 0&&(e[t]=o),i}catch(i){if(!r?.autofix)throw i;return delete e[t],n.meta.volatile?Zi(n.meta.default):n.meta.default}}$.extend("array",(e,{inner:t,meta:n},r)=>{if(!Array.isArray(e))throw new ee(`expected array but got ${e}`,r);return no(e.length,n,"array length",r,!Me(t.meta.default)),[e.map((i,o)=>Mr(e,o,t,r))]});$.extend("dict",(e,{inner:t,sKey:n},r,i)=>{if(!Pr(e))throw new ee(`expected object but got ${e}`,r);let o={};for(let a in e){let s;try{s=$.resolve(a,n,r)[0]}catch(l){if(i)continue;throw l}o[s]=Mr(e,a,t,r),e[s]=e[a],a!==s&&delete e[a]}return[o]});$.extend("tuple",(e,{list:t},n,r)=>{if(!Array.isArray(e))throw new ee(`expected array but got ${e}`,n);let i=t.map((o,a)=>Mr(e,a,o,n));return r?[i]:(i.push(...e.slice(t.length)),[i])});function to(e,t){for(let n in t)n in e||(e[n]=t[n])}$.extend("object",(e,{dict:t},n,r)=>{if(!Pr(e))throw new ee(`expected object but got ${e}`,n);let i={};for(let o in t){let a=Mr(e,o,t[o],n);(!Me(a)||o in e)&&(i[o]=a)}return r||to(i,e),[i]});$.extend("union",(e,{list:t,toString:n},r,i)=>{let o=[];for(let a of t)try{return $.resolve(e,a,r,i)}catch(s){o.push(s)}throw new ee(`expected ${n()} but got ${JSON.stringify(e)}`,r)});$.extend("intersect",(e,{list:t,toString:n},r,i)=>{if(!t.length)return[e];let o;for(let a of t){let s=$.resolve(e,a,r,!0)[0];if(!Me(s))if(Me(o))o=s;else{if(typeof o!=typeof s)throw new ee(`expected ${n()} but got ${JSON.stringify(e)}`,r);if(typeof s=="object")to(o??(o={}),s);else if(o!==s)throw new ee(`expected ${n()} but got ${JSON.stringify(e)}`,r)}}return!i&&Pr(e)&&to(o,e),[o]});$.extend("transform",(e,{inner:t,callback:n,preserve:r},i)=>{let[o,a=e]=$.resolve(e,t,i,!0);return r?[n(o)]:[n(o),n(a)]});var Xs={};function Ce(e,t,n){Xs[e]=n,Object.assign($,{[e](...r){let i=new $({type:e});return t.forEach((o,a)=>{switch(o){case"sKey":i.sKey=r[a]??$.string();break;case"inner":i.inner=$.from(r[a]);break;case"list":i.list=r[a].map($.from);break;case"dict":i.dict=ct(r[a],$.from);break;case"bits":i.bits={};for(let s in r[a])typeof r[a][s]=="number"&&(i.bits[s]=r[a][s]);break;case"callback":{let s=i.callback=r[a];s.toJSON||(s.toJSON=()=>s.toString());break}case"constructor":{let s=i.constructor=r[a];typeof s=="function"&&(s.toJSON||(s.toJSON=()=>s.name));break}default:i[o]=r[a]}}),e==="object"||e==="dict"?i.meta.default={}:e==="array"||e==="tuple"?i.meta.default=[]:e==="bitset"&&(i.meta.default=0),i}})}Ce("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);Ce("any",[],()=>"any");Ce("never",[],()=>"never");Ce("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);Ce("string",[],()=>"string");Ce("number",[],()=>"number");Ce("boolean",[],()=>"boolean");Ce("bitset",["bits"],()=>"bitset");Ce("function",[],()=>"function");Ce("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);Ce("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);Ce("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);Ce("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,n])=>`${t}${n.meta.required?"":"?"}: ${n.toString()}`).join(", ")} }`);Ce("union",["list"],({list:e},t)=>{let n=e.map(({toString:r})=>r()).join(" | ");return t?`(${n})`:n});Ce("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);Ce("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t));var dt=Object.freeze({enableCatalog:!0,enableWidget:!0,enableCompose:!0,injectGuidance:!0,cdnAllowlist:["https://esm.sh","https://cdn.jsdelivr.net","https://unpkg.com"],allowNetwork:!1,maxWidgetHeight:2400,maxWidgetBytes:4e5,sendPromptMaxChars:4e3,openLinkAllowedOrigins:[]}),ix=$.object({enableCatalog:$.boolean().default(dt.enableCatalog).description("Register `ui_render` (declarative cards, tables, charts, forms)."),enableWidget:$.boolean().default(dt.enableWidget).description("Register `ui_render_widget` (sandboxed streaming HTML/CSS/JS widgets)."),enableCompose:$.boolean().default(dt.enableCompose).description("Register `ui_compose` (one answer that interleaves markdown, native components and widgets). Needs at least one UI capability."),injectGuidance:$.boolean().default(dt.injectGuidance).description("Add a system-prompt section telling the model when and how to answer with UI."),cdnAllowlist:$.array($.string()).default([...dt.cdnAllowlist]).description("Origins widgets may load scripts, styles, fonts and images from (CSP)."),allowNetwork:$.boolean().default(dt.allowNetwork).description("Allow widgets to fetch()/WebSocket to the CDN allowlist (CSP connect-src). Off: no network calls."),maxWidgetHeight:$.natural().min(200).max(8e3).default(dt.maxWidgetHeight).description("Maximum widget frame height in pixels."),maxWidgetBytes:$.natural().min(1e4).default(dt.maxWidgetBytes).description("Reject widgets whose html+css+js exceed this many characters."),sendPromptMaxChars:$.natural().min(100).max(2e4).default(dt.sendPromptMaxChars).description("Longest message a widget, button or form may send back to the conversation."),openLinkAllowedOrigins:$.array($.string()).default([]).description("If non-empty, widgets may only open https links on these origins.")});var Vt="ui_render_widget";function Zs(e,t){let n=[];if(typeof e!="object"||e===null)return["arguments: expected object"];let r=(o,a)=>{let s=e[o];if(s===void 0){a&&n.push(`${o}: required`);return}typeof s!="string"&&n.push(`${o}: expected string`)};r("title"),r("css"),r("html",!0),r("jsFunctions"),typeof e.html=="string"&&e.html.trim()===""&&n.push("html: must not be empty");for(let o of["placeholderMessages","jsExpressions"]){let a=e[o];a!==void 0&&(!Array.isArray(a)||a.some(s=>typeof s!="string"))&&n.push(`${o}: expected array of strings`)}e.initialHeight!==void 0&&(typeof e.initialHeight!="number"||!Number.isFinite(e.initialHeight)||e.initialHeight<=0)&&n.push("initialHeight: expected positive number"),typeof e.html=="string"&&/<script[\s>]/i.test(e.html)&&n.push("html: must not contain <script>; put code in jsFunctions/jsExpressions");let i=["css","html","jsFunctions"].reduce((o,a)=>o+(typeof e[a]=="string"?e[a].length:0),0)+(Array.isArray(e.jsExpressions)?e.jsExpressions.join("").length:0);return i>t.maxWidgetBytes&&n.push(`widget is ${i} characters; the limit is ${t.maxWidgetBytes}`),n}var ft="ui_compose";var pt=Object.freeze({blocks:24,markdownChars:6e4,totalChars:2e5,titleChars:200,idChars:64}),el=Object.freeze(["markdown","catalog","widget"]),tl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ro(e,t){return`${e}#${t}`}var Lf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,nl=Object.freeze({markdown:["id","type","text"],catalog:["id","type","title","root","components"],widget:["id","type","title","initialHeight","placeholderMessages","css","html","jsFunctions","jsExpressions"]});function io(e,t,n={}){let r=[],i=[],o={markdown:0,catalog:0,widget:0,components:0,markdownChars:0};if(!tl(e))return{ok:!1,errors:["arguments: expected object"],warnings:i,blocks:[],stats:o};for(let u of Object.keys(e))u!=="title"&&u!=="blocks"&&r.push(`${u}: unknown field`);if(e.title!==void 0&&(typeof e.title!="string"?r.push("title: expected string"):e.title.length>pt.titleChars&&r.push(`title: longer than ${pt.titleChars} characters`)),!Array.isArray(e.blocks)||e.blocks.length===0)return r.push("blocks: expected a non-empty ordered array"),{ok:!1,errors:r,warnings:i,blocks:[],stats:o};e.blocks.length>pt.blocks&&r.push(`blocks: more than ${pt.blocks} blocks`);let a=new Set,s=[],l=0;return e.blocks.forEach((u,c)=>{let d=`blocks[${c}]`;if(!tl(u)){r.push(`${d}: expected object`);return}if(typeof u.id!="string"||u.id===""){r.push(`${d}.id: expected a non-empty string`);return}if(!Lf.test(u.id)){r.push(`${d}.id: ${JSON.stringify(u.id)} must start with a letter and use only letters, digits, "_" or "-" (max ${pt.idChars})`);return}if(a.has(u.id)){r.push(`${d}.id: duplicate block id ${JSON.stringify(u.id)}`);return}if(a.add(u.id),!el.includes(u.type)){r.push(`${d}.type: expected one of ${el.join(" | ")}, got ${JSON.stringify(u.type)}`);return}let p=nl[u.type];for(let m of Object.keys(u))p.includes(m)||r.push(`${d}(${u.id}).${m}: unknown field for a ${u.type} block`);if(u.type==="catalog"&&n.requireCatalog===!1){r.push(`${d}(${u.id}): catalog blocks are disabled on this host`);return}if(u.type==="widget"&&n.requireWidget===!1){r.push(`${d}(${u.id}): widget blocks are disabled on this host`);return}let f={id:u.id,type:u.type};if(u.type==="markdown"){if(typeof u.text!="string"){r.push(`${d}(${u.id}).text: expected string`);return}if(!u.text.trim()){r.push(`${d}(${u.id}).text: must not be blank`);return}if(u.text.length>pt.markdownChars){r.push(`${d}(${u.id}).text: ${u.text.length} characters; a markdown block holds at most ${pt.markdownChars}`);return}o.markdown++,o.markdownChars+=u.text.length,l+=u.text.length,f.text=u.text}else if(u.type==="catalog"){let m={root:u.root,components:u.components,...u.title!==void 0?{title:u.title}:{}},h=Tr(m);for(let b of h.errors)r.push(`${d}(${u.id}).${b}`);for(let b of h.warnings)i.push(`${u.id}: ${b}`);o.catalog++,o.components+=h.count,l+=JSON.stringify(m).length,f.title=typeof u.title=="string"?u.title:void 0,f.root=u.root,f.components=u.components}else{let m={};for(let h of nl.widget)h!=="type"&&u[h]!==void 0&&(m[h]=u[h]);for(let h of Zs(m,t))r.push(`${d}(${u.id}).${h}`);o.widget++,l+=["css","html","jsFunctions"].reduce((h,b)=>h+(typeof u[b]=="string"?u[b].length:0),0)+(Array.isArray(u.jsExpressions)?u.jsExpressions.join("").length:0);for(let h of["title","initialHeight","placeholderMessages","css","html","jsFunctions","jsExpressions"])u[h]!==void 0&&(f[h]=u[h])}s.push(f)}),!o.markdown&&!o.catalog&&!o.widget&&r.length===0&&r.push("blocks: a composition needs at least one block"),l>pt.totalChars&&r.push(`blocks: the composition is ${l} characters; the limit is ${pt.totalChars}`),{ok:r.length===0,errors:r,warnings:i,blocks:r.length?[]:s,stats:o}}var jf=Object.freeze(["setProps","replaceNode","insertChild","removeNode"]),Ff=Object.freeze({ops:50,nodesPerOp:K.components}),gx=Object.freeze({setProps:["id","props","unset"],replaceNode:["id","node","nodes"],insertChild:["parent","id","index","nodes"],removeNode:["id"]});var Wt="ui_render";var Jt="ui_patch";var jn=require("react");var Be=class extends Error{constructor(n,r){super(r);be(this,"code",n)}},He=class{constructor(t){be(this,"opts",t);be(this,"armedAt");be(this,"lastSend",-1/0);be(this,"now");be(this,"minInterval");this.now=t.now??(()=>Date.now()),this.armedAt=this.now()+(t.armDelayMs??1e3),this.minInterval=t.minIntervalMs??2e3}admitPrompt(t){let n=typeof t=="string"?t.trim():"";if(!n)throw new Be("empty","sendPrompt needs non-empty text");if(n.length>this.opts.policy.sendPromptMaxChars)throw new Be("too-long",`sendPrompt text exceeds ${this.opts.policy.sendPromptMaxChars} characters`);let r=this.now();if(r<this.armedAt)throw new Be("not-armed","sendPrompt is only allowed in response to a user action, not on load");if(r-this.lastSend<this.minInterval)throw new Be("rate-limited","sendPrompt called too often");return this.lastSend=r,n}admitLink(t){let n;try{n=new URL(String(t))}catch{throw new Be("bad-url","openLink needs an absolute https URL")}if(n.protocol!=="https:")throw new Be("bad-url","openLink only opens https URLs");let r=this.opts.policy.openLinkOrigins;if(r.length>0&&!r.some(i=>{try{return new URL(i).origin===n.origin}catch{return!1}}))throw new Be("origin",`openLink: ${n.origin} is not an allowed origin`);return n.href}};function rl(e,t,n){return`${t?.trim()||(e?`Form "${e}" submitted:`:"Form submitted:")}
7
7
  ${JSON.stringify(n,null,2)}`}function il(e,t){if(!e||typeof e!="object")return;let n=e;if(n.__diui===t)switch(n.type){case"rpc":return typeof n.id=="number"&&typeof n.method=="string"?{type:"rpc",id:n.id,method:n.method,params:n.params&&typeof n.params=="object"?n.params:{}}:void 0;case"resize":return typeof n.height=="number"&&Number.isFinite(n.height)?{type:"resize",height:n.height}:void 0;case"error":return{type:"error",kind:String(n.kind??""),message:String(n.message??"").slice(0,500)};case"ready":return{type:"ready",final:n.final===!0};case"state":return n.state&&typeof n.state=="object"&&!Array.isArray(n.state)?{type:"state",state:n.state}:void 0;default:return}}var mt=require("react"),ol="diui:v1:interrupted:",Df=20,zf=2e5,oo=Object.freeze([]),ao=new Map,so=new Map;function lo(e){let t=ao.get(e);if(t)return t;let n=oo;try{let r=localStorage.getItem(ol+e),i=r?JSON.parse(r):void 0;Array.isArray(i)&&(n=i.filter(o=>!!o&&typeof o.callId=="string"&&typeof o.argsRaw=="string"&&typeof o.at=="number"))}catch{}return ao.set(e,n),n}function _f(e,t){if(!t.argsRaw.trim()||t.argsRaw.length>zf)return;let n=[...lo(e).filter(r=>r.callId!==t.callId),t].slice(-Df);ao.set(e,n);try{localStorage.setItem(ol+e,JSON.stringify(n))}catch{}for(let r of[...so.get(e)??[]])r()}function al(e){let t=e??"",n=(0,mt.useCallback)(r=>{let i=so.get(t);return i||so.set(t,i=new Set),i.add(r),()=>{i.delete(r)}},[t]);return(0,mt.useSyncExternalStore)(n,()=>t?lo(t):oo,()=>t?lo(t):oo)}function sl(e,t,n){return t===void 0||t<1e12?!1:e.at>=t-500&&e.at<=(n??1/0)+3e3}function Pt(e,t){let n=(0,mt.useRef)({preparing:!1,raw:""});n.current=e.phase==="preparing"?{preparing:!0,raw:t||n.current.raw}:{preparing:!1,raw:""};let r=(0,mt.useRef)(e);r.current=e,(0,mt.useEffect)(()=>()=>{let{preparing:i,raw:o}=n.current,{sessionId:a,callId:s,toolName:l}=r.current;!r.current.controlled&&i&&o&&a&&_f(a,{callId:s,toolName:l,argsRaw:o,at:Date.now()})},[])}var Re=Object.freeze({cdn:["https://esm.sh","https://cdn.jsdelivr.net","https://unpkg.com"],allowNetwork:!1,maxHeight:2400,sendPromptMaxChars:4e3,openLinkOrigins:[]}),ll=e=>Array.isArray(e)&&e.every(t=>typeof t=="string")?e:void 0;function Ot(e){let t=e&&typeof e=="object"?e.policy:void 0;if(!t||typeof t!="object")return Re;let n=(r,i)=>typeof r=="number"&&Number.isFinite(r)&&r>0?r:i;return{cdn:ll(t.cdn)??Re.cdn,allowNetwork:typeof t.allowNetwork=="boolean"?t.allowNetwork:Re.allowNetwork,maxHeight:n(t.maxHeight,Re.maxHeight),sendPromptMaxChars:n(t.sendPromptMaxChars,Re.sendPromptMaxChars),openLinkOrigins:ll(t.openLinkOrigins)??Re.openLinkOrigins}}var Ne=require("react"),ae=require("react/jsx-runtime");function In(e,t){let[n,r]=(0,Ne.useState)(e),i=(0,Ne.useRef)(e),o=(0,Ne.useRef)(0),a=(0,Ne.useRef)(void 0);return i.current=e,(0,Ne.useEffect)(()=>{let s=Date.now(),l=t-(s-o.current);if(l<=0){o.current=s,r(e);return}a.current===void 0&&(a.current=setTimeout(()=>{a.current=void 0,o.current=Date.now(),r(i.current)},l))},[e,t]),(0,Ne.useEffect)(()=>()=>{a.current!==void 0&&clearTimeout(a.current)},[]),n}function de(e){return(0,ae.jsxs)("div",{className:"diui diui-shell","data-kind":e.kind,"data-state":e.state,"data-plain":e.plain||void 0,"aria-busy":e.state==="generating"||void 0,children:[(0,ae.jsxs)("div",{className:"diui-shell-head",children:[(0,ae.jsx)("span",{className:"diui-shell-icon","aria-hidden":"true",children:e.kind==="widget"?"◇":"▦"}),(0,ae.jsx)("span",{className:"diui-shell-title",children:e.title}),e.state==="generating"&&(0,ae.jsxs)("span",{className:"diui-dots","aria-hidden":"true",children:[(0,ae.jsx)("i",{}),(0,ae.jsx)("i",{}),(0,ae.jsx)("i",{})]}),e.status!==void 0&&(0,ae.jsx)("span",{className:"diui-shell-status",role:"status","aria-live":"polite",children:e.status}),e.actions!==void 0&&(0,ae.jsx)("span",{className:"diui-shell-actions",children:e.actions})]}),e.notice!==void 0&&(0,ae.jsx)("div",{className:"diui-shell-notice",role:"status",children:e.notice}),e.children!==void 0&&(0,ae.jsx)("div",{className:"diui-shell-body",children:e.children})]})}function Te(e){let[t,n]=(0,Ne.useState)(!1);return(0,ae.jsxs)("div",{className:"diui-problem",role:"status",children:[(0,ae.jsx)("span",{children:e.message}),e.detail&&(0,ae.jsx)("button",{type:"button",className:"diui-link","aria-expanded":t,onClick:()=>n(r=>!r),children:t?e.t("details.hide"):e.t("details.show")}),t&&e.detail&&(0,ae.jsx)("pre",{className:"diui-problem-detail",children:e.detail})]})}function Kt(e){let t=e.messages.length?e.messages:[e.fallback],[n,r]=(0,Ne.useState)(0);return(0,Ne.useEffect)(()=>{if(t.length<2)return;let i=setInterval(()=>r(o=>o+1),1800);return()=>clearInterval(i)},[t.length]),(0,ae.jsxs)("div",{className:"diui-placeholder","aria-live":"polite",style:e.height?{minHeight:Math.min(e.height,480)}:void 0,children:[(0,ae.jsx)("div",{className:"diui-skeleton"}),(0,ae.jsx)("div",{className:"diui-placeholder-text",children:t[n%t.length]})]})}function Ge(e){return(0,ae.jsx)("button",{type:"button",className:"diui-head-button",onClick:e.onClick,disabled:e.disabled,title:e.title,children:e.label})}function ul(){let[e,t]=(0,Ne.useState)(void 0),n=(0,Ne.useRef)(void 0);return(0,Ne.useEffect)(()=>()=>{n.current&&clearTimeout(n.current)},[]),[e,r=>{t(r),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>t(void 0),4e3)}]}var Rr=require("react");function cl(e){if(!e||typeof e!="object")return"";let{chunks:t}=e;if(Array.isArray(t)&&t.every(r=>typeof r=="string"))return t.join("");if(typeof e.keys!="function")return"";let n=[];for(let r of e.keys()){let i=e.text?.(r);if(i!==void 0){let a=e.complete?.(r)??!1,s=JSON.stringify(i);if(n.push(`${JSON.stringify(r)}:${a?s:s.slice(0,-1)}`),!a)break;continue}let o=e.value?.(r);if(o===void 0)break;n.push(`${JSON.stringify(r)}:${JSON.stringify(o)}`)}return`{${n.join(",")}${e.closed?.()?"}":""}`}function Uf(e){if(e.phase!=="preparing")return;let t=e.block.args;return t&&typeof t=="object"?t:void 0}function $t(e,t=100){let n=e.useToolCallArgumentsPartial?.(),r=n===void 0?Uf(e):void 0,[i,o]=(0,Rr.useState)(()=>cl(r));return(0,Rr.useEffect)(()=>{if(!r)return;let a=()=>o(l=>{let u=cl(r);return u===l?l:u});a();let s=setInterval(a,t);return()=>clearInterval(s)},[r,t]),n!==void 0?n:r?i:""}var dl=new Set([" "," ",`
8
8
  `,"\r"]);function uo(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r!=="\\"){t+=r;continue}let i=e[n+1];if(i===void 0)break;if(i==="u"){let a=e.slice(n+2,n+6);if(a.length<4||!/^[0-9a-fA-F]{4}$/.test(a))break;let s=parseInt(a,16);if(s>=55296&&s<=56319){let l=e.slice(n+6,n+12);if(!/^\\u[dD][c-fC-F][0-9a-fA-F]{2}$/.test(l)){if(l.length<6)break;t+=String.fromCharCode(s),n+=5;continue}t+=String.fromCharCode(s,parseInt(l.slice(2),16)),n+=11;continue}t+=String.fromCharCode(s),n+=5;continue}t+={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
9
9
  `,r:"\r",t:" "}[i]??i,n+=1}return t}function co(e,t){for(let n=t+1;n<e.length;n++){let r=e[n];if(r==="\\"){n++;continue}if(r==='"')return n+1}return-1}function fl(e,t){let n=e[t];if(n==='"')return co(e,t);if(n==="{"||n==="["){let i=0;for(let o=t;o<e.length;o++){let a=e[o];if(a==='"'){let s=co(e,o);if(s<0)return-1;o=s-1;continue}if(a==="{"||a==="[")i++;else if((a==="}"||a==="]")&&(i--,i===0))return o+1}return-1}let r=t;for(;r<e.length&&!dl.has(e[r])&&e[r]!==","&&e[r]!=="}"&&e[r]!=="]";)r++;return r<e.length?r:-1}function ht(e,t){for(;t<e.length&&dl.has(e[t]);)t++;return t}function fo(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function Bf(e,t){let n=[],r=ht(e,t+1);for(;;){if(r>=e.length)return{value:n,complete:!1,completeItems:n.length};if(e[r]==="]")return{value:n,complete:!0,completeItems:n.length};let i=fl(e,r);if(i<0){let a={value:n,complete:!1,completeItems:n.length};return e[r]==='"'&&(a.partialItem=uo(e.slice(r+1))),a}let o=fo(e.slice(r,i));if(!o.ok)return{value:n,complete:!1,completeItems:n.length};n.push(o.value),r=ht(e,i),e[r]===","&&(r=ht(e,r+1))}}function gt(e){let t={},n=ht(e,0);if(e[n]!=="{")return t;for(n=ht(e,n+1);n<e.length&&!(e[n]==="}"||e[n]!=='"');){let r=co(e,n);if(r<0)break;let i=uo(e.slice(n+1,r-1));if(n=ht(e,r),e[n]!==":"||(n=ht(e,n+1),n>=e.length))break;let o=fl(e,n);if(o>=0){let s=fo(e.slice(n,o));if(!s.ok)break;let l={value:s.value,complete:!0};Array.isArray(s.value)&&(l.completeItems=s.value.length),t[i]=l,n=ht(e,o),e[n]===","&&(n=ht(e,n+1));continue}let a=e[n];a==='"'?t[i]={value:uo(e.slice(n+1)),complete:!1}:a==="["?t[i]=Bf(e,n):t[i]={value:void 0,complete:!1};break}return t}function yt(e){if(!e)return;let t=fo(e);if(!(!t.ok||typeof t.value!="object"||t.value===null||Array.isArray(t.value)))return t.value}var pl=require("react");var jr=require("react"),Lr=new Map,po=new Map;function Fr(e,t,n){let r=Lr.get(e);if(!(r&&r.version>=t)){Lr.set(e,{version:t,title:n??r?.title});for(let i of[...po.get(e)??[]])i()}}function Nn(e){let t=e??"",n=(0,jr.useCallback)(r=>{let i=po.get(t);return i||po.set(t,i=new Set),i.add(r),()=>{i.delete(r)}},[t]);return(0,jr.useSyncExternalStore)(n,()=>Lr.get(t),()=>Lr.get(t))}var Dr="intelligent-ui",Hf=new Set([Wt,Jt,Vt,ft]);function qf(e,t){return t?!1:!(e&&typeof e=="object"&&e.ok===!1)}function ho(e){let t=e&&typeof e=="object"?e.ui:void 0;if(!t||typeof t!="object")return;let n=t;return typeof n.uiId=="string"&&typeof n.version=="number"&&typeof n.root=="string"&&Array.isArray(n.components)?n:void 0}function Vf(e,t,n){if(t.name===Jt){let o=ho(n);o&&Fr(o.uiId,o.version,o.title);return}if(t.name!==Wt&&t.name!==ft)return;let r;try{r=JSON.parse(t.argsRaw)}catch{return}if(t.name===Wt){Fr(e,1,typeof r.title=="string"?r.title:void 0);return}let i=io(r,{});if(i.ok)for(let o of i.blocks)o.type==="catalog"&&Fr(ro(e,o.id),1,o.title)}var ml={kind:Dr,match:e=>e.type==="turn/start"?{id:String(e.data.turn),role:"start"}:e.type==="tool/call"?{id:String(e.data.turn),role:"update"}:e.type==="tool/result"&&e.surfaceOp==="append"?{id:String(e.data.turn),role:"update"}:null,start:(e,t)=>{if(t.event.type!=="turn/start")throw new Error("intelligent-ui start requires turn/start");return{turn:t.event.data.turn,calls:new Map,results:[]}},update:(e,t)=>{let{event:n}=t;if(n.type==="tool/call"){if(!Hf.has(n.data.name))return e.state;let s=new Map(e.state.calls);return s.set(String(n.data.callId),{name:n.data.name,argsRaw:n.data.arguments}),{...e.state,calls:s}}if(n.type!=="tool/result")return e.state;let r=n.data.message,i=String(r.source.callId),o=e.state.calls.get(i);if(!o||!qf(n.data.meta,r.isError===!0))return e.state;Vf(i,o,n.data.meta);let a={kind:"tool-result",callId:i,call:o,content:r.content,isError:!1,meta:n.data.meta,seq:n.seq};return{...e.state,results:[...e.state.results,a]}},buildLocationData:(e,t,n)=>t!=="turn"||e.state===void 0?null:n?.kind==="turn"&&n.turn===e.state.turn&&n.key===Dr&&n.value.results===e.state.results?n:{kind:"turn",turn:e.state.turn,key:Dr,value:{results:e.state.results}}};function hl(e){let t=e.turn.data.get(Dr);if(!t)return[];let n=e.turn.end?.seq??e.seq;return t.results.filter(r=>(r.seq??0)<=n)}var mo=class{constructor(){be(this,"counts",new Map);be(this,"listeners",new Set);be(this,"version",0);be(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));be(this,"snapshot",()=>this.version)}add(t){return this.counts.set(t,(this.counts.get(t)??0)+1),this.bump(),()=>{let n=(this.counts.get(t)??1)-1;n<=0?this.counts.delete(t):this.counts.set(t,n),this.bump()}}has(t){return this.counts.has(t)}bump(){this.version++;for(let t of[...this.listeners])t()}},Tn=new mo;function gl(e){return(0,pl.useSyncExternalStore)(Tn.subscribe,Tn.snapshot,Tn.snapshot),Tn.has(e)}function Mt(e){return e.phase==="start"?e.block.argsRaw:e.phase==="result"?e.block.call?.argsRaw??"":""}function tt(e){return e.content.map(t=>t.type==="text"?t.text??"":"").join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deepseek-harness-intelligent-ui",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "description": "DeepSeek Harness Intelligent UI: generative, interactive UI in the chat (declarative component catalog + sandboxed streaming HTML widgets), inspired by CopilotKit OpenIntelligentUI.",
5
5
  "keywords": [
6
6
  "deepseek-harness",