@vpxa/aikit 0.1.250 → 0.1.252

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.250",
3
+ "version": "0.1.252",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";var i=Object.defineProperty,a=(e,t)=>{let n={};for(var r in e)i(n,r,{get:e[r],enumerable:!0});return t||i(n,Symbol.toStringTag,{value:`Module`}),n};const o=[{selector:`.bk-table`,matches:e=>!r(e.ownerDocument),load:()=>Promise.resolve().then(()=>p).then(e=>({hydrate:t=>e.hydrateTable(t)}))},{selector:`.bk-table`,matches:(t,n)=>r(t.ownerDocument)&&e(t,`.bk-table`,n),load:()=>import(`./form-SyIoFeT1.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateForm(t,n)}))},{selector:`.bk-tree`,matches:e=>!n(e.ownerDocument),load:()=>Promise.resolve().then(()=>x).then(e=>({hydrate:t=>e.hydrateTree(t)}))},{selector:`.bk-tree`,matches:e=>n(e.ownerDocument),load:()=>import(`./flame-graph-CV8KCLKu.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateFlameGraph(t,n)}))},{selector:`.bk-actions`,load:()=>Promise.resolve().then(()=>s).then(e=>({hydrate:(t,n)=>n?.onAction?e.hydrateActions(t,n.onAction):()=>{}}))},{selector:`.bk-checklist`,load:()=>Promise.resolve().then(()=>l).then(e=>({hydrate:(t,n)=>e.hydrateChecklist(t,n)}))},{selector:`.bk-cards`,matches:(n,r)=>t(n.ownerDocument)&&e(n,`.bk-cards`,r),load:()=>import(`./picker-CZJricO9.mjs`).then(e=>({hydrate:(t,n)=>e.hydratePicker(t,n)}))}];var s=a({hydrateActions:()=>c});function c(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}var l=a({hydrateChecklist:()=>f});function u(e){let t=e.createElement(`style`);return t.textContent=`
1
+ import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";function i(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}function a(e){let t=e.createElement(`style`);return t.textContent=`
2
2
  .bk-checklist-progress {
3
3
  margin-bottom: var(--dt-space-3);
4
4
  color: var(--dt-text-secondary);
@@ -12,4 +12,4 @@ import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";var i=Object.definePropert
12
12
  margin: 0;
13
13
  accent-color: var(--dt-accent-fg);
14
14
  }
15
- `,t}function d(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function f(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=u(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=d(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return d(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var p=a({hydrateTable:()=>b});const m=`data-sort-label`,h=`data-sort-dir`,g=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function _(e){let t=e.getAttribute(m);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(m,n),n}function v(e,t,n){for(let[r,i]of e.entries())i.textContent=_(i),r===t?(i.setAttribute(h,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(h)}function y(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function b(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=g.compare(y(e,t),y(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}v(t,a,o)};for(let[e,n]of t.entries()){_(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=_(e),e.removeAttribute(h),e.removeAttribute(m),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}var x=a({hydrateTree:()=>O});function S(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function C(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return S(n);n=n.parentElement}return null}function w(e){return Array.from(e.querySelectorAll(`summary`))}function T(e){return e.open||e.hasAttribute(`open`)}function E(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function D(e,t){e.textContent=t.every(e=>T(e))?`Collapse all`:`Expand all`}function O(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!T(e));for(let n of t)E(n,e);D(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{D(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=w(e).map(t=>{t.tabIndex=0;let n=n=>{let r=w(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!T(a))E(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&T(a)?E(a,!1):C(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return D(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}const k=`data-hydrated`;function A(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function j(e,t,n){e.push(()=>{n(),t.removeAttribute(k)})}function M(e={}){let t=e.container??document.body,n=[];for(let e of A(t,`.bk-table`))e.hasAttribute(k)||(e.setAttribute(k,``),j(n,e,b(e)));for(let e of A(t,`.bk-tree`))e.hasAttribute(k)||(e.setAttribute(k,``),j(n,e,O(e)));for(let r of A(t,`.bk-checklist`))r.hasAttribute(k)||(r.setAttribute(k,``),j(n,r,f(r,e)));for(let r of A(t,`.bk-actions`))if(!r.hasAttribute(k)){if(r.setAttribute(k,``),e.onAction){j(n,r,c(r,e.onAction));continue}n.push(()=>{r.removeAttribute(k)})}return()=>{for(let e of n)e();n.length=0}}async function N(e={}){let t=e.container??document.body,n={...e,container:t},r=[],i=o.map(e=>({definition:e,elements:A(t,e.selector).filter(t=>!t.hasAttribute(k)&&(e.matches?.(t,n)??!0))})).filter(({elements:e})=>e.length>0);if(i.length===0)return()=>{};let a=await Promise.all(i.map(async({definition:e,elements:t})=>({island:await e.load(),elements:t})));for(let{island:e,elements:t}of a)for(let i of t)i.hasAttribute(k)||(i.setAttribute(k,``),j(r,i,e.hydrate(i,n)));return()=>{for(let e of r)e();r.length=0}}export{o as ISLAND_REGISTRY,M as hydrate,c as hydrateActions,N as hydrateAsync,b as hydrateTable,O as hydrateTree};
15
+ `,t}function o(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function s(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=a(r),s=r.createElement(`div`);s.className=`bk-checklist-progress`,e.parentElement?.insertBefore(s,e),r.head?.appendChild(i);let c=[];for(let[e,i]of n.entries()){let a=i.querySelector(`.bk-checklist-icon`),l=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,u=r.createElement(`input`);u.type=`checkbox`,u.className=`bk-checklist-box`,u.checked=i.getAttribute(`data-checked`)===`true`;let d=()=>{i.setAttribute(`data-checked`,String(u.checked));let r=o(s,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:l,checked:u.checked,complete:r.complete,total:r.total}))};u.addEventListener(`change`,d),c.push(()=>{u.removeEventListener(`change`,d)}),a?a.replaceWith(u):i.insertBefore(u,i.firstChild)}return o(s,n),()=>{for(let e of c)e();s.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}const c=`data-sort-label`,l=`data-sort-dir`,u=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function d(e){let t=e.getAttribute(c);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(c,n),n}function f(e,t,n){for(let[r,i]of e.entries())i.textContent=d(i),r===t?(i.setAttribute(l,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(l)}function p(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function m(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,m=null,h=[],g=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=u.compare(p(e,t),p(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}f(t,a,o)};for(let[e,n]of t.entries()){d(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),g()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),h.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){m=i.ownerDocument.createElement(`input`),m.className=`bk-table-filter`,m.placeholder=`Filter...`;let t=()=>{s=m?.value.toLowerCase().trim()??``,g()};i.insertBefore(m,e),m.addEventListener(`input`,t),h.push(()=>{m?.removeEventListener(`input`,t),m?.remove(),m=null})}return g(),()=>{for(let e of h)e();for(let e of t)e.textContent=d(e),e.removeAttribute(l),e.removeAttribute(c),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}function h(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function g(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return h(n);n=n.parentElement}return null}function _(e){return Array.from(e.querySelectorAll(`summary`))}function v(e){return e.open||e.hasAttribute(`open`)}function y(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function b(e,t){e.textContent=t.every(e=>v(e))?`Collapse all`:`Expand all`}function x(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!v(e));for(let n of t)y(n,e);b(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{b(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=_(e).map(t=>{t.tabIndex=0;let n=n=>{let r=_(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!v(a))y(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&v(a)?y(a,!1):g(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return b(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}const S=[{selector:`.bk-table`,matches:e=>!r(e.ownerDocument),load:async()=>({hydrate:e=>m(e)})},{selector:`.bk-table`,matches:(t,n)=>r(t.ownerDocument)&&e(t,`.bk-table`,n),load:()=>import(`./form-SyIoFeT1.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateForm(t,n)}))},{selector:`.bk-tree`,matches:e=>!n(e.ownerDocument),load:async()=>({hydrate:e=>x(e)})},{selector:`.bk-tree`,matches:e=>n(e.ownerDocument),load:()=>import(`./flame-graph-CV8KCLKu.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateFlameGraph(t,n)}))},{selector:`.bk-actions`,load:async()=>({hydrate:(e,t)=>t?.onAction?i(e,t.onAction):()=>{}})},{selector:`.bk-checklist`,load:async()=>({hydrate:(e,t)=>s(e,t)})},{selector:`.bk-cards`,matches:(n,r)=>t(n.ownerDocument)&&e(n,`.bk-cards`,r),load:()=>import(`./picker-CZJricO9.mjs`).then(e=>({hydrate:(t,n)=>e.hydratePicker(t,n)}))}],C=`data-hydrated`;function w(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function T(e,t,n){e.push(()=>{n(),t.removeAttribute(C)})}function E(e={}){let t=e.container??document.body,n=[];for(let e of w(t,`.bk-table`))e.hasAttribute(C)||(e.setAttribute(C,``),T(n,e,m(e)));for(let e of w(t,`.bk-tree`))e.hasAttribute(C)||(e.setAttribute(C,``),T(n,e,x(e)));for(let r of w(t,`.bk-checklist`))r.hasAttribute(C)||(r.setAttribute(C,``),T(n,r,s(r,e)));for(let r of w(t,`.bk-actions`))if(!r.hasAttribute(C)){if(r.setAttribute(C,``),e.onAction){T(n,r,i(r,e.onAction));continue}n.push(()=>{r.removeAttribute(C)})}return()=>{for(let e of n)e();n.length=0}}async function D(e={}){let t=e.container??document.body,n={...e,container:t},r=[],i=S.map(e=>({definition:e,elements:w(t,e.selector).filter(t=>!t.hasAttribute(C)&&(e.matches?.(t,n)??!0))})).filter(({elements:e})=>e.length>0);if(i.length===0)return()=>{};let a=await Promise.all(i.map(async({definition:e,elements:t})=>({island:await e.load(),elements:t})));for(let{island:e,elements:t}of a)for(let i of t)i.hasAttribute(C)||(i.setAttribute(C,``),T(r,i,e.hydrate(i,n)));return()=>{for(let e of r)e();r.length=0}}export{S as ISLAND_REGISTRY,E as hydrate,i as hydrateActions,D as hydrateAsync,m as hydrateTable,x as hydrateTree};
@@ -1,4 +1,4 @@
1
- import{createRequire as e}from"node:module";import{dirname as t,extname as n,join as r}from"node:path";import{CHUNK_SIZES as i,createLogger as a}from"../../core/dist/index.js";import{copyFileSync as o,existsSync as s,mkdirSync as c,readFileSync as l,readdirSync as u,realpathSync as d,renameSync as f}from"node:fs";import{homedir as p}from"node:os";import{fileURLToPath as m,pathToFileURL as ee}from"node:url";function h(){return{mode:`unknown`,reason:``,pathsChecked:[],os:process.platform,arch:process.arch,nodeVersion:process.version,webTreeSitterImportable:!1,healAttempted:!1,healSuccess:!1,healError:null,initError:null,wasmDir:null,grammarCount:0}}let g=h();const _={get(){return{...g,pathsChecked:g.pathsChecked.map(e=>({...e}))}},update(e){Object.assign(g,e)},reset(){g=h()}},v=t(m(import.meta.url));function y(e){try{return d(e)}catch{return e}}const b={".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`},x=new Set(Object.keys(b));let S;function C(e){return[...new Set(Object.values(b))].filter(t=>s(r(e,t))).length}function w(){let e=y(v),t=[r(e,`..`,`..`,`wasm`),r(e,`..`,`wasm`)];for(let e of t){let t=y(e);if(s(r(t,`tree-sitter.wasm`)))return t}return null}function T(){let e=y(v),t=[r(p(),`.aikit`,`cache`,`wasm`),r(e,`..`,`..`,`wasm`),r(e,`..`,`wasm`),r(process.cwd(),`node_modules`,`@aikit`,`chunker`,`wasm`)],n=[];for(let e of t){let t=y(e),i=s(r(t,`tree-sitter.wasm`));if(n.push({path:t,exists:i}),i)return _.update({mode:`wasm`,reason:`Resolved WASM directory`,pathsChecked:n,wasmDir:t,grammarCount:C(t),initError:null}),t}return _.update({mode:`unknown`,reason:`No WASM directory containing tree-sitter.wasm was found`,pathsChecked:n,wasmDir:null,grammarCount:0}),null}function E(){return S===void 0&&(S=T()),S}function D(e){S=e===null?null:y(e),_.update({mode:S?`wasm`:`unknown`,reason:S?`WASM directory overridden at runtime`:`WASM directory override cleared`,wasmDir:S,grammarCount:S?C(S):0})}function O(e){let t=b[e];if(!t)return null;let n=E();if(!n)return null;let i=r(n,t);return s(i)?i:null}function k(){let e=E();if(!e)return null;let t=r(e,`tree-sitter.wasm`);return s(t)?t:null}const te=[`CI`,`GITHUB_ACTIONS`,`JENKINS_URL`,`GITLAB_CI`,`TF_BUILD`];function ne(){return te.some(e=>!!process.env[e])}function A(e,t){let n=`${t}.tmp-${process.pid}`;o(e,n),f(n,t)}function j(e){let t=r(p(),`.aikit`,`cache`,`wasm`);try{c(t,{recursive:!0});let n=u(e).filter(e=>e.endsWith(`.wasm`)),i=0;for(let a of n){let n=r(e,a),o=r(t,a);s(o)||(A(n,o),i++)}if(s(r(t,`tree-sitter.wasm`))){let e=u(t).filter(e=>e.endsWith(`.wasm`)&&e!==`tree-sitter.wasm`).length;return _.update({healSuccess:!0,healError:null,wasmDir:t,grammarCount:e,reason:`Populated user WASM cache from bundled dir (${i} files copied)`}),t}return _.update({healSuccess:!1,healError:`tree-sitter.wasm not present in cache after copy`}),null}catch(e){return _.update({healSuccess:!1,healError:String(e),reason:`Failed to populate user WASM cache`}),null}}function M(){if(ne())return _.update({healAttempted:!1,healSuccess:!1,healError:null,reason:`CI environment detected - skipping auto-heal`}),null;_.update({healAttempted:!0,healSuccess:!1,healError:null,reason:`Attempting to heal WASM cache`});let n=w();if(n){let e=j(n);if(e)return e}try{let i=e(import.meta.url),a=r(p(),`.aikit`,`cache`,`wasm`),o;try{o=t(i.resolve(`web-tree-sitter/package.json`))}catch{return _.update({healSuccess:!1,healError:n?`Bundled copy failed and web-tree-sitter not in node_modules`:`Bundled WASM dir not found and web-tree-sitter not in node_modules`,reason:`Cannot heal WASM cache - no source available`}),null}let l;try{l=t(i.resolve(`tree-sitter-wasms/package.json`))}catch{c(a,{recursive:!0});let e=r(o,`tree-sitter.wasm`);return s(e)&&(A(e,r(a,`tree-sitter.wasm`)),s(r(a,`tree-sitter.wasm`)))?(_.update({healSuccess:!0,healError:null,wasmDir:a,grammarCount:0,reason:`Healed parser WASM from web-tree-sitter (no grammar wasms available)`}),a):(_.update({healSuccess:!1,healError:`tree-sitter-wasms not found (devDependency only)`,reason:`Cannot heal grammar WASM cache without tree-sitter-wasms package`}),null)}c(a,{recursive:!0});let d=r(o,`tree-sitter.wasm`);s(d)&&A(d,r(a,`tree-sitter.wasm`));let f=r(l,`out`),m=0;if(s(f)){let e=u(f).filter(e=>e.endsWith(`.wasm`));m=e.length;for(let t of e)A(r(f,t),r(a,t))}return s(r(a,`tree-sitter.wasm`))?(_.update({healSuccess:!0,healError:null,wasmDir:a,grammarCount:m,reason:`Healed WASM cache from node_modules (dev environment)`}),a):(_.update({healSuccess:!1,healError:`tree-sitter.wasm not found after copy`,reason:`WASM cache heal completed without parser runtime`}),null)}catch(e){return _.update({healSuccess:!1,healError:String(e),reason:`WASM cache heal failed`}),null}}const N=a(`wasm-runtime`);async function re(){try{return await import(`web-tree-sitter`)}catch{}try{return e(import.meta.url)(`web-tree-sitter`)}catch{}let n=t(m(import.meta.url)),i=[r(n,`..`,`node_modules`,`web-tree-sitter`,`tree-sitter.js`),r(n,`..`,`..`,`..`,`..`,`web-tree-sitter`,`tree-sitter.js`),r(n,`..`,`..`,`..`,`..`,`..`,`node_modules`,`web-tree-sitter`,`tree-sitter.js`)];for(let e of i)if(s(e))try{return await import(ee(e).href)}catch{}throw Error(`web-tree-sitter module not found. Tried: ESM import, createRequire, and path-based resolution from ${n}`)}async function P(){let e=await re(),t=typeof e.default?.init==`function`?e.default:e.Parser;if(!t||typeof t.init!=`function`)throw Error(`Unsupported web-tree-sitter export shape: ${Object.keys(e).join(`, `)}`);return t}var F=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;recoveryAttempts=0;static MAX_RECOVERIES=3;static MAX_PARSE_SIZE=1e6;static async initialize(){if(e.instance)return e.instance;let t=new e;return await t.init()?(e.instance=t,t):null}static get(){return e.instance}static async ensure(){let t=e.get();if(t)return t;let n=await e.initialize();if(!n)throw Error(`Failed to initialize WASM tree-sitter runtime`);return n}static dispose(){e.instance&&=(e.instance.cleanupParser(),null)}cleanupParser(){this.parser?.delete(),this.parser=null,this.languages.clear(),this.loadedGrammars.clear()}disableWasmParsing(){this.cleanupParser(),this.recoveryAttempts=e.MAX_RECOVERIES}async init(){try{let e;try{e=await P(),_.update({webTreeSitterImportable:!0})}catch(e){return _.update({webTreeSitterImportable:!1,mode:`regex`,reason:`web-tree-sitter import failed: ${String(e)}`,initError:String(e)}),N.warn(`web-tree-sitter module not importable`,{error:String(e)}),!1}let t=k();if(!t){N.info(`Parser WASM not found, attempting auto-heal...`);let e=M();e&&(D(e),t=k(),N.info(`Auto-heal succeeded`,{dir:e}))}if(!t)return _.update({mode:`regex`,reason:`Parser WASM file not found after heal attempt`}),N.warn(`Parser WASM file not found (auto-heal failed or skipped)`),!1;let n=t;return await e.init({locateFile:()=>n}),this.parser=new e,this.autoPopulateUserCache(),_.update({mode:`wasm`,reason:`WASM parser initialized successfully`,initError:null}),N.debug(`WASM tree-sitter parser initialized`),!0}catch(e){return _.update({mode:`regex`,reason:`WASM initialization failed: ${String(e)}`,initError:String(e)}),N.warn(`Failed to initialize WASM tree-sitter`,{error:String(e)}),!1}}async loadLanguage(e){let t=this.languages.get(e);if(t)return t;let n=O(e);if(!n)return null;let r=this.loadedGrammars.get(n);if(r)return this.languages.set(e,r),r;try{let t=await(await P()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),N.debug(`Loaded grammar`,{ext:e}),t}catch(t){return N.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(t,n){if(!this.parser)return null;if(t.length>e.MAX_PARSE_SIZE)return N.warn(`File too large for WASM parser, skipping`,{ext:n,size:t.length}),null;let r=await this.loadLanguage(n);if(!r)return null;try{return this.parser.setLanguage(r),this.parser.parse(t)}catch(r){if(N.warn(`WASM parser crashed, attempting recovery...`,{ext:n,error:String(r)}),this.recoveryAttempts>=e.MAX_RECOVERIES)return N.error(`WASM parser recovery limit reached, falling back to null`,{attempts:this.recoveryAttempts}),this.disableWasmParsing(),null;if(!await this.recoverParser(n))return N.error(`WASM parser recovery failed, falling back to null`),null;try{return this.parser?.parse(t)??null}catch(e){return N.error(`WASM parser crashed again after recovery, falling back to null`,{error:String(e)}),null}}}async recoverParser(e){this.recoveryAttempts++;try{this.cleanupParser();let t=await P(),n=k();if(!n)return N.error(`Cannot recover: parser WASM file not found`),!1;let r=n;await t.init({locateFile:()=>r}),this.parser=new t;let i=await this.loadLanguage(e);return i?(this.parser.setLanguage(i),N.info(`WASM parser recovered successfully`,{attempt:this.recoveryAttempts}),!0):(N.error(`Cannot recover: failed to reload language`,{ext:e}),!1)}catch(e){return N.error(`WASM parser recovery threw`,{error:String(e)}),!1}}autoPopulateUserCache(){try{if(s(r(r(p(),`.aikit`,`cache`,`wasm`),`tree-sitter.wasm`)))return;let e=w();if(!e)return;N.debug(`Auto-populating user WASM cache for future reliability`,{from:e}),j(e)}catch(e){N.debug(`Auto-populate user cache failed (non-fatal)`,{error:String(e)})}}hasLanguage(e){return x.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function I(){return await F.initialize()!==null}const ie=a(`call-graph`),ae=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),oe=new Set([`call_expression`,`new_expression`,`call`]);function se(e,t){let r=n(t).toLowerCase(),i=F.get();if(i?.isLanguageLoaded(r)){let n=i.getParser(),a=i.getLanguage(r);if(n&&a){n.setLanguage(a);let r;try{r=n.parse(e)}catch(e){return ie.warn(`WASM parser.parse() crashed in call-graph extraction`,{file:t,error:String(e)}),null}if(r){let e=[];return L(r.rootNode,t,`<module>`,e),e}}}return null}function L(e,t,n,r){if(!e)return;let i=n;if(ae.has(e.type)&&(i=ce(e)??n),oe.has(e.type)){let n=le(e);n&&r.push({callerFile:t,callerName:i,calleeName:n,line:(e.startPosition?.row??0)+1})}for(let n=0;n<(e.childCount??0);n++){let a=e.child(n);a&&L(a,t,i,r)}}function ce(e){for(let t=0;t<(e.childCount??0);t++){let n=e.child(t);if(n&&(n.type===`identifier`||n.type===`property_identifier`||n.type===`name`))return n.text??null}return null}function le(e){let t=e.childForFieldName?.(`function`)??e.child(0);return t?t.type===`identifier`||t.type===`name`?t.text??null:t.type===`member_expression`||t.type===`attribute`?(t.childForFieldName?.(`property`)??t.childForFieldName?.(`attribute`))?.text??null:e.type===`new_expression`?e.child(1)?.text??null:null:null}var R=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.code.max}chunk(e,t){let n=this.findDeclarationBoundaries(e);if(n.length===0)return this.fallbackChunk(e,t);let r=[];for(let i=0;i<n.length;i++){let a=n[i].offset,o=i+1<n.length?n[i+1].offset:e.length,s=e.slice(a,o).trim();if(s=`// File: ${t.sourcePath}\n`+s,s.length>this.maxChunkSize){let n=this.splitByLines(s,this.maxChunkSize),i=this.getLineNumber(e,a);for(let e of n){let n=e.split(`
1
+ import{createRequire as e}from"node:module";import{dirname as t,extname as n,join as r}from"node:path";import{CHUNK_SIZES as i,createLogger as a}from"../../core/dist/index.js";import{copyFileSync as o,existsSync as s,mkdirSync as c,readFileSync as l,readdirSync as u,realpathSync as d,renameSync as f}from"node:fs";import{homedir as p}from"node:os";import{fileURLToPath as m,pathToFileURL as ee}from"node:url";function h(){return{mode:`unknown`,reason:``,pathsChecked:[],os:process.platform,arch:process.arch,nodeVersion:process.version,webTreeSitterImportable:!1,healAttempted:!1,healSuccess:!1,healError:null,initError:null,wasmDir:null,grammarCount:0}}let g=h();const _={get(){return{...g,pathsChecked:g.pathsChecked.map(e=>({...e}))}},update(e){Object.assign(g,e)},reset(){g=h()}},v=t(m(import.meta.url));function y(e){try{return d(e)}catch{return e}}const b={".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`},x=new Set(Object.keys(b));let S;function C(e){return[...new Set(Object.values(b))].filter(t=>s(r(e,t))).length}function w(){let e=y(v),t=[r(e,`..`,`..`,`wasm`),r(e,`..`,`wasm`)];for(let e of t){let t=y(e);if(s(r(t,`tree-sitter.wasm`)))return t}return null}function T(){let e=y(v),t=[r(p(),`.aikit`,`cache`,`wasm`),r(e,`..`,`..`,`wasm`),r(e,`..`,`wasm`),r(process.cwd(),`node_modules`,`@aikit`,`chunker`,`wasm`)],n=[];for(let e of t){let t=y(e),i=s(r(t,`tree-sitter.wasm`));if(n.push({path:t,exists:i}),i)return _.update({mode:`wasm`,reason:`Resolved WASM directory`,pathsChecked:n,wasmDir:t,grammarCount:C(t),initError:null}),t}return _.update({mode:`unknown`,reason:`No WASM directory containing tree-sitter.wasm was found`,pathsChecked:n,wasmDir:null,grammarCount:0}),null}function E(){return S===void 0&&(S=T()),S}function D(e){S=e===null?null:y(e),_.update({mode:S?`wasm`:`unknown`,reason:S?`WASM directory overridden at runtime`:`WASM directory override cleared`,wasmDir:S,grammarCount:S?C(S):0})}function O(e){let t=b[e];if(!t)return null;let n=E();if(!n)return null;let i=r(n,t);return s(i)?i:null}function k(){let e=E();if(!e)return null;let t=r(e,`tree-sitter.wasm`);return s(t)?t:null}const te=[`CI`,`GITHUB_ACTIONS`,`JENKINS_URL`,`GITLAB_CI`,`TF_BUILD`];function ne(){return te.some(e=>!!process.env[e])}function A(e,t){let n=`${t}.tmp-${process.pid}`;o(e,n),f(n,t)}function j(e){let t=r(p(),`.aikit`,`cache`,`wasm`);try{c(t,{recursive:!0});let n=u(e).filter(e=>e.endsWith(`.wasm`)),i=0;for(let a of n){let n=r(e,a),o=r(t,a);s(o)||(A(n,o),i++)}if(s(r(t,`tree-sitter.wasm`))){let e=u(t).filter(e=>e.endsWith(`.wasm`)&&e!==`tree-sitter.wasm`).length;return _.update({healSuccess:!0,healError:null,wasmDir:t,grammarCount:e,reason:`Populated user WASM cache from bundled dir (${i} files copied)`}),t}return _.update({healSuccess:!1,healError:`tree-sitter.wasm not present in cache after copy`}),null}catch(e){return _.update({healSuccess:!1,healError:String(e),reason:`Failed to populate user WASM cache`}),null}}function M(){if(ne())return _.update({healAttempted:!1,healSuccess:!1,healError:null,reason:`CI environment detected - skipping auto-heal`}),null;_.update({healAttempted:!0,healSuccess:!1,healError:null,reason:`Attempting to heal WASM cache`});let n=w();if(n){let e=j(n);if(e)return e}try{let i=e(import.meta.url),a=r(p(),`.aikit`,`cache`,`wasm`),o;try{o=t(i.resolve(`web-tree-sitter/package.json`))}catch{return _.update({healSuccess:!1,healError:n?`Bundled copy failed and web-tree-sitter not in node_modules`:`Bundled WASM dir not found and web-tree-sitter not in node_modules`,reason:`Cannot heal WASM cache - no source available`}),null}let l;try{l=t(i.resolve(`tree-sitter-wasms/package.json`))}catch{c(a,{recursive:!0});let e=r(o,`tree-sitter.wasm`);return s(e)&&(A(e,r(a,`tree-sitter.wasm`)),s(r(a,`tree-sitter.wasm`)))?(_.update({healSuccess:!0,healError:null,wasmDir:a,grammarCount:0,reason:`Healed parser WASM from web-tree-sitter (no grammar wasms available)`}),a):(_.update({healSuccess:!1,healError:`tree-sitter-wasms not found (devDependency only)`,reason:`Cannot heal grammar WASM cache without tree-sitter-wasms package`}),null)}c(a,{recursive:!0});let d=r(o,`tree-sitter.wasm`);s(d)&&A(d,r(a,`tree-sitter.wasm`));let f=r(l,`out`),m=0;if(s(f)){let e=u(f).filter(e=>e.endsWith(`.wasm`));m=e.length;for(let t of e)A(r(f,t),r(a,t))}return s(r(a,`tree-sitter.wasm`))?(_.update({healSuccess:!0,healError:null,wasmDir:a,grammarCount:m,reason:`Healed WASM cache from node_modules (dev environment)`}),a):(_.update({healSuccess:!1,healError:`tree-sitter.wasm not found after copy`,reason:`WASM cache heal completed without parser runtime`}),null)}catch(e){return _.update({healSuccess:!1,healError:String(e),reason:`WASM cache heal failed`}),null}}const N=a(`wasm-runtime`);async function re(){try{return await import(`web-tree-sitter`)}catch{}try{return e(import.meta.url)(`web-tree-sitter`)}catch{}let n=t(m(import.meta.url)),i=[r(n,`..`,`node_modules`,`web-tree-sitter`,`tree-sitter.js`),r(n,`..`,`..`,`..`,`..`,`web-tree-sitter`,`tree-sitter.js`),r(n,`..`,`..`,`..`,`..`,`..`,`node_modules`,`web-tree-sitter`,`tree-sitter.js`)];for(let e of i)if(s(e))try{return await import(ee(e).href)}catch{}throw Error(`web-tree-sitter module not found. Tried: ESM import, createRequire, and path-based resolution from ${n}`)}async function P(){let e=await re(),t=typeof e.default?.init==`function`?e.default:e.Parser;if(!t||typeof t.init!=`function`)throw Error(`Unsupported web-tree-sitter export shape: ${Object.keys(e).join(`, `)}`);return t}var F=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;recoveryAttempts=0;static MAX_RECOVERIES=3;static MAX_PARSE_SIZE=1e6;static async initialize(){if(e.instance)return e.instance;let t=new e;return await t.init()?(e.instance=t,t):null}static get(){return e.instance}static async ensure(){let t=e.get();if(t)return t;let n=await e.initialize();if(!n)throw Error(`Failed to initialize WASM tree-sitter runtime`);return n}static dispose(){e.instance&&=(e.instance.cleanupParser(),null)}cleanupParser(){this.parser?.delete(),this.parser=null,this.languages.clear(),this.loadedGrammars.clear()}disableWasmParsing(){this.cleanupParser(),this.recoveryAttempts=e.MAX_RECOVERIES}async init(){try{let e;try{e=await P(),_.update({webTreeSitterImportable:!0})}catch(e){return _.update({webTreeSitterImportable:!1,mode:`regex`,reason:`web-tree-sitter import failed: ${String(e)}`,initError:String(e)}),N.warn(`web-tree-sitter module not importable`,{error:String(e)}),!1}let t=k();if(!t){N.info(`Parser WASM not found, attempting auto-heal...`);let e=M();e&&(D(e),t=k(),N.info(`Auto-heal succeeded`,{dir:e}))}if(!t)return _.update({mode:`regex`,reason:`Parser WASM file not found after heal attempt`}),N.warn(`Parser WASM file not found (auto-heal failed or skipped)`),!1;let n=t;return await e.init({locateFile:()=>n}),this.parser=new e,this.autoPopulateUserCache(),_.update({mode:`wasm`,reason:`WASM parser initialized successfully`,initError:null}),N.debug(`WASM tree-sitter parser initialized`),!0}catch(e){return _.update({mode:`regex`,reason:`WASM initialization failed: ${String(e)}`,initError:String(e)}),N.warn(`Failed to initialize WASM tree-sitter`,{error:String(e)}),!1}}async loadLanguage(e){let t=this.languages.get(e);if(t)return t;let n=O(e);if(!n)return null;let r=this.loadedGrammars.get(n);if(r)return this.languages.set(e,r),r;try{let t=await(await P()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),N.debug(`Loaded grammar`,{ext:e}),t}catch(t){return N.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(t,n){if(!this.parser)return null;if(t.length>e.MAX_PARSE_SIZE)return N.debug(`File too large for WASM parser, skipping`,{ext:n,size:t.length}),null;let r=await this.loadLanguage(n);if(!r)return null;try{return this.parser.setLanguage(r),this.parser.parse(t)}catch(r){if(N.warn(`WASM parser crashed, attempting recovery...`,{ext:n,error:String(r)}),this.recoveryAttempts>=e.MAX_RECOVERIES)return N.error(`WASM parser recovery limit reached, falling back to null`,{attempts:this.recoveryAttempts}),this.disableWasmParsing(),null;if(!await this.recoverParser(n))return N.error(`WASM parser recovery failed, falling back to null`),null;try{return this.parser?.parse(t)??null}catch(e){return N.error(`WASM parser crashed again after recovery, falling back to null`,{error:String(e)}),null}}}async recoverParser(e){this.recoveryAttempts++;try{this.cleanupParser();let t=await P(),n=k();if(!n)return N.error(`Cannot recover: parser WASM file not found`),!1;let r=n;await t.init({locateFile:()=>r}),this.parser=new t;let i=await this.loadLanguage(e);return i?(this.parser.setLanguage(i),N.info(`WASM parser recovered successfully`,{attempt:this.recoveryAttempts}),!0):(N.error(`Cannot recover: failed to reload language`,{ext:e}),!1)}catch(e){return N.error(`WASM parser recovery threw`,{error:String(e)}),!1}}autoPopulateUserCache(){try{if(s(r(r(p(),`.aikit`,`cache`,`wasm`),`tree-sitter.wasm`)))return;let e=w();if(!e)return;N.debug(`Auto-populating user WASM cache for future reliability`,{from:e}),j(e)}catch(e){N.debug(`Auto-populate user cache failed (non-fatal)`,{error:String(e)})}}hasLanguage(e){return x.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function I(){return await F.initialize()!==null}const ie=a(`call-graph`),ae=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),oe=new Set([`call_expression`,`new_expression`,`call`]);function se(e,t){let r=n(t).toLowerCase(),i=F.get();if(i?.isLanguageLoaded(r)){let n=i.getParser(),a=i.getLanguage(r);if(n&&a){n.setLanguage(a);let r;try{r=n.parse(e)}catch(e){return ie.warn(`WASM parser.parse() crashed in call-graph extraction`,{file:t,error:String(e)}),null}if(r){let e=[];return L(r.rootNode,t,`<module>`,e),e}}}return null}function L(e,t,n,r){if(!e)return;let i=n;if(ae.has(e.type)&&(i=ce(e)??n),oe.has(e.type)){let n=le(e);n&&r.push({callerFile:t,callerName:i,calleeName:n,line:(e.startPosition?.row??0)+1})}for(let n=0;n<(e.childCount??0);n++){let a=e.child(n);a&&L(a,t,i,r)}}function ce(e){for(let t=0;t<(e.childCount??0);t++){let n=e.child(t);if(n&&(n.type===`identifier`||n.type===`property_identifier`||n.type===`name`))return n.text??null}return null}function le(e){let t=e.childForFieldName?.(`function`)??e.child(0);return t?t.type===`identifier`||t.type===`name`?t.text??null:t.type===`member_expression`||t.type===`attribute`?(t.childForFieldName?.(`property`)??t.childForFieldName?.(`attribute`))?.text??null:e.type===`new_expression`?e.child(1)?.text??null:null:null}var R=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??i.code.max}chunk(e,t){let n=this.findDeclarationBoundaries(e);if(n.length===0)return this.fallbackChunk(e,t);let r=[];for(let i=0;i<n.length;i++){let a=n[i].offset,o=i+1<n.length?n[i+1].offset:e.length,s=e.slice(a,o).trim();if(s=`// File: ${t.sourcePath}\n`+s,s.length>this.maxChunkSize){let n=this.splitByLines(s,this.maxChunkSize),i=this.getLineNumber(e,a);for(let e of n){let n=e.split(`
2
2
  `).length;r.push({text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:i,endLine:i+n-1}),i+=n}}else{let n=this.getLineNumber(e,a);r.push({text:s,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:n,endLine:n+s.split(`
3
3
  `).length-1})}}if(n[0].offset>0){let i=e.slice(0,n[0].offset).trim();i.length>0&&r.unshift({text:`// File: ${t.sourcePath}\n${i}`,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:0,startLine:1,endLine:this.getLineNumber(e,n[0].offset)-1})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}findDeclarationBoundaries(e){let t=/^(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|const|enum|abstract\s+class)\s+(\w+)/gm,n=[],r;for(;(r=t.exec(e))!==null;){let t=e.lastIndexOf(`
4
4
  `,r.index-1)+1,i=t,a=e.slice(0,t).split(`
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{rm as e}from"node:fs/promises";import{homedir as t}from"node:os";import{join as n}from"node:path";import{EMBEDDING_DEFAULTS as r}from"../../core/dist/index.js";let i=null;async function a(){if(!i){try{i=await import(`@huggingface/transformers`)}catch(e){if(e instanceof Error&&e.message.includes(`Cannot find module`)){let{createRequire:e}=await import(`node:module`);i=e(import.meta.url)(`@huggingface/transformers`)}else throw e}i.env.cacheDir=n(t(),`.cache`,`huggingface`,`transformers-js`)}return i}var o=class{pipe=null;shutdownPromise=null;dimensions;modelId;nativeDim;queryPrefix;threadConfig;constructor(e={}){if(this.modelId=e.model??r.model,this.nativeDim=e.nativeDim??r.nativeDim,this.dimensions=e.dimensions??r.dimensions,this.dimensions>this.nativeDim)throw Error(`Configured dimensions (${this.dimensions}) exceeds model native output (${this.nativeDim}). Matryoshka truncation cannot upscale — dimensions must be <= nativeDim.`);this.queryPrefix=e.queryPrefix??this.detectQueryPrefix(this.modelId),this.threadConfig={interOp:e.interOpNumThreads??1,intraOp:e.intraOpNumThreads??4}}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}getPipelineOptions(e){let t=e.backends.onnx;t.wasm||={};let n=t.wasm;return n.numThreads=this.threadConfig.intraOp,{dtype:`q8`,session_options:{interOpNumThreads:this.threadConfig.interOp,intraOpNumThreads:this.threadConfig.intraOp}}}computeNorm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t)}truncateAndRenorm(e){if(this.dimensions>=this.nativeDim){let t=this.computeNorm(e);if(!Number.isFinite(t))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(t===0)throw Error(`Embedding produced zero-norm vector from ONNX output`);return e}let t=e.subarray(0,this.dimensions),n=this.computeNorm(t);if(!Number.isFinite(n))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(n===0)throw Error(`Embedding produced zero-norm vector after truncation — input may be degenerate`);let r=new Float32Array(this.dimensions);for(let e=0;e<this.dimensions;e++)r[e]=t[e]/n;return r}async initialize(){if(this.pipe)return;this.shutdownPromise=null;let{pipeline:r,env:i}=await a();try{this.pipe=await r(`feature-extraction`,this.modelId,this.getPipelineOptions(i))}catch(a){let o=a.message?.toLowerCase()??``;if(this.isCorruptionError(o)){let a=n(i.cacheDir??n(t(),`.cache`,`huggingface`,`transformers-js`),this.modelId);console.error(`[aikit:auto-heal] Detected corrupted model cache for "${this.modelId}". Clearing cache at ${a} and retrying download...`);try{await e(a,{recursive:!0,force:!0})}catch{}try{this.pipe=await r(`feature-extraction`,this.modelId,this.getPipelineOptions(i)),console.error(`[aikit:auto-heal] Model "${this.modelId}" re-downloaded successfully.`);return}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}" after auto-heal: ${e.message}`)}}throw Error(`Failed to initialize embedding model "${this.modelId}": ${a.message}`)}}isCorruptionError(e){return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`checksum`,`corrupt`,`could not load`,`onnx`,`malformed`].some(t=>e.includes(t))}async shutdown(){return this.shutdownPromise||=this._doShutdown(),this.shutdownPromise}async _doShutdown(){let e=this.pipe;if(e)try{let t=e;typeof t.dispose==`function`?await t.dispose():typeof t.model?.dispose==`function`&&await t.model.dispose()}catch{}finally{this.pipe=null}}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t?.data)throw Error(`Embedding pipeline returned no output`);try{let e=new Float32Array(t.data);return this.truncateAndRenorm(e)}finally{t.dispose?.()}}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a?.data)throw Error(`Embedding pipeline returned no output`);try{if(i.length===1){let e=new Float32Array(a.data);n.push(this.truncateAndRenorm(e))}else for(let e=0;e<i.length;e++){let t=e*this.nativeDim,r=a.data.slice(t,t+this.nativeDim);n.push(this.truncateAndRenorm(new Float32Array(r)))}}finally{a.dispose?.()}}return n}};let s=null,c=null,l=!1;const u=Number(process.env.AIKIT_EMBED_IDLE_MS),d=Number.isFinite(u)&&u>=0?u:6e4,f=Number(process.env.AIKIT_EMBED_MAX_RSS_MB),p=Number.isFinite(f)&&f>0?f:1536;function m(){let e=process.memoryUsage;return(typeof e.rss==`function`?e.rss():e().rss)/(1024*1024)>p}function h(e){process.send?.(e)}function g(){c&&=(clearTimeout(c),null)}async function _(){if(!s)return;let e=s;s=null,await e.shutdown?.()}async function v(e,t){l&&process.exit(e),l=!0,g(),t?.notifyIdle&&h({type:`idle-exit`});try{await _()}finally{process.exit(e)}}function y(){g(),d!==0&&(c=setTimeout(()=>{v(0,{notifyIdle:!0})},d))}function b(e){return Array.from(e)}function x(e){return e instanceof Error?e.message:String(e)}function S(){if(!s)throw Error(`Embedder not initialized`);return s}async function C(e,t){h({type:`error`,id:e,message:x(t)})}async function w(e){g();try{switch(e.type){case`init`:await _(),s=new o(e.config),await s.initialize(),await s.embed(`warmup`),h({type:`ready`,dimensions:s.dimensions,modelId:s.modelId});break;case`embed`:{let t=await S().embed(e.text);h({type:`result`,id:e.id,data:b(t)});break}case`embedBatch`:{let t=await S().embedBatch(e.texts,e.batchSize);h({type:`batchResult`,id:e.id,data:t.map(e=>b(e))});break}case`embedQuery`:{let t=await S().embedQuery(e.text);h({type:`result`,id:e.id,data:b(t)});break}case`shutdown`:await v(0);return}}catch(t){if(await C(e.type===`shutdown`?`shutdown`:e.type===`init`?`init`:e.id,t),e.type===`init`){await v(1);return}}if(m()){await v(0,{notifyIdle:!0});return}y()}async function T(e,t){await C(e,t),await v(1)}process.on(`message`,e=>{w(e)}),process.on(`SIGTERM`,()=>{v(0)}),process.on(`uncaughtException`,e=>{T(`fatal`,e)}),process.on(`unhandledRejection`,e=>{T(`fatal`,e)});export{};
2
+ import{rm as e}from"node:fs/promises";import{homedir as t}from"node:os";import{join as n}from"node:path";import{EMBEDDING_DEFAULTS as r}from"../../core/dist/index.js";let i=null;function a(e){if(!(e instanceof Error))return!1;let t=e.code;return t===`ERR_MODULE_NOT_FOUND`||t===`MODULE_NOT_FOUND`?!0:/cannot find (module|package)|module not found/i.test(e.message)}async function o(){if(!i){try{i=await import(`@huggingface/transformers`)}catch(e){if(a(e)){let{createRequire:t}=await import(`node:module`),n=t(import.meta.url);try{i=n("@huggingface/transformers")}catch(t){let n=e instanceof Error?e.message:String(e),r=t instanceof Error?t.message:String(t);throw Error(`Unable to load @huggingface/transformers via ESM or CJS. ESM: ${n}; CJS: ${r}`)}}else throw e}i.env.cacheDir=n(t(),`.cache`,`huggingface`,`transformers-js`)}return i}var s=class{pipe=null;shutdownPromise=null;dimensions;modelId;nativeDim;queryPrefix;threadConfig;constructor(e={}){if(this.modelId=e.model??r.model,this.nativeDim=e.nativeDim??r.nativeDim,this.dimensions=e.dimensions??r.dimensions,this.dimensions>this.nativeDim)throw Error(`Configured dimensions (${this.dimensions}) exceeds model native output (${this.nativeDim}). Matryoshka truncation cannot upscale — dimensions must be <= nativeDim.`);this.queryPrefix=e.queryPrefix??this.detectQueryPrefix(this.modelId),this.threadConfig={interOp:e.interOpNumThreads??1,intraOp:e.intraOpNumThreads??4}}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}getPipelineOptions(e){let t=e.backends.onnx;t.wasm||={};let n=t.wasm;return n.numThreads=this.threadConfig.intraOp,{dtype:`q8`,session_options:{interOpNumThreads:this.threadConfig.interOp,intraOpNumThreads:this.threadConfig.intraOp}}}computeNorm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t)}truncateAndRenorm(e){if(this.dimensions>=this.nativeDim){let t=this.computeNorm(e);if(!Number.isFinite(t))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(t===0)throw Error(`Embedding produced zero-norm vector from ONNX output`);return e}let t=e.subarray(0,this.dimensions),n=this.computeNorm(t);if(!Number.isFinite(n))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(n===0)throw Error(`Embedding produced zero-norm vector after truncation — input may be degenerate`);let r=new Float32Array(this.dimensions);for(let e=0;e<this.dimensions;e++)r[e]=t[e]/n;return r}async initialize(){if(this.pipe)return;this.shutdownPromise=null;let{pipeline:r,env:i}=await o();try{this.pipe=await r(`feature-extraction`,this.modelId,this.getPipelineOptions(i))}catch(a){let o=a.message?.toLowerCase()??``;if(this.isCorruptionError(o)){let a=n(i.cacheDir??n(t(),`.cache`,`huggingface`,`transformers-js`),this.modelId);console.error(`[aikit:auto-heal] Detected corrupted model cache for "${this.modelId}". Clearing cache at ${a} and retrying download...`);try{await e(a,{recursive:!0,force:!0})}catch{}try{this.pipe=await r(`feature-extraction`,this.modelId,this.getPipelineOptions(i)),console.error(`[aikit:auto-heal] Model "${this.modelId}" re-downloaded successfully.`);return}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}" after auto-heal: ${e.message}`)}}throw Error(`Failed to initialize embedding model "${this.modelId}": ${a.message}`)}}isCorruptionError(e){return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`checksum`,`corrupt`,`could not load`,`onnx`,`malformed`].some(t=>e.includes(t))}async shutdown(){return this.shutdownPromise||=this._doShutdown(),this.shutdownPromise}async _doShutdown(){let e=this.pipe;if(e)try{let t=e;typeof t.dispose==`function`?await t.dispose():typeof t.model?.dispose==`function`&&await t.model.dispose()}catch{}finally{this.pipe=null}}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t?.data)throw Error(`Embedding pipeline returned no output`);try{let e=new Float32Array(t.data);return this.truncateAndRenorm(e)}finally{t.dispose?.()}}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a?.data)throw Error(`Embedding pipeline returned no output`);try{if(i.length===1){let e=new Float32Array(a.data);n.push(this.truncateAndRenorm(e))}else for(let e=0;e<i.length;e++){let t=e*this.nativeDim,r=a.data.slice(t,t+this.nativeDim);n.push(this.truncateAndRenorm(new Float32Array(r)))}}finally{a.dispose?.()}}return n}};let c=null,l=null,u=!1;const d=Number(process.env.AIKIT_EMBED_IDLE_MS),f=Number.isFinite(d)&&d>=0?d:6e4,p=Number(process.env.AIKIT_EMBED_MAX_RSS_MB),m=Number.isFinite(p)&&p>0?p:1536;function h(){let e=process.memoryUsage;return(typeof e.rss==`function`?e.rss():e().rss)/(1024*1024)>m}function g(e){process.send?.(e)}async function _(e){await new Promise(t=>{if(!process.send){t();return}let n=!1,r=()=>{n||(n=!0,t())};try{process.send.length<2?(process.send(e),r()):(process.send(e,()=>r()),setTimeout(r,25).unref?.())}catch{r()}})}function v(){l&&=(clearTimeout(l),null)}async function y(){if(!c)return;let e=c;c=null,await e.shutdown?.()}async function b(e,t){u&&process.exit(e),u=!0,v(),t?.notifyIdle&&g({type:`idle-exit`});try{await y()}finally{process.exit(e)}}function x(){v(),f!==0&&(l=setTimeout(()=>{b(0,{notifyIdle:!0})},f))}function S(e){return Array.from(e)}function C(e){return e instanceof Error?e.message:String(e)}function w(){if(!c)throw Error(`Embedder not initialized`);return c}async function T(e,t){await _({type:`error`,id:e,message:C(t)})}async function E(e){v();try{switch(e.type){case`init`:await y(),c=new s(e.config),await c.initialize(),await c.embed(`warmup`),g({type:`ready`,dimensions:c.dimensions,modelId:c.modelId});break;case`embed`:{let t=await w().embed(e.text);g({type:`result`,id:e.id,data:S(t)});break}case`embedBatch`:{let t=await w().embedBatch(e.texts,e.batchSize);g({type:`batchResult`,id:e.id,data:t.map(e=>S(e))});break}case`embedQuery`:{let t=await w().embedQuery(e.text);g({type:`result`,id:e.id,data:S(t)});break}case`shutdown`:await b(0);return}}catch(t){if(await T(e.type===`shutdown`?`shutdown`:e.type===`init`?`init`:e.id,t),e.type===`init`){await b(1);return}}if(h()){await b(0,{notifyIdle:!0});return}x()}async function D(e,t){await T(e,t),await b(1)}process.on(`message`,e=>{E(e)}),process.on(`SIGTERM`,()=>{b(0)}),process.on(`uncaughtException`,e=>{D(`fatal`,e)}),process.on(`unhandledRejection`,e=>{D(`fatal`,e)});export{};
@@ -54,6 +54,7 @@ declare class EmbedderProxy implements IEmbedder {
54
54
  private readonly workerPath;
55
55
  private readonly pendingRequests;
56
56
  private readonly childState;
57
+ private readonly childErrors;
57
58
  private child;
58
59
  private readyChild;
59
60
  private pendingInit;
@@ -1 +1 @@
1
- import{fork as e}from"node:child_process";import{randomUUID as t}from"node:crypto";import{existsSync as n}from"node:fs";import{dirname as r,join as i}from"node:path";import{fileURLToPath as a}from"node:url";import{CircuitBreaker as o,CircuitOpenError as s,EMBEDDING_DEFAULTS as c,HealthBus as l}from"../../core/dist/index.js";import{rm as u}from"node:fs/promises";import{homedir as d}from"node:os";var f=class{options;logger;healthBus=l.instance();cb;initTimeoutMs;requestTimeoutMs;maxRetries;retryBaseDelayMs;workerAvailable=!0;workerPath=i(r(a(import.meta.url)),`embedder-worker.js`);pendingRequests=new Map;childState=new WeakMap;child=null;readyChild=null;pendingInit=null;pendingShutdown=null;initializePromise=null;shutdownPromise=null;cooldownRespawnTimer=null;currentDimensions;currentModelId;coldStart=!0;constructor(e={}){this.options=e,this.logger=e.logger,this.healthBus.register(`embedder`),this.cb=new o({threshold:3,cooldownMs:6e4,name:`embedder`}),this.cb.on(`open`,()=>{this.healthBus.reportDegraded(`embedder`,`Circuit breaker open — consecutive timeouts`),this.startCooldownRespawn()}),this.cb.on(`closed`,()=>{this.healthBus.reportRecovered(`embedder`)}),this.initTimeoutMs=Math.max(0,e.initTimeoutMs??6e4),this.requestTimeoutMs=Math.max(0,e.requestTimeoutMs??(process.platform===`win32`?6e4:3e4)),this.maxRetries=Math.max(0,e.maxRetries??3),this.retryBaseDelayMs=Math.max(0,e.retryBaseDelayMs??500),this.currentDimensions=e.dimensions??c.dimensions,this.currentModelId=e.model??c.model}get dimensions(){return this.currentDimensions}get modelId(){return this.currentModelId}get isCircuitOpen(){return this.cb.isOpen()}async initialize(){if(!(this.readyChild&&this.child===this.readyChild)&&this.workerAvailable){if(!n(this.workerPath)){this.workerAvailable=!1,console.warn(`[aikit] Embedder worker not found at ${this.workerPath}. Embedding disabled - search will use keyword matching only. This usually means the npx cache is corrupted; restart to fix.`);return}if(this.initializePromise)return this.initializePromise;if(this.shutdownPromise){try{await this.shutdownPromise}catch{}if(this.readyChild&&this.child===this.readyChild)return}return this.initializePromise=this.startWorker().finally(()=>{this.initializePromise=null}),this.initializePromise}}async embed(e){if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.sendVectorRequestWithRetry({type:`embed`,text:e})}async embedQuery(e){if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.sendVectorRequestWithRetry({type:`embedQuery`,text:e})}async embedBatch(e,t){if(e.length===0)return[];if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.withWorkerExitRetry(`embedBatch`,()=>this.sendBatchRequest(e,t))}async sendBatchRequest(e,n){await this.initialize();let r=this.requireReadyChild(),i=t(),a=new Promise((e,t)=>{this.pendingRequests.set(i,{child:r,resolve:t=>e(t),reject:t})});try{r.send({type:`embedBatch`,id:i,texts:e,batchSize:n})}catch(e){throw this.pendingRequests.delete(i),this.toError(e,`Failed to send embedBatch request to worker`)}let o=this.requestTimeoutMs>0?Math.max(this.requestTimeoutMs*3,9e4):0;if(o>0){let t,n=new Promise((n,r)=>{t=setTimeout(()=>{this.pendingRequests.delete(i),this.markWorkerUnresponsive(),r(Error(`Embedder embedBatch request timed out after ${o/1e3}s (${e.length} texts). The worker has been killed and will attempt to respawn automatically.`))},o)});try{return await Promise.race([a,n])}finally{t!==void 0&&clearTimeout(t)}}return a}async shutdown(){if(this.clearCooldownRespawnTimer(),this.shutdownPromise)return this.shutdownPromise;let e=this.child;if(!e)return;let t=this.requireChildState(e);t.shutdownRequested=!0,this.readyChild===e&&(this.readyChild=null),this.shutdownPromise=new Promise((t,n)=>{this.pendingShutdown={child:e,resolve:t,reject:n}}).finally(()=>{this.shutdownPromise=null});try{e.send({type:`shutdown`})}catch(t){let n=this.toError(t,`Failed to send shutdown request to worker`);throw this.clearChildReference(e),this.rejectPendingForChild(e,n),this.rejectLifecycleIfOwned(`shutdown`,e,n),n}return this.shutdownPromise}async startWorker(){this.child&&this.readyChild!==this.child&&(this.child=null),this.clearCooldownRespawnTimer(),this.coldStart=!0;let e=this.spawnChild();this.child=e,this.readyChild=null;let t=new Promise((t,n)=>{this.pendingInit={child:e,resolve:t,reject:n}});try{e.send({type:`init`,config:this.buildInitConfig()})}catch(t){let n=this.toError(t,`Failed to send init request to worker`);throw this.pendingInit=null,this.clearChildReference(e),n}if(this.initTimeoutMs>0){let n,r=new Promise((e,t)=>{n=setTimeout(()=>{t(Error(`Embedder worker initialization timed out after ${this.initTimeoutMs/1e3}s. The ONNX model may be downloading or the child process is stuck. Check network connectivity and disk space, or restart the server.`))},this.initTimeoutMs)});try{await Promise.race([t,r]);return}catch(t){this.pendingInit=null;try{e.kill()}catch{}throw this.clearChildReference(e),t}finally{n!==void 0&&clearTimeout(n)}}await t}spawnChild(){let t=e(this.workerPath,[],{env:this.buildChildEnv()});return this.childState.set(t,{idleExitNotified:!1,shutdownRequested:!1,terminated:!1}),t.on(`message`,e=>{this.handleChildMessage(t,e)}),t.once(`error`,e=>{this.handleChildFailure(t,this.toError(e,`Embedder worker failed`))}),t.once(`exit`,(e,n)=>{this.handleChildExit(t,e,n)}),t}handleChildMessage(e,t){switch(t.type){case`ready`:{this.currentDimensions=t.dimensions,this.currentModelId=t.modelId,this.healthBus.reportRecovered(`embedder`),this.child===e&&(this.readyChild=e,this.cb.getState()!==`closed`&&this.cb.reset());let n=this.pendingInit;n?.child===e&&(this.pendingInit=null,n.resolve());return}case`result`:{let n=this.pendingRequests.get(t.id);if(!n||n.child!==e)return;this.pendingRequests.delete(t.id),this.coldStart=!1,this.cb.recordSuccess(),n.resolve(new Float32Array(t.data));return}case`batchResult`:{let n=this.pendingRequests.get(t.id);if(!n||n.child!==e)return;if(this.pendingRequests.delete(t.id),!t.data||!Array.isArray(t.data)||t.data.length===0)n.reject(Error(`Worker returned empty or invalid batch result`));else{let e=t.data.map(e=>new Float32Array(e)),r=e.findIndex(e=>e.length===0);r>=0?n.reject(Error(`Worker returned zero-length vector at index ${r}`)):(this.coldStart=!1,this.cb.recordSuccess(),n.resolve(e))}return}case`error`:{let n=Error(t.message);if(t.id===`init`){this.clearChildReference(e),this.rejectLifecycleIfOwned(`init`,e,n);return}if(t.id===`shutdown`){this.rejectLifecycleIfOwned(`shutdown`,e,n);return}let r=this.pendingRequests.get(t.id);if(!r||r.child!==e)return;this.pendingRequests.delete(t.id),r.reject(n);return}case`idle-exit`:{let t=this.requireChildState(e);t.idleExitNotified=!0,this.clearChildReference(e);return}}}handleChildExit(e,t,n){let r=this.requireChildState(e);if(r.terminated)return;r.terminated=!0,this.clearChildReference(e);let i=r.shutdownRequested||r.idleExitNotified,a=Error(i?`Embedder worker exited before completing request`:`Embedder worker exited unexpectedly (code ${t??`null`}${n?`, signal ${n}`:``})`);this.rejectLifecycleIfOwned(`init`,e,a),i?this.resolveLifecycleIfOwned(`shutdown`,e):this.rejectLifecycleIfOwned(`shutdown`,e,a),this.rejectPendingForChild(e,a),i||this.cb.recordFailure()}handleChildFailure(e,t){let n=this.requireChildState(e);n.terminated||(n.terminated=!0,this.clearChildReference(e),this.rejectLifecycleIfOwned(`init`,e,t),this.rejectLifecycleIfOwned(`shutdown`,e,t),this.rejectPendingForChild(e,t))}async sendVectorRequestWithRetry(e){return this.withWorkerExitRetry(e.type,()=>this.sendVectorRequest(e))}async sendVectorRequest(e){await this.initialize();let n=this.requireReadyChild(),r=t(),i=this.requestTimeoutMs>0?this.coldStart?this.requestTimeoutMs*2:this.requestTimeoutMs:0,a=new Promise((e,t)=>{this.pendingRequests.set(r,{child:n,resolve:t=>e(t),reject:t})});try{n.send({...e,id:r})}catch(t){throw this.pendingRequests.delete(r),this.toError(t,`Failed to send ${e.type} request to worker`)}if(i>0){let t,n=new Promise((n,a)=>{t=setTimeout(()=>{this.pendingRequests.delete(r),this.markWorkerUnresponsive(),a(Error(`Embedder ${e.type} request timed out after ${i/1e3}s. The worker has been killed and will attempt to respawn automatically.`))},i)});try{return await Promise.race([a,n])}finally{t!==void 0&&clearTimeout(t)}}return a}async withWorkerExitRetry(e,t){let n=null,r=this.maxRetries;for(let i=0;i<=r;i++)try{return await t()}catch(t){let a=this.toError(t,`Failed to process ${e} request`);if(!this.isWorkerExitError(a))throw a;if(n??=a,i===0&&/exited/i.test(a.message)&&!/timed out/i.test(a.message)&&(r=Math.min(r,1)),i===r)throw n;let o=i+1,s=this.retryBaseDelayMs*2**i;if(this.healthBus.reportDegraded(`embedder`,`Worker crashed during ${e} — retrying (${o}/${r})`),this.logger?.warn?.(`Embedder retry ${o}/${r} after ${s}ms`,{requestType:e,delayMs:s,error:a.message}),this.child=null,this.readyChild=null,await this.wait(s),this.cb.isOpen())throw n??a}throw n??Error(`Failed to process ${e} request`)}isWorkerExitError(e){return/embedder worker exited|EPIPE|ECONNRESET|ERR_IPC_CHANNEL_CLOSED|channel closed|write after end/i.test(e.message)}wait(e){return new Promise(t=>{setTimeout(t,e)})}requireReadyChild(){if(!this.child||this.readyChild!==this.child)throw Error(`Embedder worker is not initialized`);return this.child}buildInitConfig(){return{model:this.options.model,dimensions:this.options.dimensions,nativeDim:this.options.nativeDim,queryPrefix:this.options.queryPrefix,interOpNumThreads:this.options.interOpNumThreads,intraOpNumThreads:this.options.intraOpNumThreads}}buildChildEnv(){return this.options.idleTimeoutMs===void 0?process.env:{...process.env,AIKIT_EMBED_IDLE_MS:String(this.options.idleTimeoutMs)}}requireChildState(e){let t=this.childState.get(e);if(!t)throw Error(`Embedder worker state not found`);return t}clearChildReference(e){this.child===e&&(this.child=null),this.readyChild===e&&(this.readyChild=null)}clearCooldownRespawnTimer(){this.cooldownRespawnTimer&&=(clearTimeout(this.cooldownRespawnTimer),null)}startCooldownRespawn(){this.clearCooldownRespawnTimer(),this.cooldownRespawnTimer=setTimeout(()=>{this.cooldownRespawnTimer=null,!this.child&&!this.shutdownPromise&&this.workerAvailable&&this.initialize().catch(()=>{})},6e4),this.logger?.warn?.(`Embedder circuit breaker OPEN — too many consecutive failures`,{cooldownMs:6e4})}markWorkerUnresponsive(){let e=this.child;if(e){try{e.kill()}catch{}this.clearChildReference(e),this.cb.recordFailure(),this.cb.isOpen()||setImmediate(()=>{!this.child&&this.workerAvailable&&!this.shutdownPromise&&this.initialize().catch(()=>{})})}}assertCircuitClosed(){if(this.cb.isOpen())throw new s(this.cb.remainingCooldownMs())}rejectPendingForChild(e,t){for(let[n,r]of this.pendingRequests)r.child===e&&(this.pendingRequests.delete(n),r.reject(t))}resolveLifecycleIfOwned(e,t){let n=this.pendingShutdown;!n||n.child!==t||(this.pendingShutdown=null,n.resolve())}rejectLifecycleIfOwned(e,t,n){let r=e===`init`?this.pendingInit:this.pendingShutdown;!r||r.child!==t||(e===`init`?this.pendingInit=null:this.pendingShutdown=null,r.reject(n))}toError(e,t){return e instanceof Error?e:Error(`${t}: ${String(e)}`)}};let p=null;async function m(){if(!p){try{p=await import(`@huggingface/transformers`)}catch(e){if(e instanceof Error&&e.message.includes(`Cannot find module`)){let{createRequire:e}=await import(`node:module`);p=e(import.meta.url)(`@huggingface/transformers`)}else throw e}p.env.cacheDir=i(d(),`.cache`,`huggingface`,`transformers-js`)}return p}var h=class{pipe=null;shutdownPromise=null;dimensions;modelId;nativeDim;queryPrefix;threadConfig;constructor(e={}){if(this.modelId=e.model??c.model,this.nativeDim=e.nativeDim??c.nativeDim,this.dimensions=e.dimensions??c.dimensions,this.dimensions>this.nativeDim)throw Error(`Configured dimensions (${this.dimensions}) exceeds model native output (${this.nativeDim}). Matryoshka truncation cannot upscale — dimensions must be <= nativeDim.`);this.queryPrefix=e.queryPrefix??this.detectQueryPrefix(this.modelId),this.threadConfig={interOp:e.interOpNumThreads??1,intraOp:e.intraOpNumThreads??4}}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}getPipelineOptions(e){let t=e.backends.onnx;t.wasm||={};let n=t.wasm;return n.numThreads=this.threadConfig.intraOp,{dtype:`q8`,session_options:{interOpNumThreads:this.threadConfig.interOp,intraOpNumThreads:this.threadConfig.intraOp}}}computeNorm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t)}truncateAndRenorm(e){if(this.dimensions>=this.nativeDim){let t=this.computeNorm(e);if(!Number.isFinite(t))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(t===0)throw Error(`Embedding produced zero-norm vector from ONNX output`);return e}let t=e.subarray(0,this.dimensions),n=this.computeNorm(t);if(!Number.isFinite(n))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(n===0)throw Error(`Embedding produced zero-norm vector after truncation — input may be degenerate`);let r=new Float32Array(this.dimensions);for(let e=0;e<this.dimensions;e++)r[e]=t[e]/n;return r}async initialize(){if(this.pipe)return;this.shutdownPromise=null;let{pipeline:e,env:t}=await m();try{this.pipe=await e(`feature-extraction`,this.modelId,this.getPipelineOptions(t))}catch(n){let r=n.message?.toLowerCase()??``;if(this.isCorruptionError(r)){let n=i(t.cacheDir??i(d(),`.cache`,`huggingface`,`transformers-js`),this.modelId);console.error(`[aikit:auto-heal] Detected corrupted model cache for "${this.modelId}". Clearing cache at ${n} and retrying download...`);try{await u(n,{recursive:!0,force:!0})}catch{}try{this.pipe=await e(`feature-extraction`,this.modelId,this.getPipelineOptions(t)),console.error(`[aikit:auto-heal] Model "${this.modelId}" re-downloaded successfully.`);return}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}" after auto-heal: ${e.message}`)}}throw Error(`Failed to initialize embedding model "${this.modelId}": ${n.message}`)}}isCorruptionError(e){return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`checksum`,`corrupt`,`could not load`,`onnx`,`malformed`].some(t=>e.includes(t))}async shutdown(){return this.shutdownPromise||=this._doShutdown(),this.shutdownPromise}async _doShutdown(){let e=this.pipe;if(e)try{let t=e;typeof t.dispose==`function`?await t.dispose():typeof t.model?.dispose==`function`&&await t.model.dispose()}catch{}finally{this.pipe=null}}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t?.data)throw Error(`Embedding pipeline returned no output`);try{let e=new Float32Array(t.data);return this.truncateAndRenorm(e)}finally{t.dispose?.()}}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a?.data)throw Error(`Embedding pipeline returned no output`);try{if(i.length===1){let e=new Float32Array(a.data);n.push(this.truncateAndRenorm(e))}else for(let e=0;e<i.length;e++){let t=e*this.nativeDim,r=a.data.slice(t,t+this.nativeDim);n.push(this.truncateAndRenorm(new Float32Array(r)))}}finally{a.dispose?.()}}return n}};export{f as EmbedderProxy,h as OnnxEmbedder};
1
+ import{fork as e}from"node:child_process";import{randomUUID as t}from"node:crypto";import{existsSync as n}from"node:fs";import{dirname as r,join as i}from"node:path";import{fileURLToPath as a}from"node:url";import{CircuitBreaker as o,CircuitOpenError as s,EMBEDDING_DEFAULTS as c,HealthBus as l}from"../../core/dist/index.js";import{rm as u}from"node:fs/promises";import{homedir as d}from"node:os";var f=class{options;logger;healthBus=l.instance();cb;initTimeoutMs;requestTimeoutMs;maxRetries;retryBaseDelayMs;workerAvailable=!0;workerPath=i(r(a(import.meta.url)),`embedder-worker.js`);pendingRequests=new Map;childState=new WeakMap;childErrors=new WeakMap;child=null;readyChild=null;pendingInit=null;pendingShutdown=null;initializePromise=null;shutdownPromise=null;cooldownRespawnTimer=null;currentDimensions;currentModelId;coldStart=!0;constructor(e={}){this.options=e,this.logger=e.logger,this.healthBus.register(`embedder`),this.cb=new o({threshold:3,cooldownMs:6e4,name:`embedder`}),this.cb.on(`open`,()=>{this.healthBus.reportDegraded(`embedder`,`Circuit breaker open — consecutive timeouts`),this.startCooldownRespawn()}),this.cb.on(`closed`,()=>{this.healthBus.reportRecovered(`embedder`)}),this.initTimeoutMs=Math.max(0,e.initTimeoutMs??6e4),this.requestTimeoutMs=Math.max(0,e.requestTimeoutMs??(process.platform===`win32`?6e4:3e4)),this.maxRetries=Math.max(0,e.maxRetries??3),this.retryBaseDelayMs=Math.max(0,e.retryBaseDelayMs??500),this.currentDimensions=e.dimensions??c.dimensions,this.currentModelId=e.model??c.model}get dimensions(){return this.currentDimensions}get modelId(){return this.currentModelId}get isCircuitOpen(){return this.cb.isOpen()}async initialize(){if(!(this.readyChild&&this.child===this.readyChild)&&this.workerAvailable){if(!n(this.workerPath)){this.workerAvailable=!1,console.warn(`[aikit] Embedder worker not found at ${this.workerPath}. Embedding disabled - search will use keyword matching only. This usually means the npx cache is corrupted; restart to fix.`);return}if(this.initializePromise)return this.initializePromise;if(this.shutdownPromise){try{await this.shutdownPromise}catch{}if(this.readyChild&&this.child===this.readyChild)return}return this.initializePromise=this.startWorker().finally(()=>{this.initializePromise=null}),this.initializePromise}}async embed(e){if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.sendVectorRequestWithRetry({type:`embed`,text:e})}async embedQuery(e){if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.sendVectorRequestWithRetry({type:`embedQuery`,text:e})}async embedBatch(e,t){if(e.length===0)return[];if(!this.workerAvailable||(this.assertCircuitClosed(),await this.initialize(),!this.workerAvailable))throw Error(`Embedding worker is not available — embeddings cannot be computed. Check server logs for initialization errors.`);return this.withWorkerExitRetry(`embedBatch`,()=>this.sendBatchRequest(e,t))}async sendBatchRequest(e,n){await this.initialize();let r=this.requireReadyChild(),i=t(),a=new Promise((e,t)=>{this.pendingRequests.set(i,{child:r,resolve:t=>e(t),reject:t})});try{r.send({type:`embedBatch`,id:i,texts:e,batchSize:n})}catch(e){throw this.pendingRequests.delete(i),this.toError(e,`Failed to send embedBatch request to worker`)}let o=this.requestTimeoutMs>0?Math.max(this.requestTimeoutMs*3,9e4):0;if(o>0){let t,n=new Promise((n,r)=>{t=setTimeout(()=>{this.pendingRequests.delete(i),this.markWorkerUnresponsive(),r(Error(`Embedder embedBatch request timed out after ${o/1e3}s (${e.length} texts). The worker has been killed and will attempt to respawn automatically.`))},o)});try{return await Promise.race([a,n])}finally{t!==void 0&&clearTimeout(t)}}return a}async shutdown(){if(this.clearCooldownRespawnTimer(),this.shutdownPromise)return this.shutdownPromise;let e=this.child;if(!e)return;let t=this.requireChildState(e);t.shutdownRequested=!0,this.readyChild===e&&(this.readyChild=null),this.shutdownPromise=new Promise((t,n)=>{this.pendingShutdown={child:e,resolve:t,reject:n}}).finally(()=>{this.shutdownPromise=null});try{e.send({type:`shutdown`})}catch(t){let n=this.toError(t,`Failed to send shutdown request to worker`);throw this.clearChildReference(e),this.rejectPendingForChild(e,n),this.rejectLifecycleIfOwned(`shutdown`,e,n),n}return this.shutdownPromise}async startWorker(){this.child&&this.readyChild!==this.child&&(this.child=null),this.clearCooldownRespawnTimer(),this.coldStart=!0;let e=this.spawnChild();this.child=e,this.readyChild=null;let t=new Promise((t,n)=>{this.pendingInit={child:e,resolve:t,reject:n}});try{e.send({type:`init`,config:this.buildInitConfig()})}catch(t){let n=this.toError(t,`Failed to send init request to worker`);throw this.pendingInit=null,this.clearChildReference(e),n}if(this.initTimeoutMs>0){let n,r=new Promise((e,t)=>{n=setTimeout(()=>{t(Error(`Embedder worker initialization timed out after ${this.initTimeoutMs/1e3}s. The ONNX model may be downloading or the child process is stuck. Check network connectivity and disk space, or restart the server.`))},this.initTimeoutMs)});try{await Promise.race([t,r]);return}catch(t){this.pendingInit=null;try{e.kill()}catch{}throw this.clearChildReference(e),t}finally{n!==void 0&&clearTimeout(n)}}await t}spawnChild(){let t=e(this.workerPath,[],{env:this.buildChildEnv()});return this.childState.set(t,{idleExitNotified:!1,shutdownRequested:!1,terminated:!1}),t.on(`message`,e=>{this.handleChildMessage(t,e)}),t.once(`error`,e=>{this.handleChildFailure(t,this.toError(e,`Embedder worker failed`))}),t.once(`exit`,(e,n)=>{this.handleChildExit(t,e,n)}),t}handleChildMessage(e,t){switch(t.type){case`ready`:{this.currentDimensions=t.dimensions,this.currentModelId=t.modelId,this.healthBus.reportRecovered(`embedder`),this.child===e&&(this.readyChild=e,this.cb.getState()!==`closed`&&this.cb.reset());let n=this.pendingInit;n?.child===e&&(this.pendingInit=null,n.resolve());return}case`result`:{let n=this.pendingRequests.get(t.id);if(!n||n.child!==e)return;this.pendingRequests.delete(t.id),this.coldStart=!1,this.cb.recordSuccess(),n.resolve(new Float32Array(t.data));return}case`batchResult`:{let n=this.pendingRequests.get(t.id);if(!n||n.child!==e)return;if(this.pendingRequests.delete(t.id),!t.data||!Array.isArray(t.data)||t.data.length===0)n.reject(Error(`Worker returned empty or invalid batch result`));else{let e=t.data.map(e=>new Float32Array(e)),r=e.findIndex(e=>e.length===0);r>=0?n.reject(Error(`Worker returned zero-length vector at index ${r}`)):(this.coldStart=!1,this.cb.recordSuccess(),n.resolve(e))}return}case`error`:{let n=Error(t.message);if(this.childErrors.set(e,n),t.id===`init`){this.clearChildReference(e),this.rejectLifecycleIfOwned(`init`,e,n);return}if(t.id===`shutdown`){this.rejectLifecycleIfOwned(`shutdown`,e,n);return}let r=this.pendingRequests.get(t.id);if(!r||r.child!==e)return;this.pendingRequests.delete(t.id),r.reject(n);return}case`idle-exit`:{let t=this.requireChildState(e);t.idleExitNotified=!0,this.clearChildReference(e);return}}}handleChildExit(e,t,n){let r=this.requireChildState(e);if(r.terminated)return;r.terminated=!0,this.clearChildReference(e);let i=r.shutdownRequested||r.idleExitNotified,a=this.childErrors.get(e)??Error(i?`Embedder worker exited before completing request`:`Embedder worker exited unexpectedly (code ${t??`null`}${n?`, signal ${n}`:``})`);this.rejectLifecycleIfOwned(`init`,e,a),i?this.resolveLifecycleIfOwned(`shutdown`,e):this.rejectLifecycleIfOwned(`shutdown`,e,a),this.rejectPendingForChild(e,a),i||this.cb.recordFailure()}handleChildFailure(e,t){let n=this.requireChildState(e);n.terminated||(n.terminated=!0,this.clearChildReference(e),this.rejectLifecycleIfOwned(`init`,e,t),this.rejectLifecycleIfOwned(`shutdown`,e,t),this.rejectPendingForChild(e,t))}async sendVectorRequestWithRetry(e){return this.withWorkerExitRetry(e.type,()=>this.sendVectorRequest(e))}async sendVectorRequest(e){await this.initialize();let n=this.requireReadyChild(),r=t(),i=this.requestTimeoutMs>0?this.coldStart?this.requestTimeoutMs*2:this.requestTimeoutMs:0,a=new Promise((e,t)=>{this.pendingRequests.set(r,{child:n,resolve:t=>e(t),reject:t})});try{n.send({...e,id:r})}catch(t){throw this.pendingRequests.delete(r),this.toError(t,`Failed to send ${e.type} request to worker`)}if(i>0){let t,n=new Promise((n,a)=>{t=setTimeout(()=>{this.pendingRequests.delete(r),this.markWorkerUnresponsive(),a(Error(`Embedder ${e.type} request timed out after ${i/1e3}s. The worker has been killed and will attempt to respawn automatically.`))},i)});try{return await Promise.race([a,n])}finally{t!==void 0&&clearTimeout(t)}}return a}async withWorkerExitRetry(e,t){let n=null,r=this.maxRetries;for(let i=0;i<=r;i++)try{return await t()}catch(t){let a=this.toError(t,`Failed to process ${e} request`);if(!this.isWorkerExitError(a))throw a;if(n??=a,i===0&&/exited/i.test(a.message)&&!/timed out/i.test(a.message)&&(r=Math.min(r,1)),i===r)throw n;let o=i+1,s=this.retryBaseDelayMs*2**i;if(this.healthBus.reportDegraded(`embedder`,`Worker crashed during ${e} — retrying (${o}/${r})`),this.logger?.warn?.(`Embedder retry ${o}/${r} after ${s}ms`,{requestType:e,delayMs:s,error:a.message}),this.child=null,this.readyChild=null,await this.wait(s),this.cb.isOpen())throw n??a}throw n??Error(`Failed to process ${e} request`)}isWorkerExitError(e){return/embedder worker exited|EPIPE|ECONNRESET|ERR_IPC_CHANNEL_CLOSED|channel closed|write after end/i.test(e.message)}wait(e){return new Promise(t=>{setTimeout(t,e)})}requireReadyChild(){if(!this.child||this.readyChild!==this.child)throw Error(`Embedder worker is not initialized`);return this.child}buildInitConfig(){return{model:this.options.model,dimensions:this.options.dimensions,nativeDim:this.options.nativeDim,queryPrefix:this.options.queryPrefix,interOpNumThreads:this.options.interOpNumThreads,intraOpNumThreads:this.options.intraOpNumThreads}}buildChildEnv(){return this.options.idleTimeoutMs===void 0?process.env:{...process.env,AIKIT_EMBED_IDLE_MS:String(this.options.idleTimeoutMs)}}requireChildState(e){let t=this.childState.get(e);if(!t)throw Error(`Embedder worker state not found`);return t}clearChildReference(e){this.child===e&&(this.child=null),this.readyChild===e&&(this.readyChild=null)}clearCooldownRespawnTimer(){this.cooldownRespawnTimer&&=(clearTimeout(this.cooldownRespawnTimer),null)}startCooldownRespawn(){this.clearCooldownRespawnTimer(),this.cooldownRespawnTimer=setTimeout(()=>{this.cooldownRespawnTimer=null,!this.child&&!this.shutdownPromise&&this.workerAvailable&&this.initialize().catch(()=>{})},6e4),this.logger?.warn?.(`Embedder circuit breaker OPEN — too many consecutive failures`,{cooldownMs:6e4})}markWorkerUnresponsive(){let e=this.child;if(e){try{e.kill()}catch{}this.clearChildReference(e),this.cb.recordFailure(),this.cb.isOpen()||setImmediate(()=>{!this.child&&this.workerAvailable&&!this.shutdownPromise&&this.initialize().catch(()=>{})})}}assertCircuitClosed(){if(this.cb.isOpen())throw new s(this.cb.remainingCooldownMs())}rejectPendingForChild(e,t){for(let[n,r]of this.pendingRequests)r.child===e&&(this.pendingRequests.delete(n),r.reject(t))}resolveLifecycleIfOwned(e,t){let n=this.pendingShutdown;!n||n.child!==t||(this.pendingShutdown=null,n.resolve())}rejectLifecycleIfOwned(e,t,n){let r=e===`init`?this.pendingInit:this.pendingShutdown;!r||r.child!==t||(e===`init`?this.pendingInit=null:this.pendingShutdown=null,r.reject(n))}toError(e,t){return e instanceof Error?e:Error(`${t}: ${String(e)}`)}};let p=null;function m(e){if(!(e instanceof Error))return!1;let t=e.code;return t===`ERR_MODULE_NOT_FOUND`||t===`MODULE_NOT_FOUND`?!0:/cannot find (module|package)|module not found/i.test(e.message)}async function h(){if(!p){try{p=await import(`@huggingface/transformers`)}catch(e){if(m(e)){let{createRequire:t}=await import(`node:module`),n=t(import.meta.url);try{p=n("@huggingface/transformers")}catch(t){let n=e instanceof Error?e.message:String(e),r=t instanceof Error?t.message:String(t);throw Error(`Unable to load @huggingface/transformers via ESM or CJS. ESM: ${n}; CJS: ${r}`)}}else throw e}p.env.cacheDir=i(d(),`.cache`,`huggingface`,`transformers-js`)}return p}var g=class{pipe=null;shutdownPromise=null;dimensions;modelId;nativeDim;queryPrefix;threadConfig;constructor(e={}){if(this.modelId=e.model??c.model,this.nativeDim=e.nativeDim??c.nativeDim,this.dimensions=e.dimensions??c.dimensions,this.dimensions>this.nativeDim)throw Error(`Configured dimensions (${this.dimensions}) exceeds model native output (${this.nativeDim}). Matryoshka truncation cannot upscale — dimensions must be <= nativeDim.`);this.queryPrefix=e.queryPrefix??this.detectQueryPrefix(this.modelId),this.threadConfig={interOp:e.interOpNumThreads??1,intraOp:e.intraOpNumThreads??4}}detectQueryPrefix(e){let t=e.toLowerCase();return t.includes(`bge`)||t.includes(`mxbai-embed`)?`Represent this sentence for searching relevant passages: `:t.includes(`/e5-`)||t.includes(`multilingual-e5`)?`query: `:``}getPipelineOptions(e){let t=e.backends.onnx;t.wasm||={};let n=t.wasm;return n.numThreads=this.threadConfig.intraOp,{dtype:`q8`,session_options:{interOpNumThreads:this.threadConfig.interOp,intraOpNumThreads:this.threadConfig.intraOp}}}computeNorm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t)}truncateAndRenorm(e){if(this.dimensions>=this.nativeDim){let t=this.computeNorm(e);if(!Number.isFinite(t))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(t===0)throw Error(`Embedding produced zero-norm vector from ONNX output`);return e}let t=e.subarray(0,this.dimensions),n=this.computeNorm(t);if(!Number.isFinite(n))throw Error(`Embedding produced non-finite norm — output contained NaN or Infinity`);if(n===0)throw Error(`Embedding produced zero-norm vector after truncation — input may be degenerate`);let r=new Float32Array(this.dimensions);for(let e=0;e<this.dimensions;e++)r[e]=t[e]/n;return r}async initialize(){if(this.pipe)return;this.shutdownPromise=null;let{pipeline:e,env:t}=await h();try{this.pipe=await e(`feature-extraction`,this.modelId,this.getPipelineOptions(t))}catch(n){let r=n.message?.toLowerCase()??``;if(this.isCorruptionError(r)){let n=i(t.cacheDir??i(d(),`.cache`,`huggingface`,`transformers-js`),this.modelId);console.error(`[aikit:auto-heal] Detected corrupted model cache for "${this.modelId}". Clearing cache at ${n} and retrying download...`);try{await u(n,{recursive:!0,force:!0})}catch{}try{this.pipe=await e(`feature-extraction`,this.modelId,this.getPipelineOptions(t)),console.error(`[aikit:auto-heal] Model "${this.modelId}" re-downloaded successfully.`);return}catch(e){throw Error(`Failed to initialize embedding model "${this.modelId}" after auto-heal: ${e.message}`)}}throw Error(`Failed to initialize embedding model "${this.modelId}": ${n.message}`)}}isCorruptionError(e){return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`checksum`,`corrupt`,`could not load`,`onnx`,`malformed`].some(t=>e.includes(t))}async shutdown(){return this.shutdownPromise||=this._doShutdown(),this.shutdownPromise}async _doShutdown(){let e=this.pipe;if(e)try{let t=e;typeof t.dispose==`function`?await t.dispose():typeof t.model?.dispose==`function`&&await t.model.dispose()}catch{}finally{this.pipe=null}}async embed(e){this.pipe||await this.initialize();let t=await this.pipe?.(e,{pooling:`mean`,normalize:!0});if(!t?.data)throw Error(`Embedding pipeline returned no output`);try{let e=new Float32Array(t.data);return this.truncateAndRenorm(e)}finally{t.dispose?.()}}async embedQuery(e){return this.embed(this.queryPrefix+e)}async embedBatch(e,t=64){if(e.length===0)return[];this.pipe||await this.initialize();let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.pipe?.(i,{pooling:`mean`,normalize:!0});if(!a?.data)throw Error(`Embedding pipeline returned no output`);try{if(i.length===1){let e=new Float32Array(a.data);n.push(this.truncateAndRenorm(e))}else for(let e=0;e<i.length;e++){let t=e*this.nativeDim,r=a.data.slice(t,t+this.nativeDim);n.push(this.truncateAndRenorm(new Float32Array(r)))}}finally{a.dispose?.()}}return n}};export{f as EmbedderProxy,g as OnnxEmbedder};
@@ -1954,7 +1954,7 @@ Boolean requesting whether a visible border and background is provided by the ho
1954
1954
  - omitted: host decides border`)}),I({method:V(`ui/request-display-mode`),params:I({mode:IS.describe(`The display mode being requested.`)})});var QS=I({mode:IS.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),$S=R([V(`model`),V(`app`)]).describe(`Tool visibility scope - who can access the tool.`);I({resourceUri:j().optional(),visibility:F($S).optional().describe(`Who can access this tool. Default: ["model", "app"]
1955
1955
  - "model": Tool visible to and callable by the agent
1956
1956
  - "app": Tool callable by the app from this server only`),csp:h_().optional(),permissions:h_().optional()}),I({mimeTypes:F(j()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),I({method:V(`ui/download-file`),params:I({contents:F(R([Tx,Ex])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),I({method:V(`ui/message`),params:I({role:V(`user`).describe(`Message role, currently only "user" is supported.`),content:F(Dx).describe(`Message content blocks (text, image, etc.).`)})}),I({method:V(`ui/notifications/sandbox-resource-ready`),params:I({html:j().describe(`HTML content to load into the inner iframe.`),sandbox:j().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:VS.optional().describe(`CSP configuration from resource metadata.`),permissions:HS.optional().describe(`Sandbox permissions from resource metadata.`)})});var eC=I({method:V(`ui/notifications/tool-result`),params:Ix.describe(`Standard MCP tool execution result.`)}),tC=I({toolInfo:I({id:nb.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Nx.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:FS.optional().describe(`Current color theme preference.`),styles:qS.optional().describe(`Style configuration for theming the app.`),displayMode:IS.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:F(IS).optional().describe(`Display modes the host supports.`),containerDimensions:R([I({height:M().describe(`Fixed container height in pixels.`)}),I({maxHeight:R([M(),f_()]).optional().describe(`Maximum container height in pixels.`)})]).and(R([I({width:M().describe(`Fixed container width in pixels.`)}),I({maxWidth:R([M(),f_()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
1957
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),nC=I({method:V(`ui/notifications/host-context-changed`),params:tC.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(Dx).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:_b.describe(`App identification (name and version).`),appCapabilities:ZS.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var rC=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:_b.describe(`Host application identification and version.`),hostCapabilities:XS.describe(`Features and capabilities provided by the host.`),hostContext:tC.describe(`Rich context about the host environment.`)}).passthrough(),iC={target:`draft-2020-12`};async function aC(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](iC);if(n.vendor===`zod`){let{z:n}=await jS(async()=>{let{z:e}=await Promise.resolve().then(()=>(Wy(),Hy));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function oC(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function sC(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function cC(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function lC(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}var uC=class e extends MS{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:US,toolinputpartial:WS,toolresult:eC,toolcancelled:GS,hostcontextchanged:nC};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||h({jitless:!0}),this.setRequestHandler(Db,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=DS(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await oC(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await oC(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await aC(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await aC(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(JS,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Rx,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Px,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Ix,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},sx,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},tx,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?eS:$x;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},BS,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},fb,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},RS,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},zS,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},QS,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new PS(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:NS}},rC,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function dC(e){let t=e.getAttribute(hC);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(hC,n),n}function fC(e,t,n){for(let[r,i]of e.entries())i.textContent=dC(i),r===t?(i.setAttribute(gC,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(gC)}function pC(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function mC(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=_C.compare(pC(e,t),pC(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}fC(t,a,o)};for(let[e,n]of t.entries()){dC(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=dC(e),e.removeAttribute(gC),e.removeAttribute(hC),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}var hC,gC,_C,vC=t((()=>{hC=`data-sort-label`,gC=`data-sort-dir`,_C=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`})}));function yC(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function bC(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return yC(n);n=n.parentElement}return null}function xC(e){return Array.from(e.querySelectorAll(`summary`))}function SC(e){return e.open||e.hasAttribute(`open`)}function CC(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function wC(e,t){e.textContent=t.every(e=>SC(e))?`Collapse all`:`Expand all`}function TC(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!SC(e));for(let n of t)CC(n,e);wC(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{wC(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=xC(e).map(t=>{t.tabIndex=0;let n=n=>{let r=xC(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!SC(a))CC(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&SC(a)?CC(a,!1):bC(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return wC(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}var EC=t((()=>{}));function DC(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}var OC=t((()=>{}));function kC(e){let t=e.createElement(`style`);return t.textContent=MC,t}function AC(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function jC(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=kC(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=AC(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return AC(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var MC,NC=t((()=>{MC=`
1957
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),nC=I({method:V(`ui/notifications/host-context-changed`),params:tC.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(Dx).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:_b.describe(`App identification (name and version).`),appCapabilities:ZS.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var rC=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:_b.describe(`Host application identification and version.`),hostCapabilities:XS.describe(`Features and capabilities provided by the host.`),hostContext:tC.describe(`Rich context about the host environment.`)}).passthrough(),iC={target:`draft-2020-12`};async function aC(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](iC);if(n.vendor===`zod`){let{z:n}=await jS(async()=>{let{z:e}=await Promise.resolve().then(()=>(Wy(),Hy));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function oC(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function sC(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function cC(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function lC(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}var uC=class e extends MS{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:US,toolinputpartial:WS,toolresult:eC,toolcancelled:GS,hostcontextchanged:nC};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||h({jitless:!0}),this.setRequestHandler(Db,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=DS(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await oC(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await oC(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await aC(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await aC(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(JS,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Rx,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Px,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Ix,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},sx,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},tx,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?eS:$x;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},BS,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},fb,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},RS,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},zS,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},QS,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new PS(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:NS}},rC,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function dC(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}var fC=`
1958
1958
  .bk-checklist-progress {
1959
1959
  margin-bottom: var(--dt-space-3);
1960
1960
  color: var(--dt-text-secondary);
@@ -1968,9 +1968,9 @@ container holding the app. Specify either width or maxWidth, and either height o
1968
1968
  margin: 0;
1969
1969
  accent-color: var(--dt-accent-fg);
1970
1970
  }
1971
- `}));OC(),NC(),vC(),EC();var PC=`data-hydrated`;function FC(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function IC(e,t,n){e.push(()=>{n(),t.removeAttribute(PC)})}function LC(e={}){let t=e.container??document.body,n=[];for(let e of FC(t,`.bk-table`))e.hasAttribute(PC)||(e.setAttribute(PC,``),IC(n,e,mC(e)));for(let e of FC(t,`.bk-tree`))e.hasAttribute(PC)||(e.setAttribute(PC,``),IC(n,e,TC(e)));for(let r of FC(t,`.bk-checklist`))r.hasAttribute(PC)||(r.setAttribute(PC,``),IC(n,r,jC(r,e)));for(let r of FC(t,`.bk-actions`))if(!r.hasAttribute(PC)){if(r.setAttribute(PC,``),e.onAction){IC(n,r,DC(r,e.onAction));continue}n.push(()=>{r.removeAttribute(PC)})}return()=>{for(let e of n)e();n.length=0}}vC();var RC=`bk-styles`,zC=new Set;function BC(e){for(let t of e.css)t.trim().length>0&&zC.add(t);return[...zC].join(`
1972
- `)}function VC(e){return di(e,{transport:`browser`})}function HC(e,t=document){let n=BC(e),r=t.getElementById(RC);r||(r=t.createElement(`style`),r.id=RC,t.head.appendChild(r)),r.textContent=n}function UC(e,t){let n=VC(t);return HC(n,e.ownerDocument),e.innerHTML=n.html,n}function WC(e,t,n){return UC(e,{schemaVersion:1,title:`AI Kit Present`,blocks:t}),LC({container:e,onAction:n})}function GC(e){return function(t,n){let r=n??t.label;if(!e){fetch(`/callback`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actionId:t.id,value:r})});return}e.updateModelContext({content:[{type:`text`,text:`Latest UI action: ${t.label}${n?` → ${n}`:``}`}],structuredContent:{actionId:t.id,actionType:t.type,label:t.label,value:r,timestamp:new Date().toISOString()}}),e.sendMessage({role:`user`,content:[{type:`text`,text:`User selected: ${t.label}${n?` → ${n}`:``}`}]})}}function KC(e){return typeof e==`object`&&!!e}function qC(e,t){let n=e.id.split(`@`)[0];return n===`timeline`&&KC(t)&&Array.isArray(t.events)?t.events:n===`tree`&&Array.isArray(t)?{root:{label:`Root`,children:t}}:t}function JC(e,t,n){let r=oi.get(e);if(!r?.supportedTransports.includes(`browser`))return null;let i=qC(r,t);return{blocks:r.blocksFromData(i,{colorScheme:n.colorScheme,transport:`browser`,lang:n.lang,dir:n.dir}),actions:r.actionsFromData?.(i)??[]}}var YC=`present-data`;function XC(e=document,t=YC){let n=e.getElementById(t);return n?.textContent?JSON.parse(n.textContent):null}function ZC(e){return e?{callTool:(t,n)=>e.callServerTool({name:t,arguments:n}),sendMessage:async t=>{await e.sendMessage({role:`user`,content:[{type:`text`,text:t}]})},updateContext:async t=>{await e.updateModelContext({content:[{type:`text`,text:t}]})}}:{callTool:async()=>{throw Error(`callTool is not available in browser mode`)},sendMessage:async()=>{},updateContext:async()=>{}}}var QC=class{app;currentMode=`inline`;availableModes=[];toolbar=null;constructor(e){this.app=e}apply(e){e.displayMode&&(this.currentMode=e.displayMode),e.availableDisplayModes&&(this.availableModes=e.availableDisplayModes),this.updateToolbar()}async requestMode(e){try{let t=await this.app.requestDisplayMode({mode:e});return this.currentMode=t.mode,document.documentElement.dataset.display=t.mode,this.updateToolbar(),t.mode}catch{return this.currentMode}}updateToolbar(){if(this.availableModes.length<=1){this.toolbar?.remove(),this.toolbar=null;return}this.toolbar||=this.createToolbar(),this.renderButtons()}createToolbar(){let e=document.createElement(`div`);return e.className=`display-mode-toolbar`,document.body.appendChild(e),e}renderButtons(){if(!this.toolbar)return;this.toolbar.innerHTML=``;let e={inline:`▣`,fullscreen:`⛶`,pip:`◱`};for(let t of this.availableModes){let n=document.createElement(`button`);n.className=`dm-btn${t===this.currentMode?` dm-active`:``}`,n.textContent=e[t]??t,n.title=t,n.addEventListener(`click`,()=>this.requestMode(t)),this.toolbar.appendChild(n)}}},$C=new Set;function ew(e,t){if($C.has(e))return;$C.add(e);let n=document.createElement(`style`);n.textContent=t,document.head.appendChild(n)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n&&(r.textContent=n),r}function tw(e){return e==null?`null`:Array.isArray(e)?`[${e.map(tw).join(`, `)}]`:String(e)}function nw(e){return typeof e==`object`&&!!e&&`type`in e}var rw=[[400,`compact`],[800,`comfortable`]],iw=class{root;displayMode=`inline`;sizeClass=`comfortable`;constructor(e){this.root=e??document.documentElement}apply(e){this.applyDisplayMode(e),this.applyContainerDimensions(e),this.applySafeArea(e),this.applyPlatform(e),this.applyDeviceCapabilities(e)}getDisplayMode(){return this.displayMode}getSize(){return this.sizeClass}applyDisplayMode(e){e.displayMode&&(this.displayMode=e.displayMode,this.root.dataset.display=e.displayMode)}applyContainerDimensions(e){let t=e.containerDimensions;if(!t)return;let n=this.root.style,r=`width`in t?t.width:`maxWidth`in t?t.maxWidth:void 0,i=`height`in t?t.height:`maxHeight`in t?t.maxHeight:void 0;r!==void 0&&(n.setProperty(`--aikit-container-w`,`${r}px`),this.sizeClass=this.deriveSizeClass(r),this.root.dataset.size=this.sizeClass,n.setProperty(`--aikit-content-max-width`,this.deriveMaxWidth(r)),n.setProperty(`--aikit-body-pad-x`,this.derivePadX()),n.setProperty(`--aikit-grid-cols`,this.deriveGridCols()),n.setProperty(`--aikit-card-min`,this.deriveCardMin()),n.setProperty(`--aikit-metric-min`,this.deriveMetricMin())),i!==void 0&&(n.setProperty(`--aikit-container-h`,`${i}px`),n.setProperty(`--aikit-body-pad-y`,this.derivePadY()))}applySafeArea(e){let t=e.safeAreaInsets;if(!t)return;let n=this.root.style;n.setProperty(`--aikit-safe-top`,`${t.top}px`),n.setProperty(`--aikit-safe-right`,`${t.right}px`),n.setProperty(`--aikit-safe-bottom`,`${t.bottom}px`),n.setProperty(`--aikit-safe-left`,`${t.left}px`)}applyPlatform(e){e.platform&&(this.root.dataset.platform=e.platform)}applyDeviceCapabilities(e){let t=e.deviceCapabilities;t&&(t.touch!==void 0&&(this.root.dataset.touch=String(t.touch)),t.hover!==void 0&&(this.root.dataset.hover=String(t.hover)))}deriveSizeClass(e){for(let[t,n]of rw)if(e<t)return n;return`full`}deriveMaxWidth(e){return this.displayMode===`pip`?`100%`:this.displayMode===`fullscreen`?`none`:e<960?`100%`:`900px`}derivePadX(){return this.sizeClass===`compact`?`8px`:`16px`}derivePadY(){return this.sizeClass===`compact`?`8px`:`16px`}deriveGridCols(){switch(this.sizeClass){case`compact`:return`1`;case`comfortable`:return`2`;case`full`:return`3`}}deriveCardMin(){return this.sizeClass===`compact`?`100%`:`250px`}deriveMetricMin(){return this.sizeClass===`compact`?`100px`:`150px`}},aw=`AI Kit Present`;function ow(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;if(Array.isArray(t.blocks)&&t.blocks.length>0)return t.blocks}return e}function sw(e){if(Array.isArray(e))return e.length===0?[{type:`markdown`,value:`*Empty array*`}]:nw(e[0])?e.filter(nw):typeof e[0]==`object`&&e[0]!==null?[{type:`table`,value:e}]:[{type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
1973
- `)}];if(typeof e==`string`)return[{type:`markdown`,value:e}];if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?[{type:`graph`,value:t}]:Array.isArray(t.metrics)?[{type:`metrics`,value:t.metrics}]:[{type:`json`,value:t}]}return[{type:`text`,value:String(e??``)}]}function cw(e){return{...e,options:e.options?.map(e=>typeof e==`string`?{label:e,value:e}:e)}}function lw(e){let t=ow(e.content);return{schemaVersion:1,title:e.title??aw,template:e.template,data:t,blocks:sw(t),actions:e.actions?.map(cw)}}var uw=class{templates=new Map;register(e){this.templates.set(e.name,e)}get(e){return this.templates.get(e)}detect(e){let t,n=0;for(let r of this.templates.values()){let i=r.detect(e);i>n&&(n=i,t=r)}return n>0?t:void 0}getAll(){return[...this.templates.values()]}},dw={"--color-background-primary":`--aikit-bg`,"--color-background-secondary":`--aikit-surface`,"--color-background-tertiary":`--aikit-surface2`,"--color-text-primary":`--aikit-text`,"--color-text-secondary":`--aikit-muted`,"--color-border-primary":`--aikit-border`,"--color-ring-primary":`--aikit-accent`,"--color-text-success":`--aikit-success`,"--color-text-danger":`--aikit-error`,"--color-text-warning":`--aikit-warning`,"--color-text-info":`--aikit-info`,"--font-sans":`--aikit-font-sans`,"--font-mono":`--aikit-font-mono`,"--border-radius-md":`--aikit-radius`,"--shadow-sm":`--aikit-shadow`},fw={"--aikit-bg":`--bg`,"--aikit-text":`--fg`,"--aikit-surface":`--surface`,"--aikit-border":`--border`,"--aikit-accent":`--accent`,"--aikit-success":`--success`,"--aikit-warning":`--warning`,"--aikit-error":`--error`,"--aikit-font-sans":`--font-sans`,"--aikit-font-mono":`--font-mono`,"--aikit-radius":`--radius`,"--aikit-shadow":`--shadow`},pw=`aikit-design-token-bridge`,mw={light:{"--bg":`#ffffff`,"--fg":`rgb(26 26 46)`,"--surface":`#f8f9fa`,"--border":`#e2e8f0`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#1e1e2e`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#ffffff`,"--aikit-surface":`#f8f9fa`,"--aikit-surface2":`#f8f9fa`,"--aikit-text":`rgb(26 26 46)`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#e2e8f0`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#1e1e2e`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`},dark:{"--bg":`#0d1117`,"--fg":`#e6edf3`,"--surface":`#161b22`,"--border":`#30363d`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#161b22`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#0d1117`,"--aikit-surface":`#161b22`,"--aikit-surface2":`#161b22`,"--aikit-text":`#e6edf3`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#30363d`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#161b22`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`}},hw={"--chart-1":`#79c0ff`,"--chart-2":`#38bdf8`,"--chart-3":`#34d399`,"--chart-4":`#fbbf24`,"--chart-5":`#f87171`,"--chart-6":`#a78bfa`,"--chart-7":`#f472b6`,"--chart-8":`#2dd4bf`,"--chart-9":`#fb923c`,"--chart-10":`#22d3ee`,"--chart-11":`#c084fc`,"--chart-12":`#a3e635`,"--chart-others":`#a8a29e`},gw=`
1971
+ `;function pC(e){let t=e.createElement(`style`);return t.textContent=fC,t}function mC(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function hC(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=pC(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=mC(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return mC(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var gC=`data-sort-label`,_C=`data-sort-dir`,vC=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function yC(e){let t=e.getAttribute(gC);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(gC,n),n}function bC(e,t,n){for(let[r,i]of e.entries())i.textContent=yC(i),r===t?(i.setAttribute(_C,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(_C)}function xC(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function SC(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=vC.compare(xC(e,t),xC(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}bC(t,a,o)};for(let[e,n]of t.entries()){yC(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=yC(e),e.removeAttribute(_C),e.removeAttribute(gC),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}function CC(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function wC(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return CC(n);n=n.parentElement}return null}function TC(e){return Array.from(e.querySelectorAll(`summary`))}function EC(e){return e.open||e.hasAttribute(`open`)}function DC(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function OC(e,t){e.textContent=t.every(e=>EC(e))?`Collapse all`:`Expand all`}function kC(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!EC(e));for(let n of t)DC(n,e);OC(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{OC(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=TC(e).map(t=>{t.tabIndex=0;let n=n=>{let r=TC(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!EC(a))DC(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&EC(a)?DC(a,!1):wC(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return OC(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}var AC=`data-hydrated`;function jC(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function MC(e,t,n){e.push(()=>{n(),t.removeAttribute(AC)})}function NC(e={}){let t=e.container??document.body,n=[];for(let e of jC(t,`.bk-table`))e.hasAttribute(AC)||(e.setAttribute(AC,``),MC(n,e,SC(e)));for(let e of jC(t,`.bk-tree`))e.hasAttribute(AC)||(e.setAttribute(AC,``),MC(n,e,kC(e)));for(let r of jC(t,`.bk-checklist`))r.hasAttribute(AC)||(r.setAttribute(AC,``),MC(n,r,hC(r,e)));for(let r of jC(t,`.bk-actions`))if(!r.hasAttribute(AC)){if(r.setAttribute(AC,``),e.onAction){MC(n,r,dC(r,e.onAction));continue}n.push(()=>{r.removeAttribute(AC)})}return()=>{for(let e of n)e();n.length=0}}var PC=`bk-styles`,FC=new Set;function IC(e){for(let t of e.css)t.trim().length>0&&FC.add(t);return[...FC].join(`
1972
+ `)}function LC(e){return di(e,{transport:`browser`})}function RC(e,t=document){let n=IC(e),r=t.getElementById(PC);r||(r=t.createElement(`style`),r.id=PC,t.head.appendChild(r)),r.textContent=n}function zC(e,t){let n=LC(t);return RC(n,e.ownerDocument),e.innerHTML=n.html,n}function BC(e,t,n){return zC(e,{schemaVersion:1,title:`AI Kit Present`,blocks:t}),NC({container:e,onAction:n})}function VC(e){return function(t,n){let r=n??t.label;if(!e){fetch(`/callback`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actionId:t.id,value:r})});return}e.updateModelContext({content:[{type:`text`,text:`Latest UI action: ${t.label}${n?` → ${n}`:``}`}],structuredContent:{actionId:t.id,actionType:t.type,label:t.label,value:r,timestamp:new Date().toISOString()}}),e.sendMessage({role:`user`,content:[{type:`text`,text:`User selected: ${t.label}${n?` → ${n}`:``}`}]})}}function HC(e){return typeof e==`object`&&!!e}function UC(e,t){let n=e.id.split(`@`)[0];return n===`timeline`&&HC(t)&&Array.isArray(t.events)?t.events:n===`tree`&&Array.isArray(t)?{root:{label:`Root`,children:t}}:t}function WC(e,t,n){let r=oi.get(e);if(!r?.supportedTransports.includes(`browser`))return null;let i=UC(r,t);return{blocks:r.blocksFromData(i,{colorScheme:n.colorScheme,transport:`browser`,lang:n.lang,dir:n.dir}),actions:r.actionsFromData?.(i)??[]}}var GC=`present-data`;function KC(e=document,t=GC){let n=e.getElementById(t);return n?.textContent?JSON.parse(n.textContent):null}function qC(e){return e?{callTool:(t,n)=>e.callServerTool({name:t,arguments:n}),sendMessage:async t=>{await e.sendMessage({role:`user`,content:[{type:`text`,text:t}]})},updateContext:async t=>{await e.updateModelContext({content:[{type:`text`,text:t}]})}}:{callTool:async()=>{throw Error(`callTool is not available in browser mode`)},sendMessage:async()=>{},updateContext:async()=>{}}}var JC=class{app;currentMode=`inline`;availableModes=[];toolbar=null;constructor(e){this.app=e}apply(e){e.displayMode&&(this.currentMode=e.displayMode),e.availableDisplayModes&&(this.availableModes=e.availableDisplayModes),this.updateToolbar()}async requestMode(e){try{let t=await this.app.requestDisplayMode({mode:e});return this.currentMode=t.mode,document.documentElement.dataset.display=t.mode,this.updateToolbar(),t.mode}catch{return this.currentMode}}updateToolbar(){if(this.availableModes.length<=1){this.toolbar?.remove(),this.toolbar=null;return}this.toolbar||=this.createToolbar(),this.renderButtons()}createToolbar(){let e=document.createElement(`div`);return e.className=`display-mode-toolbar`,document.body.appendChild(e),e}renderButtons(){if(!this.toolbar)return;this.toolbar.innerHTML=``;let e={inline:`▣`,fullscreen:`⛶`,pip:`◱`};for(let t of this.availableModes){let n=document.createElement(`button`);n.className=`dm-btn${t===this.currentMode?` dm-active`:``}`,n.textContent=e[t]??t,n.title=t,n.addEventListener(`click`,()=>this.requestMode(t)),this.toolbar.appendChild(n)}}},YC=new Set;function XC(e,t){if(YC.has(e))return;YC.add(e);let n=document.createElement(`style`);n.textContent=t,document.head.appendChild(n)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n&&(r.textContent=n),r}function ZC(e){return e==null?`null`:Array.isArray(e)?`[${e.map(ZC).join(`, `)}]`:String(e)}function QC(e){return typeof e==`object`&&!!e&&`type`in e}var $C=[[400,`compact`],[800,`comfortable`]],ew=class{root;displayMode=`inline`;sizeClass=`comfortable`;constructor(e){this.root=e??document.documentElement}apply(e){this.applyDisplayMode(e),this.applyContainerDimensions(e),this.applySafeArea(e),this.applyPlatform(e),this.applyDeviceCapabilities(e)}getDisplayMode(){return this.displayMode}getSize(){return this.sizeClass}applyDisplayMode(e){e.displayMode&&(this.displayMode=e.displayMode,this.root.dataset.display=e.displayMode)}applyContainerDimensions(e){let t=e.containerDimensions;if(!t)return;let n=this.root.style,r=`width`in t?t.width:`maxWidth`in t?t.maxWidth:void 0,i=`height`in t?t.height:`maxHeight`in t?t.maxHeight:void 0;r!==void 0&&(n.setProperty(`--aikit-container-w`,`${r}px`),this.sizeClass=this.deriveSizeClass(r),this.root.dataset.size=this.sizeClass,n.setProperty(`--aikit-content-max-width`,this.deriveMaxWidth(r)),n.setProperty(`--aikit-body-pad-x`,this.derivePadX()),n.setProperty(`--aikit-grid-cols`,this.deriveGridCols()),n.setProperty(`--aikit-card-min`,this.deriveCardMin()),n.setProperty(`--aikit-metric-min`,this.deriveMetricMin())),i!==void 0&&(n.setProperty(`--aikit-container-h`,`${i}px`),n.setProperty(`--aikit-body-pad-y`,this.derivePadY()))}applySafeArea(e){let t=e.safeAreaInsets;if(!t)return;let n=this.root.style;n.setProperty(`--aikit-safe-top`,`${t.top}px`),n.setProperty(`--aikit-safe-right`,`${t.right}px`),n.setProperty(`--aikit-safe-bottom`,`${t.bottom}px`),n.setProperty(`--aikit-safe-left`,`${t.left}px`)}applyPlatform(e){e.platform&&(this.root.dataset.platform=e.platform)}applyDeviceCapabilities(e){let t=e.deviceCapabilities;t&&(t.touch!==void 0&&(this.root.dataset.touch=String(t.touch)),t.hover!==void 0&&(this.root.dataset.hover=String(t.hover)))}deriveSizeClass(e){for(let[t,n]of $C)if(e<t)return n;return`full`}deriveMaxWidth(e){return this.displayMode===`pip`?`100%`:this.displayMode===`fullscreen`?`none`:e<960?`100%`:`900px`}derivePadX(){return this.sizeClass===`compact`?`8px`:`16px`}derivePadY(){return this.sizeClass===`compact`?`8px`:`16px`}deriveGridCols(){switch(this.sizeClass){case`compact`:return`1`;case`comfortable`:return`2`;case`full`:return`3`}}deriveCardMin(){return this.sizeClass===`compact`?`100%`:`250px`}deriveMetricMin(){return this.sizeClass===`compact`?`100px`:`150px`}},tw=`AI Kit Present`;function nw(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;if(Array.isArray(t.blocks)&&t.blocks.length>0)return t.blocks}return e}function rw(e){if(Array.isArray(e))return e.length===0?[{type:`markdown`,value:`*Empty array*`}]:QC(e[0])?e.filter(QC):typeof e[0]==`object`&&e[0]!==null?[{type:`table`,value:e}]:[{type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
1973
+ `)}];if(typeof e==`string`)return[{type:`markdown`,value:e}];if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?[{type:`graph`,value:t}]:Array.isArray(t.metrics)?[{type:`metrics`,value:t.metrics}]:[{type:`json`,value:t}]}return[{type:`text`,value:String(e??``)}]}function iw(e){return{...e,options:e.options?.map(e=>typeof e==`string`?{label:e,value:e}:e)}}function aw(e){let t=nw(e.content);return{schemaVersion:1,title:e.title??tw,template:e.template,data:t,blocks:rw(t),actions:e.actions?.map(iw)}}var ow=class{templates=new Map;register(e){this.templates.set(e.name,e)}get(e){return this.templates.get(e)}detect(e){let t,n=0;for(let r of this.templates.values()){let i=r.detect(e);i>n&&(n=i,t=r)}return n>0?t:void 0}getAll(){return[...this.templates.values()]}},sw={"--color-background-primary":`--aikit-bg`,"--color-background-secondary":`--aikit-surface`,"--color-background-tertiary":`--aikit-surface2`,"--color-text-primary":`--aikit-text`,"--color-text-secondary":`--aikit-muted`,"--color-border-primary":`--aikit-border`,"--color-ring-primary":`--aikit-accent`,"--color-text-success":`--aikit-success`,"--color-text-danger":`--aikit-error`,"--color-text-warning":`--aikit-warning`,"--color-text-info":`--aikit-info`,"--font-sans":`--aikit-font-sans`,"--font-mono":`--aikit-font-mono`,"--border-radius-md":`--aikit-radius`,"--shadow-sm":`--aikit-shadow`},cw={"--aikit-bg":`--bg`,"--aikit-text":`--fg`,"--aikit-surface":`--surface`,"--aikit-border":`--border`,"--aikit-accent":`--accent`,"--aikit-success":`--success`,"--aikit-warning":`--warning`,"--aikit-error":`--error`,"--aikit-font-sans":`--font-sans`,"--aikit-font-mono":`--font-mono`,"--aikit-radius":`--radius`,"--aikit-shadow":`--shadow`},lw=`aikit-design-token-bridge`,uw={light:{"--bg":`#ffffff`,"--fg":`rgb(26 26 46)`,"--surface":`#f8f9fa`,"--border":`#e2e8f0`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#1e1e2e`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#ffffff`,"--aikit-surface":`#f8f9fa`,"--aikit-surface2":`#f8f9fa`,"--aikit-text":`rgb(26 26 46)`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#e2e8f0`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#1e1e2e`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`},dark:{"--bg":`#0d1117`,"--fg":`#e6edf3`,"--surface":`#161b22`,"--border":`#30363d`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#161b22`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#0d1117`,"--aikit-surface":`#161b22`,"--aikit-surface2":`#161b22`,"--aikit-text":`#e6edf3`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#30363d`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#161b22`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`}},dw={"--chart-1":`#79c0ff`,"--chart-2":`#38bdf8`,"--chart-3":`#34d399`,"--chart-4":`#fbbf24`,"--chart-5":`#f87171`,"--chart-6":`#a78bfa`,"--chart-7":`#f472b6`,"--chart-8":`#2dd4bf`,"--chart-9":`#fb923c`,"--chart-10":`#22d3ee`,"--chart-11":`#c084fc`,"--chart-12":`#a3e635`,"--chart-others":`#a8a29e`},fw=`
1974
1974
  :root {
1975
1975
  --dt-bg-primary: var(--aikit-bg, #0d1117);
1976
1976
  --dt-bg-secondary: var(--aikit-surface, #161b22);
@@ -2039,7 +2039,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2039
2039
  [data-theme='light'] {
2040
2040
  color-scheme: light;
2041
2041
  }
2042
- `,_w=class{root;constructor(e){this.root=e??document.documentElement,this.applyFallbackVariables(),this.ensureDesignTokenBridge()}apply(e){e.theme&&cC(e.theme),this.applyFallbackVariables(e.theme),e.styles?.variables&&(lC(e.styles.variables),this.mapTokens(e.styles.variables)),e.styles?.css?.fonts&&this.injectFonts(e.styles.css.fonts)}getTheme(){return sC()}resolveFallbackTheme(e){if(e)return e;let t=this.root.dataset.theme;return t===`light`||t===`dark`?t:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}applyFallbackVariables(e){let t=this.resolveFallbackTheme(e),n=this.root.style;for(let[e,r]of Object.entries(mw[t]))n.setProperty(e,r);for(let[e,t]of Object.entries(hw))n.setProperty(e,t);n.colorScheme=t}mapTokens(e){let t=this.root.style;for(let[n,r]of Object.entries(dw)){let i=e[n];if(i){t.setProperty(r,i);let e=fw[r];e&&t.setProperty(e,i)}}this.getTheme()===`dark`?(t.setProperty(`--code-bg`,e[`--color-background-tertiary`]??`#0f0f1a`),t.setProperty(`--code-fg`,`#cdd6f4`)):(t.setProperty(`--code-bg`,`#f0f0f5`),t.setProperty(`--code-fg`,`#1a1a2e`)),t.setProperty(`--aikit-code-bg`,t.getPropertyValue(`--code-bg`)),t.setProperty(`--aikit-code-fg`,t.getPropertyValue(`--code-fg`));let n=e[`--color-ring-primary`];n&&(t.setProperty(`--aikit-accent-light`,n),t.setProperty(`--accent-light`,n),t.setProperty(`--aikit-hover-bg`,`color-mix(in srgb, ${n} 10%, transparent)`))}injectFonts(e){let t=`aikit-host-fonts`;if(document.getElementById(t))return;let n=document.createElement(`style`);n.id=t,n.textContent=e,document.head.appendChild(n)}ensureDesignTokenBridge(){if(document.getElementById(pw))return;let e=document.createElement(`style`);e.id=pw,e.textContent=gw,document.head.appendChild(e)}},vw=`
2042
+ `,pw=class{root;constructor(e){this.root=e??document.documentElement,this.applyFallbackVariables(),this.ensureDesignTokenBridge()}apply(e){e.theme&&cC(e.theme),this.applyFallbackVariables(e.theme),e.styles?.variables&&(lC(e.styles.variables),this.mapTokens(e.styles.variables)),e.styles?.css?.fonts&&this.injectFonts(e.styles.css.fonts)}getTheme(){return sC()}resolveFallbackTheme(e){if(e)return e;let t=this.root.dataset.theme;return t===`light`||t===`dark`?t:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}applyFallbackVariables(e){let t=this.resolveFallbackTheme(e),n=this.root.style;for(let[e,r]of Object.entries(uw[t]))n.setProperty(e,r);for(let[e,t]of Object.entries(dw))n.setProperty(e,t);n.colorScheme=t}mapTokens(e){let t=this.root.style;for(let[n,r]of Object.entries(sw)){let i=e[n];if(i){t.setProperty(r,i);let e=cw[r];e&&t.setProperty(e,i)}}this.getTheme()===`dark`?(t.setProperty(`--code-bg`,e[`--color-background-tertiary`]??`#0f0f1a`),t.setProperty(`--code-fg`,`#cdd6f4`)):(t.setProperty(`--code-bg`,`#f0f0f5`),t.setProperty(`--code-fg`,`#1a1a2e`)),t.setProperty(`--aikit-code-bg`,t.getPropertyValue(`--code-bg`)),t.setProperty(`--aikit-code-fg`,t.getPropertyValue(`--code-fg`));let n=e[`--color-ring-primary`];n&&(t.setProperty(`--aikit-accent-light`,n),t.setProperty(`--accent-light`,n),t.setProperty(`--aikit-hover-bg`,`color-mix(in srgb, ${n} 10%, transparent)`))}injectFonts(e){let t=`aikit-host-fonts`;if(document.getElementById(t))return;let n=document.createElement(`style`);n.id=t,n.textContent=e,document.head.appendChild(n)}ensureDesignTokenBridge(){if(document.getElementById(lw))return;let e=document.createElement(`style`);e.id=lw,e.textContent=fw,document.head.appendChild(e)}},mw=`
2043
2043
  .tpl-dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; }
2044
2044
  .db-card { min-height: 136px; padding: 14px; border: 1px solid var(--aikit-border, #3c3c3c);
2045
2045
  border-left-width: 4px; border-radius: var(--aikit-radius, 10px); background: var(--aikit-surface, #252526);
@@ -2065,7 +2065,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2065
2065
  .db-list-item { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--aikit-text, #e5e7eb);
2066
2066
  font: 500 13px var(--aikit-font-sans, Inter, sans-serif); }
2067
2067
  .db-list-item span:last-child { color: var(--aikit-muted, #9ca3af); font-family: var(--aikit-font-mono, Consolas, monospace); }
2068
- `,yw={name:`dashboard`,label:`Dashboard`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.metrics)?t.metrics[0]:void 0;return n&&typeof n.label==`string`&&`value`in n?.85:0},render(e,t,n){ew(`tpl-dashboard`,vw);let r=t,i=Q(`div`,`block tpl-dashboard`);for(let e of r.metrics){let t=Q(`article`,`db-card status-${e.status??`info`}`),n=Q(`div`,`db-header`);if(n.appendChild(Q(`div`,`db-label`,e.label)),e.trend){let t=e.trend.direction===`up`?`▲`:e.trend.direction===`down`?`▼`:`—`;n.appendChild(Q(`div`,`db-trend ${e.trend.direction}`,`${t} ${e.trend.value}`))}if(t.appendChild(n),t.appendChild(Q(`div`,`db-value`,tw(e.value))),e.type===`progress`){let n=Q(`div`,`db-progress-track`),r=Q(`div`,`db-progress-fill`);r.style.width=`${Math.max(0,Math.min(100,e.progress??0))}%`,n.appendChild(r),t.appendChild(n),t.appendChild(Q(`div`,`db-progress-meta`,`${Math.max(0,Math.min(100,e.progress??0))}% complete`))}if(e.type===`list`&&e.items?.length){let n=Q(`ul`,`db-list`);for(let t of e.items){let e=Q(`li`,`db-list-item`);e.appendChild(Q(`span`,``,t.label)),e.appendChild(Q(`span`,``,t.value)),n.appendChild(e)}t.appendChild(n)}i.appendChild(t)}e.appendChild(i)},styles(){return vw}},bw=`
2068
+ `,hw={name:`dashboard`,label:`Dashboard`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.metrics)?t.metrics[0]:void 0;return n&&typeof n.label==`string`&&`value`in n?.85:0},render(e,t,n){XC(`tpl-dashboard`,mw);let r=t,i=Q(`div`,`block tpl-dashboard`);for(let e of r.metrics){let t=Q(`article`,`db-card status-${e.status??`info`}`),n=Q(`div`,`db-header`);if(n.appendChild(Q(`div`,`db-label`,e.label)),e.trend){let t=e.trend.direction===`up`?`▲`:e.trend.direction===`down`?`▼`:`—`;n.appendChild(Q(`div`,`db-trend ${e.trend.direction}`,`${t} ${e.trend.value}`))}if(t.appendChild(n),t.appendChild(Q(`div`,`db-value`,ZC(e.value))),e.type===`progress`){let n=Q(`div`,`db-progress-track`),r=Q(`div`,`db-progress-fill`);r.style.width=`${Math.max(0,Math.min(100,e.progress??0))}%`,n.appendChild(r),t.appendChild(n),t.appendChild(Q(`div`,`db-progress-meta`,`${Math.max(0,Math.min(100,e.progress??0))}% complete`))}if(e.type===`list`&&e.items?.length){let n=Q(`ul`,`db-list`);for(let t of e.items){let e=Q(`li`,`db-list-item`);e.appendChild(Q(`span`,``,t.label)),e.appendChild(Q(`span`,``,t.value)),n.appendChild(e)}t.appendChild(n)}i.appendChild(t)}e.appendChild(i)},styles(){return mw}},gw=`
2069
2069
  .fg-breadcrumb { display: flex; align-items: center; gap: 4px; padding: 8px 0; flex-wrap: wrap; }
2070
2070
  .fg-crumb { background: var(--aikit-surface, #252526); border: 1px solid var(--aikit-border, #3c3c3c);
2071
2071
  color: var(--aikit-text, #ccc); padding: 3px 10px; border-radius: 4px; cursor: pointer; font-size: 12px; }
@@ -2080,7 +2080,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2080
2080
  text-overflow: ellipsis; font-weight: 500; }
2081
2081
  .fg-info { font-size: 12px; color: var(--aikit-muted, #858585); padding: 8px 0;
2082
2082
  border-top: 1px solid var(--aikit-border, #3c3c3c); margin-top: 8px; }
2083
- `;function xw(e){return{name:String(e.name??``),total:typeof e.total==`number`?e.total:typeof e.value==`number`?e.value:0,self:typeof e.self==`number`?e.self:void 0,children:Array.isArray(e.children)?e.children.map(e=>xw(e)):void 0}}var Sw={name:`flame-graph`,label:`Flame Graph`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e.profile;return t&&typeof t==`object`&&t.children?.9:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-flame-graph`),a=xw(r.profile),o=a,s=[a],c=Q(`div`,`fg-breadcrumb`);i.appendChild(c);let l=Q(`div`,`fg-canvas`);i.appendChild(l);let u=Q(`div`,`fg-info`);i.appendChild(u);function d(){c.innerHTML=``;for(let e=0;e<s.length;e++){let t=s[e],n=document.createElement(`button`);n.className=`fg-crumb`,n.textContent=t.name,n.addEventListener(`click`,()=>{s.splice(e+1),o=t,d()}),c.appendChild(n),e<s.length-1&&c.appendChild(Q(`span`,`fg-sep`,`›`))}l.innerHTML=``,f(l,o,0,o.total),u.textContent=`${o.name} — total: ${o.total}${o.self==null?``:`, self: ${o.self}`}`}function f(e,t,r,i){let a=Q(`div`,`fg-row`);a.style.paddingLeft=`${r*2}px`;let c=Q(`div`,`fg-bar`),l=Math.max(2,t.total/i*100);c.style.width=`${l}%`,c.style.background=ee(r),c.title=`${t.name}: ${t.total}${t.self==null?``:` (self: ${t.self})`}`;let te=Q(`span`,`fg-bar-label`,`${t.name} (${t.total})`);if(c.appendChild(te),t.children?.length&&(c.style.cursor=`pointer`,c.addEventListener(`click`,()=>{o=t,s.push(t),d(),n.emitAction({type:`button`,id:`zoom`,label:`Zoom`},JSON.stringify({name:t.name,total:t.total}))})),c.addEventListener(`mouseenter`,()=>{u.textContent=`${t.name} — total: ${t.total}${t.self==null?``:`, self: ${t.self}`}`}),a.appendChild(c),e.appendChild(a),t.children)for(let n of t.children)f(e,n,r+1,i)}function ee(e){let t=getComputedStyle(document.documentElement),n=[t.getPropertyValue(`--chart-5`).trim()||`#e24d28`,t.getPropertyValue(`--chart-9`).trim()||`#e8602a`,t.getPropertyValue(`--chart-4`).trim()||`#edad2a`,t.getPropertyValue(`--chart-1`).trim()||`#f5c842`,t.getPropertyValue(`--chart-3`).trim()||`#fce94f`,t.getPropertyValue(`--chart-6`).trim()||`#c4a000`,t.getPropertyValue(`--chart-7`).trim()||`#e07028`,t.getPropertyValue(`--chart-8`).trim()||`#d45500`];return n[e%n.length]}d(),ew(`tpl-flame-graph`,bw),e.appendChild(i)},styles(){return bw}},Cw=`
2083
+ `;function _w(e){return{name:String(e.name??``),total:typeof e.total==`number`?e.total:typeof e.value==`number`?e.value:0,self:typeof e.self==`number`?e.self:void 0,children:Array.isArray(e.children)?e.children.map(e=>_w(e)):void 0}}var vw={name:`flame-graph`,label:`Flame Graph`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e.profile;return t&&typeof t==`object`&&t.children?.9:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-flame-graph`),a=_w(r.profile),o=a,s=[a],c=Q(`div`,`fg-breadcrumb`);i.appendChild(c);let l=Q(`div`,`fg-canvas`);i.appendChild(l);let u=Q(`div`,`fg-info`);i.appendChild(u);function d(){c.innerHTML=``;for(let e=0;e<s.length;e++){let t=s[e],n=document.createElement(`button`);n.className=`fg-crumb`,n.textContent=t.name,n.addEventListener(`click`,()=>{s.splice(e+1),o=t,d()}),c.appendChild(n),e<s.length-1&&c.appendChild(Q(`span`,`fg-sep`,`›`))}l.innerHTML=``,f(l,o,0,o.total),u.textContent=`${o.name} — total: ${o.total}${o.self==null?``:`, self: ${o.self}`}`}function f(e,t,r,i){let a=Q(`div`,`fg-row`);a.style.paddingLeft=`${r*2}px`;let c=Q(`div`,`fg-bar`),l=Math.max(2,t.total/i*100);c.style.width=`${l}%`,c.style.background=ee(r),c.title=`${t.name}: ${t.total}${t.self==null?``:` (self: ${t.self})`}`;let te=Q(`span`,`fg-bar-label`,`${t.name} (${t.total})`);if(c.appendChild(te),t.children?.length&&(c.style.cursor=`pointer`,c.addEventListener(`click`,()=>{o=t,s.push(t),d(),n.emitAction({type:`button`,id:`zoom`,label:`Zoom`},JSON.stringify({name:t.name,total:t.total}))})),c.addEventListener(`mouseenter`,()=>{u.textContent=`${t.name} — total: ${t.total}${t.self==null?``:`, self: ${t.self}`}`}),a.appendChild(c),e.appendChild(a),t.children)for(let n of t.children)f(e,n,r+1,i)}function ee(e){let t=getComputedStyle(document.documentElement),n=[t.getPropertyValue(`--chart-5`).trim()||`#e24d28`,t.getPropertyValue(`--chart-9`).trim()||`#e8602a`,t.getPropertyValue(`--chart-4`).trim()||`#edad2a`,t.getPropertyValue(`--chart-1`).trim()||`#f5c842`,t.getPropertyValue(`--chart-3`).trim()||`#fce94f`,t.getPropertyValue(`--chart-6`).trim()||`#c4a000`,t.getPropertyValue(`--chart-7`).trim()||`#e07028`,t.getPropertyValue(`--chart-8`).trim()||`#d45500`];return n[e%n.length]}d(),XC(`tpl-flame-graph`,gw),e.appendChild(i)},styles(){return gw}},yw=`
2084
2084
  .tpl-kanban { overflow-x: auto; }
2085
2085
  .kbn-board { display: flex; gap: 14px; align-items: flex-start; min-width: min-content; padding-bottom: 4px; }
2086
2086
  .kbn-column { width: 280px; flex: 0 0 280px; border: 1px solid var(--aikit-border, #3c3c3c); border-radius: var(--aikit-radius, 10px);
@@ -2106,7 +2106,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2106
2106
  .kbn-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
2107
2107
  .kbn-tag { padding: 2px 8px; border-radius: 999px; background: var(--aikit-surface, #252526); color: var(--aikit-muted, #9ca3af);
2108
2108
  font: 500 11px var(--aikit-font-sans, Inter, sans-serif); }
2109
- `,ww={name:`kanban`,label:`Kanban`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.cards)?t.cards[0]:void 0;return Array.isArray(t.columns)&&Array.isArray(t.cards)&&typeof n?.column==`string`?.85:0},render(e,t,n){ew(`tpl-kanban`,Cw);let r=t,i=r.cards.map(e=>({...e,tags:e.tags?[...e.tags]:void 0})),a=new Set,o=``,s=Q(`div`,`block tpl-kanban`),c=Q(`div`,`kbn-board`);s.appendChild(c);let l=()=>{c.innerHTML=``;for(let e of r.columns){let t=Q(`section`,`kbn-column`),r=Q(`div`,`kbn-column-header`),s=Q(`div`,`kbn-column-title`),u=Q(`span`,`kbn-column-swatch`);e.color&&(u.style.background=e.color),s.appendChild(u),s.appendChild(Q(`span`,``,e.label)),r.appendChild(s);let d=i.filter(t=>t.column===e.id);r.appendChild(Q(`span`,`kbn-column-count`,String(d.length))),t.appendChild(r);let f=Q(`div`,`kbn-cards`);t.addEventListener(`dragover`,e=>{e.preventDefault(),t.classList.add(`drop-target`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drop-target`)}),t.addEventListener(`drop`,r=>{if(r.preventDefault(),t.classList.remove(`drop-target`),!o)return;let a=i.find(e=>e.id===o);!a||a.column===e.id||(a.column=e.id,l(),n.emitAction({type:`button`,id:`move-card`,label:`Move Card`},JSON.stringify({id:a.id,column:e.id})))});for(let e of d){let t=Q(`article`,`kbn-card priority-${e.priority??`low`}`);if(t.draggable=!0,t.appendChild(Q(`div`,`kbn-card-title`,e.title)),e.description){let n=Q(`div`,`kbn-card-description`,e.description);n.hidden=!a.has(e.id),t.appendChild(n),t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id),n.hidden=!a.has(e.id)})}else t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id)});if(e.tags?.length){let n=Q(`div`,`kbn-tags`);for(let t of e.tags)n.appendChild(Q(`span`,`kbn-tag`,t));t.appendChild(n)}t.addEventListener(`dragstart`,()=>{o=e.id,t.classList.add(`dragging`)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),o=``}),f.appendChild(t)}t.appendChild(f),c.appendChild(t)}};l(),e.appendChild(s)},styles(){return Cw}},Tw=`
2109
+ `,bw={name:`kanban`,label:`Kanban`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.cards)?t.cards[0]:void 0;return Array.isArray(t.columns)&&Array.isArray(t.cards)&&typeof n?.column==`string`?.85:0},render(e,t,n){XC(`tpl-kanban`,yw);let r=t,i=r.cards.map(e=>({...e,tags:e.tags?[...e.tags]:void 0})),a=new Set,o=``,s=Q(`div`,`block tpl-kanban`),c=Q(`div`,`kbn-board`);s.appendChild(c);let l=()=>{c.innerHTML=``;for(let e of r.columns){let t=Q(`section`,`kbn-column`),r=Q(`div`,`kbn-column-header`),s=Q(`div`,`kbn-column-title`),u=Q(`span`,`kbn-column-swatch`);e.color&&(u.style.background=e.color),s.appendChild(u),s.appendChild(Q(`span`,``,e.label)),r.appendChild(s);let d=i.filter(t=>t.column===e.id);r.appendChild(Q(`span`,`kbn-column-count`,String(d.length))),t.appendChild(r);let f=Q(`div`,`kbn-cards`);t.addEventListener(`dragover`,e=>{e.preventDefault(),t.classList.add(`drop-target`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drop-target`)}),t.addEventListener(`drop`,r=>{if(r.preventDefault(),t.classList.remove(`drop-target`),!o)return;let a=i.find(e=>e.id===o);!a||a.column===e.id||(a.column=e.id,l(),n.emitAction({type:`button`,id:`move-card`,label:`Move Card`},JSON.stringify({id:a.id,column:e.id})))});for(let e of d){let t=Q(`article`,`kbn-card priority-${e.priority??`low`}`);if(t.draggable=!0,t.appendChild(Q(`div`,`kbn-card-title`,e.title)),e.description){let n=Q(`div`,`kbn-card-description`,e.description);n.hidden=!a.has(e.id),t.appendChild(n),t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id),n.hidden=!a.has(e.id)})}else t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id)});if(e.tags?.length){let n=Q(`div`,`kbn-tags`);for(let t of e.tags)n.appendChild(Q(`span`,`kbn-tag`,t));t.appendChild(n)}t.addEventListener(`dragstart`,()=>{o=e.id,t.classList.add(`dragging`)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),o=``}),f.appendChild(t)}t.appendChild(f),c.appendChild(t)}};l(),e.appendChild(s)},styles(){return yw}},xw=`
2110
2110
  .sort-list { list-style: none; padding: 0; margin: 0; }
2111
2111
  .sort-item { display: flex; align-items: center; gap: 10px; padding: 10px 14px; margin: 4px 0;
2112
2112
  background: var(--aikit-surface, #252526); border: 1px solid var(--aikit-border, #3c3c3c);
@@ -2117,7 +2117,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2117
2117
  .drag-handle { font-size: 18px; color: var(--aikit-muted, #858585); cursor: grab; user-select: none; }
2118
2118
  .sort-label { flex: 1; color: var(--aikit-text, #ccc); }
2119
2119
  .sort-pos { font-size: 12px; color: var(--aikit-muted, #858585); font-variant-numeric: tabular-nums; }
2120
- `,Ew={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);ew(`tpl-list-sort`,Tw);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return Tw}},Dw=document.getElementById(`app`);if(!Dw)throw Error(`Missing #app element`);var $=Dw,Ow=XC(),kw=Ow?void 0:new uC({name:`AI Kit Present`,version:`1.0.0`}),Aw=new uw;Aw.register(Ew),Aw.register(Sw),Aw.register(yw),Aw.register(ww);var jw=GC(kw),Mw={app:kw,data:ZC(kw),emitAction:jw},Nw=new _w,Pw=new iw,Fw=kw?new QC(kw):void 0,Iw=null;function Lw(){Iw?.(),Iw=null,Uw?.destroy&&Uw.destroy(),Uw=null}function Rw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function zw(e,t,n){let r=Rw(t,n);Iw=WC(e,t,(e,t)=>{jw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Bw(e,t,n){let r=document.documentElement.dir,i=JC(e,t,{colorScheme:Nw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var Vw;function Hw(e){Lw(),$.innerHTML=``;let t=lw(e);if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge streaming`,`⟳`)),$.appendChild(t)}let n=Q(`div`,`content`);zw(n,t.blocks??[]),$.appendChild(n)}var Uw=null;function Ww(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function Gw(e){Lw(),$.innerHTML=``;let t=lw(e),n=t.data;if(!n){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge`,`AI KIT`)),$.appendChild(t)}let r=t.template?Aw.get(t.template):Aw.detect(n),i=Q(`div`,`content`);if(r)Uw=r,r.render(i,n,Mw);else if(t.template){let r=Bw(t.template,n,e);r?zw(i,r.blocks,r.actions):zw(i,t.blocks??[],e.actions)}else zw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=WC(t,[{type:`actions`,value:e.actions}],(t,n)=>{jw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Iw;Iw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}kw?(kw.connect().then(()=>{let e=kw.getHostContext();e&&(Nw.apply(e),Pw.apply(e),Fw?.apply(e))}),kw.onhostcontextchanged=e=>{Nw.apply(e),Pw.apply(e),Fw?.apply(e),Uw?.onThemeChange&&Uw.onThemeChange(Nw.getTheme())},kw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(Vw),Vw=setTimeout(()=>{try{let e=t.content;if(!e)return;Hw({title:t.title,template:t.template,content:e})}catch{}},80))},kw.ontoolinput=()=>{clearTimeout(Vw),delete $.dataset.streaming},kw.ontoolresult=e=>{if(clearTimeout(Vw),delete $.dataset.streaming,e.structuredContent)try{Gw(e.structuredContent);return}catch(e){Ww(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{Gw(JSON.parse(t))}catch{Gw({content:t})}}):Ow&&(document.documentElement.dataset.theme=`dark`,Gw(Ow));</script>
2120
+ `,Sw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);XC(`tpl-list-sort`,xw);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return xw}},Cw=document.getElementById(`app`);if(!Cw)throw Error(`Missing #app element`);var $=Cw,ww=KC(),Tw=ww?void 0:new uC({name:`AI Kit Present`,version:`1.0.0`}),Ew=new ow;Ew.register(Sw),Ew.register(vw),Ew.register(hw),Ew.register(bw);var Dw=VC(Tw),Ow={app:Tw,data:qC(Tw),emitAction:Dw},kw=new pw,Aw=new ew,jw=Tw?new JC(Tw):void 0,Mw=null;function Nw(){Mw?.(),Mw=null,zw?.destroy&&zw.destroy(),zw=null}function Pw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function Fw(e,t,n){let r=Pw(t,n);Mw=BC(e,t,(e,t)=>{Dw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Iw(e,t,n){let r=document.documentElement.dir,i=WC(e,t,{colorScheme:kw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var Lw;function Rw(e){Nw(),$.innerHTML=``;let t=aw(e);if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge streaming`,`⟳`)),$.appendChild(t)}let n=Q(`div`,`content`);Fw(n,t.blocks??[]),$.appendChild(n)}var zw=null;function Bw(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function Vw(e){Nw(),$.innerHTML=``;let t=aw(e),n=t.data;if(!n){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge`,`AI KIT`)),$.appendChild(t)}let r=t.template?Ew.get(t.template):Ew.detect(n),i=Q(`div`,`content`);if(r)zw=r,r.render(i,n,Ow);else if(t.template){let r=Iw(t.template,n,e);r?Fw(i,r.blocks,r.actions):Fw(i,t.blocks??[],e.actions)}else Fw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=BC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Dw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Mw;Mw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Tw?(Tw.connect().then(()=>{let e=Tw.getHostContext();e&&(kw.apply(e),Aw.apply(e),jw?.apply(e))}),Tw.onhostcontextchanged=e=>{kw.apply(e),Aw.apply(e),jw?.apply(e),zw?.onThemeChange&&zw.onThemeChange(kw.getTheme())},Tw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(Lw),Lw=setTimeout(()=>{try{let e=t.content;if(!e)return;Rw({title:t.title,template:t.template,content:e})}catch{}},80))},Tw.ontoolinput=()=>{clearTimeout(Lw),delete $.dataset.streaming},Tw.ontoolresult=e=>{if(clearTimeout(Lw),delete $.dataset.streaming,e.structuredContent)try{Vw(e.structuredContent);return}catch(e){Bw(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{Vw(JSON.parse(t))}catch{Vw({content:t})}}):ww&&(document.documentElement.dataset.theme=`dark`,Vw(ww));</script>
2121
2121
  </head>
2122
2122
  <body>
2123
2123
  <div id="app">