@vpxa/aikit 0.1.189 → 0.1.190

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.189",
3
+ "version": "0.1.190",
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",
@@ -1741,7 +1741,7 @@ html[data-theme='dark'] .aikit-theme-toggle-icon--moon {
1741
1741
  }
1742
1742
  `,Ut={actions:m,cards:ee,chart:ne,checklist:Ce,code:we,comparison:Ee,"component-detail":Ne,"data-table-schema":Re,"docs-browser":Be,"docs-hub":We,finding:Ke,graph:qe,heading:Je,kv:Xe,"lifecycle-flow":it,list:at,markdown:ut,mermaid:dt,metrics:pt,paragraph:mt,progress:gt,prompt:vt,separator:yt,"status-board":xt,table:wt,tags:Et,text:Dt,timeline:Ot,tree:kt};function Wt(e,t){let r={...e,value:o(e.value)},i=Ut[r.type],a=i?i(r,t):Kt(r);return r.title&&![`heading`,`finding`].includes(r.type)?`<section class="bk-section bk-section--${n(r.type)}"><h3 class="bk-section-title">${n(r.title)}</h3>${a}</section>`:a}function Gt(e,t){return e.map(e=>Wt(e,t)).join(`
1743
1743
  `)}function Kt(e){if(e.value===void 0||e.value===null)return``;if(typeof e.value==`string`)return`<p class="bk-paragraph">${n(e.value)}</p>`;try{return`<pre class="bk-fallback">${n(JSON.stringify(e.value,null,2))}</pre>`}catch{return`<pre class="bk-fallback">${n(String(e.value))}</pre>`}}var qt=class{templates=new Map;register(e){this.templates.set(e.id,e)}get(e){let t=this.templates.get(e);if(t)return t;let n=e.includes(`@`)?e:`${e}@`,r,i=-1;for(let[e,t]of this.templates){if(!e.startsWith(n))continue;let a=Number.parseInt(e.split(`@`)[1]??`0`,10);a>i&&(i=a,r=t)}return r}has(e){return this.get(e)!==void 0}list(){return[...this.templates.values()]}};const Jt=[`mcp-app`,`browser`];function B(e){return typeof e==`object`&&!!e}function Yt(e){return Array.isArray(e)?e.flatMap(e=>!B(e)||typeof e.label!=`string`?[]:[{label:e.label,checked:!!e.checked}]):[]}const Xt={id:`checklist@1`,label:`Checklist`,description:`Checklist with optional title and checklist hydration metadata.`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`label`,`checked`],properties:{label:{type:`string`},checked:{type:`boolean`}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=[],n=B(e)&&typeof e.title==`string`?e.title:void 0,r=B(e)?Yt(e.items):[];return n&&t.push({type:`heading`,value:n}),t.push({type:`checklist`,value:r}),t},hydration:[`checklist`],supportedTransports:Jt},Zt=[`mcp-app`,`browser`,`export`];function V(e){return typeof e==`object`&&!!e}function Qt(e){return V(e)&&typeof e.label==`string`&&(typeof e.value==`string`||typeof e.value==`number`)}function $t(e){return V(e)&&typeof e.key==`string`&&typeof e.label==`string`}function en(e){return Array.isArray(e)?e.filter(V):[]}function tn(e,t){if(Array.isArray(e)){let t=e.filter($t);if(t.length>0)return t}return Object.keys(t[0]??{}).map(e=>({key:e,label:e}))}const nn={id:`data-table@1`,label:`Data Table`,description:`Static data table with optional metrics and sortable table hydration.`,inputSchema:{type:`object`,properties:{columns:{type:`array`,items:{type:`object`,required:[`key`,`label`],properties:{key:{type:`string`},label:{type:`string`}},additionalProperties:!1}},rows:{type:`array`,items:{type:`object`}},stats:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:[`string`,`number`]},status:{type:`string`}},additionalProperties:!1}}},required:[`rows`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=V(e)?en(e.rows):[],n=V(e)?tn(e.columns,t):[],r=n.map(e=>e.label),i=t.map(e=>n.map(t=>e[t.key])),a=[];if(V(e)&&Array.isArray(e.stats)){let t=e.stats.filter(Qt);t.length>0&&a.push({type:`metrics`,value:t})}return a.push({type:`table`,columns:n,headers:r,rows:i,value:{headers:r,rows:i}}),a},hydration:[`table`],supportedTransports:Zt},rn=[`mcp-app`,`browser`,`export`];function H(e){return typeof e==`object`&&!!e}function an(e){return Array.isArray(e)?e.flatMap(e=>!H(e)||typeof e.type!=`string`||typeof e.content!=`string`?[]:[{type:e.type,content:e.content}]):[]}function on(e){return Array.isArray(e)?e.flatMap(e=>!H(e)||typeof e.header!=`string`?[]:[{header:e.header,changes:an(e.changes)}]):[]}function sn(e){return!H(e)||!Array.isArray(e.files)?[]:e.files.flatMap(e=>!H(e)||typeof e.path!=`string`||typeof e.status!=`string`?[]:[{path:e.path,status:e.status,additions:typeof e.additions==`number`?e.additions:0,deletions:typeof e.deletions==`number`?e.deletions:0,hunks:on(e.hunks)}])}function cn(e){return e===`add`?`+`:e===`delete`?`-`:` `}function ln(e){let t=e.hunks.flatMap(e=>[e.header,...e.changes.map(e=>`${cn(e.type)}${e.content}`)]).join(`
1744
- `);return[{type:`heading`,value:e.path},{type:`paragraph`,value:`${e.status} | +${e.additions} / -${e.deletions}`},{type:`code`,language:`diff`,value:t}]}const un={id:`diff-view@1`,label:`Diff View`,description:`Static diff summary rendered as per-file diff code blocks.`,inputSchema:{type:`object`,properties:{files:{type:`array`,items:{type:`object`,required:[`path`,`status`,`additions`,`deletions`,`hunks`],properties:{path:{type:`string`},status:{type:`string`},additions:{type:`number`},deletions:{type:`number`},hunks:{type:`array`,items:{type:`object`,required:[`header`,`changes`],properties:{header:{type:`string`},changes:{type:`array`,items:{type:`object`,required:[`type`,`content`],properties:{type:{type:`string`},content:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`files`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>sn(e).flatMap(ln),hydration:[],supportedTransports:rn},dn=[`mcp-app`,`browser`,`export`];function U(e){return typeof e==`object`&&!!e}function fn(e){return U(e)&&typeof e.type==`string`}function pn(e){return Array.isArray(e)&&e.every(fn)}function mn(e){if(!U(e))return{sections:[]};let t=Array.isArray(e.sections)?e.sections.flatMap(e=>{if(!U(e)||typeof e.heading!=`string`)return[];let t=typeof e.content==`string`||pn(e.content)?e.content:``;return[{heading:e.heading,content:t}]}):[];return{title:typeof e.title==`string`?e.title:void 0,sections:t}}function hn(e){let t=[{type:`heading`,value:e.heading}];return typeof e.content==`string`?(t.push({type:`paragraph`,value:e.content}),t):(t.push(...e.content),t)}const gn={id:`document@1`,label:`Document`,description:`Structured document with optional title and section content blocks.`,inputSchema:{type:`object`,properties:{title:{type:`string`},sections:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`heading`,`content`],properties:{heading:{type:`string`},content:{oneOf:[{type:`string`},{type:`array`,items:{type:`object`}}]}}}}},required:[`sections`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=mn(e),n=[];t.title&&n.push({type:`heading`,value:t.title});for(let e of t.sections)n.push(...hn(e));return n},hydration:[],supportedTransports:dn},_n=[`mcp-app`,`browser`,`export`];function vn(e){return typeof e==`object`&&!!e}function yn(e){return vn(e)?{code:typeof e.code==`string`?e.code:`ERROR`,message:typeof e.message==`string`?e.message:`Unknown error`,details:typeof e.details==`string`?e.details:void 0,stack:typeof e.stack==`string`?e.stack:void 0}:{code:`ERROR`,message:`Unknown error`}}const W={id:`error@1`,label:`Error`,description:`Static error view with message and optional stack trace.`,inputSchema:{type:`object`,properties:{code:{type:`string`},message:{type:`string`},details:{type:`string`},stack:{type:`string`}},required:[`code`,`message`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=yn(e),n=[{type:`heading`,value:`Error`},{type:`code`,title:t.code,language:`text`,value:t.details?`${t.message}\n\n${t.details}`:t.message}];return t.stack&&n.push({type:`code`,title:`Stack Trace`,language:`text`,value:t.stack}),n},hydration:[],supportedTransports:_n};function G(e){return typeof e==`object`&&!!e}function bn(e){return Array.isArray(e)?e.flatMap(e=>!G(e)||typeof e.name!=`string`||typeof e.label!=`string`?[]:[{name:e.name,label:e.label,type:typeof e.type==`string`?e.type:void 0,required:typeof e.required==`boolean`?e.required:void 0,placeholder:typeof e.placeholder==`string`?e.placeholder:void 0,default:typeof e.default==`string`?e.default:void 0,options:Array.isArray(e.options)?e.options.filter(e=>typeof e==`string`||G(e)&&typeof e.label==`string`&&typeof e.value==`string`):void 0,value:typeof e.value==`string`||typeof e.value==`boolean`?e.value:void 0}]):[]}const xn={id:`form@1`,label:`Form`,description:`Browser-only form template rendered as a heading and table of field metadata.`,inputSchema:{type:`object`,properties:{title:{type:`string`},fields:{type:`array`,items:{type:`object`,required:[`name`,`label`],properties:{name:{type:`string`},label:{type:`string`},type:{type:`string`},required:{type:`boolean`},placeholder:{type:`string`},default:{type:`string`},options:{type:`array`,items:{anyOf:[{type:`string`},{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:`string`}},additionalProperties:!1}]}},value:{type:[`string`,`boolean`]}},additionalProperties:!1}}},required:[`fields`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t={title:G(e)&&typeof e.title==`string`?e.title:`Form`,fields:G(e)?bn(e.fields):[]};return[{type:`heading`,value:t.title},{type:`table`,value:{headers:[`Label`,`Name`,`Type`,`Required`,`Default/Placeholder`],rows:t.fields.map(e=>[e.label||e.name,e.name,e.type||`text`,e.required?`Yes`:`No`,e.placeholder||e.default||``])}}]},hydration:[`form`],supportedTransports:[`browser`]},Sn=[`mcp-app`,`browser`];function K(e){return typeof e==`object`&&!!e}function Cn(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>!K(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label}]);return t.length>0?t:void 0}function wn(e){return Array.isArray(e)?e.flatMap(e=>!K(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label,category:typeof e.category==`string`?e.category:void 0,tags:Array.isArray(e.tags)?e.tags.filter(e=>typeof e==`string`):void 0}]):[]}function Tn(e){return K(e)?{categories:Cn(e.categories),items:wn(e.items)}:{items:[]}}function En(e){return{title:e.label,body:e.id,description:e.tags&&e.tags.length>0?e.tags.join(`, `):void 0}}function Dn(e,t){return t.length===0?[]:[{type:`heading`,value:e},{type:`cards`,value:t.map(En)}]}const On={id:`picker@1`,label:`Picker`,description:`Grouped item picker rendered as cards with picker hydration metadata.`,inputSchema:{type:`object`,properties:{categories:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`}},additionalProperties:!1}},items:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`},category:{type:`string`},tags:{type:`array`,items:{type:`string`}}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=Tn(e),n=[];if(t.categories&&t.categories.length>0){let e=new Set(t.categories.map(e=>e.id)),r=[];for(let e of t.categories){let n=Dn(e.label,t.items.filter(t=>t.category===e.id));n.length>0&&r.push(n)}let i=Dn(`Other`,t.items.filter(t=>!t.category||!e.has(t.category)));return i.length>0&&r.push(i),n.push(...r.flatMap((e,t)=>t>0?[{type:`separator`},...e]:e)),n}return t.items.length>0&&n.push({type:`cards`,value:t.items.map(En)}),n},hydration:[`picker`],supportedTransports:Sn},kn=[`mcp-app`,`browser`,`export`];function q(e){return typeof e==`object`&&!!e}function An(e){return q(e)&&typeof e.type==`string`}function jn(e){return Array.isArray(e)&&e.every(An)}function Mn(e){return q(e)&&typeof e.label==`string`&&(typeof e.value==`string`||typeof e.value==`number`)}function Nn(e){return Array.isArray(e)?e.flatMap(e=>{if(!q(e)||typeof e.heading!=`string`)return[];let t=typeof e.content==`string`||jn(e.content)?e.content:``;return[{heading:e.heading,content:t}]}):[]}function Pn(e){return Array.isArray(e)?e.flatMap(e=>q(e)?[{title:typeof e.title==`string`?e.title:void 0,value:e.value,headers:Array.isArray(e.headers)?e.headers.filter(e=>typeof e==`string`):void 0,rows:Array.isArray(e.rows)?e.rows.filter(e=>Array.isArray(e)):void 0}]:[]):[]}function Fn(e){let t=[{type:`heading`,value:e.heading}];return typeof e.content==`string`?(t.push({type:`paragraph`,value:e.content}),t):(t.push(...e.content),t)}function In(e){let t={type:`table`};return e.title&&(t.title=e.title),e.value!==void 0&&(t.value=e.value),e.headers&&(t.headers=e.headers),e.rows&&(t.rows=e.rows),t}const Ln={id:`report@1`,label:`Report`,description:`Static report with title, optional metrics, narrative sections, and tables.`,inputSchema:{type:`object`,properties:{title:{type:`string`},metrics:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:[`string`,`number`]},status:{type:`string`}},additionalProperties:!1}},sections:{type:`array`,items:{type:`object`,required:[`heading`,`content`],properties:{heading:{type:`string`},content:{oneOf:[{type:`string`},{type:`array`,items:{type:`object`}}]}},additionalProperties:!1}},tables:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},value:{},headers:{type:`array`,items:{type:`string`}},rows:{type:`array`,items:{type:`array`,items:{}}}},additionalProperties:!1}}},required:[`title`,`sections`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t={title:q(e)&&typeof e.title==`string`?e.title:`Report`,metrics:q(e)&&Array.isArray(e.metrics)?e.metrics.filter(Mn):void 0,sections:q(e)?Nn(e.sections):[],tables:q(e)?Pn(e.tables):void 0},n=[{type:`heading`,value:t.title}];t.metrics&&t.metrics.length>0&&n.push({type:`metrics`,value:t.metrics});for(let e of t.sections)n.push(...Fn(e));for(let e of t.tables??[])n.push(In(e));return n},hydration:[],supportedTransports:kn},Rn=[`mcp-app`,`browser`,`export`];function J(e){return typeof e==`object`&&!!e}function zn(e){return Array.isArray(e)?e.flatMap(e=>{if(!J(e)||typeof e.category!=`string`||!Array.isArray(e.items))return[];let t=e.items.flatMap(e=>!J(e)||typeof e.label!=`string`||typeof e.status!=`string`?[]:[{label:e.label,status:e.status,badge:typeof e.badge==`string`?e.badge:void 0}]);return[{category:e.category,items:t}]}):[]}function Bn(e){return e.map(e=>({title:e.label,status:e.status,badge:e.badge}))}const Vn={id:`status-board@1`,label:`Status Board`,description:`Static status board grouped into category headings and card collections.`,inputSchema:{type:`object`,properties:{categories:{type:`array`,items:{type:`object`,required:[`category`,`items`],properties:{category:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`label`,`status`],properties:{label:{type:`string`},status:{type:`string`},badge:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`categories`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=J(e)?zn(e.categories):[],n=[];for(let e of t)n.push({type:`heading`,value:e.category}),n.push({type:`cards`,value:Bn(e.items)});return n},hydration:[],supportedTransports:Rn},Hn=[`mcp-app`,`browser`,`export`];function Un(e){return typeof e==`object`&&!!e}function Wn(e){return Array.isArray(e)?e.flatMap(e=>!Un(e)||typeof e.title!=`string`?[]:[{title:e.title,description:typeof e.description==`string`?e.description:void 0,timestamp:typeof e.timestamp==`string`?e.timestamp:void 0,status:typeof e.status==`string`?e.status:void 0}]):[]}function Gn(e){return Array.isArray(e)?{entries:Wn(e)}:Un(e)?{entries:Wn(e.entries??e.events??e.items),title:typeof e.title==`string`?e.title:void 0}:{entries:[]}}const Y={type:`array`,items:{type:`object`,required:[`title`],properties:{title:{type:`string`},description:{type:`string`},timestamp:{type:`string`},status:{type:`string`}},additionalProperties:!1}},Kn={id:`timeline@1`,label:`Timeline`,description:`Static timeline events rendered as a timeline block.`,inputSchema:{oneOf:[Y,{type:`object`,properties:{title:{type:`string`},entries:Y,events:Y,items:Y},anyOf:[{required:[`entries`]},{required:[`events`]},{required:[`items`]}],additionalProperties:!1}]},defaultLayout:{},blocksFromData:e=>{let{entries:t,title:n}=Gn(e),r=[];return n&&r.push({type:`heading`,value:n}),r.push({type:`timeline`,value:t}),r},hydration:[],supportedTransports:Hn},qn=[`mcp-app`,`browser`,`export`];function X(e){return typeof e==`object`&&!!e}function Jn(e){return X(e)&&typeof e.label==`string`}function Yn(e){return{name:e.label,children:Array.isArray(e.children)?e.children.filter(Jn).map(Yn):[]}}function Xn(e){if(!X(e))return{};let t=e.root;return Jn(t)?Yn(t):X(t)?t:e}const Zn={id:`tree@1`,label:`Tree`,description:`Static tree view data with optional tree hydration metadata.`,inputSchema:{oneOf:[{type:`object`,properties:{root:{type:`object`}},required:[`root`],additionalProperties:!0},{type:`object`,additionalProperties:!0}]},defaultLayout:{},blocksFromData:e=>[{type:`tree`,value:Xn(e)}],hydration:[`tree`],supportedTransports:qn},Z=new qt;Z.register(Xt),Z.register(un),Z.register(gn),Z.register(On),Z.register(Ln),Z.register(Kn),Z.register(Zn),Z.register(nn),Z.register(W),Z.register(xn),Z.register(Vn);let Q=0;function Qn(){return Q=(Q+1)%(2**53-1),`${Date.now().toString(16).padStart(12,`0`).slice(-12)}${Q.toString(16).padStart(4,`0`).slice(-4)}${Array.from({length:8},()=>Math.floor(Math.random()*256).toString(16).padStart(2,`0`)).join(``)}`}function $n(e){return{id:e,version:1,entry:`@aikit/blocks-interactive/dist/islands/${e}.js`,selector:`[data-island="${e}"]`,needsData:!0}}function er(e,t){let n=new TextEncoder;return n.encode(e).byteLength+t.reduce((e,t)=>e+n.encode(t).byteLength,0)}function tr(e,t){let n=[],r=t.registry??Z,i={colorScheme:e.colorScheme??t.colorScheme??`auto`,transport:t.transport,lang:e.lang,dir:e.dir},a=[...e.blocks??[]],o=[...a],s=[],c=[...e.actions??[]];if(e.template){let t=r.get(e.template);if(t)try{o=t.blocksFromData(e.data,i),t.actionsFromData&&(c=[...c,...t.actionsFromData(e.data)]),s=t.hydration.map(e=>$n(e))}catch(t){let r=t instanceof Error?t.message:String(t);n.push({level:`error`,message:`Template ${e.template} failed: ${r}`}),o=a.length===0?W.blocksFromData({code:`TEMPLATE_RENDER_ERROR`,message:`Failed to render template ${e.template}`,details:r},i):[...a]}else n.push({level:`warn`,message:`Template not found: ${e.template}`})}let l=Gt(o,i),u=[L(o.map(e=>e.type))],d=t.nonce??Qn(),f=e.metadata?.surfaceId??`surface-${d}`,p=s.length>0?JSON.stringify({data:e.data,blocks:o}):void 0,m=t.blockVendorScripts?[...new Set(o.flatMap(e=>t.blockVendorScripts?.[e.type]??[]))]:void 0;return{surfaceId:f,nonce:d,html:l,css:u,vendorScripts:m&&m.length>0?m:void 0,islands:s,actions:c,payload:p,estimatedBytes:er(l,u),exportPolicy:s.length>0?`local-interactive`:`static-only`,diagnostics:n.length>0?n:void 0}}function nr(e){return e===`up`||e===`down`||e===`neutral`}function $(e){return typeof e==`object`&&!!e}function rr(e){return!$(e)||!Array.isArray(e.metrics)?{metrics:[]}:{metrics:e.metrics.flatMap(e=>{if(!$(e)||typeof e.label!=`string`||typeof e.value!=`string`&&typeof e.value!=`number`)return[];let t=$(e.trend)&&typeof e.trend.value==`string`&&nr(e.trend.direction)?{value:e.trend.value,direction:e.trend.direction}:void 0,n=Array.isArray(e.items)?e.items.flatMap(e=>!$(e)||typeof e.label!=`string`||typeof e.value!=`string`?[]:[{label:e.label,value:e.value}]):void 0;return[{id:typeof e.id==`string`?e.id:void 0,label:e.label,value:e.value,trend:t,status:e.status===`success`||e.status===`warning`||e.status===`error`||e.status===`info`?e.status:void 0,type:e.type===`progress`||e.type===`list`||e.type===`stat`?e.type:void 0,progress:typeof e.progress==`number`?dr(e.progress):void 0,items:n}]})}}function ir(e){let t=e.type===`progress`&&typeof e.progress==`number`?`${e.progress}%`:void 0;return{label:e.label,value:e.value,trend:e.trend?.value??t,status:e.status}}function ar(e){return e.type!==`progress`||typeof e.progress!=`number`?null:{label:e.label,value:dr(e.progress),max:100}}function or(e){return $(e)?{columns:Array.isArray(e.columns)?e.columns.flatMap(e=>!$(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label}]):[],cards:Array.isArray(e.cards)?e.cards.flatMap(e=>!$(e)||typeof e.id!=`string`||typeof e.title!=`string`||typeof e.column!=`string`?[]:[{id:e.id,title:e.title,description:typeof e.description==`string`?e.description:void 0,column:e.column,tags:Array.isArray(e.tags)?e.tags.filter(e=>typeof e==`string`):void 0,priority:e.priority===`high`||e.priority===`medium`||e.priority===`low`?e.priority:void 0}]):[]}:{columns:[],cards:[]}}function sr(e){return{title:e.title,description:e.description,badge:e.priority,body:e.tags?.join(`, `),status:e.priority}}function cr(e){return!$(e)||!Array.isArray(e.items)?[]:e.items.flatMap(e=>!$(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label}])}function lr(e){return $(e)?{name:typeof e.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=>lr(e)):[]}:{name:``,total:0,children:[]}}function ur(e){return{name:e.self==null?`${e.name} (${e.total})`:`${e.name} (${e.total} total / ${e.self} self)`,children:(e.children??[]).map(ur)}}function dr(e){return Math.max(0,Math.min(100,e))}function fr(e){let t=rr(e),n=[];t.metrics.length>0&&n.push({type:`metrics`,value:t.metrics.map(ir)});let r=t.metrics.map(ar).filter(e=>e!==null);r.length>0&&n.push({type:`progress`,value:r});for(let e of t.metrics)e.type===`list`&&e.items&&e.items.length>0&&(n.push({type:`heading`,value:e.label}),n.push({type:`table`,value:e.items}));return n}function pr(e){let t=or(e),n=[];return t.columns.forEach((e,r)=>{r>0&&n.push({type:`separator`,value:``});let i=t.cards.filter(t=>t.column===e.id);n.push({type:`heading`,value:e.label}),n.push({type:`cards`,value:i.map(sr)})}),n}function mr(e){let t=cr(e);return t.length===0?[]:[{type:`cards`,value:t.map((e,t)=>({title:e.label,body:e.id,badge:`#${t+1}`}))}]}function hr(e){return!$(e)||!$(e.profile)?[]:[{type:`tree`,value:ur(lr(e.profile))}]}const gr={id:`dashboard@1`,label:`Dashboard`,description:`Metric cards grid with optional charts.`,inputSchema:{type:`object`,properties:{metrics:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{id:{type:`string`},label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:`object`,properties:{value:{type:`string`},direction:{enum:[`up`,`down`,`neutral`]}},required:[`value`,`direction`],additionalProperties:!1},status:{enum:[`success`,`warning`,`error`,`info`]},type:{enum:[`stat`,`progress`,`list`]},progress:{type:`number`},items:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`metrics`],additionalProperties:!1},defaultLayout:{maxWidth:`1200px`},blocksFromData:e=>fr(e),hydration:[],supportedTransports:[`mcp-app`,`browser`]},_r={id:`kanban@1`,label:`Kanban`,description:`Drag-and-drop task board grouped by columns.`,inputSchema:{type:`object`,properties:{columns:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`},color:{type:`string`}},additionalProperties:!1}},cards:{type:`array`,items:{type:`object`,required:[`id`,`title`,`column`],properties:{id:{type:`string`},title:{type:`string`},description:{type:`string`},column:{type:`string`},tags:{type:`array`,items:{type:`string`}},priority:{enum:[`high`,`medium`,`low`]}},additionalProperties:!1}}},required:[`columns`,`cards`],additionalProperties:!1},defaultLayout:{maxWidth:`1400px`},blocksFromData:e=>pr(e),hydration:[],supportedTransports:[`browser`]},vr={id:`list-sort@1`,label:`Sortable List`,description:`Reorderable list of items with browser drag-and-drop interactions.`,inputSchema:{type:`object`,properties:{items:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{maxWidth:`720px`},blocksFromData:e=>mr(e),hydration:[],supportedTransports:[`browser`]},yr={id:`flame-graph@1`,label:`Flame Graph`,description:`Hierarchical performance profile with interactive zoom state.`,inputSchema:{type:`object`,properties:{profile:{type:`object`}},required:[`profile`],additionalProperties:!1},defaultLayout:{maxWidth:`1200px`},blocksFromData:e=>hr(e),hydration:[`flame-graph`],supportedTransports:[`browser`]};function br(e){return e.replace(/</g,`\\u003c`).replace(/>/g,`\\u003e`).replace(/&/g,`\\u0026`).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}function xr(e,t){let n=[`
1744
+ `);return[{type:`heading`,value:e.path},{type:`paragraph`,value:`${e.status} | +${e.additions} / -${e.deletions}`},{type:`code`,language:`diff`,value:t}]}const un={id:`diff-view@1`,label:`Diff View`,description:`Static diff summary rendered as per-file diff code blocks.`,inputSchema:{type:`object`,properties:{files:{type:`array`,items:{type:`object`,required:[`path`,`status`,`additions`,`deletions`,`hunks`],properties:{path:{type:`string`},status:{type:`string`},additions:{type:`number`},deletions:{type:`number`},hunks:{type:`array`,items:{type:`object`,required:[`header`,`changes`],properties:{header:{type:`string`},changes:{type:`array`,items:{type:`object`,required:[`type`,`content`],properties:{type:{type:`string`},content:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`files`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>sn(e).flatMap(ln),hydration:[],supportedTransports:rn},dn=[`mcp-app`,`browser`,`export`];function U(e){return typeof e==`object`&&!!e}function fn(e){return U(e)&&typeof e.type==`string`}function pn(e){return Array.isArray(e)&&e.every(fn)}function mn(e){if(!U(e))return{sections:[]};let t=Array.isArray(e.sections)?e.sections.flatMap(e=>{if(!U(e)||typeof e.heading!=`string`)return[];let t=typeof e.content==`string`||pn(e.content)?e.content:``;return[{heading:e.heading,content:t}]}):[];return{title:typeof e.title==`string`?e.title:void 0,sections:t}}function hn(e){let t=[{type:`heading`,value:e.heading}];return typeof e.content==`string`?(t.push({type:`paragraph`,value:e.content}),t):(t.push(...e.content),t)}const gn={id:`document@1`,label:`Document`,description:`Structured document with optional title and section content blocks.`,inputSchema:{type:`object`,properties:{title:{type:`string`},sections:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`heading`,`content`],properties:{heading:{type:`string`},content:{oneOf:[{type:`string`},{type:`array`,items:{type:`object`}}]}}}}},required:[`sections`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=mn(e),n=[];t.title&&n.push({type:`heading`,value:t.title});for(let e of t.sections)n.push(...hn(e));return n},hydration:[],supportedTransports:dn},_n=[`mcp-app`,`browser`,`export`];function vn(e){return typeof e==`object`&&!!e}function yn(e){return vn(e)?{code:typeof e.code==`string`?e.code:`ERROR`,message:typeof e.message==`string`?e.message:`Unknown error`,details:typeof e.details==`string`?e.details:void 0,stack:typeof e.stack==`string`?e.stack:void 0}:{code:`ERROR`,message:`Unknown error`}}const W={id:`error@1`,label:`Error`,description:`Static error view with message and optional stack trace.`,inputSchema:{type:`object`,properties:{code:{type:`string`},message:{type:`string`},details:{type:`string`},stack:{type:`string`}},required:[`code`,`message`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=yn(e),n=[{type:`heading`,value:`Error`},{type:`code`,title:t.code,language:`text`,value:t.details?`${t.message}\n\n${t.details}`:t.message}];return t.stack&&n.push({type:`code`,title:`Stack Trace`,language:`text`,value:t.stack}),n},hydration:[],supportedTransports:_n};function G(e){return typeof e==`object`&&!!e}function bn(e){return Array.isArray(e)?e.flatMap(e=>!G(e)||typeof e.name!=`string`||typeof e.label!=`string`?[]:[{name:e.name,label:e.label,type:typeof e.type==`string`?e.type:void 0,required:typeof e.required==`boolean`?e.required:void 0,placeholder:typeof e.placeholder==`string`?e.placeholder:void 0,default:typeof e.default==`string`?e.default:void 0,options:Array.isArray(e.options)?e.options.filter(e=>typeof e==`string`||G(e)&&typeof e.label==`string`&&typeof e.value==`string`):void 0,value:typeof e.value==`string`||typeof e.value==`boolean`?e.value:void 0}]):[]}const xn={id:`form@1`,label:`Form`,description:`Browser-only form template rendered as a heading and table of field metadata.`,inputSchema:{type:`object`,properties:{title:{type:`string`},fields:{type:`array`,items:{type:`object`,required:[`name`,`label`],properties:{name:{type:`string`},label:{type:`string`},type:{type:`string`},required:{type:`boolean`},placeholder:{type:`string`},default:{type:`string`},options:{type:`array`,items:{anyOf:[{type:`string`},{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:`string`}},additionalProperties:!1}]}},value:{type:[`string`,`boolean`]}},additionalProperties:!1}}},required:[`fields`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t={title:G(e)&&typeof e.title==`string`?e.title:`Form`,fields:G(e)?bn(e.fields):[]};return[{type:`heading`,value:t.title},{type:`table`,value:{headers:[`Label`,`Name`,`Type`,`Required`,`Default/Placeholder`],rows:t.fields.map(e=>[e.label||e.name,e.name,e.type||`text`,e.required?`Yes`:`No`,e.placeholder||e.default||``])}}]},hydration:[`form`],supportedTransports:[`browser`]},Sn=[`mcp-app`,`browser`];function K(e){return typeof e==`object`&&!!e}function Cn(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>!K(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label}]);return t.length>0?t:void 0}function wn(e){return Array.isArray(e)?e.flatMap(e=>!K(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label,category:typeof e.category==`string`?e.category:void 0,tags:Array.isArray(e.tags)?e.tags.filter(e=>typeof e==`string`):void 0}]):[]}function Tn(e){return K(e)?{categories:Cn(e.categories),items:wn(e.items)}:{items:[]}}function En(e){return{title:e.label,body:e.id,description:e.tags&&e.tags.length>0?e.tags.join(`, `):void 0}}function Dn(e,t){return t.length===0?[]:[{type:`heading`,value:e},{type:`cards`,value:t.map(En)}]}const On={id:`picker@1`,label:`Picker`,description:`Grouped item picker rendered as cards with picker hydration metadata.`,inputSchema:{type:`object`,properties:{categories:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`}},additionalProperties:!1}},items:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`},category:{type:`string`},tags:{type:`array`,items:{type:`string`}}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=Tn(e),n=[];if(t.categories&&t.categories.length>0){let e=new Set(t.categories.map(e=>e.id)),r=[];for(let e of t.categories){let n=Dn(e.label,t.items.filter(t=>t.category===e.id));n.length>0&&r.push(n)}let i=Dn(`Other`,t.items.filter(t=>!t.category||!e.has(t.category)));return i.length>0&&r.push(i),n.push(...r.flatMap((e,t)=>t>0?[{type:`separator`},...e]:e)),n}return t.items.length>0&&n.push({type:`cards`,value:t.items.map(En)}),n},hydration:[`picker`],supportedTransports:Sn},kn=[`mcp-app`,`browser`,`export`];function q(e){return typeof e==`object`&&!!e}function An(e){return q(e)&&typeof e.type==`string`}function jn(e){return Array.isArray(e)&&e.every(An)}function Mn(e){return q(e)&&typeof e.label==`string`&&(typeof e.value==`string`||typeof e.value==`number`)}function Nn(e){return Array.isArray(e)?e.flatMap(e=>{if(!q(e)||typeof e.heading!=`string`)return[];let t=typeof e.content==`string`||jn(e.content)?e.content:``;return[{heading:e.heading,content:t}]}):[]}function Pn(e){return Array.isArray(e)?e.flatMap(e=>q(e)?[{title:typeof e.title==`string`?e.title:void 0,value:e.value,headers:Array.isArray(e.headers)?e.headers.filter(e=>typeof e==`string`):void 0,rows:Array.isArray(e.rows)?e.rows.filter(e=>Array.isArray(e)):void 0}]:[]):[]}function Fn(e){let t=[{type:`heading`,value:e.heading}];return typeof e.content==`string`?(t.push({type:`paragraph`,value:e.content}),t):(t.push(...e.content),t)}function In(e){let t={type:`table`};return e.title&&(t.title=e.title),e.value!==void 0&&(t.value=e.value),e.headers&&(t.headers=e.headers),e.rows&&(t.rows=e.rows),t}const Ln={id:`report@1`,label:`Report`,description:`Static report with title, optional metrics, narrative sections, and tables.`,inputSchema:{type:`object`,properties:{title:{type:`string`},metrics:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:[`string`,`number`]},status:{type:`string`}},additionalProperties:!1}},sections:{type:`array`,items:{type:`object`,required:[`heading`,`content`],properties:{heading:{type:`string`},content:{oneOf:[{type:`string`},{type:`array`,items:{type:`object`}}]}},additionalProperties:!1}},tables:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},value:{},headers:{type:`array`,items:{type:`string`}},rows:{type:`array`,items:{type:`array`,items:{}}}},additionalProperties:!1}}},required:[`title`,`sections`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t={title:q(e)&&typeof e.title==`string`?e.title:`Report`,metrics:q(e)&&Array.isArray(e.metrics)?e.metrics.filter(Mn):void 0,sections:q(e)?Nn(e.sections):[],tables:q(e)?Pn(e.tables):void 0},n=[{type:`heading`,value:t.title}];t.metrics&&t.metrics.length>0&&n.push({type:`metrics`,value:t.metrics});for(let e of t.sections)n.push(...Fn(e));for(let e of t.tables??[])n.push(In(e));return n},hydration:[],supportedTransports:kn},Rn=[`mcp-app`,`browser`,`export`];function J(e){return typeof e==`object`&&!!e}function zn(e){return Array.isArray(e)?e.flatMap(e=>{if(!J(e)||typeof e.category!=`string`||!Array.isArray(e.items))return[];let t=e.items.flatMap(e=>!J(e)||typeof e.label!=`string`||typeof e.status!=`string`?[]:[{label:e.label,status:e.status,badge:typeof e.badge==`string`?e.badge:void 0}]);return[{category:e.category,items:t}]}):[]}function Bn(e){return e.map(e=>({title:e.label,status:e.status,badge:e.badge}))}const Vn={id:`status-board@1`,label:`Status Board`,description:`Static status board grouped into category headings and card collections.`,inputSchema:{type:`object`,properties:{categories:{type:`array`,items:{type:`object`,required:[`category`,`items`],properties:{category:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`label`,`status`],properties:{label:{type:`string`},status:{type:`string`},badge:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`categories`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=J(e)?zn(e.categories):[],n=[];for(let e of t)n.push({type:`heading`,value:e.category}),n.push({type:`cards`,value:Bn(e.items)});return n},hydration:[],supportedTransports:Rn},Hn=[`mcp-app`,`browser`,`export`];function Un(e){return typeof e==`object`&&!!e}function Wn(e){return Array.isArray(e)?e.flatMap(e=>!Un(e)||typeof e.title!=`string`?[]:[{title:e.title,description:typeof e.description==`string`?e.description:void 0,timestamp:typeof e.timestamp==`string`?e.timestamp:void 0,status:typeof e.status==`string`?e.status:void 0}]):[]}function Gn(e){return Array.isArray(e)?{entries:Wn(e)}:Un(e)?{entries:Wn(e.entries??e.events??e.items),title:typeof e.title==`string`?e.title:void 0}:{entries:[]}}const Y={type:`array`,items:{type:`object`,required:[`title`],properties:{title:{type:`string`},description:{type:`string`},timestamp:{type:`string`},status:{type:`string`}},additionalProperties:!1}},Kn={id:`timeline@1`,label:`Timeline`,description:`Static timeline events rendered as a timeline block.`,inputSchema:{oneOf:[Y,{type:`object`,properties:{title:{type:`string`},entries:Y,events:Y,items:Y},anyOf:[{required:[`entries`]},{required:[`events`]},{required:[`items`]}],additionalProperties:!1}]},defaultLayout:{},blocksFromData:e=>{let{entries:t,title:n}=Gn(e),r=[];return n&&r.push({type:`heading`,value:n}),r.push({type:`timeline`,value:t}),r},hydration:[],supportedTransports:Hn},qn=[`mcp-app`,`browser`,`export`];function X(e){return typeof e==`object`&&!!e}function Jn(e){return X(e)&&typeof e.label==`string`}function Yn(e){return{name:e.label,children:Array.isArray(e.children)?e.children.filter(Jn).map(Yn):[]}}function Xn(e){if(!X(e))return{};let t=e.root;return Jn(t)?Yn(t):X(t)?t:e}const Zn={id:`tree@1`,label:`Tree`,description:`Static tree view data with optional tree hydration metadata.`,inputSchema:{oneOf:[{type:`object`,properties:{root:{type:`object`}},required:[`root`],additionalProperties:!0},{type:`object`,additionalProperties:!0}]},defaultLayout:{},blocksFromData:e=>[{type:`tree`,value:Xn(e)}],hydration:[`tree`],supportedTransports:qn},Z=new qt;Z.register(Xt),Z.register(un),Z.register(gn),Z.register(On),Z.register(Ln),Z.register(Kn),Z.register(Zn),Z.register(nn),Z.register(W),Z.register(xn),Z.register(Vn);let Q=0;function Qn(){return Q=(Q+1)%(2**53-1),`${Date.now().toString(16).padStart(12,`0`).slice(-12)}${Q.toString(16).padStart(4,`0`).slice(-4)}${Array.from({length:8},()=>Math.floor(Math.random()*256).toString(16).padStart(2,`0`)).join(``)}`}function $n(e){return{id:e,version:1,entry:`@aikit/blocks-interactive/dist/islands/${e}.mjs`,selector:`[data-island="${e}"]`,needsData:!0}}function er(e,t){let n=new TextEncoder;return n.encode(e).byteLength+t.reduce((e,t)=>e+n.encode(t).byteLength,0)}function tr(e,t){let n=[],r=t.registry??Z,i={colorScheme:e.colorScheme??t.colorScheme??`auto`,transport:t.transport,lang:e.lang,dir:e.dir},a=[...e.blocks??[]],o=[...a],s=[],c=[...e.actions??[]];if(e.template){let t=r.get(e.template);if(t)try{o=t.blocksFromData(e.data,i),t.actionsFromData&&(c=[...c,...t.actionsFromData(e.data)]),s=t.hydration.map(e=>$n(e))}catch(t){let r=t instanceof Error?t.message:String(t);n.push({level:`error`,message:`Template ${e.template} failed: ${r}`}),o=a.length===0?W.blocksFromData({code:`TEMPLATE_RENDER_ERROR`,message:`Failed to render template ${e.template}`,details:r},i):[...a]}else n.push({level:`warn`,message:`Template not found: ${e.template}`})}let l=Gt(o,i),u=[L(o.map(e=>e.type))],d=t.nonce??Qn(),f=e.metadata?.surfaceId??`surface-${d}`,p=s.length>0?JSON.stringify({data:e.data,blocks:o}):void 0,m=t.blockVendorScripts?[...new Set(o.flatMap(e=>t.blockVendorScripts?.[e.type]??[]))]:void 0;return{surfaceId:f,nonce:d,html:l,css:u,vendorScripts:m&&m.length>0?m:void 0,islands:s,actions:c,payload:p,estimatedBytes:er(l,u),exportPolicy:s.length>0?`local-interactive`:`static-only`,diagnostics:n.length>0?n:void 0}}function nr(e){return e===`up`||e===`down`||e===`neutral`}function $(e){return typeof e==`object`&&!!e}function rr(e){return!$(e)||!Array.isArray(e.metrics)?{metrics:[]}:{metrics:e.metrics.flatMap(e=>{if(!$(e)||typeof e.label!=`string`||typeof e.value!=`string`&&typeof e.value!=`number`)return[];let t=$(e.trend)&&typeof e.trend.value==`string`&&nr(e.trend.direction)?{value:e.trend.value,direction:e.trend.direction}:void 0,n=Array.isArray(e.items)?e.items.flatMap(e=>!$(e)||typeof e.label!=`string`||typeof e.value!=`string`?[]:[{label:e.label,value:e.value}]):void 0;return[{id:typeof e.id==`string`?e.id:void 0,label:e.label,value:e.value,trend:t,status:e.status===`success`||e.status===`warning`||e.status===`error`||e.status===`info`?e.status:void 0,type:e.type===`progress`||e.type===`list`||e.type===`stat`?e.type:void 0,progress:typeof e.progress==`number`?dr(e.progress):void 0,items:n}]})}}function ir(e){let t=e.type===`progress`&&typeof e.progress==`number`?`${e.progress}%`:void 0;return{label:e.label,value:e.value,trend:e.trend?.value??t,status:e.status}}function ar(e){return e.type!==`progress`||typeof e.progress!=`number`?null:{label:e.label,value:dr(e.progress),max:100}}function or(e){return $(e)?{columns:Array.isArray(e.columns)?e.columns.flatMap(e=>!$(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label}]):[],cards:Array.isArray(e.cards)?e.cards.flatMap(e=>!$(e)||typeof e.id!=`string`||typeof e.title!=`string`||typeof e.column!=`string`?[]:[{id:e.id,title:e.title,description:typeof e.description==`string`?e.description:void 0,column:e.column,tags:Array.isArray(e.tags)?e.tags.filter(e=>typeof e==`string`):void 0,priority:e.priority===`high`||e.priority===`medium`||e.priority===`low`?e.priority:void 0}]):[]}:{columns:[],cards:[]}}function sr(e){return{title:e.title,description:e.description,badge:e.priority,body:e.tags?.join(`, `),status:e.priority}}function cr(e){return!$(e)||!Array.isArray(e.items)?[]:e.items.flatMap(e=>!$(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label}])}function lr(e){return $(e)?{name:typeof e.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=>lr(e)):[]}:{name:``,total:0,children:[]}}function ur(e){return{name:e.self==null?`${e.name} (${e.total})`:`${e.name} (${e.total} total / ${e.self} self)`,children:(e.children??[]).map(ur)}}function dr(e){return Math.max(0,Math.min(100,e))}function fr(e){let t=rr(e),n=[];t.metrics.length>0&&n.push({type:`metrics`,value:t.metrics.map(ir)});let r=t.metrics.map(ar).filter(e=>e!==null);r.length>0&&n.push({type:`progress`,value:r});for(let e of t.metrics)e.type===`list`&&e.items&&e.items.length>0&&(n.push({type:`heading`,value:e.label}),n.push({type:`table`,value:e.items}));return n}function pr(e){let t=or(e),n=[];return t.columns.forEach((e,r)=>{r>0&&n.push({type:`separator`,value:``});let i=t.cards.filter(t=>t.column===e.id);n.push({type:`heading`,value:e.label}),n.push({type:`cards`,value:i.map(sr)})}),n}function mr(e){let t=cr(e);return t.length===0?[]:[{type:`cards`,value:t.map((e,t)=>({title:e.label,body:e.id,badge:`#${t+1}`}))}]}function hr(e){return!$(e)||!$(e.profile)?[]:[{type:`tree`,value:ur(lr(e.profile))}]}const gr={id:`dashboard@1`,label:`Dashboard`,description:`Metric cards grid with optional charts.`,inputSchema:{type:`object`,properties:{metrics:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{id:{type:`string`},label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:`object`,properties:{value:{type:`string`},direction:{enum:[`up`,`down`,`neutral`]}},required:[`value`,`direction`],additionalProperties:!1},status:{enum:[`success`,`warning`,`error`,`info`]},type:{enum:[`stat`,`progress`,`list`]},progress:{type:`number`},items:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`metrics`],additionalProperties:!1},defaultLayout:{maxWidth:`1200px`},blocksFromData:e=>fr(e),hydration:[],supportedTransports:[`mcp-app`,`browser`]},_r={id:`kanban@1`,label:`Kanban`,description:`Drag-and-drop task board grouped by columns.`,inputSchema:{type:`object`,properties:{columns:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`},color:{type:`string`}},additionalProperties:!1}},cards:{type:`array`,items:{type:`object`,required:[`id`,`title`,`column`],properties:{id:{type:`string`},title:{type:`string`},description:{type:`string`},column:{type:`string`},tags:{type:`array`,items:{type:`string`}},priority:{enum:[`high`,`medium`,`low`]}},additionalProperties:!1}}},required:[`columns`,`cards`],additionalProperties:!1},defaultLayout:{maxWidth:`1400px`},blocksFromData:e=>pr(e),hydration:[],supportedTransports:[`browser`]},vr={id:`list-sort@1`,label:`Sortable List`,description:`Reorderable list of items with browser drag-and-drop interactions.`,inputSchema:{type:`object`,properties:{items:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{maxWidth:`720px`},blocksFromData:e=>mr(e),hydration:[],supportedTransports:[`browser`]},yr={id:`flame-graph@1`,label:`Flame Graph`,description:`Hierarchical performance profile with interactive zoom state.`,inputSchema:{type:`object`,properties:{profile:{type:`object`}},required:[`profile`],additionalProperties:!1},defaultLayout:{maxWidth:`1200px`},blocksFromData:e=>hr(e),hydration:[`flame-graph`],supportedTransports:[`browser`]};function br(e){return e.replace(/</g,`\\u003c`).replace(/>/g,`\\u003e`).replace(/&/g,`\\u0026`).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}function xr(e,t){let n=[`
1745
1745
  * {
1746
1746
  box-sizing: border-box;
1747
1747
  }
@@ -1823,7 +1823,7 @@ ${Et}
1823
1823
  `;function Fn(e){let t=[Pn],n=new Set;for(let r of e)!n.has(r)&&Nn[r]&&(n.add(r),t.push(Nn[r]));return t.join(`
1824
1824
  `)}var In={actions:ne,cards:ie,chart:pe,checklist:Ke,code:Je,comparison:Ze,"component-detail":at,"data-table-schema":dt,"docs-browser":mt,"docs-hub":yt,finding:St,graph:Tt,heading:Dt,kv:At,"lifecycle-flow":Gt,list:qt,markdown:Qt,mermaid:en,metrics:rn,paragraph:on,progress:ln,prompt:fn,separator:mn,"status-board":_n,table:Sn,tags:Tn,text:Dn,timeline:kn,tree:Mn};function Ln(e,t){let n={...e,value:c(e.value)},r=In[n.type],a=r?r(n,t):zn(n);return n.title&&![`heading`,`finding`].includes(n.type)?`<section class="bk-section bk-section--${i(n.type)}"><h3 class="bk-section-title">${i(n.title)}</h3>${a}</section>`:a}function Rn(e,t){return e.map(e=>Ln(e,t)).join(`
1825
1825
  `)}function zn(e){if(e.value===void 0||e.value===null)return``;if(typeof e.value==`string`)return`<p class="bk-paragraph">${i(e.value)}</p>`;try{return`<pre class="bk-fallback">${i(JSON.stringify(e.value,null,2))}</pre>`}catch{return`<pre class="bk-fallback">${i(String(e.value))}</pre>`}}var Bn=class{templates=new Map;register(e){this.templates.set(e.id,e)}get(e){let t=this.templates.get(e);if(t)return t;let n=e.includes(`@`)?e:`${e}@`,r,i=-1;for(let[e,t]of this.templates){if(!e.startsWith(n))continue;let a=Number.parseInt(e.split(`@`)[1]??`0`,10);a>i&&(i=a,r=t)}return r}has(e){return this.get(e)!==void 0}list(){return[...this.templates.values()]}},Vn=[`mcp-app`,`browser`];function Hn(e){return typeof e==`object`&&!!e}function Un(e){return Array.isArray(e)?e.flatMap(e=>!Hn(e)||typeof e.label!=`string`?[]:[{label:e.label,checked:!!e.checked}]):[]}var Wn={id:`checklist@1`,label:`Checklist`,description:`Checklist with optional title and checklist hydration metadata.`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`label`,`checked`],properties:{label:{type:`string`},checked:{type:`boolean`}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=[],n=Hn(e)&&typeof e.title==`string`?e.title:void 0,r=Hn(e)?Un(e.items):[];return n&&t.push({type:`heading`,value:n}),t.push({type:`checklist`,value:r}),t},hydration:[`checklist`],supportedTransports:Vn},Gn=[`mcp-app`,`browser`,`export`];function Kn(e){return typeof e==`object`&&!!e}function qn(e){return Kn(e)&&typeof e.label==`string`&&(typeof e.value==`string`||typeof e.value==`number`)}function Jn(e){return Kn(e)&&typeof e.key==`string`&&typeof e.label==`string`}function Yn(e){return Array.isArray(e)?e.filter(Kn):[]}function Xn(e,t){if(Array.isArray(e)){let t=e.filter(Jn);if(t.length>0)return t}return Object.keys(t[0]??{}).map(e=>({key:e,label:e}))}var Zn={id:`data-table@1`,label:`Data Table`,description:`Static data table with optional metrics and sortable table hydration.`,inputSchema:{type:`object`,properties:{columns:{type:`array`,items:{type:`object`,required:[`key`,`label`],properties:{key:{type:`string`},label:{type:`string`}},additionalProperties:!1}},rows:{type:`array`,items:{type:`object`}},stats:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:[`string`,`number`]},status:{type:`string`}},additionalProperties:!1}}},required:[`rows`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=Kn(e)?Yn(e.rows):[],n=Kn(e)?Xn(e.columns,t):[],r=n.map(e=>e.label),i=t.map(e=>n.map(t=>e[t.key])),a=[];if(Kn(e)&&Array.isArray(e.stats)){let t=e.stats.filter(qn);t.length>0&&a.push({type:`metrics`,value:t})}return a.push({type:`table`,columns:n,headers:r,rows:i,value:{headers:r,rows:i}}),a},hydration:[`table`],supportedTransports:Gn},Qn=[`mcp-app`,`browser`,`export`];function $n(e){return typeof e==`object`&&!!e}function er(e){return Array.isArray(e)?e.flatMap(e=>!$n(e)||typeof e.type!=`string`||typeof e.content!=`string`?[]:[{type:e.type,content:e.content}]):[]}function tr(e){return Array.isArray(e)?e.flatMap(e=>!$n(e)||typeof e.header!=`string`?[]:[{header:e.header,changes:er(e.changes)}]):[]}function nr(e){return!$n(e)||!Array.isArray(e.files)?[]:e.files.flatMap(e=>!$n(e)||typeof e.path!=`string`||typeof e.status!=`string`?[]:[{path:e.path,status:e.status,additions:typeof e.additions==`number`?e.additions:0,deletions:typeof e.deletions==`number`?e.deletions:0,hunks:tr(e.hunks)}])}function rr(e){return e===`add`?`+`:e===`delete`?`-`:` `}function ir(e){let t=e.hunks.flatMap(e=>[e.header,...e.changes.map(e=>`${rr(e.type)}${e.content}`)]).join(`
1826
- `);return[{type:`heading`,value:e.path},{type:`paragraph`,value:`${e.status} | +${e.additions} / -${e.deletions}`},{type:`code`,language:`diff`,value:t}]}var ar={id:`diff-view@1`,label:`Diff View`,description:`Static diff summary rendered as per-file diff code blocks.`,inputSchema:{type:`object`,properties:{files:{type:`array`,items:{type:`object`,required:[`path`,`status`,`additions`,`deletions`,`hunks`],properties:{path:{type:`string`},status:{type:`string`},additions:{type:`number`},deletions:{type:`number`},hunks:{type:`array`,items:{type:`object`,required:[`header`,`changes`],properties:{header:{type:`string`},changes:{type:`array`,items:{type:`object`,required:[`type`,`content`],properties:{type:{type:`string`},content:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`files`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>nr(e).flatMap(ir),hydration:[],supportedTransports:Qn},or=[`mcp-app`,`browser`,`export`];function sr(e){return typeof e==`object`&&!!e}function cr(e){return sr(e)&&typeof e.type==`string`}function lr(e){return Array.isArray(e)&&e.every(cr)}function ur(e){if(!sr(e))return{sections:[]};let t=Array.isArray(e.sections)?e.sections.flatMap(e=>{if(!sr(e)||typeof e.heading!=`string`)return[];let t=typeof e.content==`string`||lr(e.content)?e.content:``;return[{heading:e.heading,content:t}]}):[];return{title:typeof e.title==`string`?e.title:void 0,sections:t}}function dr(e){let t=[{type:`heading`,value:e.heading}];return typeof e.content==`string`?(t.push({type:`paragraph`,value:e.content}),t):(t.push(...e.content),t)}var fr={id:`document@1`,label:`Document`,description:`Structured document with optional title and section content blocks.`,inputSchema:{type:`object`,properties:{title:{type:`string`},sections:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`heading`,`content`],properties:{heading:{type:`string`},content:{oneOf:[{type:`string`},{type:`array`,items:{type:`object`}}]}}}}},required:[`sections`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=ur(e),n=[];t.title&&n.push({type:`heading`,value:t.title});for(let e of t.sections)n.push(...dr(e));return n},hydration:[],supportedTransports:or},pr=[`mcp-app`,`browser`,`export`];function mr(e){return typeof e==`object`&&!!e}function hr(e){return mr(e)?{code:typeof e.code==`string`?e.code:`ERROR`,message:typeof e.message==`string`?e.message:`Unknown error`,details:typeof e.details==`string`?e.details:void 0,stack:typeof e.stack==`string`?e.stack:void 0}:{code:`ERROR`,message:`Unknown error`}}var gr={id:`error@1`,label:`Error`,description:`Static error view with message and optional stack trace.`,inputSchema:{type:`object`,properties:{code:{type:`string`},message:{type:`string`},details:{type:`string`},stack:{type:`string`}},required:[`code`,`message`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=hr(e),n=[{type:`heading`,value:`Error`},{type:`code`,title:t.code,language:`text`,value:t.details?`${t.message}\n\n${t.details}`:t.message}];return t.stack&&n.push({type:`code`,title:`Stack Trace`,language:`text`,value:t.stack}),n},hydration:[],supportedTransports:pr};function _r(e){return typeof e==`object`&&!!e}function vr(e){return Array.isArray(e)?e.flatMap(e=>!_r(e)||typeof e.name!=`string`||typeof e.label!=`string`?[]:[{name:e.name,label:e.label,type:typeof e.type==`string`?e.type:void 0,required:typeof e.required==`boolean`?e.required:void 0,placeholder:typeof e.placeholder==`string`?e.placeholder:void 0,default:typeof e.default==`string`?e.default:void 0,options:Array.isArray(e.options)?e.options.filter(e=>typeof e==`string`||_r(e)&&typeof e.label==`string`&&typeof e.value==`string`):void 0,value:typeof e.value==`string`||typeof e.value==`boolean`?e.value:void 0}]):[]}var yr={id:`form@1`,label:`Form`,description:`Browser-only form template rendered as a heading and table of field metadata.`,inputSchema:{type:`object`,properties:{title:{type:`string`},fields:{type:`array`,items:{type:`object`,required:[`name`,`label`],properties:{name:{type:`string`},label:{type:`string`},type:{type:`string`},required:{type:`boolean`},placeholder:{type:`string`},default:{type:`string`},options:{type:`array`,items:{anyOf:[{type:`string`},{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:`string`}},additionalProperties:!1}]}},value:{type:[`string`,`boolean`]}},additionalProperties:!1}}},required:[`fields`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t={title:_r(e)&&typeof e.title==`string`?e.title:`Form`,fields:_r(e)?vr(e.fields):[]};return[{type:`heading`,value:t.title},{type:`table`,value:{headers:[`Label`,`Name`,`Type`,`Required`,`Default/Placeholder`],rows:t.fields.map(e=>[e.label||e.name,e.name,e.type||`text`,e.required?`Yes`:`No`,e.placeholder||e.default||``])}}]},hydration:[`form`],supportedTransports:[`browser`]},br=[`mcp-app`,`browser`];function xr(e){return typeof e==`object`&&!!e}function Sr(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>!xr(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label}]);return t.length>0?t:void 0}function Cr(e){return Array.isArray(e)?e.flatMap(e=>!xr(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label,category:typeof e.category==`string`?e.category:void 0,tags:Array.isArray(e.tags)?e.tags.filter(e=>typeof e==`string`):void 0}]):[]}function wr(e){return xr(e)?{categories:Sr(e.categories),items:Cr(e.items)}:{items:[]}}function Tr(e){return{title:e.label,body:e.id,description:e.tags&&e.tags.length>0?e.tags.join(`, `):void 0}}function Er(e,t){return t.length===0?[]:[{type:`heading`,value:e},{type:`cards`,value:t.map(Tr)}]}var Dr={id:`picker@1`,label:`Picker`,description:`Grouped item picker rendered as cards with picker hydration metadata.`,inputSchema:{type:`object`,properties:{categories:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`}},additionalProperties:!1}},items:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`},category:{type:`string`},tags:{type:`array`,items:{type:`string`}}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=wr(e),n=[];if(t.categories&&t.categories.length>0){let e=new Set(t.categories.map(e=>e.id)),r=[];for(let e of t.categories){let n=Er(e.label,t.items.filter(t=>t.category===e.id));n.length>0&&r.push(n)}let i=Er(`Other`,t.items.filter(t=>!t.category||!e.has(t.category)));return i.length>0&&r.push(i),n.push(...r.flatMap((e,t)=>t>0?[{type:`separator`},...e]:e)),n}return t.items.length>0&&n.push({type:`cards`,value:t.items.map(Tr)}),n},hydration:[`picker`],supportedTransports:br},Or=[`mcp-app`,`browser`,`export`];function kr(e){return typeof e==`object`&&!!e}function Ar(e){return kr(e)&&typeof e.type==`string`}function jr(e){return Array.isArray(e)&&e.every(Ar)}function Mr(e){return kr(e)&&typeof e.label==`string`&&(typeof e.value==`string`||typeof e.value==`number`)}function Nr(e){return Array.isArray(e)?e.flatMap(e=>{if(!kr(e)||typeof e.heading!=`string`)return[];let t=typeof e.content==`string`||jr(e.content)?e.content:``;return[{heading:e.heading,content:t}]}):[]}function Pr(e){return Array.isArray(e)?e.flatMap(e=>kr(e)?[{title:typeof e.title==`string`?e.title:void 0,value:e.value,headers:Array.isArray(e.headers)?e.headers.filter(e=>typeof e==`string`):void 0,rows:Array.isArray(e.rows)?e.rows.filter(e=>Array.isArray(e)):void 0}]:[]):[]}function Fr(e){let t=[{type:`heading`,value:e.heading}];return typeof e.content==`string`?(t.push({type:`paragraph`,value:e.content}),t):(t.push(...e.content),t)}function Ir(e){let t={type:`table`};return e.title&&(t.title=e.title),e.value!==void 0&&(t.value=e.value),e.headers&&(t.headers=e.headers),e.rows&&(t.rows=e.rows),t}var Lr={id:`report@1`,label:`Report`,description:`Static report with title, optional metrics, narrative sections, and tables.`,inputSchema:{type:`object`,properties:{title:{type:`string`},metrics:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:[`string`,`number`]},status:{type:`string`}},additionalProperties:!1}},sections:{type:`array`,items:{type:`object`,required:[`heading`,`content`],properties:{heading:{type:`string`},content:{oneOf:[{type:`string`},{type:`array`,items:{type:`object`}}]}},additionalProperties:!1}},tables:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},value:{},headers:{type:`array`,items:{type:`string`}},rows:{type:`array`,items:{type:`array`,items:{}}}},additionalProperties:!1}}},required:[`title`,`sections`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t={title:kr(e)&&typeof e.title==`string`?e.title:`Report`,metrics:kr(e)&&Array.isArray(e.metrics)?e.metrics.filter(Mr):void 0,sections:kr(e)?Nr(e.sections):[],tables:kr(e)?Pr(e.tables):void 0},n=[{type:`heading`,value:t.title}];t.metrics&&t.metrics.length>0&&n.push({type:`metrics`,value:t.metrics});for(let e of t.sections)n.push(...Fr(e));for(let e of t.tables??[])n.push(Ir(e));return n},hydration:[],supportedTransports:Or},Rr=[`mcp-app`,`browser`,`export`];function zr(e){return typeof e==`object`&&!!e}function Br(e){return Array.isArray(e)?e.flatMap(e=>{if(!zr(e)||typeof e.category!=`string`||!Array.isArray(e.items))return[];let t=e.items.flatMap(e=>!zr(e)||typeof e.label!=`string`||typeof e.status!=`string`?[]:[{label:e.label,status:e.status,badge:typeof e.badge==`string`?e.badge:void 0}]);return[{category:e.category,items:t}]}):[]}function Vr(e){return e.map(e=>({title:e.label,status:e.status,badge:e.badge}))}var Hr={id:`status-board@1`,label:`Status Board`,description:`Static status board grouped into category headings and card collections.`,inputSchema:{type:`object`,properties:{categories:{type:`array`,items:{type:`object`,required:[`category`,`items`],properties:{category:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`label`,`status`],properties:{label:{type:`string`},status:{type:`string`},badge:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`categories`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=zr(e)?Br(e.categories):[],n=[];for(let e of t)n.push({type:`heading`,value:e.category}),n.push({type:`cards`,value:Vr(e.items)});return n},hydration:[],supportedTransports:Rr},Ur=[`mcp-app`,`browser`,`export`];function Wr(e){return typeof e==`object`&&!!e}function Gr(e){return Array.isArray(e)?e.flatMap(e=>!Wr(e)||typeof e.title!=`string`?[]:[{title:e.title,description:typeof e.description==`string`?e.description:void 0,timestamp:typeof e.timestamp==`string`?e.timestamp:void 0,status:typeof e.status==`string`?e.status:void 0}]):[]}function Kr(e){return Array.isArray(e)?{entries:Gr(e)}:Wr(e)?{entries:Gr(e.entries??e.events??e.items),title:typeof e.title==`string`?e.title:void 0}:{entries:[]}}var qr={type:`array`,items:{type:`object`,required:[`title`],properties:{title:{type:`string`},description:{type:`string`},timestamp:{type:`string`},status:{type:`string`}},additionalProperties:!1}},Jr={id:`timeline@1`,label:`Timeline`,description:`Static timeline events rendered as a timeline block.`,inputSchema:{oneOf:[qr,{type:`object`,properties:{title:{type:`string`},entries:qr,events:qr,items:qr},anyOf:[{required:[`entries`]},{required:[`events`]},{required:[`items`]}],additionalProperties:!1}]},defaultLayout:{},blocksFromData:e=>{let{entries:t,title:n}=Kr(e),r=[];return n&&r.push({type:`heading`,value:n}),r.push({type:`timeline`,value:t}),r},hydration:[],supportedTransports:Ur},Yr=[`mcp-app`,`browser`,`export`];function Xr(e){return typeof e==`object`&&!!e}function Zr(e){return Xr(e)&&typeof e.label==`string`}function Qr(e){return{name:e.label,children:Array.isArray(e.children)?e.children.filter(Zr).map(Qr):[]}}function $r(e){if(!Xr(e))return{};let t=e.root;return Zr(t)?Qr(t):Xr(t)?t:e}var ei={id:`tree@1`,label:`Tree`,description:`Static tree view data with optional tree hydration metadata.`,inputSchema:{oneOf:[{type:`object`,properties:{root:{type:`object`}},required:[`root`],additionalProperties:!0},{type:`object`,additionalProperties:!0}]},defaultLayout:{},blocksFromData:e=>[{type:`tree`,value:$r(e)}],hydration:[`tree`],supportedTransports:Yr},ti=new Bn;ti.register(Wn),ti.register(ar),ti.register(fr),ti.register(Dr),ti.register(Lr),ti.register(Jr),ti.register(ei),ti.register(Zn),ti.register(gr),ti.register(yr),ti.register(Hr);var ni=0;function ri(){return ni=(ni+1)%(2**53-1),`${Date.now().toString(16).padStart(12,`0`).slice(-12)}${ni.toString(16).padStart(4,`0`).slice(-4)}${Array.from({length:8},()=>Math.floor(Math.random()*256).toString(16).padStart(2,`0`)).join(``)}`}function ii(e){return{id:e,version:1,entry:`@aikit/blocks-interactive/dist/islands/${e}.js`,selector:`[data-island="${e}"]`,needsData:!0}}function ai(e,t){let n=new TextEncoder;return n.encode(e).byteLength+t.reduce((e,t)=>e+n.encode(t).byteLength,0)}function oi(e,t){let n=[],r=t.registry??ti,i={colorScheme:e.colorScheme??t.colorScheme??`auto`,transport:t.transport,lang:e.lang,dir:e.dir},a=[...e.blocks??[]],o=[...a],s=[],c=[...e.actions??[]];if(e.template){let t=r.get(e.template);if(t)try{o=t.blocksFromData(e.data,i),t.actionsFromData&&(c=[...c,...t.actionsFromData(e.data)]),s=t.hydration.map(e=>ii(e))}catch(t){let r=t instanceof Error?t.message:String(t);n.push({level:`error`,message:`Template ${e.template} failed: ${r}`}),o=a.length===0?gr.blocksFromData({code:`TEMPLATE_RENDER_ERROR`,message:`Failed to render template ${e.template}`,details:r},i):[...a]}else n.push({level:`warn`,message:`Template not found: ${e.template}`})}let l=Rn(o,i),u=[Fn(o.map(e=>e.type))],d=t.nonce??ri(),f=e.metadata?.surfaceId??`surface-${d}`,p=s.length>0?JSON.stringify({data:e.data,blocks:o}):void 0,ee=t.blockVendorScripts?[...new Set(o.flatMap(e=>t.blockVendorScripts?.[e.type]??[]))]:void 0;return{surfaceId:f,nonce:d,html:l,css:u,vendorScripts:ee&&ee.length>0?ee:void 0,islands:s,actions:c,payload:p,estimatedBytes:ai(l,u),exportPolicy:s.length>0?`local-interactive`:`static-only`,diagnostics:n.length>0?n:void 0}}function h(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}function g(e){return e&&Object.assign(fi,e),fi}var si,ci,li,ui,di,fi,pi=t((()=>{ci=Object.freeze({status:`aborted`}),li=Symbol(`zod_brand`),ui=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},di=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}},(si=globalThis).__zod_globalConfig??(si.__zod_globalConfig={}),fi=globalThis.__zod_globalConfig})),mi=n({BIGINT_FORMAT_RANGES:()=>va,Class:()=>ya,NUMBER_FORMAT_RANGES:()=>_a,aborted:()=>Xi,allowsEval:()=>pa,assert:()=>yi,assertEqual:()=>hi,assertIs:()=>_i,assertNever:()=>vi,assertNotEqual:()=>gi,assignProp:()=>Di,base64ToUint8Array:()=>aa,base64urlToUint8Array:()=>sa,cached:()=>Si,captureStackTrace:()=>fa,cleanEnum:()=>ia,cleanRegex:()=>wi,clone:()=>Bi,cloneDef:()=>ki,createTransparentProxy:()=>Vi,defineLazy:()=>v,esc:()=>Ni,escapeRegex:()=>zi,explicitlyAborted:()=>Zi,extend:()=>Gi,finalizeIssue:()=>ea,floatSafeRemainder:()=>Ti,getElementAtPath:()=>Ai,getEnumValues:()=>bi,getLengthableOrigin:()=>na,getParsedType:()=>ma,getSizableOrigin:()=>ta,hexToUint8Array:()=>la,isObject:()=>Fi,isPlainObject:()=>Ii,issue:()=>ra,joinValues:()=>_,jsonStringifyReplacer:()=>xi,merge:()=>qi,mergeDefs:()=>Oi,normalizeParams:()=>y,nullish:()=>Ci,numKeys:()=>Ri,objectClone:()=>Ei,omit:()=>Wi,optionalKeys:()=>Hi,parsedType:()=>x,partial:()=>Ji,pick:()=>Ui,prefixIssues:()=>Qi,primitiveTypes:()=>ga,promiseAllObject:()=>ji,propertyKeyTypes:()=>ha,randomString:()=>Mi,required:()=>Yi,safeExtend:()=>Ki,shallowClone:()=>Li,slugify:()=>Pi,stringifyPrimitive:()=>b,uint8ArrayToBase64:()=>oa,uint8ArrayToBase64url:()=>ca,uint8ArrayToHex:()=>ua,unwrapMessage:()=>$i});function hi(e){return e}function gi(e){return e}function _i(e){}function vi(e){throw Error(`Unexpected value in exhaustive check`)}function yi(e){}function bi(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function _(e,t=`|`){return e.map(e=>b(e)).join(t)}function xi(e,t){return typeof t==`bigint`?t.toString():t}function Si(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error(`cached value already set`)}}}function Ci(e){return e==null}function wi(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ti(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function v(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==da)return r===void 0&&(r=da,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ei(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Di(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oi(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function ki(e){return Oi(e._zod.def)}function Ai(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function ji(e){let t=Object.keys(e),n=t.map(t=>e[t]);return Promise.all(n).then(e=>{let n={};for(let r=0;r<t.length;r++)n[t[r]]=e[r];return n})}function Mi(e=10){let t=``;for(let n=0;n<e;n++)t+=`abcdefghijklmnopqrstuvwxyz`[Math.floor(Math.random()*26)];return t}function Ni(e){return JSON.stringify(e)}function Pi(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}function Fi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ii(e){if(Fi(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Fi(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Li(e){return Ii(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Ri(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function zi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Bi(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function y(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Vi(e){let t;return new Proxy({},{get(n,r,i){return t??=e(),Reflect.get(t,r,i)},set(n,r,i,a){return t??=e(),Reflect.set(t,r,i,a)},has(n,r){return t??=e(),Reflect.has(t,r)},deleteProperty(n,r){return t??=e(),Reflect.deleteProperty(t,r)},ownKeys(n){return t??=e(),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??=e(),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,i){return t??=e(),Reflect.defineProperty(t,r,i)}})}function b(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Hi(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}function Ui(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Bi(e,Oi(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Di(this,`shape`,e),e},checks:[]}))}function Wi(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Bi(e,Oi(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Di(this,`shape`,r),r},checks:[]}))}function Gi(e,t){if(!Ii(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Bi(e,Oi(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Di(this,`shape`,n),n}}))}function Ki(e,t){if(!Ii(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Bi(e,Oi(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Di(this,`shape`,n),n}}))}function qi(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Bi(e,Oi(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Di(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Ji(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Bi(t,Oi(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Di(this,`shape`,i),i},checks:[]}))}function Yi(e,t,n){return Bi(t,Oi(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Di(this,`shape`,i),i}}))}function Xi(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Zi(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Qi(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function $i(e){return typeof e==`string`?e:e?.message}function ea(e,t,n){let r=e.message?e.message:$i(e.inst?._zod.def?.error?.(e))??$i(t?.error?.(e))??$i(n.customError?.(e))??$i(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function ta(e){return e instanceof Set?`set`:e instanceof Map?`map`:e instanceof File?`file`:`unknown`}function na(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function x(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function ra(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function ia(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function aa(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function oa(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function sa(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return aa(t+`=`.repeat((4-t.length%4)%4))}function ca(e){return oa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function la(e){let t=e.replace(/^0x/,``);if(t.length%2!=0)throw Error(`Invalid hex string length`);let n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=Number.parseInt(t.slice(e,e+2),16);return n}function ua(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}var da,fa,pa,ma,ha,ga,_a,va,ya,S=t((()=>{pi(),da=Symbol(`evaluating`),fa=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{},pa=Si(()=>{if(fi.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}}),ma=e=>{let t=typeof e;switch(t){case`undefined`:return`undefined`;case`string`:return`string`;case`number`:return Number.isNaN(e)?`nan`:`number`;case`boolean`:return`boolean`;case`function`:return`function`;case`bigint`:return`bigint`;case`symbol`:return`symbol`;case`object`:return Array.isArray(e)?`array`:e===null?`null`:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?`promise`:typeof Map<`u`&&e instanceof Map?`map`:typeof Set<`u`&&e instanceof Set?`set`:typeof Date<`u`&&e instanceof Date?`date`:typeof File<`u`&&e instanceof File?`file`:`object`;default:throw Error(`Unknown data type: ${t}`)}},ha=new Set([`string`,`number`,`symbol`]),ga=new Set([`string`,`number`,`bigint`,`boolean`,`symbol`,`undefined`]),_a={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},va={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]},ya=class{constructor(...e){}}}));function ba(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function xa(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}function Sa(e,t=e=>e.message){let n={errors:[]},r=(e,i=[])=>{var a,o;for(let s of e.issues)if(s.code===`invalid_union`&&s.errors.length)s.errors.map(e=>r({issues:e},[...i,...s.path]));else if(s.code===`invalid_key`)r({issues:s.issues},[...i,...s.path]);else if(s.code===`invalid_element`)r({issues:s.issues},[...i,...s.path]);else{let e=[...i,...s.path];if(e.length===0){n.errors.push(t(s));continue}let r=n,c=0;for(;c<e.length;){let n=e[c],i=c===e.length-1;typeof n==`string`?(r.properties??={},(a=r.properties)[n]??(a[n]={errors:[]}),r=r.properties[n]):(r.items??=[],(o=r.items)[n]??(o[n]={errors:[]}),r=r.items[n]),i&&r.errors.push(t(s)),c++}}};return r(e),n}function Ca(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function wa(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${Ca(e.path)}`);return t.join(`
1826
+ `);return[{type:`heading`,value:e.path},{type:`paragraph`,value:`${e.status} | +${e.additions} / -${e.deletions}`},{type:`code`,language:`diff`,value:t}]}var ar={id:`diff-view@1`,label:`Diff View`,description:`Static diff summary rendered as per-file diff code blocks.`,inputSchema:{type:`object`,properties:{files:{type:`array`,items:{type:`object`,required:[`path`,`status`,`additions`,`deletions`,`hunks`],properties:{path:{type:`string`},status:{type:`string`},additions:{type:`number`},deletions:{type:`number`},hunks:{type:`array`,items:{type:`object`,required:[`header`,`changes`],properties:{header:{type:`string`},changes:{type:`array`,items:{type:`object`,required:[`type`,`content`],properties:{type:{type:`string`},content:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`files`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>nr(e).flatMap(ir),hydration:[],supportedTransports:Qn},or=[`mcp-app`,`browser`,`export`];function sr(e){return typeof e==`object`&&!!e}function cr(e){return sr(e)&&typeof e.type==`string`}function lr(e){return Array.isArray(e)&&e.every(cr)}function ur(e){if(!sr(e))return{sections:[]};let t=Array.isArray(e.sections)?e.sections.flatMap(e=>{if(!sr(e)||typeof e.heading!=`string`)return[];let t=typeof e.content==`string`||lr(e.content)?e.content:``;return[{heading:e.heading,content:t}]}):[];return{title:typeof e.title==`string`?e.title:void 0,sections:t}}function dr(e){let t=[{type:`heading`,value:e.heading}];return typeof e.content==`string`?(t.push({type:`paragraph`,value:e.content}),t):(t.push(...e.content),t)}var fr={id:`document@1`,label:`Document`,description:`Structured document with optional title and section content blocks.`,inputSchema:{type:`object`,properties:{title:{type:`string`},sections:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`heading`,`content`],properties:{heading:{type:`string`},content:{oneOf:[{type:`string`},{type:`array`,items:{type:`object`}}]}}}}},required:[`sections`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=ur(e),n=[];t.title&&n.push({type:`heading`,value:t.title});for(let e of t.sections)n.push(...dr(e));return n},hydration:[],supportedTransports:or},pr=[`mcp-app`,`browser`,`export`];function mr(e){return typeof e==`object`&&!!e}function hr(e){return mr(e)?{code:typeof e.code==`string`?e.code:`ERROR`,message:typeof e.message==`string`?e.message:`Unknown error`,details:typeof e.details==`string`?e.details:void 0,stack:typeof e.stack==`string`?e.stack:void 0}:{code:`ERROR`,message:`Unknown error`}}var gr={id:`error@1`,label:`Error`,description:`Static error view with message and optional stack trace.`,inputSchema:{type:`object`,properties:{code:{type:`string`},message:{type:`string`},details:{type:`string`},stack:{type:`string`}},required:[`code`,`message`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=hr(e),n=[{type:`heading`,value:`Error`},{type:`code`,title:t.code,language:`text`,value:t.details?`${t.message}\n\n${t.details}`:t.message}];return t.stack&&n.push({type:`code`,title:`Stack Trace`,language:`text`,value:t.stack}),n},hydration:[],supportedTransports:pr};function _r(e){return typeof e==`object`&&!!e}function vr(e){return Array.isArray(e)?e.flatMap(e=>!_r(e)||typeof e.name!=`string`||typeof e.label!=`string`?[]:[{name:e.name,label:e.label,type:typeof e.type==`string`?e.type:void 0,required:typeof e.required==`boolean`?e.required:void 0,placeholder:typeof e.placeholder==`string`?e.placeholder:void 0,default:typeof e.default==`string`?e.default:void 0,options:Array.isArray(e.options)?e.options.filter(e=>typeof e==`string`||_r(e)&&typeof e.label==`string`&&typeof e.value==`string`):void 0,value:typeof e.value==`string`||typeof e.value==`boolean`?e.value:void 0}]):[]}var yr={id:`form@1`,label:`Form`,description:`Browser-only form template rendered as a heading and table of field metadata.`,inputSchema:{type:`object`,properties:{title:{type:`string`},fields:{type:`array`,items:{type:`object`,required:[`name`,`label`],properties:{name:{type:`string`},label:{type:`string`},type:{type:`string`},required:{type:`boolean`},placeholder:{type:`string`},default:{type:`string`},options:{type:`array`,items:{anyOf:[{type:`string`},{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:`string`}},additionalProperties:!1}]}},value:{type:[`string`,`boolean`]}},additionalProperties:!1}}},required:[`fields`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t={title:_r(e)&&typeof e.title==`string`?e.title:`Form`,fields:_r(e)?vr(e.fields):[]};return[{type:`heading`,value:t.title},{type:`table`,value:{headers:[`Label`,`Name`,`Type`,`Required`,`Default/Placeholder`],rows:t.fields.map(e=>[e.label||e.name,e.name,e.type||`text`,e.required?`Yes`:`No`,e.placeholder||e.default||``])}}]},hydration:[`form`],supportedTransports:[`browser`]},br=[`mcp-app`,`browser`];function xr(e){return typeof e==`object`&&!!e}function Sr(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>!xr(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label}]);return t.length>0?t:void 0}function Cr(e){return Array.isArray(e)?e.flatMap(e=>!xr(e)||typeof e.id!=`string`||typeof e.label!=`string`?[]:[{id:e.id,label:e.label,category:typeof e.category==`string`?e.category:void 0,tags:Array.isArray(e.tags)?e.tags.filter(e=>typeof e==`string`):void 0}]):[]}function wr(e){return xr(e)?{categories:Sr(e.categories),items:Cr(e.items)}:{items:[]}}function Tr(e){return{title:e.label,body:e.id,description:e.tags&&e.tags.length>0?e.tags.join(`, `):void 0}}function Er(e,t){return t.length===0?[]:[{type:`heading`,value:e},{type:`cards`,value:t.map(Tr)}]}var Dr={id:`picker@1`,label:`Picker`,description:`Grouped item picker rendered as cards with picker hydration metadata.`,inputSchema:{type:`object`,properties:{categories:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`}},additionalProperties:!1}},items:{type:`array`,items:{type:`object`,required:[`id`,`label`],properties:{id:{type:`string`},label:{type:`string`},category:{type:`string`},tags:{type:`array`,items:{type:`string`}}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=wr(e),n=[];if(t.categories&&t.categories.length>0){let e=new Set(t.categories.map(e=>e.id)),r=[];for(let e of t.categories){let n=Er(e.label,t.items.filter(t=>t.category===e.id));n.length>0&&r.push(n)}let i=Er(`Other`,t.items.filter(t=>!t.category||!e.has(t.category)));return i.length>0&&r.push(i),n.push(...r.flatMap((e,t)=>t>0?[{type:`separator`},...e]:e)),n}return t.items.length>0&&n.push({type:`cards`,value:t.items.map(Tr)}),n},hydration:[`picker`],supportedTransports:br},Or=[`mcp-app`,`browser`,`export`];function kr(e){return typeof e==`object`&&!!e}function Ar(e){return kr(e)&&typeof e.type==`string`}function jr(e){return Array.isArray(e)&&e.every(Ar)}function Mr(e){return kr(e)&&typeof e.label==`string`&&(typeof e.value==`string`||typeof e.value==`number`)}function Nr(e){return Array.isArray(e)?e.flatMap(e=>{if(!kr(e)||typeof e.heading!=`string`)return[];let t=typeof e.content==`string`||jr(e.content)?e.content:``;return[{heading:e.heading,content:t}]}):[]}function Pr(e){return Array.isArray(e)?e.flatMap(e=>kr(e)?[{title:typeof e.title==`string`?e.title:void 0,value:e.value,headers:Array.isArray(e.headers)?e.headers.filter(e=>typeof e==`string`):void 0,rows:Array.isArray(e.rows)?e.rows.filter(e=>Array.isArray(e)):void 0}]:[]):[]}function Fr(e){let t=[{type:`heading`,value:e.heading}];return typeof e.content==`string`?(t.push({type:`paragraph`,value:e.content}),t):(t.push(...e.content),t)}function Ir(e){let t={type:`table`};return e.title&&(t.title=e.title),e.value!==void 0&&(t.value=e.value),e.headers&&(t.headers=e.headers),e.rows&&(t.rows=e.rows),t}var Lr={id:`report@1`,label:`Report`,description:`Static report with title, optional metrics, narrative sections, and tables.`,inputSchema:{type:`object`,properties:{title:{type:`string`},metrics:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:[`string`,`number`]},status:{type:`string`}},additionalProperties:!1}},sections:{type:`array`,items:{type:`object`,required:[`heading`,`content`],properties:{heading:{type:`string`},content:{oneOf:[{type:`string`},{type:`array`,items:{type:`object`}}]}},additionalProperties:!1}},tables:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},value:{},headers:{type:`array`,items:{type:`string`}},rows:{type:`array`,items:{type:`array`,items:{}}}},additionalProperties:!1}}},required:[`title`,`sections`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t={title:kr(e)&&typeof e.title==`string`?e.title:`Report`,metrics:kr(e)&&Array.isArray(e.metrics)?e.metrics.filter(Mr):void 0,sections:kr(e)?Nr(e.sections):[],tables:kr(e)?Pr(e.tables):void 0},n=[{type:`heading`,value:t.title}];t.metrics&&t.metrics.length>0&&n.push({type:`metrics`,value:t.metrics});for(let e of t.sections)n.push(...Fr(e));for(let e of t.tables??[])n.push(Ir(e));return n},hydration:[],supportedTransports:Or},Rr=[`mcp-app`,`browser`,`export`];function zr(e){return typeof e==`object`&&!!e}function Br(e){return Array.isArray(e)?e.flatMap(e=>{if(!zr(e)||typeof e.category!=`string`||!Array.isArray(e.items))return[];let t=e.items.flatMap(e=>!zr(e)||typeof e.label!=`string`||typeof e.status!=`string`?[]:[{label:e.label,status:e.status,badge:typeof e.badge==`string`?e.badge:void 0}]);return[{category:e.category,items:t}]}):[]}function Vr(e){return e.map(e=>({title:e.label,status:e.status,badge:e.badge}))}var Hr={id:`status-board@1`,label:`Status Board`,description:`Static status board grouped into category headings and card collections.`,inputSchema:{type:`object`,properties:{categories:{type:`array`,items:{type:`object`,required:[`category`,`items`],properties:{category:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`label`,`status`],properties:{label:{type:`string`},status:{type:`string`},badge:{type:`string`}},additionalProperties:!1}}},additionalProperties:!1}}},required:[`categories`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=zr(e)?Br(e.categories):[],n=[];for(let e of t)n.push({type:`heading`,value:e.category}),n.push({type:`cards`,value:Vr(e.items)});return n},hydration:[],supportedTransports:Rr},Ur=[`mcp-app`,`browser`,`export`];function Wr(e){return typeof e==`object`&&!!e}function Gr(e){return Array.isArray(e)?e.flatMap(e=>!Wr(e)||typeof e.title!=`string`?[]:[{title:e.title,description:typeof e.description==`string`?e.description:void 0,timestamp:typeof e.timestamp==`string`?e.timestamp:void 0,status:typeof e.status==`string`?e.status:void 0}]):[]}function Kr(e){return Array.isArray(e)?{entries:Gr(e)}:Wr(e)?{entries:Gr(e.entries??e.events??e.items),title:typeof e.title==`string`?e.title:void 0}:{entries:[]}}var qr={type:`array`,items:{type:`object`,required:[`title`],properties:{title:{type:`string`},description:{type:`string`},timestamp:{type:`string`},status:{type:`string`}},additionalProperties:!1}},Jr={id:`timeline@1`,label:`Timeline`,description:`Static timeline events rendered as a timeline block.`,inputSchema:{oneOf:[qr,{type:`object`,properties:{title:{type:`string`},entries:qr,events:qr,items:qr},anyOf:[{required:[`entries`]},{required:[`events`]},{required:[`items`]}],additionalProperties:!1}]},defaultLayout:{},blocksFromData:e=>{let{entries:t,title:n}=Kr(e),r=[];return n&&r.push({type:`heading`,value:n}),r.push({type:`timeline`,value:t}),r},hydration:[],supportedTransports:Ur},Yr=[`mcp-app`,`browser`,`export`];function Xr(e){return typeof e==`object`&&!!e}function Zr(e){return Xr(e)&&typeof e.label==`string`}function Qr(e){return{name:e.label,children:Array.isArray(e.children)?e.children.filter(Zr).map(Qr):[]}}function $r(e){if(!Xr(e))return{};let t=e.root;return Zr(t)?Qr(t):Xr(t)?t:e}var ei={id:`tree@1`,label:`Tree`,description:`Static tree view data with optional tree hydration metadata.`,inputSchema:{oneOf:[{type:`object`,properties:{root:{type:`object`}},required:[`root`],additionalProperties:!0},{type:`object`,additionalProperties:!0}]},defaultLayout:{},blocksFromData:e=>[{type:`tree`,value:$r(e)}],hydration:[`tree`],supportedTransports:Yr},ti=new Bn;ti.register(Wn),ti.register(ar),ti.register(fr),ti.register(Dr),ti.register(Lr),ti.register(Jr),ti.register(ei),ti.register(Zn),ti.register(gr),ti.register(yr),ti.register(Hr);var ni=0;function ri(){return ni=(ni+1)%(2**53-1),`${Date.now().toString(16).padStart(12,`0`).slice(-12)}${ni.toString(16).padStart(4,`0`).slice(-4)}${Array.from({length:8},()=>Math.floor(Math.random()*256).toString(16).padStart(2,`0`)).join(``)}`}function ii(e){return{id:e,version:1,entry:`@aikit/blocks-interactive/dist/islands/${e}.mjs`,selector:`[data-island="${e}"]`,needsData:!0}}function ai(e,t){let n=new TextEncoder;return n.encode(e).byteLength+t.reduce((e,t)=>e+n.encode(t).byteLength,0)}function oi(e,t){let n=[],r=t.registry??ti,i={colorScheme:e.colorScheme??t.colorScheme??`auto`,transport:t.transport,lang:e.lang,dir:e.dir},a=[...e.blocks??[]],o=[...a],s=[],c=[...e.actions??[]];if(e.template){let t=r.get(e.template);if(t)try{o=t.blocksFromData(e.data,i),t.actionsFromData&&(c=[...c,...t.actionsFromData(e.data)]),s=t.hydration.map(e=>ii(e))}catch(t){let r=t instanceof Error?t.message:String(t);n.push({level:`error`,message:`Template ${e.template} failed: ${r}`}),o=a.length===0?gr.blocksFromData({code:`TEMPLATE_RENDER_ERROR`,message:`Failed to render template ${e.template}`,details:r},i):[...a]}else n.push({level:`warn`,message:`Template not found: ${e.template}`})}let l=Rn(o,i),u=[Fn(o.map(e=>e.type))],d=t.nonce??ri(),f=e.metadata?.surfaceId??`surface-${d}`,p=s.length>0?JSON.stringify({data:e.data,blocks:o}):void 0,ee=t.blockVendorScripts?[...new Set(o.flatMap(e=>t.blockVendorScripts?.[e.type]??[]))]:void 0;return{surfaceId:f,nonce:d,html:l,css:u,vendorScripts:ee&&ee.length>0?ee:void 0,islands:s,actions:c,payload:p,estimatedBytes:ai(l,u),exportPolicy:s.length>0?`local-interactive`:`static-only`,diagnostics:n.length>0?n:void 0}}function h(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}function g(e){return e&&Object.assign(fi,e),fi}var si,ci,li,ui,di,fi,pi=t((()=>{ci=Object.freeze({status:`aborted`}),li=Symbol(`zod_brand`),ui=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},di=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}},(si=globalThis).__zod_globalConfig??(si.__zod_globalConfig={}),fi=globalThis.__zod_globalConfig})),mi=n({BIGINT_FORMAT_RANGES:()=>va,Class:()=>ya,NUMBER_FORMAT_RANGES:()=>_a,aborted:()=>Xi,allowsEval:()=>pa,assert:()=>yi,assertEqual:()=>hi,assertIs:()=>_i,assertNever:()=>vi,assertNotEqual:()=>gi,assignProp:()=>Di,base64ToUint8Array:()=>aa,base64urlToUint8Array:()=>sa,cached:()=>Si,captureStackTrace:()=>fa,cleanEnum:()=>ia,cleanRegex:()=>wi,clone:()=>Bi,cloneDef:()=>ki,createTransparentProxy:()=>Vi,defineLazy:()=>v,esc:()=>Ni,escapeRegex:()=>zi,explicitlyAborted:()=>Zi,extend:()=>Gi,finalizeIssue:()=>ea,floatSafeRemainder:()=>Ti,getElementAtPath:()=>Ai,getEnumValues:()=>bi,getLengthableOrigin:()=>na,getParsedType:()=>ma,getSizableOrigin:()=>ta,hexToUint8Array:()=>la,isObject:()=>Fi,isPlainObject:()=>Ii,issue:()=>ra,joinValues:()=>_,jsonStringifyReplacer:()=>xi,merge:()=>qi,mergeDefs:()=>Oi,normalizeParams:()=>y,nullish:()=>Ci,numKeys:()=>Ri,objectClone:()=>Ei,omit:()=>Wi,optionalKeys:()=>Hi,parsedType:()=>x,partial:()=>Ji,pick:()=>Ui,prefixIssues:()=>Qi,primitiveTypes:()=>ga,promiseAllObject:()=>ji,propertyKeyTypes:()=>ha,randomString:()=>Mi,required:()=>Yi,safeExtend:()=>Ki,shallowClone:()=>Li,slugify:()=>Pi,stringifyPrimitive:()=>b,uint8ArrayToBase64:()=>oa,uint8ArrayToBase64url:()=>ca,uint8ArrayToHex:()=>ua,unwrapMessage:()=>$i});function hi(e){return e}function gi(e){return e}function _i(e){}function vi(e){throw Error(`Unexpected value in exhaustive check`)}function yi(e){}function bi(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function _(e,t=`|`){return e.map(e=>b(e)).join(t)}function xi(e,t){return typeof t==`bigint`?t.toString():t}function Si(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error(`cached value already set`)}}}function Ci(e){return e==null}function wi(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ti(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function v(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==da)return r===void 0&&(r=da,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ei(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Di(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oi(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function ki(e){return Oi(e._zod.def)}function Ai(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function ji(e){let t=Object.keys(e),n=t.map(t=>e[t]);return Promise.all(n).then(e=>{let n={};for(let r=0;r<t.length;r++)n[t[r]]=e[r];return n})}function Mi(e=10){let t=``;for(let n=0;n<e;n++)t+=`abcdefghijklmnopqrstuvwxyz`[Math.floor(Math.random()*26)];return t}function Ni(e){return JSON.stringify(e)}function Pi(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}function Fi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ii(e){if(Fi(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Fi(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Li(e){return Ii(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Ri(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function zi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Bi(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function y(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Vi(e){let t;return new Proxy({},{get(n,r,i){return t??=e(),Reflect.get(t,r,i)},set(n,r,i,a){return t??=e(),Reflect.set(t,r,i,a)},has(n,r){return t??=e(),Reflect.has(t,r)},deleteProperty(n,r){return t??=e(),Reflect.deleteProperty(t,r)},ownKeys(n){return t??=e(),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??=e(),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,i){return t??=e(),Reflect.defineProperty(t,r,i)}})}function b(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Hi(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}function Ui(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Bi(e,Oi(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Di(this,`shape`,e),e},checks:[]}))}function Wi(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Bi(e,Oi(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Di(this,`shape`,r),r},checks:[]}))}function Gi(e,t){if(!Ii(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Bi(e,Oi(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Di(this,`shape`,n),n}}))}function Ki(e,t){if(!Ii(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Bi(e,Oi(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Di(this,`shape`,n),n}}))}function qi(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Bi(e,Oi(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Di(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Ji(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Bi(t,Oi(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Di(this,`shape`,i),i},checks:[]}))}function Yi(e,t,n){return Bi(t,Oi(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Di(this,`shape`,i),i}}))}function Xi(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Zi(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Qi(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function $i(e){return typeof e==`string`?e:e?.message}function ea(e,t,n){let r=e.message?e.message:$i(e.inst?._zod.def?.error?.(e))??$i(t?.error?.(e))??$i(n.customError?.(e))??$i(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function ta(e){return e instanceof Set?`set`:e instanceof Map?`map`:e instanceof File?`file`:`unknown`}function na(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function x(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function ra(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function ia(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function aa(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function oa(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function sa(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return aa(t+`=`.repeat((4-t.length%4)%4))}function ca(e){return oa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function la(e){let t=e.replace(/^0x/,``);if(t.length%2!=0)throw Error(`Invalid hex string length`);let n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=Number.parseInt(t.slice(e,e+2),16);return n}function ua(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}var da,fa,pa,ma,ha,ga,_a,va,ya,S=t((()=>{pi(),da=Symbol(`evaluating`),fa=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{},pa=Si(()=>{if(fi.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}}),ma=e=>{let t=typeof e;switch(t){case`undefined`:return`undefined`;case`string`:return`string`;case`number`:return Number.isNaN(e)?`nan`:`number`;case`boolean`:return`boolean`;case`function`:return`function`;case`bigint`:return`bigint`;case`symbol`:return`symbol`;case`object`:return Array.isArray(e)?`array`:e===null?`null`:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?`promise`:typeof Map<`u`&&e instanceof Map?`map`:typeof Set<`u`&&e instanceof Set?`set`:typeof Date<`u`&&e instanceof Date?`date`:typeof File<`u`&&e instanceof File?`file`:`object`;default:throw Error(`Unknown data type: ${t}`)}},ha=new Set([`string`,`number`,`symbol`]),ga=new Set([`string`,`number`,`bigint`,`boolean`,`symbol`,`undefined`]),_a={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},va={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]},ya=class{constructor(...e){}}}));function ba(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function xa(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}function Sa(e,t=e=>e.message){let n={errors:[]},r=(e,i=[])=>{var a,o;for(let s of e.issues)if(s.code===`invalid_union`&&s.errors.length)s.errors.map(e=>r({issues:e},[...i,...s.path]));else if(s.code===`invalid_key`)r({issues:s.issues},[...i,...s.path]);else if(s.code===`invalid_element`)r({issues:s.issues},[...i,...s.path]);else{let e=[...i,...s.path];if(e.length===0){n.errors.push(t(s));continue}let r=n,c=0;for(;c<e.length;){let n=e[c],i=c===e.length-1;typeof n==`string`?(r.properties??={},(a=r.properties)[n]??(a[n]={errors:[]}),r=r.properties[n]):(r.items??=[],(o=r.items)[n]??(o[n]={errors:[]}),r=r.items[n]),i&&r.errors.push(t(s)),c++}}};return r(e),n}function Ca(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function wa(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${Ca(e.path)}`);return t.join(`
1827
1827
  `)}var Ta,Ea,Da,Oa=t((()=>{pi(),S(),Ta=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,xi,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ea=h(`$ZodError`,Ta),Da=h(`$ZodError`,Ta,{Parent:Error})})),ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja,Ya,Xa,Za,Qa,$a=t((()=>{pi(),Oa(),S(),ka=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new ui;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>ea(e,a,g())));throw fa(t,i?.callee),t}return o.value},Aa=ka(Da),ja=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>ea(e,a,g())));throw fa(t,i?.callee),t}return o.value},Ma=ja(Da),Na=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new ui;return a.issues.length?{success:!1,error:new(e??Ea)(a.issues.map(e=>ea(e,i,g())))}:{success:!0,data:a.value}},Pa=Na(Da),Fa=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>ea(e,i,g())))}:{success:!0,data:a.value}},Ia=Fa(Da),La=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ka(e)(t,n,i)},Ra=La(Da),za=e=>(t,n,r)=>ka(e)(t,n,r),Ba=za(Da),Va=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ja(e)(t,n,i)},Ha=Va(Da),Ua=e=>async(t,n,r)=>ja(e)(t,n,r),Wa=Ua(Da),Ga=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Na(e)(t,n,i)},Ka=Ga(Da),qa=e=>(t,n,r)=>Na(e)(t,n,r),Ja=qa(Da),Ya=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Fa(e)(t,n,i)},Xa=Ya(Da),Za=e=>async(t,n,r)=>Fa(e)(t,n,r),Qa=Za(Da)})),eo=n({base64:()=>No,base64url:()=>Po,bigint:()=>Ho,boolean:()=>Go,browserEmail:()=>Eo,cidrv4:()=>jo,cidrv6:()=>Mo,cuid:()=>so,cuid2:()=>co,date:()=>Bo,datetime:()=>io,domain:()=>Io,duration:()=>mo,e164:()=>Ro,email:()=>xo,emoji:()=>to,extendedDuration:()=>ho,guid:()=>go,hex:()=>Xo,hostname:()=>Fo,html5Email:()=>So,httpProtocol:()=>Lo,idnEmail:()=>To,integer:()=>Uo,ipv4:()=>Oo,ipv6:()=>ko,ksuid:()=>fo,lowercase:()=>Jo,mac:()=>Ao,md5_base64:()=>Qo,md5_base64url:()=>$o,md5_hex:()=>Zo,nanoid:()=>po,null:()=>Ko,number:()=>Wo,rfc5322Email:()=>Co,sha1_base64:()=>ts,sha1_base64url:()=>ns,sha1_hex:()=>es,sha256_base64:()=>is,sha256_base64url:()=>as,sha256_hex:()=>rs,sha384_base64:()=>ss,sha384_base64url:()=>cs,sha384_hex:()=>os,sha512_base64:()=>us,sha512_base64url:()=>ds,sha512_hex:()=>ls,string:()=>Vo,time:()=>ro,ulid:()=>lo,undefined:()=>qo,unicodeEmail:()=>wo,uppercase:()=>Yo,uuid:()=>_o,uuid4:()=>vo,uuid6:()=>yo,uuid7:()=>bo,xid:()=>uo});function to(){return new RegExp(Do,`u`)}function no(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ro(e){return RegExp(`^${no(e)}$`)}function io(e){let t=no({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${zo}T(?:${r})$`)}function ao(e,t){return RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function oo(e){return RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var so,co,lo,uo,fo,po,mo,ho,go,_o,vo,yo,bo,xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro,zo,Bo,Vo,Ho,Uo,Wo,Go,Ko,qo,Jo,Yo,Xo,Zo,Qo,$o,es,ts,ns,rs,is,as,os,ss,cs,ls,us,ds,fs=t((()=>{S(),so=/^[cC][0-9a-z]{6,}$/,co=/^[0-9a-z]+$/,lo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,uo=/^[0-9a-vA-V]{20}$/,fo=/^[A-Za-z0-9]{27}$/,po=/^[a-zA-Z0-9_-]{21}$/,mo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ho=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,go=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_o=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,vo=_o(4),yo=_o(6),bo=_o(7),xo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,So=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Co=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,wo=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,To=wo,Eo=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Do=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,Oo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ko=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ao=e=>{let t=zi(e??`:`);return RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},jo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Mo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,No=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Po=/^[A-Za-z0-9_-]*$/,Fo=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Io=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Lo=/^https?$/,Ro=/^\+[1-9]\d{6,14}$/,zo=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Bo=RegExp(`^${zo}$`),Vo=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Ho=/^-?\d+n?$/,Uo=/^-?\d+$/,Wo=/^-?\d+(?:\.\d+)?$/,Go=/^(?:true|false)$/i,Ko=/^null$/i,qo=/^undefined$/i,Jo=/^[^A-Z]*$/,Yo=/^[^a-z]*$/,Xo=/^[0-9a-fA-F]*$/,Zo=/^[0-9a-fA-F]{32}$/,Qo=ao(22,`==`),$o=oo(22),es=/^[0-9a-fA-F]{40}$/,ts=ao(27,`=`),ns=oo(27),rs=/^[0-9a-fA-F]{64}$/,is=ao(43,`=`),as=oo(43),os=/^[0-9a-fA-F]{96}$/,ss=ao(64,``),cs=oo(64),ls=/^[0-9a-fA-F]{128}$/,us=ao(86,`==`),ds=oo(86)}));function ps(e,t,n){e.issues.length&&t.issues.push(...Qi(n,e.issues))}var C,ms,hs,gs,_s,vs,ys,bs,xs,Ss,Cs,ws,Ts,Es,Ds,Os,ks,As,js,Ms,Ns,Ps,Fs,Is=t((()=>{pi(),fs(),S(),C=h(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ms={number:`number`,bigint:`bigint`,object:`date`},hs=h(`$ZodCheckLessThan`,(e,t)=>{C.init(e,t);let n=ms[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),gs=h(`$ZodCheckGreaterThan`,(e,t)=>{C.init(e,t);let n=ms[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_s=h(`$ZodCheckMultipleOf`,(e,t)=>{C.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Ti(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),vs=h(`$ZodCheckNumberFormat`,(e,t)=>{C.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=_a[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Uo)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),ys=h(`$ZodCheckBigIntFormat`,(e,t)=>{C.init(e,t);let[n,r]=va[t.format];e._zod.onattach.push(e=>{let i=e._zod.bag;i.format=t.format,i.minimum=n,i.maximum=r}),e._zod.check=i=>{let a=i.value;a<n&&i.issues.push({origin:`bigint`,input:a,code:`too_small`,minimum:n,inclusive:!0,inst:e,continue:!t.abort}),a>r&&i.issues.push({origin:`bigint`,input:a,code:`too_big`,maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),bs=h(`$ZodCheckMaxSize`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ci(t)&&t.size!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;r.size<=t.maximum||n.issues.push({origin:ta(r),code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),xs=h(`$ZodCheckMinSize`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ci(t)&&t.size!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;r.size>=t.minimum||n.issues.push({origin:ta(r),code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ss=h(`$ZodCheckSizeEquals`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ci(t)&&t.size!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=n=>{let r=n.value,i=r.size;if(i===t.size)return;let a=i>t.size;n.issues.push({origin:ta(r),...a?{code:`too_big`,maximum:t.size}:{code:`too_small`,minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Cs=h(`$ZodCheckMaxLength`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ci(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=na(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ws=h(`$ZodCheckMinLength`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ci(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=na(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ts=h(`$ZodCheckLengthEquals`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ci(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=na(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Es=h(`$ZodCheckStringFormat`,(e,t)=>{var n,r;C.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ds=h(`$ZodCheckRegex`,(e,t)=>{Es.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Os=h(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Jo,Es.init(e,t)}),ks=h(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Yo,Es.init(e,t)}),As=h(`$ZodCheckIncludes`,(e,t)=>{C.init(e,t);let n=zi(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),js=h(`$ZodCheckStartsWith`,(e,t)=>{C.init(e,t);let n=RegExp(`^${zi(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ms=h(`$ZodCheckEndsWith`,(e,t)=>{C.init(e,t);let n=RegExp(`.*${zi(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ns=h(`$ZodCheckProperty`,(e,t)=>{C.init(e,t),e._zod.check=e=>{let n=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(n=>ps(n,e,t.property));ps(n,e,t.property)}}),Ps=h(`$ZodCheckMimeType`,(e,t)=>{C.init(e,t);let n=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:`invalid_value`,values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}}),Fs=h(`$ZodCheckOverwrite`,(e,t)=>{C.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}})})),Ls,Rs=t((()=>{Ls=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
1828
1828
  `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
1829
1829
  `))}}})),zs,Bs=t((()=>{zs={major:4,minor:4,patch:3}}));function Vs(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}function Hs(e){if(!Po.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Vs(t.padEnd(Math.ceil(t.length/4)*4,`=`))}function Us(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}function Ws(e,t,n){e.issues.length&&t.issues.push(...Qi(n,e.issues)),t.value[n]=e.value}function Gs(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...Qi(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Ks(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Hi(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function qs(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Gs(e,n,i,t,u,d))):Gs(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}function Js(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Xi(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ea(e,r,g())))}),t)}function Ys(e,t,n,r){let i=e.filter(e=>e.issues.length===0);return i.length===1?(t.value=i[0].value,t):(i.length===0?t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ea(e,r,g())))}):t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:[],inclusive:!1}),t)}function Xs(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ii(e)&&Ii(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Xs(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Xs(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Zs(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Xi(e))return e;let o=Xs(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}function Qs(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function $s(e,t,n){e.issues.length&&t.issues.push(...Qi(n,e.issues)),t.value[n]=e.value}function ec(e,t,n,r,i){for(let a=0;a<n.length;a++){let n=e[a],o=a<r.length;if(n.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...Qi(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}function tc(e,t,n,r,i,a,o){e.issues.length&&(ha.has(typeof r)?n.issues.push(...Qi(r,e.issues)):n.issues.push({code:`invalid_key`,origin:`map`,input:i,inst:a,issues:e.issues.map(e=>ea(e,o,g()))})),t.issues.length&&(ha.has(typeof r)?n.issues.push(...Qi(r,t.issues)):n.issues.push({origin:`map`,code:`invalid_element`,input:i,inst:a,key:r,issues:t.issues.map(e=>ea(e,o,g()))})),n.value.set(e.value,t.value)}function nc(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function rc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}function ic(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function ac(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function oc(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}function sc(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||`forward`)===`forward`){let r=t.transform(e.value,e);return r instanceof Promise?r.then(r=>cc(e,r,t.out,n)):cc(e,r,t.out,n)}else{let r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(r=>cc(e,r,t.in,n)):cc(e,r,t.in,n)}}function cc(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}function lc(e){return e.value=Object.freeze(e.value),e}function uc(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ra(e))}}var w,dc,T,fc,pc,mc,hc,gc,_c,vc,yc,bc,xc,Sc,Cc,wc,Tc,Ec,Dc,Oc,kc,Ac,jc,Mc,Nc,Pc,Fc,Ic,Lc,Rc,zc,Bc,Vc,Hc,Uc,Wc,Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc,$c,el,tl,nl,rl,il,al,ol,sl,cl,ll,ul,dl,fl,pl,ml,hl,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El,Dl,Ol,kl=t((()=>{Is(),pi(),Rs(),$a(),fs(),S(),Bs(),w=h(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=zs;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Xi(e),i;for(let a of t){if(a._zod.def.when){if(Zi(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new ui;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Xi(e,t))});else{if(e.issues.length===t)continue;r||=Xi(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(Xi(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new ui;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new ui;return o.then(e=>t(e,r,a))}return t(o,r,a)}}v(e,`~standard`,()=>({validate:t=>{try{let n=Pa(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ia(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),dc=h(`$ZodString`,(e,t)=>{w.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Vo(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),T=h(`$ZodStringFormat`,(e,t)=>{Es.init(e,t),dc.init(e,t)}),fc=h(`$ZodGUID`,(e,t)=>{t.pattern??=go,T.init(e,t)}),pc=h(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=_o(e)}else t.pattern??=_o();T.init(e,t)}),mc=h(`$ZodEmail`,(e,t)=>{t.pattern??=xo,T.init(e,t)}),hc=h(`$ZodURL`,(e,t)=>{T.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Lo.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),gc=h(`$ZodEmoji`,(e,t)=>{t.pattern??=to(),T.init(e,t)}),_c=h(`$ZodNanoID`,(e,t)=>{t.pattern??=po,T.init(e,t)}),vc=h(`$ZodCUID`,(e,t)=>{t.pattern??=so,T.init(e,t)}),yc=h(`$ZodCUID2`,(e,t)=>{t.pattern??=co,T.init(e,t)}),bc=h(`$ZodULID`,(e,t)=>{t.pattern??=lo,T.init(e,t)}),xc=h(`$ZodXID`,(e,t)=>{t.pattern??=uo,T.init(e,t)}),Sc=h(`$ZodKSUID`,(e,t)=>{t.pattern??=fo,T.init(e,t)}),Cc=h(`$ZodISODateTime`,(e,t)=>{t.pattern??=io(t),T.init(e,t)}),wc=h(`$ZodISODate`,(e,t)=>{t.pattern??=Bo,T.init(e,t)}),Tc=h(`$ZodISOTime`,(e,t)=>{t.pattern??=ro(t),T.init(e,t)}),Ec=h(`$ZodISODuration`,(e,t)=>{t.pattern??=mo,T.init(e,t)}),Dc=h(`$ZodIPv4`,(e,t)=>{t.pattern??=Oo,T.init(e,t),e._zod.bag.format=`ipv4`}),Oc=h(`$ZodIPv6`,(e,t)=>{t.pattern??=ko,T.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),kc=h(`$ZodMAC`,(e,t)=>{t.pattern??=Ao(t.delimiter),T.init(e,t),e._zod.bag.format=`mac`}),Ac=h(`$ZodCIDRv4`,(e,t)=>{t.pattern??=jo,T.init(e,t)}),jc=h(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Mo,T.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}}),Mc=h(`$ZodBase64`,(e,t)=>{t.pattern??=No,T.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Vs(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Nc=h(`$ZodBase64URL`,(e,t)=>{t.pattern??=Po,T.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Hs(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Pc=h(`$ZodE164`,(e,t)=>{t.pattern??=Ro,T.init(e,t)}),Fc=h(`$ZodJWT`,(e,t)=>{T.init(e,t),e._zod.check=n=>{Us(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Ic=h(`$ZodCustomStringFormat`,(e,t)=>{T.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:`invalid_format`,format:t.format,input:n.value,inst:e,continue:!t.abort})}}),Lc=h(`$ZodNumber`,(e,t)=>{w.init(e,t),e._zod.pattern=e._zod.bag.pattern??Wo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Rc=h(`$ZodNumberFormat`,(e,t)=>{vs.init(e,t),Lc.init(e,t)}),zc=h(`$ZodBoolean`,(e,t)=>{w.init(e,t),e._zod.pattern=Go,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Bc=h(`$ZodBigInt`,(e,t)=>{w.init(e,t),e._zod.pattern=Ho,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value==`bigint`||n.issues.push({expected:`bigint`,code:`invalid_type`,input:n.value,inst:e}),n}}),Vc=h(`$ZodBigIntFormat`,(e,t)=>{ys.init(e,t),Bc.init(e,t)}),Hc=h(`$ZodSymbol`,(e,t)=>{w.init(e,t),e._zod.parse=(t,n)=>{let r=t.value;return typeof r==`symbol`||t.issues.push({expected:`symbol`,code:`invalid_type`,input:r,inst:e}),t}}),Uc=h(`$ZodUndefined`,(e,t)=>{w.init(e,t),e._zod.pattern=qo,e._zod.values=new Set([void 0]),e._zod.parse=(t,n)=>{let r=t.value;return r===void 0||t.issues.push({expected:`undefined`,code:`invalid_type`,input:r,inst:e}),t}}),Wc=h(`$ZodNull`,(e,t)=>{w.init(e,t),e._zod.pattern=Ko,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Gc=h(`$ZodAny`,(e,t)=>{w.init(e,t),e._zod.parse=e=>e}),Kc=h(`$ZodUnknown`,(e,t)=>{w.init(e,t),e._zod.parse=e=>e}),qc=h(`$ZodNever`,(e,t)=>{w.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)}),Jc=h(`$ZodVoid`,(e,t)=>{w.init(e,t),e._zod.parse=(t,n)=>{let r=t.value;return r===void 0||t.issues.push({expected:`void`,code:`invalid_type`,input:r,inst:e}),t}}),Yc=h(`$ZodDate`,(e,t)=>{w.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let i=n.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||n.issues.push({expected:`date`,code:`invalid_type`,input:i,...a?{received:`Invalid Date`}:{},inst:e}),n}}),Xc=h(`$ZodArray`,(e,t)=>{w.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>Ws(t,n,e))):Ws(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}}),Zc=h(`$ZodObject`,(e,t)=>{if(w.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=Si(()=>Ks(t));v(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Fi,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>Gs(n,t,e,s,r,i))):Gs(a,t,e,s,r,i)}return i?qs(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Qc=h(`$ZodObjectJIT`,(e,t)=>{Zc.init(e,t);let n=e._zod.parse,r=Si(()=>Ks(t)),i=e=>{let t=new Ls([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Ni(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Ni(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
@@ -1 +1 @@
1
- import{t as e}from"./curated-manager-BnP6VqvL.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";var u=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e)}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.options.staleTimeoutMinutes??30;return this.stateStore.sessionDeleteStale(e)}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}};const d=r(a(import.meta.url)),f=(()=>{try{let e=i(d,`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),p=c(`server`);function m(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const h=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}})();function g(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}const{values:_}=h?s({allowPositionals:!0,options:{transport:{type:`string`,default:m()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:m(),port:process.env.AIKIT_PORT??`3210`}};async function v(){if(process.on(`unhandledRejection`,e=>{p.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{p.error(`Uncaught exception — exiting`,l(e)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:f}),_.transport===`http`){let[{default:e},{loadConfig:n,resolveIndexMode:r},{registerDashboardRoutes:i,resolveDashboardDir:a},{registerSettingsRoutes:o,resolveSettingsDir:s},{createSettingsRouter:c},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-DAnAxrUW.js`),import(`./dashboard-static-CnXafYTs.js`),import(`./settings-static-BkVLqWOr.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-BfqgawfR.js`).then(e=>e.t)]),m=n();p.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json());let v=Number(_.port);h.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${v}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let y=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(y)),i(h,a(),p);let b=new Date().toISOString();h.use(`/settings/api`,c({log:p,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:b})})),o(h,s(),p),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let x=!1,S=null,C=null,w=null,T=null,E=null,D=null,O=Promise.resolve(),k=async(e,n)=>{if(!x||!w||!T){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=O,i;O=new Promise(e=>{i=e}),await r;try{let r=g(e);if(!E){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new T({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{D=e,C?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&C?.onSessionEnd(e),D=null}});e.onclose=()=>{E===e&&(E=null),D===e.sessionId&&(D=null)},E=e,await w.connect(e)}let i=E;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(D=i.sessionId,C?.onSessionStart(i.sessionId,{transport:`http`}),C?.onSessionActivity(i.sessionId)):r&&C?.onSessionActivity(r))}catch(e){if(p.error(`MCP handler error`,l(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}};h.post(`/mcp`,k),h.get(`/mcp`,k),h.delete(`/mcp`,k);let A=h.listen(v,`127.0.0.1`,()=>{p.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:n},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-BvVBHkFD.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);i(),a();let o=r(m),s=e(m,o);w=s.server,T=n,x=!0,p.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),s.ready.then(()=>{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);C=new u(s.aikit.stateStore),C.startGC(),D&&(C.onSessionStart(D,{transport:`http`}),C.onSessionActivity(D))}).catch(e=>p.error(`Failed to start session manager`,l(e))),o===`auto`?s.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);p.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),p.info(`Initial index complete`)}catch(e){p.error(`Initial index failed; will retry on aikit_reindex`,l(e))}}).catch(e=>p.error(`AI Kit init or indexing failed`,l(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,m,s.aikit.store),n=s.aikit.store;S=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.setSmartScheduler(t),p.info(`Smart index scheduler started (HTTP mode)`)}catch(e){p.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>p.error(`AI Kit initialization failed`,l(e))):(s.ready.catch(e=>p.error(`AI Kit initialization failed`,l(e))),p.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){p.error(`Failed to load server modules`,l(e))}},100)}),j=async e=>{p.info(`Shutdown signal received`,{signal:e}),S?.stop(),C?.stop(),D&&C?.onSessionEnd(D),E&&(await E.close().catch(()=>void 0),E=null,D=null),A.close(),w&&await w.close(),process.exit(0)};process.on(`SIGINT`,()=>j(`SIGINT`)),process.on(`SIGTERM`,()=>j(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:i,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-DAnAxrUW.js`),import(`./server-BvVBHkFD.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();p.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),i(),o();let u=n(c),d=r(c,u),{server:f,startInit:m,ready:h,runInitialIndex:g}=d,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await f.connect(v),p.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?a(n):n;return p.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(c,r),c.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?a(t):t}),!0},b=!1;try{b=y((await f.server.listRoots()).roots),b||p.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){p.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...l(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{p.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);f.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await f.server.listRoots()).roots))}catch(t){p.warn(`roots/list retry failed after notification`,l(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(async()=>{p.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{p.error(`Initialization failed — server will continue with limited tools`,l(e))}),u===`auto`?g().catch(e=>p.error(`Initial index failed`,l(e))):u===`smart`?h.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,c,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),p.info(`Smart index scheduler started (stdio mode)`)}catch(e){p.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>p.error(`AI Kit init failed for smart scheduler`,l(e))):p.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}v().catch(e=>{p.error(`Fatal error`,l(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
1
+ import{t as e}from"./curated-manager-BnP6VqvL.js";import{randomUUID as t}from"node:crypto";import{readFileSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import{parseArgs as s}from"node:util";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";var u=class{stateStore;options;gcTimer=null;constructor(e,t={}){this.stateStore=e,this.options=t}onSessionStart(e,t){this.stateStore.sessionCreate(e,t)}onSessionActivity(e){this.stateStore.sessionTouch(e)}onSessionEnd(e){this.stateStore.sessionDelete(e)}startGC(){if(this.gcTimer)return;let e=(this.options.gcIntervalMinutes??5)*60*1e3;this.gcTimer=setInterval(()=>{this.runGC()},e),this.gcTimer.unref()}runGC(){let e=this.options.staleTimeoutMinutes??30;return this.stateStore.sessionDeleteStale(e)}stop(){this.gcTimer&&=(clearInterval(this.gcTimer),null)}getActiveSessions(){return this.stateStore.sessionList().length}};const d=r(a(import.meta.url)),f=(()=>{try{let e=i(d,`..`,`..`,`..`,`package.json`);return JSON.parse(n(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),p=c(`server`);function m(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const h=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===o(e).href}catch{return!1}})();function g(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}const{values:_}=h?s({allowPositionals:!0,options:{transport:{type:`string`,default:m()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:m(),port:process.env.AIKIT_PORT??`3210`}};async function v(){if(process.on(`unhandledRejection`,e=>{p.error(`Unhandled rejection`,l(e))}),process.on(`uncaughtException`,e=>{p.error(`Uncaught exception — exiting`,l(e)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:f}),_.transport===`http`){let[{default:e},{loadConfig:n,resolveIndexMode:r},{registerDashboardRoutes:i,resolveDashboardDir:a},{registerSettingsRoutes:o,resolveSettingsDir:s},{createSettingsRouter:c},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-DAnAxrUW.js`),import(`./dashboard-static-CnXafYTs.js`),import(`./settings-static-BkVLqWOr.js`),import(`./routes-CR3fI-HJ.js`),import(`./auth-BfqgawfR.js`).then(e=>e.t)]),m=n();p.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json());let v=Number(_.port);h.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${v}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let y=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(y)),i(h,a(),p);let b=new Date().toISOString();h.use(`/settings/api`,c({log:p,mcpInfo:()=>({transport:`http`,port:v,pid:process.pid,startedAt:b})})),o(h,s(),p),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let x=!1,S=null,C=null,w=null,T=null,E=null,D=null,O=Promise.resolve(),k=async(e,n)=>{if(!x||!w||!T){n.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=O,i;O=new Promise(e=>{i=e}),await r;try{let r=g(e);if(!E){if(r){n.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new T({sessionIdGenerator:()=>t(),onsessioninitialized:async e=>{D=e,C?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&C?.onSessionEnd(e),D=null}});e.onclose=()=>{E===e&&(E=null),D===e.sessionId&&(D=null)},E=e,await w.connect(e)}let i=E;await i.handleRequest(e,n,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(D=i.sessionId,C?.onSessionStart(i.sessionId,{transport:`http`}),C?.onSessionActivity(i.sessionId)):r&&C?.onSessionActivity(r))}catch(e){if(p.error(`MCP handler error`,l(e)),!n.headersSent){let t=e instanceof Error?e.message:String(e),r=t.includes(`Not Acceptable`);n.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?t:`Internal server error`},id:null})}}finally{i()}};h.post(`/mcp`,k),h.get(`/mcp`,k),h.delete(`/mcp`,k);let A=h.listen(v,`127.0.0.1`,()=>{p.info(`MCP server listening`,{url:`http://127.0.0.1:${v}/mcp`,port:v}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:n},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-CHnF9LI9.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-BgHzxxCW.js`)]);i(),a();let o=r(m),s=e(m,o);w=s.server,T=n,x=!0,p.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),s.ready.then(()=>{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);C=new u(s.aikit.stateStore),C.startGC(),D&&(C.onSessionStart(D,{transport:`http`}),C.onSessionActivity(D))}).catch(e=>p.error(`Failed to start session manager`,l(e))),o===`auto`?s.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);p.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),p.info(`Initial index complete`)}catch(e){p.error(`Initial index failed; will retry on aikit_reindex`,l(e))}}).catch(e=>p.error(`AI Kit init or indexing failed`,l(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(s.aikit.indexer,m,s.aikit.store),n=s.aikit.store;S=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),s.setSmartScheduler(t),p.info(`Smart index scheduler started (HTTP mode)`)}catch(e){p.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>p.error(`AI Kit initialization failed`,l(e))):(s.ready.catch(e=>p.error(`AI Kit initialization failed`,l(e))),p.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){p.error(`Failed to load server modules`,l(e))}},100)}),j=async e=>{p.info(`Shutdown signal received`,{signal:e}),S?.stop(),C?.stop(),D&&C?.onSessionEnd(D),E&&(await E.close().catch(()=>void 0),E=null,D=null),A.close(),w&&await w.close(),process.exit(0)};process.on(`SIGINT`,()=>j(`SIGINT`)),process.on(`SIGTERM`,()=>j(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:i,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-DAnAxrUW.js`),import(`./server-CHnF9LI9.js`),import(`./version-check-BgHzxxCW.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();p.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),i(),o();let u=n(c),d=r(c,u),{server:f,startInit:m,ready:h,runInitialIndex:g}=d,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await f.connect(v),p.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?a(n):n;return p.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(c,r),c.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?a(t):t}),!0},b=!1;try{b=y((await f.server.listRoots()).roots),b||p.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){p.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...l(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{p.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);f.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await f.server.listRoots()).roots))}catch(t){p.warn(`roots/list retry failed after notification`,l(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(async()=>{p.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=d.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{p.error(`Initialization failed — server will continue with limited tools`,l(e))}),u===`auto`?g().catch(e=>p.error(`Initial index failed`,l(e))):u===`smart`?h.then(async()=>{try{if(!d.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(d.aikit.indexer,c,d.aikit.store),n=d.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),d.setSmartScheduler(t),p.info(`Smart index scheduler started (stdio mode)`)}catch(e){p.error(`Failed to start smart index scheduler`,l(e))}}).catch(e=>p.error(`AI Kit init failed for smart scheduler`,l(e))):p.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}v().catch(e=>{p.error(`Fatal error`,l(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
@@ -2635,8 +2635,8 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
2635
2635
  }
2636
2636
  mermaid.initialize({ startOnLoad: false, theme: theme });
2637
2637
  mermaid.run();
2638
- };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:Kd()}},Jd=new Map([[`mermaid`,qd]]);function Yd(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Jd.get(r);if(e){if(t===`browser`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}if(t===`mcp-app`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}n.push({src:e.cdn,initScript:e.initScript,onload:e.onload})}}return n.length>0?n:void 0}function Xd(){let e=[];for(let t of Jd.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Zd=300*1e3;let X=null;process.on(`exit`,()=>{let e=X;if(e){try{e.close()}catch{}X=null}});function Qd(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${q(e.description)}</p>`:``;return[`<h1 class="present-surface-title">${q(e.title)}</h1>`,t].filter(Boolean).join(`
2639
- `)}function $d(e,t){return e.length===0?``:`
2638
+ };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:Kd()}},Jd=new Map([[`mermaid`,qd]]);function Yd(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Jd.get(r);if(e){if(t===`browser`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}if(t===`mcp-app`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}n.push({src:e.cdn,initScript:e.initScript,onload:e.onload})}}return n.length>0?n:void 0}function Xd(){let e=[];for(let t of Jd.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Zd=300*1e3,Qd=S(import.meta.url);let X=null;process.on(`exit`,()=>{let e=X;if(e){try{e.close()}catch{}X=null}});function $d(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${q(e.description)}</p>`:``;return[`<h1 class="present-surface-title">${q(e.title)}</h1>`,t].filter(Boolean).join(`
2639
+ `)}function ef(e,t){return e.length===0?``:`
2640
2640
  <section class="present-surface-actions">
2641
2641
  <div class="present-action-bar">${e.map(e=>{let t=q(e.id),n=q(e.label);return e.type===`select`||e.type===`multi-select`?`<label class="present-action-field"><span>${n}</span><select data-action-id="${t}"${e.type===`multi-select`?` multiple`:``}>${(e.options??[]).map(e=>`<option value="${q(e.value)}">${q(e.label)}</option>`).join(``)}</select></label>`:`<button type="button" class="present-action-btn present-action-${q(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}).join(``)}</div>
2642
2642
  <p id="present-action-status" class="present-action-status" aria-live="polite"></p>
@@ -2763,8 +2763,8 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
2763
2763
  navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
2764
2764
  });
2765
2765
  })();
2766
- <\/script>`}function ef(e){try{bn(process.platform===`win32`?`start "" "${e}"`:process.platform===`darwin`?`open "${e}"`:`xdg-open "${e}"`)}catch{}}async function tf(e){try{let t=kn();await t.launch(`ui`),await(await t.getContext().newPage()).goto(e,{waitUntil:`domcontentloaded`})}catch{ef(e)}}function nf(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
2767
- `)}function rf(e){return e.some(e=>e.id!==`__dismiss`)}function af(e){return e.replace(`</head>`,`<style>
2766
+ <\/script>`}function tf(e){try{bn(process.platform===`win32`?`start "" "${e}"`:process.platform===`darwin`?`open "${e}"`:`xdg-open "${e}"`)}catch{}}async function nf(e){try{let t=kn();await t.launch(`ui`),await(await t.getContext().newPage()).goto(e,{waitUntil:`domcontentloaded`})}catch{tf(e)}}function rf(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
2767
+ `)}function af(e){return e.some(e=>e.id!==`__dismiss`)}function of(e){let t=e?.split(`?`)[0];if(t?.startsWith(`/@aikit/blocks-interactive/dist/`))return N(M(Qd.resolve(`@aikit/blocks-interactive/package.json`)),`dist`,t.slice(32))}function sf(e){return e.replace(`</head>`,`<style>
2768
2768
  .toolbar, .badge, body > header, body > footer { display: none !important; }
2769
2769
  body { padding-top: 0 !important; margin-top: 0 !important; }
2770
2770
  </style>
@@ -2775,8 +2775,8 @@ window.addEventListener('message', function(e) {
2775
2775
  }
2776
2776
  });
2777
2777
  <\/script>
2778
- </body>`)}function of(){let e=X;e&&(e.close(),X=null)}async function sf(e,t){if(ff(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=Gt({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2779
- `);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=af(yd(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=ir({title:e.title,html:[Qd(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2778
+ </body>`)}function cf(){let e=X;e&&(e.close(),X=null)}async function lf(e,t){if(mf(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=Gt({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2779
+ `);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=sf(yd(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=ir({title:e.title,html:[$d(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2780
2780
  (function() {
2781
2781
  const iframe = document.querySelector('.present-viewer-iframe');
2782
2782
  if (!iframe) return;
@@ -2792,11 +2792,11 @@ window.addEventListener('message', function(e) {
2792
2792
  })();
2793
2793
  <\/script>`,`</div>`].join(`
2794
2794
  `),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: calc(100vh - 12rem);`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
2795
- `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{of(),i=await new Promise((e,t)=>{let i=pr((e,t)=>{if(e.url===`/viewer`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(n);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(r)});i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=i,e(`http://127.0.0.1:${n.port}`)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}return tf(i),{content:[{type:`text`,text:nf(e,i,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function cf(e){ff(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=fr(e,{transport:`browser`,registry:Hd,blockVendorScripts:$u()}),n=dd(t.surfaceId,t.actions),r=Yd(t.vendorScripts,`browser`),i=Xd(),a=ir({title:e.title,html:[Qd(e),t.html,$d(t.actions,n.nonce)].filter(Boolean).join(`
2796
- `),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``;try{let e=X;e&&(e.close(),X=null),o=await new Promise((e,t)=>{let r=pr((e,t)=>{if(e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s);return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}if(tf(o),!rf(t.actions)){let t=X;return t&&(n.promise.finally(()=>{X===t&&(t.close(),X=null)}),setTimeout(()=>{X===t&&(t.close(),X=null)},Zd)),{content:[{type:`text`,text:nf(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let c=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>e(n.settleTimeout(Zd)),Zd)})]),l=X;l&&(l.close(),X=null);let u=c.kind===`result`?`Selected action: ${c.result.actionId}`:c.kind===`timeout`?`Timed out after ${c.waitedMs}ms.`:c.kind===`cancelled`?`Cancelled: ${c.reason}.`:c.kind===`error`?`Error: ${c.error.message}`:`Rendered.`;return{content:[{type:`text`,text:nf(e,o,u)}],structuredContent:c,isError:c.kind===`error`}}const lf=`ui://aikit/present.html`;let uf=``;function df(){return uf}function ff(e){uf=e}function pf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const mf=/\\u[0-9a-fA-F]{4}/,hf=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,gf=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,_f=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function vf(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function yf(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(hf.test(t[e])&&gf.test(t[e+1]))return!0;return!1}function bf(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function xf(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?bf(n).length===t:!1}function Sf(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2797
- `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&hf.test(e)&&gf.test(o)){let r=bf(e),o=[];i();let s=a+2;for(;s<t.length&&xf(t[s],r.length);)o.push(bf(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Cf(e){let t=vf(e);return!t||!yf(t)?[e]:Sf(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function wf(e){if(typeof e==`string`)return _f.test(e);if(Array.isArray(e))return e.some(e=>wf(e));if(!pf(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?wf(n):!1)}function Tf(e,t){return{preferBrowser:[t,e._meta,pf(e.metadata)?e.metadata.source:void 0].some(e=>wf(e))}}function Ef(e){if(!e.template)return!0;let t=gd(e.template);return t?t.supportedTransports.includes(`browser`):Ud(e)?.supportedTransports.includes(`browser`)??!1}function Df(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${q(e.description)}</p>`:``;return[`<section class="present-surface-header">`,` <h1>${q(e.title)}</h1>`,t,`</section>`,`<style>`,` .present-surface-header { display: grid; gap: 0.75rem; margin-bottom: 1.5rem; }`,` .present-surface-header h1 { margin: 0; font-size: 1.875rem; }`,` .present-surface-description { margin: 0; color: var(--dt-text-secondary, #475467); }`,`</style>`].filter(Boolean).join(`
2798
- `)}function Of(e,t){let n=[e.title];return e.description&&n.push(e.description),lr(t)?n.push(``,`Selected action: ${t.result.actionId}`):cr(t)?n.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?n.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`&&n.push(``,`Cancelled: ${t.reason}.`),n.join(`
2799
- `)}const kf={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Af(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Ud(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[kf]}:e}function jf(e){return e.replace(`</head>`,`<style>
2795
+ `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{cf(),i=await new Promise((e,t)=>{let i=pr((e,t)=>{if(e.url===`/viewer`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(n);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(r)});i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=i,e(`http://127.0.0.1:${n.port}`)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}return nf(i),{content:[{type:`text`,text:rf(e,i,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function uf(e){mf(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=fr(e,{transport:`browser`,registry:Hd,blockVendorScripts:$u()}),n=dd(t.surfaceId,t.actions),r=Yd(t.vendorScripts,`browser`),i=Xd(),a=ir({title:e.title,html:[$d(e),t.html,ef(t.actions,n.nonce)].filter(Boolean).join(`
2796
+ `),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``;try{let e=X;e&&(e.close(),X=null),o=await new Promise((e,t)=>{let r=pr((e,t)=>{if(e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s);return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}let o=of(e.url);if(o)try{let e=k(o,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(e);return}catch{}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}X=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}if(nf(o),!af(t.actions)){let t=X;return t&&(n.promise.finally(()=>{X===t&&(t.close(),X=null)}),setTimeout(()=>{X===t&&(t.close(),X=null)},Zd)),{content:[{type:`text`,text:rf(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let c=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>e(n.settleTimeout(Zd)),Zd)})]),l=X;l&&(l.close(),X=null);let u=c.kind===`result`?`Selected action: ${c.result.actionId}`:c.kind===`timeout`?`Timed out after ${c.waitedMs}ms.`:c.kind===`cancelled`?`Cancelled: ${c.reason}.`:c.kind===`error`?`Error: ${c.error.message}`:`Rendered.`;return{content:[{type:`text`,text:rf(e,o,u)}],structuredContent:c,isError:c.kind===`error`}}const df=`ui://aikit/present.html`;let ff=``;function pf(){return ff}function mf(e){ff=e}function hf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const gf=/\\u[0-9a-fA-F]{4}/,_f=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,vf=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,yf=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function bf(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function xf(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(_f.test(t[e])&&vf.test(t[e+1]))return!0;return!1}function Sf(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function Cf(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Sf(n).length===t:!1}function wf(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2797
+ `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&_f.test(e)&&vf.test(o)){let r=Sf(e),o=[];i();let s=a+2;for(;s<t.length&&Cf(t[s],r.length);)o.push(Sf(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Tf(e){let t=bf(e);return!t||!xf(t)?[e]:wf(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function Ef(e){if(typeof e==`string`)return yf.test(e);if(Array.isArray(e))return e.some(e=>Ef(e));if(!hf(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Ef(n):!1)}function Df(e,t){return{preferBrowser:[t,e._meta,hf(e.metadata)?e.metadata.source:void 0].some(e=>Ef(e))}}function Of(e){if(!e.template)return!0;let t=gd(e.template);return t?t.supportedTransports.includes(`browser`):Ud(e)?.supportedTransports.includes(`browser`)??!1}function kf(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${q(e.description)}</p>`:``;return[`<section class="present-surface-header">`,` <h1>${q(e.title)}</h1>`,t,`</section>`,`<style>`,` .present-surface-header { display: grid; gap: 0.75rem; margin-bottom: 1.5rem; }`,` .present-surface-header h1 { margin: 0; font-size: 1.875rem; }`,` .present-surface-description { margin: 0; color: var(--dt-text-secondary, #475467); }`,`</style>`].filter(Boolean).join(`
2798
+ `)}function Af(e,t){let n=[e.title];return e.description&&n.push(e.description),lr(t)?n.push(``,`Selected action: ${t.result.actionId}`):cr(t)?n.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?n.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`&&n.push(``,`Cancelled: ${t.reason}.`),n.join(`
2799
+ `)}const jf={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Mf(e){if((e.actions?.length??0)>0||!e.template)return e;let t=Ud(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[jf]}:e}function Nf(e){return e.replace(`</head>`,`<style>
2800
2800
  .toolbar, .badge, body > header, body > footer { display: none !important; }
2801
2801
  body { padding-top: 0 !important; margin-top: 0 !important; }
2802
2802
  </style>
@@ -2818,7 +2818,7 @@ window.addEventListener('message', function(e) {
2818
2818
  }
2819
2819
  });
2820
2820
  <\/script>
2821
- </body>`)}function Mf(e){let t=`<script>
2821
+ </body>`)}function Pf(e){let t=`<script>
2822
2822
  (function(){
2823
2823
  var last=0;
2824
2824
  function notify(){
@@ -2829,8 +2829,8 @@ window.addEventListener('message', function(e) {
2829
2829
  if(typeof ResizeObserver!=="undefined"){new ResizeObserver(notify).observe(document.documentElement)}
2830
2830
  else{setInterval(notify,500)}
2831
2831
  })();
2832
- <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function Nf(e,t,n){return{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function Pf(e,t){if(!pf(e)||!(`schemaVersion`in e))return{ok:!1,response:Nf(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:Nf(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&mf.test(e.title))return{ok:!1,response:Nf(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!pf(e)||e.type!==`markdown`)return[e];let t=vf(e);return!t||!yf(t)?[e]:Cf(e)})}:e;return{ok:!0,surface:n,options:Tf(n,t)}}async function Ff(e,t={}){let n=Af(e);if(e.template){let r=gd(e.template);if(r)return await If(n,r,t)}return Wd(n)||t.preferBrowser&&Ef(n)?await cf(n):Lf(n)}async function If(e,t,n={}){if(e.data!=null&&t.inputSchema){let n=Gt({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2833
- `);return Nf(`VIEWER_DATA_INVALID`,`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`)}}let r=t.supportedTransports.includes(`browser`),i=t.supportedTransports.includes(`mcp-app`);if(n.preferBrowser&&r||r&&!i)return await sf(e,t);if(!i)return Nf(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${t.id}" does not support an available transport`);try{let n=jf(yd(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`);return ff(Mf(ir({title:e.title,html:[Df(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2832
+ <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function Ff(e,t,n){return{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function If(e,t){if(!hf(e)||!(`schemaVersion`in e))return{ok:!1,response:Ff(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:Ff(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&gf.test(e.title))return{ok:!1,response:Ff(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!hf(e)||e.type!==`markdown`)return[e];let t=bf(e);return!t||!xf(t)?[e]:Tf(e)})}:e;return{ok:!0,surface:n,options:Df(n,t)}}async function Lf(e,t={}){let n=Mf(e);if(e.template){let r=gd(e.template);if(r)return await Rf(n,r,t)}return Wd(n)||t.preferBrowser&&Of(n)?await uf(n):zf(n)}async function Rf(e,t,n={}){if(e.data!=null&&t.inputSchema){let n=Gt({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2833
+ `);return Ff(`VIEWER_DATA_INVALID`,`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`)}}let r=t.supportedTransports.includes(`browser`),i=t.supportedTransports.includes(`mcp-app`);if(n.preferBrowser&&r||r&&!i)return await lf(e,t);if(!i)return Ff(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${t.id}" does not support an available transport`);try{let n=Nf(yd(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`);return mf(Pf(ir({title:e.title,html:[kf(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2834
2834
  (function() {
2835
2835
  const iframe = document.querySelector('.present-viewer-iframe');
2836
2836
  if (!iframe) return;
@@ -2853,16 +2853,16 @@ window.addEventListener('message', function(e) {
2853
2853
  });
2854
2854
  <\/script>`,`</div>`].join(`
2855
2855
  `),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: 640px;`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
2856
- `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`}))),{content:[{type:`text`,text:[Of(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
2856
+ `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`}))),{content:[{type:`text`,text:[Af(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
2857
2857
 
2858
- `)}],ui:{type:`resource`,uri:lf}}}catch(e){return Nf(`VIEWER_RENDER_FAILED`,e instanceof Error?e.message:`Failed to render viewer template`)}}function Lf(e){try{let t=fr(e,{transport:`mcp-app`,registry:Hd,blockVendorScripts:$u()}),n=Yd(t.vendorScripts,`mcp-app`);return uf=Mf(ir({title:e.title,html:[Df(e),t.html].filter(Boolean).join(`
2859
- `),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,headScripts:n})),{content:[{type:`text`,text:[Of(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
2858
+ `)}],ui:{type:`resource`,uri:df}}}catch(e){return Ff(`VIEWER_RENDER_FAILED`,e instanceof Error?e.message:`Failed to render viewer template`)}}function zf(e){try{let t=fr(e,{transport:`mcp-app`,registry:Hd,blockVendorScripts:$u()}),n=Yd(t.vendorScripts,`mcp-app`);return ff=Pf(ir({title:e.title,html:[kf(e),t.html].filter(Boolean).join(`
2859
+ `),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,headScripts:n})),{content:[{type:`text`,text:[Af(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
2860
2860
 
2861
- `)}],ui:{type:`resource`,uri:lf}}}catch(e){return Nf(`RENDER_FAILED`,e instanceof Error?e.message:`Failed to render ChannelSurface`)}}const Rf=L.object({label:L.string(),value:L.string(),description:L.string().optional()}),zf=L.object({id:L.string().describe(`Unique action identifier`),type:L.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:L.string().describe(`Visible action label`),variant:L.enum([`primary`,`danger`,`default`]).optional(),options:L.array(Rf).optional(),schema:L.record(L.string(),L.unknown()).optional()}),Bf=L.object({type:L.string(),title:L.string().optional(),value:L.unknown().optional(),language:L.string().optional()}).catchall(L.unknown()),Vf={schemaVersion:L.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:L.string().describe(`Surface title shown to the user.`),description:L.string().optional().describe(`Optional supporting copy for the surface.`),template:L.string().optional().describe(`Optional template id such as report@1.`),layout:L.object({maxWidth:L.string().optional(),padding:L.string().optional(),columns:L.number().optional()}).optional(),blocks:L.array(Bf).optional().describe(`Typed block content for the surface.`),data:L.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:L.array(zf).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:L.object({timeout:L.number().optional(),required:L.boolean().optional()}).optional(),metadata:L.object({surfaceId:L.string().optional(),createdAt:L.string().optional(),source:L.string().optional()}).optional(),colorScheme:L.enum([`light`,`dark`,`auto`]).optional(),lang:L.string().optional(),dir:L.enum([`ltr`,`rtl`,`auto`]).optional()};L.object({surfaceId:L.string(),actionId:L.string(),actionType:L.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:L.unknown().optional(),formData:L.record(L.string(),L.unknown()).optional(),selection:L.union([L.string(),L.array(L.string())]).optional(),label:L.string().optional(),timestamp:L.string(),sourceTransport:L.enum([`mcp-app`,`browser`,`export`])});function Hf(e,t){let n=U(`present`),r=[`Render a ChannelSurface for the user.`,`Quick ref:`,`- Full schema: aikit://schemas/channel-surface`,`- Required: schemaVersion: 1, title`,`- Content: blocks[] for direct rendering, or template + data for registry-backed rendering`,`- Actions: actions[] of SurfaceAction; interactive surfaces use browser transport and return ChannelOutcome`,`- Optional fields: description, layout, response, metadata, colorScheme, lang, dir`,`- Transports: mcp-app, browser, export`,`- Use schema resource for block enums and action details.`].join(`
2862
- `);Xn(e,`present`,{title:n.title,description:r,inputSchema:Vf,annotations:n.annotations,_meta:{ui:{resourceUri:lf}}},async(e,t)=>{let n=Pf(e,t);return n.ok?await Ff(n.surface,n.options):n.response});try{Yn(e,`Present View`,lf,{description:`AI Kit present tool viewer`},async()=>({contents:[{uri:lf,mimeType:Jn,text:df()||`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=vd().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}}const Uf=F(`tools`);function Wf(e,t){let n=new Fn({structure:new Ln,dependencies:new Mn,symbols:new Rn,patterns:new In,entryPoints:new Pn,diagrams:new Nn}),r=U(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:L.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:L.array(L.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Uf.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??``;if(!e)throw Uf.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);O(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&ne(N(e,`${t}.md`),n+r,`utf-8`);Uf.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Uf.warn(`Failed to persist knowledge to .ai/context/`,{error:I(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
2861
+ `)}],ui:{type:`resource`,uri:df}}}catch(e){return Ff(`RENDER_FAILED`,e instanceof Error?e.message:`Failed to render ChannelSurface`)}}const Bf=L.object({label:L.string(),value:L.string(),description:L.string().optional()}),Vf=L.object({id:L.string().describe(`Unique action identifier`),type:L.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:L.string().describe(`Visible action label`),variant:L.enum([`primary`,`danger`,`default`]).optional(),options:L.array(Bf).optional(),schema:L.record(L.string(),L.unknown()).optional()}),Hf=L.object({type:L.string(),title:L.string().optional(),value:L.unknown().optional(),language:L.string().optional()}).catchall(L.unknown()),Uf={schemaVersion:L.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:L.string().describe(`Surface title shown to the user.`),description:L.string().optional().describe(`Optional supporting copy for the surface.`),template:L.string().optional().describe(`Optional template id such as report@1.`),layout:L.object({maxWidth:L.string().optional(),padding:L.string().optional(),columns:L.number().optional()}).optional(),blocks:L.array(Hf).optional().describe(`Typed block content for the surface.`),data:L.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:L.array(Vf).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:L.object({timeout:L.number().optional(),required:L.boolean().optional()}).optional(),metadata:L.object({surfaceId:L.string().optional(),createdAt:L.string().optional(),source:L.string().optional()}).optional(),colorScheme:L.enum([`light`,`dark`,`auto`]).optional(),lang:L.string().optional(),dir:L.enum([`ltr`,`rtl`,`auto`]).optional()};L.object({surfaceId:L.string(),actionId:L.string(),actionType:L.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:L.unknown().optional(),formData:L.record(L.string(),L.unknown()).optional(),selection:L.union([L.string(),L.array(L.string())]).optional(),label:L.string().optional(),timestamp:L.string(),sourceTransport:L.enum([`mcp-app`,`browser`,`export`])});function Wf(e,t){let n=U(`present`),r=[`Render a ChannelSurface for the user.`,`Quick ref:`,`- Full schema: aikit://schemas/channel-surface`,`- Required: schemaVersion: 1, title`,`- Content: blocks[] for direct rendering, or template + data for registry-backed rendering`,`- Actions: actions[] of SurfaceAction; interactive surfaces use browser transport and return ChannelOutcome`,`- Optional fields: description, layout, response, metadata, colorScheme, lang, dir`,`- Transports: mcp-app, browser, export`,`- Use schema resource for block enums and action details.`].join(`
2862
+ `);Xn(e,`present`,{title:n.title,description:r,inputSchema:Uf,annotations:n.annotations,_meta:{ui:{resourceUri:df}}},async(e,t)=>{let n=If(e,t);return n.ok?await Lf(n.surface,n.options):n.response});try{Yn(e,`Present View`,df,{description:`AI Kit present tool viewer`},async()=>({contents:[{uri:df,mimeType:Jn,text:pf()||`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=vd().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}}const Gf=F(`tools`);function Kf(e,t){let n=new Fn({structure:new Ln,dependencies:new Mn,symbols:new Rn,patterns:new In,entryPoints:new Pn,diagrams:new Nn}),r=U(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:L.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:L.array(L.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},async({scope:e,aspects:r})=>{try{let i=e??`.`;Gf.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??``;if(!e)throw Gf.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);O(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(a))r&&typeof r==`string`&&ne(N(e,`${t}.md`),n+r,`utf-8`);Gf.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Gf.warn(`Failed to persist knowledge to .ai/context/`,{error:I(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
2863
2863
 
2864
2864
  ---
2865
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Uf.error(`Knowledge production failed`,I(e)),K(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}})}const Gf=F(`tools`);function Kf(e,t,n,r,i,a,o){let s=U(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:L.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:L.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
2865
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Gf.error(`Knowledge production failed`,I(e)),K(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}})}const qf=F(`tools`);function Jf(e,t,n,r,i,a,o){let s=U(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:L.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:L.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
2866
2866
 
2867
2867
  A reindex operation is currently running. Search and other tools continue to work with existing data. Use \`status({})\` to check when it completes.`}]};if(o===`smart`&&!s)return{content:[{type:`text`,text:`## Smart Indexing Active
2868
2868
 
@@ -2870,40 +2870,40 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
2870
2870
 
2871
2871
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
2872
2872
 
2873
- Use \`status({})\` to check smart indexing queue status.`}]};let l=Ss(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),Gf.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&Gf.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(Gf.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),Gf.info(`FTS index rebuilt after reindex`)}catch(e){Gf.warn(`FTS index rebuild failed`,I(e))}try{let e=await r.reindexAll();Gf.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Gf.warn(`Curated re-index failed`,I(e))}if(a)try{await a.notifyAfterReindex()}catch(e){Gf.warn(`Post-reindex resource notification failed`,I(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),Gf.error(`Background reindex failed`,I(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return Gf.error(`Reindex failed`,I(e)),K(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}})}const qf=F(`tools`);function Jf(e){let t=U(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:L.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:L.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:L.string().optional().describe(`Filter by tool name (list only)`),source:L.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:L.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return Bt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Vt({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return Ht().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
2873
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=Ss(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),qf.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&qf.debug(`Re-index progress`,{prefix:e,current:t.filesProcessed+1,total:t.filesTotal,file:t.currentFile})};return(e?t.reindexAll(n,u(`Reindex`)):t.index(n,u(`Index`))).then(async e=>{if(qf.info(`Background re-index complete`,{filesProcessed:e.filesProcessed,chunksCreated:e.chunksCreated,durationMs:e.durationMs}),l.complete(`Reindex complete: ${e.filesProcessed} files, ${e.chunksCreated} chunks in ${e.durationMs}ms`),i)try{await i.createFtsIndex(),qf.info(`FTS index rebuilt after reindex`)}catch(e){qf.warn(`FTS index rebuild failed`,I(e))}try{let e=await r.reindexAll();qf.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){qf.warn(`Curated re-index failed`,I(e))}if(a)try{await a.notifyAfterReindex()}catch(e){qf.warn(`Post-reindex resource notification failed`,I(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),qf.error(`Background reindex failed`,I(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return qf.error(`Reindex failed`,I(e)),K(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}})}const Yf=F(`tools`);function Xf(e){let t=U(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:L.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:L.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:L.string().optional().describe(`Filter by tool name (list only)`),source:L.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:L.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return Bt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Vt({last:t,tool:n,source:r,since:i});if(a.length===0)return{content:[{type:`text`,text:`No replay entries found. Activity is logged when tools are invoked via MCP or CLI.`}]};let o=a.map(e=>`${e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts} ${e.status===`ok`?`✓`:`✗`} ${e.tool} (${e.durationMs}ms) [${e.source}]\n in: ${e.input}\n out: ${e.output}`);return Ht().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
2874
2874
 
2875
- `)}`}]}}catch(e){return qf.error(`Replay failed`,I(e)),K(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}})}const Yf=F(`tools`);function Xf(e){let t=U(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:L.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:L.string().optional().describe(`Restore point ID (required for action=restore)`),limit:L.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=ht().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
2875
+ `)}`}]}}catch(e){return Yf.error(`Replay failed`,I(e)),K(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}})}const Zf=F(`tools`);function Qf(e){let t=U(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:L.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:L.string().optional().describe(`Restore point ID (required for action=restore)`),limit:L.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=ht().slice(0,n);return e.length===0?{content:[{type:`text`,text:`No restore points found.`}]}:{content:[{type:`text`,text:`## Restore Points\n\n${e.map(e=>`- **${e.id}** (${e.timestamp}) — ${e.operation}: ${e.description} (${e.files.length} files)`).join(`
2876
2876
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Ut(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
2877
- `)}`}]}}catch(e){return Yf.error(`Restore failed`,I(e)),K(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const Zf=/<\/?curated-context>/gi;function Qf(e){return e.replace(Zf,``)}function $f(e){return`<curated-context>\n${Qf(e)}\n</curated-context>`}const ep=F(`tools`);function tp(e,t,i,a){r(e,t,i);let o=e.memoryMetaGet(t);if(!o)return;let s=_(o,{...n,...a});s&&(v(e,t,s),h(e,t,i))}function np(e,t){let n=[],r=re(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?Zt(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function rp(e,t,n){return n?e:t===`curated`?e*1.2:e}function ip(e,t){return t?e:e.map(e=>({record:e.record,score:rp(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}async function ap(e,t,n,r,i){if(!e||t>=e.config.fallbackThreshold&&n.length>0)return{results:n,triggered:!1,cacheHit:!1};let a=!1;try{let t=e.cache.get(r);return t?a=!0:(t=await e.client.search(r,i),t.length>0&&e.cache.set(r,t)),t.length>0?{results:qn(n,t,i).map(e=>({record:{id:`er:${e.sourcePath}`,content:e.content,sourcePath:e.source===`er`?`[ER] ${e.sourcePath}`:e.sourcePath,startLine:e.startLine??0,endLine:e.endLine??0,contentType:e.contentType??`documentation`,headingPath:e.headingPath,origin:e.source===`er`?`curated`:e.origin??`indexed`,category:e.category,tags:e.tags??[],chunkIndex:0,totalChunks:1,fileHash:``,indexedAt:new Date().toISOString(),version:1},score:e.score})),triggered:!0,cacheHit:a}:{results:n,triggered:!0,cacheHit:a}}catch(e){return ep.warn(`ER fallback failed`,I(e)),{results:n,triggered:!0,cacheHit:a}}}function op(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function sp(e,t){let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>=2);return n.length<2?e:e.map(e=>{let t=e.record.content.toLowerCase();if(t.length>5e3)return e;let r=n.map(e=>{let n=[],r=t.indexOf(e);for(;r!==-1&&n.length<10;)n.push(r),r=t.indexOf(e,r+1);return n});if(r.some(e=>e.length===0))return e;let i=t.length;for(let e of r[0]){let t=e,a=e+n[0].length;for(let i=1;i<r.length;i++){let o=r[i][0],s=Math.abs(o-e);for(let t=1;t<r[i].length;t++){let n=Math.abs(r[i][t]-e);n<s&&(s=n,o=r[i][t])}t=Math.min(t,o),a=Math.max(a,o+n[i].length)}i=Math.min(i,a-t)}let a=1+.25/(1+i/200);return{record:e.record,score:e.score*a}}).sort((e,t)=>t.score-e.score)}function cp(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function lp(e,t,n=8){let r=new Set(t.toLowerCase().split(/\s+/).filter(e=>e.length>=2)),i=new Map,a=e.length;for(let t of e){let e=t.record.content.split(/[^a-zA-Z0-9_]+/).filter(e=>e.length>=3&&!up.has(e.toLowerCase())),n=new Set;for(let t of e){let e=t.toLowerCase();/[_A-Z]/.test(t)&&i.set(`__id__${e}`,1),n.has(e)||(n.add(e),i.set(e,(i.get(e)??0)+1))}}let o=[];for(let[e,t]of i){if(e.startsWith(`__id__`)||r.has(e)||t>a*.8)continue;let n=Math.log(a/t),s=+!!i.has(`__id__${e}`),c=e.length>8?.5:0;o.push({term:e,score:n+s+c})}return o.sort((e,t)=>t.score-e.score).slice(0,n).map(e=>e.term)}const up=new Set(`the.and.for.are.but.not.you.all.can.had.her.was.one.our.out.has.have.from.this.that.with.they.been.said.each.which.their.will.other.about.many.then.them.these.some.would.make.like.into.could.time.very.when.come.just.know.take.people.also.back.after.only.more.than.over.such.import.export.const.function.return.true.false.null.undefined.string.number.boolean.void.type.interface`.split(`.`));async function dp(e,t){try{let n=await e.getStats();if(!n.lastIndexedAt)return;let r=new Date(n.lastIndexedAt).getTime(),i=Date.now(),a=[...new Set(t.map(e=>e.record.sourcePath))].filter(e=>!e.startsWith(`[ER]`)).slice(0,5);if(a.length===0)return;let o=0;for(let e of a)try{(await _n(e)).mtimeMs>r&&o++}catch{o++}if(o>0){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${o} file(s) modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function fp(e,t,n,r,i,a,o,s,c,l){let u=U(`search`);e.registerTool(`search`,{title:u.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:So,inputSchema:{query:L.string().max(5e3).describe(`Natural language search query`),limit:L.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:L.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:L.enum(le).optional().describe(`Filter by content type`),source_type:L.enum(fe).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:L.enum(de).optional().describe(`Filter by knowledge origin`),category:L.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:L.array(L.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:L.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:L.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:L.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:L.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:L.array(L.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:u.annotations},async({query:e,limit:u,search_mode:d,content_type:f,source_type:p,origin:m,category:h,tags:g,min_score:_,graph_hops:v,max_tokens:y,dedup:b,workspaces:x})=>{try{let S={limit:u,minScore:_,contentType:f,sourceType:p,origin:m,category:h,tags:g},C,w=!1,T=!1,E=``,D=np(e,s);if(d===`keyword`)C=await n.ftsSearch(e,S),C=C.slice(0,u);else if(d===`semantic`){let r=await t.embedQuery(D);C=await n.search(r,S);let a=await ap(i,C[0]?.score??0,C,e,u);C=a.results,w=a.triggered,T=a.cacheHit}else{let r=await t.embedQuery(D),a=n.coarseSearch,o=a?a.bind(n):n.search.bind(n),[s,c]=await Promise.all([o(r,{...S,limit:u*2}),n.ftsSearch(e,{...S,limit:u*2}).catch(()=>[])]);s.length===0&&c.length>0?(C=c.slice(0,u),E=` (FTS-only: vector index rebuilding)`):C=c.length===0&&s.length>0?s.slice(0,u):op(s,c).slice(0,u);let l=await ap(i,s[0]?.score??0,C,e,u);C=l.results,w=l.triggered,T=l.cacheHit}C=ip(C,m).slice(0,u),a&&a.recordSearch(e,w,T),C.length>1&&(C=sp(C,e)),C=cp(C);let O=``;if(x&&x.length>0){let n=Qs(x,he(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await $s(n);try{let i;i=d===`keyword`?await tc(r,e,{...S,limit:u}):await ec(r,await t.embedQuery(e),{...S,limit:u});for(let e of i)C.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});C=C.sort((e,t)=>t.score-e.score).slice(0,u),O=` + ${n.length} workspace(s)`}finally{await i()}}}if(b===`file`&&C.length>1){let e=new Map;for(let t of C){let n=t.record.sourcePath,r=e.get(n);r?(t.score>r.best.score&&(r.best=t),r.ranges.push({start:t.record.startLine,end:t.record.endLine})):e.set(n,{best:t,ranges:[{start:t.record.startLine,end:t.record.endLine}]})}C=[...e.values()].sort((e,t)=>t.best.score-e.best.score).map(({best:e,ranges:t})=>({record:{...e.record,content:t.length>1?`${e.record.content}\n\n_Matched ${t.length} sections: ${t.sort((e,t)=>e.start-t.start).map(e=>`L${e.start}-${e.end}`).join(`, `)}_`:e.record.content},score:e.score}))}if(C.length>1){let e=C[0].score,t=Math.max(e*.4,.1);C=C.filter(e=>e.score>=t)}if(C.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100})).text.trim().split(`
2878
- `)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,S);a.length>0&&(C=a,E=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,ep.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){ep.debug(`Smart search fallback failed`,{error:String(e)})}if(C.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:d,query:e}}}let k,A;if(v>0&&!r&&(A="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),v>0&&r)try{let e=await rt(r,C.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:v,maxPerHit:5});k=new Map;for(let t of e)if(t.graphContext.nodes.length>0){let e=t.graphContext.nodes.slice(0,5).map(e=>` - **${e.name}** (${e.type})`).join(`
2877
+ `)}`}]}}catch(e){return Zf.error(`Restore failed`,I(e)),K(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const $f=/<\/?curated-context>/gi;function ep(e){return e.replace($f,``)}function tp(e){return`<curated-context>\n${ep(e)}\n</curated-context>`}const np=F(`tools`);function rp(e,t,i,a){r(e,t,i);let o=e.memoryMetaGet(t);if(!o)return;let s=_(o,{...n,...a});s&&(v(e,t,s),h(e,t,i))}function ip(e,t){let n=[],r=re(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?Zt(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function ap(e,t,n){return n?e:t===`curated`?e*1.2:e}function op(e,t){return t?e:e.map(e=>({record:e.record,score:ap(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}async function sp(e,t,n,r,i){if(!e||t>=e.config.fallbackThreshold&&n.length>0)return{results:n,triggered:!1,cacheHit:!1};let a=!1;try{let t=e.cache.get(r);return t?a=!0:(t=await e.client.search(r,i),t.length>0&&e.cache.set(r,t)),t.length>0?{results:qn(n,t,i).map(e=>({record:{id:`er:${e.sourcePath}`,content:e.content,sourcePath:e.source===`er`?`[ER] ${e.sourcePath}`:e.sourcePath,startLine:e.startLine??0,endLine:e.endLine??0,contentType:e.contentType??`documentation`,headingPath:e.headingPath,origin:e.source===`er`?`curated`:e.origin??`indexed`,category:e.category,tags:e.tags??[],chunkIndex:0,totalChunks:1,fileHash:``,indexedAt:new Date().toISOString(),version:1},score:e.score})),triggered:!0,cacheHit:a}:{results:n,triggered:!0,cacheHit:a}}catch(e){return np.warn(`ER fallback failed`,I(e)),{results:n,triggered:!0,cacheHit:a}}}function cp(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function lp(e,t){let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>=2);return n.length<2?e:e.map(e=>{let t=e.record.content.toLowerCase();if(t.length>5e3)return e;let r=n.map(e=>{let n=[],r=t.indexOf(e);for(;r!==-1&&n.length<10;)n.push(r),r=t.indexOf(e,r+1);return n});if(r.some(e=>e.length===0))return e;let i=t.length;for(let e of r[0]){let t=e,a=e+n[0].length;for(let i=1;i<r.length;i++){let o=r[i][0],s=Math.abs(o-e);for(let t=1;t<r[i].length;t++){let n=Math.abs(r[i][t]-e);n<s&&(s=n,o=r[i][t])}t=Math.min(t,o),a=Math.max(a,o+n[i].length)}i=Math.min(i,a-t)}let a=1+.25/(1+i/200);return{record:e.record,score:e.score*a}}).sort((e,t)=>t.score-e.score)}function up(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function dp(e,t,n=8){let r=new Set(t.toLowerCase().split(/\s+/).filter(e=>e.length>=2)),i=new Map,a=e.length;for(let t of e){let e=t.record.content.split(/[^a-zA-Z0-9_]+/).filter(e=>e.length>=3&&!fp.has(e.toLowerCase())),n=new Set;for(let t of e){let e=t.toLowerCase();/[_A-Z]/.test(t)&&i.set(`__id__${e}`,1),n.has(e)||(n.add(e),i.set(e,(i.get(e)??0)+1))}}let o=[];for(let[e,t]of i){if(e.startsWith(`__id__`)||r.has(e)||t>a*.8)continue;let n=Math.log(a/t),s=+!!i.has(`__id__${e}`),c=e.length>8?.5:0;o.push({term:e,score:n+s+c})}return o.sort((e,t)=>t.score-e.score).slice(0,n).map(e=>e.term)}const fp=new Set(`the.and.for.are.but.not.you.all.can.had.her.was.one.our.out.has.have.from.this.that.with.they.been.said.each.which.their.will.other.about.many.then.them.these.some.would.make.like.into.could.time.very.when.come.just.know.take.people.also.back.after.only.more.than.over.such.import.export.const.function.return.true.false.null.undefined.string.number.boolean.void.type.interface`.split(`.`));async function pp(e,t){try{let n=await e.getStats();if(!n.lastIndexedAt)return;let r=new Date(n.lastIndexedAt).getTime(),i=Date.now(),a=[...new Set(t.map(e=>e.record.sourcePath))].filter(e=>!e.startsWith(`[ER]`)).slice(0,5);if(a.length===0)return;let o=0;for(let e of a)try{(await _n(e)).mtimeMs>r&&o++}catch{o++}if(o>0){let e=i-r,t=Math.floor(e/6e4),n=t<1?`<1 min`:`${t} min`;return`> ⚠️ **Index may be stale** — ${o} file(s) modified since last index (${n} ago). Use \`reindex\` to refresh.`}}catch{}}function mp(e,t,n,r,i,a,o,s,c,l){let u=U(`search`);e.registerTool(`search`,{title:u.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:So,inputSchema:{query:L.string().max(5e3).describe(`Natural language search query`),limit:L.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:L.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:L.enum(le).optional().describe(`Filter by content type`),source_type:L.enum(fe).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:L.enum(de).optional().describe(`Filter by knowledge origin`),category:L.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:L.array(L.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:L.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:L.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:L.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:L.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:L.array(L.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:u.annotations},async({query:e,limit:u,search_mode:d,content_type:f,source_type:p,origin:m,category:h,tags:g,min_score:_,graph_hops:v,max_tokens:y,dedup:b,workspaces:x})=>{try{let S={limit:u,minScore:_,contentType:f,sourceType:p,origin:m,category:h,tags:g},C,w=!1,T=!1,E=``,D=ip(e,s);if(d===`keyword`)C=await n.ftsSearch(e,S),C=C.slice(0,u);else if(d===`semantic`){let r=await t.embedQuery(D);C=await n.search(r,S);let a=await sp(i,C[0]?.score??0,C,e,u);C=a.results,w=a.triggered,T=a.cacheHit}else{let r=await t.embedQuery(D),a=n.coarseSearch,o=a?a.bind(n):n.search.bind(n),[s,c]=await Promise.all([o(r,{...S,limit:u*2}),n.ftsSearch(e,{...S,limit:u*2}).catch(()=>[])]);s.length===0&&c.length>0?(C=c.slice(0,u),E=` (FTS-only: vector index rebuilding)`):C=c.length===0&&s.length>0?s.slice(0,u):cp(s,c).slice(0,u);let l=await sp(i,s[0]?.score??0,C,e,u);C=l.results,w=l.triggered,T=l.cacheHit}C=op(C,m).slice(0,u),a&&a.recordSearch(e,w,T),C.length>1&&(C=lp(C,e)),C=up(C);let O=``;if(x&&x.length>0){let n=Qs(x,he(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await $s(n);try{let i;i=d===`keyword`?await tc(r,e,{...S,limit:u}):await ec(r,await t.embedQuery(e),{...S,limit:u});for(let e of i)C.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});C=C.sort((e,t)=>t.score-e.score).slice(0,u),O=` + ${n.length} workspace(s)`}finally{await i()}}}if(b===`file`&&C.length>1){let e=new Map;for(let t of C){let n=t.record.sourcePath,r=e.get(n);r?(t.score>r.best.score&&(r.best=t),r.ranges.push({start:t.record.startLine,end:t.record.endLine})):e.set(n,{best:t,ranges:[{start:t.record.startLine,end:t.record.endLine}]})}C=[...e.values()].sort((e,t)=>t.best.score-e.best.score).map(({best:e,ranges:t})=>({record:{...e.record,content:t.length>1?`${e.record.content}\n\n_Matched ${t.length} sections: ${t.sort((e,t)=>e.start-t.start).map(e=>`L${e.start}-${e.end}`).join(`, `)}_`:e.record.content},score:e.score}))}if(C.length>1){let e=C[0].score,t=Math.max(e*.4,.1);C=C.filter(e=>e.score>=t)}if(C.length===0){if(o?.available)try{let r=(await o.createMessage({prompt:`The search query "${e}" returned 0 results in AI Kit code search. Suggest ONE alternative search query that might find relevant results. Reply with ONLY the alternative query, nothing else.`,systemPrompt:`You are a search query optimizer for AI Kit code search. Generate a single alternative query.`,maxTokens:100})).text.trim().split(`
2878
+ `)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,S);a.length>0&&(C=a,E=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,np.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){np.debug(`Smart search fallback failed`,{error:String(e)})}if(C.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:d,query:e}}}let k,A;if(v>0&&!r&&(A="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),v>0&&r)try{let e=await rt(r,C.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:v,maxPerHit:5});k=new Map;for(let t of e)if(t.graphContext.nodes.length>0){let e=t.graphContext.nodes.slice(0,5).map(e=>` - **${e.name}** (${e.type})`).join(`
2879
2879
  `),n=new Map;for(let e of t.graphContext.nodes)n.set(e.id,e.name);let r=t.graphContext.edges.slice(0,5).map(e=>` - ${n.get(e.fromId)??e.fromId} —[${e.type}]→ ${n.get(e.toId)??e.toId}`).join(`
2880
2880
  `),i=[`- **Graph Context** (${v} hop${v>1?`s`:``}):`];e&&i.push(` Entities:\n${e}`),r&&i.push(` Relationships:\n${r}`),k.set(t.recordId,i.join(`
2881
- `))}}catch(e){ep.warn(`Graph augmentation failed`,I(e)),A=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let j=Date.now();for(let e of C)if(e.record.origin===`curated`&&e.record.indexedAt){let t=j-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(C.sort((e,t)=>t.score-e.score),C=we(C),s)for(let e of C){if(e.record.origin!==`curated`)continue;let t=El(e.record.sourcePath);t&&tp(s,t,c,l)}let ee=C.map((e,t)=>{let n=e.record;return`${`### Result ${t+1} (score: ${e.score.toFixed(3)})`}\n${[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,k?.get(n.id)??null].filter(Boolean).join(`
2882
- `)}\n\n${n.origin===`curated`?$f(n.content):n.content}`}).join(`
2881
+ `))}}catch(e){np.warn(`Graph augmentation failed`,I(e)),A=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let j=Date.now();for(let e of C)if(e.record.origin===`curated`&&e.record.indexedAt){let t=j-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(C.sort((e,t)=>t.score-e.score),C=we(C),s)for(let e of C){if(e.record.origin!==`curated`)continue;let t=El(e.record.sourcePath);t&&rp(s,t,c,l)}let ee=C.map((e,t)=>{let n=e.record;return`${`### Result ${t+1} (score: ${e.score.toFixed(3)})`}\n${[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin===`indexed`?null:`- **Origin**: ${n.origin}`,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(`, `)}`:null,k?.get(n.id)??null].filter(Boolean).join(`
2882
+ `)}\n\n${n.origin===`curated`?tp(n.content):n.content}`}).join(`
2883
2883
 
2884
2884
  ---
2885
2885
 
2886
- `),te=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+O,ne=lp(C,e),re=ne.length>0?`\n_Distinctive terms: ${ne.map(e=>`\`${e}\``).join(`, `)}_`:``,M=await dp(n,C),ie=[];if(C.length===0)ie.push("`reindex` — no results found, index may be stale"),ie.push("`find` — try federated search with glob/regex");else{let e=C[0]?.record.sourcePath;e&&ie.push(`\`lookup\` — see all chunks from \`${e}\``),ie.push("`symbol` — resolve a specific symbol from the results"),ie.push("`compact` — compress a result file for focused reading")}let N=[A?`${A}\n\n`:``,M?`${M}\n\n`:``,ee,`\n\n---\n_Search mode: ${te} | ${C.length} results_${re}`,`\n_Next: ${ie.join(` | `)}_`],ae=E+N.join(``);y&&(ae=sn(ae,y));let P=new Set,oe=[];for(let e of C){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=El(e.record.sourcePath);if(!t)continue;let n=wl(t,e.record.headingPath??t);n&&!P.has(n.uri)&&(P.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ae},...oe],structuredContent:{results:C.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:C.length,searchMode:d,query:e}}}catch(e){return ep.error(`Search failed`,I(e)),K(`INTERNAL`,`Search failed: ${e instanceof Error?e.message:String(e)}`)}})}const pp=F(`tools`);function mp(e,t,n){let r=U(`session_digest`);e.registerTool(`session_digest`,{title:r.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:L.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:L.string().optional().describe(`ISO timestamp — only include activity after this time`),last:L.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:L.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:L.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:L.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:L.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await Jt(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):qt(l,u)).digest}]}}catch(e){return pp.error(`Session digest failed`,I(e)),K(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}})}const hp=1e4,gp={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function _p(e){return e??gp}function vp(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function yp(e,t,n){let r=vp(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function bp(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function xp(e,t=!1,n){vp(e,`workspace`);let r=_p(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function Sp(e,t,n){let r=_p(n),i=xp(t.workspace,t.global??!1,r),a=yp(t.key,`key`,500),o=yp(t.value,`value`,hp),s=t.agent?yp(t.agent,`agent`,500):void 0,c=bp(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Cp(e,t,n){let r=vp(t,`workspace`),i=yp(n,`key`,500);return e.signalGet(r,i)}function wp(e,t){let n=vp(t,`workspace`);return e.signalList(n)}function Tp(e,t,n){let r=vp(t,`workspace`),i=n===void 0?void 0:yp(n,`key`,500);return e.signalClear(r,i)}function Ep(e,t,n){let r=_p(n),i=yp(t.resource,`resource`,500),a=yp(t.holder,`holder`,500),o=vp(t.workspace,`workspace`),s=t.intent?yp(t.intent,`intent`,hp):void 0,c=bp(t.ttlMinutes??r.defaultLeaseTtlMinutes,`ttlMinutes`);if(c>60)throw Error(`ttlMinutes exceeds max of 60`);let l=e.leaseAcquire(i,a,o,s,c),u=e.leaseGet(i,o);return u?{acquired:l,holder:u.holder,expiresAt:u.expiresAt}:{acquired:l}}function Dp(e,t,n,r){let i=vp(t,`workspace`),a=yp(n,`resource`,500),o=yp(r,`holder`,500);return e.leaseRelease(a,o,i)}function Op(e,t){let n=vp(t,`workspace`);return e.leaseList(n)}const kp=F(`tools:signal`);function Ap(e){return JSON.stringify(e,null,2)}function jp(e,t,n){let r=U(`signal`),i={...gp,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:L.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:L.string().describe(`Workspace identifier (required)`),key:L.string().optional().describe(`Signal key (for post/get/clear)`),value:L.string().optional().describe(`Signal value (for post)`),agent:L.string().optional().describe(`Agent identifier`),resource:L.string().optional().describe(`Resource path (for lease/unlease)`),holder:L.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:L.string().optional().describe(`What the holder plans to do`),ttl:L.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:L.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=Sp(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:Ap({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Cp(t,xp(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:Ap(e)}],structuredContent:{signals:e}}}case`list`:{let e=wp(t,xp(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:Ap(e)}],structuredContent:{signals:e}}}case`clear`:{let e=Tp(t,xp(n,d??!1,i),r);return{content:[{type:`text`,text:Ap({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=Ep(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:Ap(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=Dp(t,n,s,c);return{content:[{type:`text`,text:Ap({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=Op(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:Ap(e)}],structuredContent:{leases:e}}}}}catch(e){return kp.error(`Signal operation failed`,I(e)),K(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}})}const Mp=F(`tools`);function Np(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{Mp.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),Mp.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function Pp(e){return e.onboarded?e.indexStale?{kind:`reindex`,reason:`Index stale. Run reindex() to update.`}:e.contextPressure>70?{kind:`handoff`,reason:`Context pressure high. Consider session handoff.`}:{kind:`proceed`,reason:`Ready to work.`}:{kind:`onboard`,reason:`Index not initialized. Run onboard({ path: "." }) first.`}}function Fp(){let e=Bn.get(),t=zn.get();if(e)return`- **Tree-sitter (WASM)**: ✅ Available (${t.grammarCount} grammars, dir: ${t.wasmDir})`;let n=t.pathsChecked.length?t.pathsChecked.map(e=>` ${e.exists?`✓`:`✗`} ${e.path}`).join(`
2886
+ `),te=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+O,ne=dp(C,e),re=ne.length>0?`\n_Distinctive terms: ${ne.map(e=>`\`${e}\``).join(`, `)}_`:``,M=await pp(n,C),ie=[];if(C.length===0)ie.push("`reindex` — no results found, index may be stale"),ie.push("`find` — try federated search with glob/regex");else{let e=C[0]?.record.sourcePath;e&&ie.push(`\`lookup\` — see all chunks from \`${e}\``),ie.push("`symbol` — resolve a specific symbol from the results"),ie.push("`compact` — compress a result file for focused reading")}let N=[A?`${A}\n\n`:``,M?`${M}\n\n`:``,ee,`\n\n---\n_Search mode: ${te} | ${C.length} results_${re}`,`\n_Next: ${ie.join(` | `)}_`],ae=E+N.join(``);y&&(ae=sn(ae,y));let P=new Set,oe=[];for(let e of C){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=El(e.record.sourcePath);if(!t)continue;let n=wl(t,e.record.headingPath??t);n&&!P.has(n.uri)&&(P.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ae},...oe],structuredContent:{results:C.map(e=>({sourcePath:e.record.sourcePath,contentType:e.record.contentType,score:e.score,...e.record.headingPath?{headingPath:e.record.headingPath}:{},...e.record.startLine?{startLine:e.record.startLine}:{},...e.record.endLine?{endLine:e.record.endLine}:{},...e.record.origin===`indexed`?{}:{origin:e.record.origin},...e.record.category?{category:e.record.category}:{},...e.record.tags?.length?{tags:e.record.tags}:{}})),totalResults:C.length,searchMode:d,query:e}}}catch(e){return np.error(`Search failed`,I(e)),K(`INTERNAL`,`Search failed: ${e instanceof Error?e.message:String(e)}`)}})}const hp=F(`tools`);function gp(e,t,n){let r=U(`session_digest`);e.registerTool(`session_digest`,{title:r.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:L.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:L.string().optional().describe(`ISO timestamp — only include activity after this time`),last:L.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:L.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:L.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:L.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:L.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await Jt(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):qt(l,u)).digest}]}}catch(e){return hp.error(`Session digest failed`,I(e)),K(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}})}const _p=1e4,vp={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function yp(e){return e??vp}function bp(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function xp(e,t,n){let r=bp(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function Sp(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function Cp(e,t=!1,n){bp(e,`workspace`);let r=yp(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function wp(e,t,n){let r=yp(n),i=Cp(t.workspace,t.global??!1,r),a=xp(t.key,`key`,500),o=xp(t.value,`value`,_p),s=t.agent?xp(t.agent,`agent`,500):void 0,c=Sp(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Tp(e,t,n){let r=bp(t,`workspace`),i=xp(n,`key`,500);return e.signalGet(r,i)}function Ep(e,t){let n=bp(t,`workspace`);return e.signalList(n)}function Dp(e,t,n){let r=bp(t,`workspace`),i=n===void 0?void 0:xp(n,`key`,500);return e.signalClear(r,i)}function Op(e,t,n){let r=yp(n),i=xp(t.resource,`resource`,500),a=xp(t.holder,`holder`,500),o=bp(t.workspace,`workspace`),s=t.intent?xp(t.intent,`intent`,_p):void 0,c=Sp(t.ttlMinutes??r.defaultLeaseTtlMinutes,`ttlMinutes`);if(c>60)throw Error(`ttlMinutes exceeds max of 60`);let l=e.leaseAcquire(i,a,o,s,c),u=e.leaseGet(i,o);return u?{acquired:l,holder:u.holder,expiresAt:u.expiresAt}:{acquired:l}}function kp(e,t,n,r){let i=bp(t,`workspace`),a=xp(n,`resource`,500),o=xp(r,`holder`,500);return e.leaseRelease(a,o,i)}function Ap(e,t){let n=bp(t,`workspace`);return e.leaseList(n)}const jp=F(`tools:signal`);function Mp(e){return JSON.stringify(e,null,2)}function Np(e,t,n){let r=U(`signal`),i={...vp,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:L.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:L.string().describe(`Workspace identifier (required)`),key:L.string().optional().describe(`Signal key (for post/get/clear)`),value:L.string().optional().describe(`Signal value (for post)`),agent:L.string().optional().describe(`Agent identifier`),resource:L.string().optional().describe(`Resource path (for lease/unlease)`),holder:L.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:L.string().optional().describe(`What the holder plans to do`),ttl:L.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:L.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=wp(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:Mp({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Tp(t,Cp(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:Mp(e)}],structuredContent:{signals:e}}}case`list`:{let e=Ep(t,Cp(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:Mp(e)}],structuredContent:{signals:e}}}case`clear`:{let e=Dp(t,Cp(n,d??!1,i),r);return{content:[{type:`text`,text:Mp({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=Op(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:Mp(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=kp(t,n,s,c);return{content:[{type:`text`,text:Mp({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=Ap(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:Mp(e)}],structuredContent:{leases:e}}}}}catch(e){return jp.error(`Signal operation failed`,I(e)),K(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}})}const Pp=F(`tools`);function Fp(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{Pp.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),Pp.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function Ip(e){return e.onboarded?e.indexStale?{kind:`reindex`,reason:`Index stale. Run reindex() to update.`}:e.contextPressure>70?{kind:`handoff`,reason:`Context pressure high. Consider session handoff.`}:{kind:`proceed`,reason:`Ready to work.`}:{kind:`onboard`,reason:`Index not initialized. Run onboard({ path: "." }) first.`}}function Lp(){let e=Bn.get(),t=zn.get();if(e)return`- **Tree-sitter (WASM)**: ✅ Available (${t.grammarCount} grammars, dir: ${t.wasmDir})`;let n=t.pathsChecked.length?t.pathsChecked.map(e=>` ${e.exists?`✓`:`✗`} ${e.path}`).join(`
2887
2887
  `):` none`,r=t.healAttempted?` Auto-heal: ${t.healSuccess?`✓ succeeded`:`✗ failed (${t.healError??`unknown`})`}`:` Auto-heal: not attempted`;return[`- **Tree-sitter (WASM)**: ⚠ Unavailable (regex fallback)`,` Reason: ${t.reason||`unknown`}`,` Paths checked:`,n,r,` OS: ${t.os} ${t.arch} | Node: ${t.nodeVersion}`,` Fix: Reinstall package or run vendor:wasm script`].join(`
2888
- `)}const Ip=5*6e4;let Lp=null,Rp=null;function zp(e,t,n,r){let i=Math.min(e/2e4,1),a=Math.min((t+n)/5e4,1),o=Math.min(r/200,1);return Math.round(i*40+a*35+o*25)}function Bp(){let e=Date.now();if(Lp&&e-Lp.ts<Ip)return Lp.value;try{let t=P(Sn(),`.copilot`,`.aikit-scaffold.json`);if(!D(t))return Lp={value:null,ts:e},null;let n=JSON.parse(k(t,`utf-8`)).version??null;return Lp={value:n,ts:e},n}catch{return Lp={value:null,ts:e},null}}function Vp(){let e=Date.now();if(Rp&&e-Rp.ts<Ip)return Rp.value;try{let t=P(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!D(t))return Rp={value:null,ts:e},null;let n=JSON.parse(k(t,`utf-8`)).version??null;return Rp={value:n,ts:e},n}catch{return Rp={value:null,ts:e},null}}function Hp(e){let t=U(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:po,annotations:t.annotations},async()=>{let e=b(),t=Bp(),n=Vp(),r=t!=null&&t!==e,i=n!=null&&n!==e,a=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${Bn.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||i){let o=x(),s=[];r&&s.push(`user scaffold v${t}`),i&&s.push(`workspace scaffold v${n}`);let c=s.join(`, `);o.state===`success`?a.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${c} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):o.state===`pending`?a.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade is running in the background…`):o.state===`failed`?(y(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(y(),a.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade triggered — check again shortly.`))}let o={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:Pp({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
2889
- `)}],structuredContent:o}})}function Up(e,t,n,r,i,a,o,s){let c=U(`status`);e.registerTool(`status`,{title:c.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:po,annotations:c.annotations},async()=>{let e=[];try{let[c,l]=await Promise.all([Np(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),Np(t.listSourcePaths(),[],`store.listSourcePaths`)]),u=c.value;c.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let d=l.value;l.timedOut&&e.push(`⚠ File listing timed out`);let f=null,p=0,m=[`## AI Kit Status`,``,`- **Total Records**: ${u.totalRecords}`,`- **Total Files**: ${u.totalFiles}`,`- **Last Indexed**: ${u.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(u.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...d.slice(0,50).map(e=>`- ${e}`),d.length>50?`\n... and ${d.length-50} more files`:``];if(n)try{let t=await Np(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),m.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;f={nodes:e.nodeCount,edges:e.edgeCount},m.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await Np(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||m.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&m.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{m.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let h=a?.onboardDir??``,g=D(h),_=i?.onboardComplete||g;if(m.push(``,`### Onboard Status`,_?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${h}\``),r)try{let t=await Np(r.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),m.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;p=e.length,m.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{m.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let v=zp(u.totalRecords,f?.nodes??0,f?.edges??0,p),S=u.lastIndexedAt?new Date(u.lastIndexedAt).getTime():0,C=S>0?Date.now()-S:1/0,w=Pp({onboarded:_,indexStale:_&&C>1440*60*1e3,contextPressure:v});m.push(``),m.push(`## 📊 Context Pressure: ${v}/100`),v>=80?m.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):v>=50?m.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):m.push(`✅ Low pressure — plenty of headroom for more content.`);let T=0;if(u.lastIndexedAt){T=new Date(u.lastIndexedAt).getTime();let e=(Date.now()-T)/(1e3*60*60);m.push(``,`### Index Freshness`,e>24?o===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}m.push(``,`### Next Action`,`- **${w.kind}**: ${w.reason}`);let E=null,O=t;if(typeof O.getDiagnostics==`function`)try{E=O.getDiagnostics(),m.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${E.adapterType}`,`- **Vector search**: ${E.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,E.dbPath?`- **DB**: ${E.dbPath}`:``,E.dbSizeBytes==null?``:`- **DB size**: ${(E.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${E.embeddingDim}`,`- **Vector dtype**: ${E.vectorDtype}`)}catch{}if(o===`smart`)if(m.push(``,`### Smart Indexing`),s){let e=s();e?m.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):m.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else m.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=a?.stateDir?N(a.stateDir,`stash`):null;if(e&&D(e)){let t=te(e).mtimeMs;t>T&&(T=t)}}catch{}let e=[];if(r)try{let t=p>0?await r.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>T&&(T=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=T>0?Date.now()-T:0;if(t>=144e5){let n=Math.floor(t/36e5);if(m.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){m.push(`**Recent decisions/notes:**`);for(let t of e)m.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}m.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}m.push(``,`### Runtime`,Fp());let k=Bp(),A=Vp(),j=b(),ee=k!=null&&k!==j,ne=A!=null&&A!==j;if(ee||ne){let e=x(),t=[];ee&&t.push(`user scaffold v${k}`),ne&&t.push(`workspace scaffold v${A}`);let n=t.join(`, `);e.state===`success`?m.push(``,`### ✅ Upgrade Applied`,`- Server v${j} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?m.push(``,`### ⏳ Upgrade In Progress`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(y(),m.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${j} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(y(),m.push(``,`### ⬆ Upgrade Available`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&m.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let re=xa();if(re.length>0){let e=re.sort((e,t)=>t.callCount-e.callCount);m.push(``,`### Tool Usage This Session`,``),m.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),m.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);m.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=pa();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;m.push(``,`### Auto-GC: ${e} ${M.state}`),m.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&m.push(`- GC cycles triggered: ${M.gcCount}`)}let ie=m.join(`
2890
- `),ae={totalRecords:u.totalRecords,totalFiles:u.totalFiles,lastIndexedAt:u.lastIndexedAt??null,onboarded:_,onboardDir:h,contentTypes:u.contentTypeBreakdown,wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:f,curatedCount:p,serverVersion:j,scaffoldVersion:k??null,workspaceScaffoldVersion:A??null,upgradeAvailable:ee||ne,storeBackend:a?.store?.backend,storeDiagnostics:E??null,contextPressure:v,nextAction:w};return{content:[{type:`text`,text:ie+(o===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:ae}}catch(e){return Mp.error(`Status failed`,I(e)),K(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}})}const Wp=F(`tools`);function Gp(e){let t=U(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:L.array(L.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:L.number().min(1).max(20).default(5).describe(`Max results per query`),site:L.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:L.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await fn({query:e,limit:t,site:n,provider:r}),a=[`## Search: ${i.query} _(via ${i.provider})_`,``];if(i.results.length===0)a.push(`No results found.`);else for(let e of i.results)a.push(`### [${e.title}](${e.url})`,e.snippet,``);return a.join(`
2891
- `)};if(i.length===1)try{return{content:[{type:`text`,text:`${await a(i[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return Wp.error(`Web search failed`,I(e)),K(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Wp.error(`Web search failed`,{query:i[e],error:n}),s.push(`## ❌ Search failed: ${i[e]}\n\n${n}`)}}let l=`_Searched ${o.length-c}/${o.length} queries successfully._`;s.push(``,`---`,l,"_Next: Use `web_fetch` to read any of these pages in full._");let u=s.join(`
2888
+ `)}const Rp=5*6e4;let zp=null,Bp=null;function Vp(e,t,n,r){let i=Math.min(e/2e4,1),a=Math.min((t+n)/5e4,1),o=Math.min(r/200,1);return Math.round(i*40+a*35+o*25)}function Hp(){let e=Date.now();if(zp&&e-zp.ts<Rp)return zp.value;try{let t=P(Sn(),`.copilot`,`.aikit-scaffold.json`);if(!D(t))return zp={value:null,ts:e},null;let n=JSON.parse(k(t,`utf-8`)).version??null;return zp={value:n,ts:e},n}catch{return zp={value:null,ts:e},null}}function Up(){let e=Date.now();if(Bp&&e-Bp.ts<Rp)return Bp.value;try{let t=P(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!D(t))return Bp={value:null,ts:e},null;let n=JSON.parse(k(t,`utf-8`)).version??null;return Bp={value:n,ts:e},n}catch{return Bp={value:null,ts:e},null}}function Wp(e){let t=U(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:po,annotations:t.annotations},async()=>{let e=b(),t=Hp(),n=Up(),r=t!=null&&t!==e,i=n!=null&&n!==e,a=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${Bn.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||i){let o=x(),s=[];r&&s.push(`user scaffold v${t}`),i&&s.push(`workspace scaffold v${n}`);let c=s.join(`, `);o.state===`success`?a.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${c} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):o.state===`pending`?a.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade is running in the background…`):o.state===`failed`?(y(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(y(),a.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade triggered — check again shortly.`))}let o={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:Ip({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
2889
+ `)}],structuredContent:o}})}function Gp(e,t,n,r,i,a,o,s){let c=U(`status`);e.registerTool(`status`,{title:c.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:po,annotations:c.annotations},async()=>{let e=[];try{let[c,l]=await Promise.all([Fp(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),Fp(t.listSourcePaths(),[],`store.listSourcePaths`)]),u=c.value;c.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let d=l.value;l.timedOut&&e.push(`⚠ File listing timed out`);let f=null,p=0,m=[`## AI Kit Status`,``,`- **Total Records**: ${u.totalRecords}`,`- **Total Files**: ${u.totalFiles}`,`- **Last Indexed**: ${u.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(u.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...d.slice(0,50).map(e=>`- ${e}`),d.length>50?`\n... and ${d.length-50} more files`:``];if(n)try{let t=await Fp(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),m.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;f={nodes:e.nodeCount,edges:e.edgeCount},m.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await Fp(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||m.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&m.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{m.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let h=a?.onboardDir??``,g=D(h),_=i?.onboardComplete||g;if(m.push(``,`### Onboard Status`,_?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${h}\``),r)try{let t=await Fp(r.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),m.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;p=e.length,m.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{m.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let v=Vp(u.totalRecords,f?.nodes??0,f?.edges??0,p),S=u.lastIndexedAt?new Date(u.lastIndexedAt).getTime():0,C=S>0?Date.now()-S:1/0,w=Ip({onboarded:_,indexStale:_&&C>1440*60*1e3,contextPressure:v});m.push(``),m.push(`## 📊 Context Pressure: ${v}/100`),v>=80?m.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):v>=50?m.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):m.push(`✅ Low pressure — plenty of headroom for more content.`);let T=0;if(u.lastIndexedAt){T=new Date(u.lastIndexedAt).getTime();let e=(Date.now()-T)/(1e3*60*60);m.push(``,`### Index Freshness`,e>24?o===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}m.push(``,`### Next Action`,`- **${w.kind}**: ${w.reason}`);let E=null,O=t;if(typeof O.getDiagnostics==`function`)try{E=O.getDiagnostics(),m.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${E.adapterType}`,`- **Vector search**: ${E.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,E.dbPath?`- **DB**: ${E.dbPath}`:``,E.dbSizeBytes==null?``:`- **DB size**: ${(E.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${E.embeddingDim}`,`- **Vector dtype**: ${E.vectorDtype}`)}catch{}if(o===`smart`)if(m.push(``,`### Smart Indexing`),s){let e=s();e?m.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):m.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else m.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=a?.stateDir?N(a.stateDir,`stash`):null;if(e&&D(e)){let t=te(e).mtimeMs;t>T&&(T=t)}}catch{}let e=[];if(r)try{let t=p>0?await r.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>T&&(T=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=T>0?Date.now()-T:0;if(t>=144e5){let n=Math.floor(t/36e5);if(m.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){m.push(`**Recent decisions/notes:**`);for(let t of e)m.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}m.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}m.push(``,`### Runtime`,Lp());let k=Hp(),A=Up(),j=b(),ee=k!=null&&k!==j,ne=A!=null&&A!==j;if(ee||ne){let e=x(),t=[];ee&&t.push(`user scaffold v${k}`),ne&&t.push(`workspace scaffold v${A}`);let n=t.join(`, `);e.state===`success`?m.push(``,`### ✅ Upgrade Applied`,`- Server v${j} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?m.push(``,`### ⏳ Upgrade In Progress`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(y(),m.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${j} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(y(),m.push(``,`### ⬆ Upgrade Available`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&m.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let re=xa();if(re.length>0){let e=re.sort((e,t)=>t.callCount-e.callCount);m.push(``,`### Tool Usage This Session`,``),m.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),m.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);m.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=pa();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;m.push(``,`### Auto-GC: ${e} ${M.state}`),m.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&m.push(`- GC cycles triggered: ${M.gcCount}`)}let ie=m.join(`
2890
+ `),ae={totalRecords:u.totalRecords,totalFiles:u.totalFiles,lastIndexedAt:u.lastIndexedAt??null,onboarded:_,onboardDir:h,contentTypes:u.contentTypeBreakdown,wasmAvailable:!!Bn.get(),wasmDiagnostics:zn.get(),graphStats:f,curatedCount:p,serverVersion:j,scaffoldVersion:k??null,workspaceScaffoldVersion:A??null,upgradeAvailable:ee||ne,storeBackend:a?.store?.backend,storeDiagnostics:E??null,contextPressure:v,nextAction:w};return{content:[{type:`text`,text:ie+(o===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:ae}}catch(e){return Pp.error(`Status failed`,I(e)),K(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}})}const Kp=F(`tools`);function qp(e){let t=U(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:L.array(L.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:L.number().min(1).max(20).default(5).describe(`Max results per query`),site:L.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:L.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await fn({query:e,limit:t,site:n,provider:r}),a=[`## Search: ${i.query} _(via ${i.provider})_`,``];if(i.results.length===0)a.push(`No results found.`);else for(let e of i.results)a.push(`### [${e.title}](${e.url})`,e.snippet,``);return a.join(`
2891
+ `)};if(i.length===1)try{return{content:[{type:`text`,text:`${await a(i[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return Kp.error(`Web search failed`,I(e)),K(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Kp.error(`Web search failed`,{query:i[e],error:n}),s.push(`## ❌ Search failed: ${i[e]}\n\n${n}`)}}let l=`_Searched ${o.length-c}/${o.length} queries successfully._`;s.push(``,`---`,l,"_Next: Use `web_fetch` to read any of these pages in full._");let u=s.join(`
2892
2892
 
2893
- `);return c===o.length?K(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function Kp(e){let t=U(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:L.string().url().describe(`Request URL (http/https only)`),method:L.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:L.record(L.string(),L.string()).optional().describe(`Request headers as key-value pairs`),body:L.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:L.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await st({url:e,method:t,headers:n,body:r,timeout:i}),o=[`## ${t} ${e}`,``,`**Status:** ${a.status} ${a.statusText}`,`**Time:** ${a.durationMs}ms`,`**Size:** ${a.sizeBytes} bytes`,`**Content-Type:** ${a.contentType}`,``,`### Headers`,"```json",JSON.stringify(a.headers),"```",``,`### Body`,a.contentType.includes(`json`)?"```json":"```",a.body,"```"];return a.truncated&&o.push(``,`_Response truncated — total size: ${a.sizeBytes} bytes_`),{content:[{type:`text`,text:o.join(`
2894
- `)}]}}catch(e){return Wp.error(`HTTP request failed`,I(e)),K(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}})}function qp(e){let t=U(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:L.string().max(500).describe(`Regex pattern (without delimiters)`),flags:L.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:L.array(L.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:L.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:L.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=Ft({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return K(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
2895
- `)}]}})}function Jp(e){let t=U(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:L.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:L.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=We({operation:e,input:t});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${t.length>100?`${t.slice(0,100)}...`:t}\`\n**Output:**\n\`\`\`\n${n.output}\n\`\`\``}]}}catch(e){return Wp.error(`Encode failed`,I(e)),K(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}})}function Yp(e){let t=U(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:ho,inputSchema:{path:L.string().describe(`File or directory path to measure`),extensions:L.array(L.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await _t({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r.join(`
2896
- `)}],structuredContent:i}}catch(e){return Wp.error(`Measure failed`,I(e)),K(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}})}function Xp(e){let t=U(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:L.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:L.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:L.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:L.boolean().default(!0).describe(`Highlight breaking changes`),cwd:L.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Te({from:e,to:t,format:n,includeBreaking:r,cwd:i}),o=`${a.stats.total} commits (${Object.entries(a.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${a.markdown}\n---\n_${o}_`}]}}catch(e){return Wp.error(`Changelog failed`,I(e)),K(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}})}function Zp(e){let t=U(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:L.string().max(5e5).describe(`JSON data to validate (as string)`),schema:L.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Gt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
2893
+ `);return c===o.length?K(`INTERNAL`,u):{content:[{type:`text`,text:u}]}})}function Jp(e){let t=U(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:L.string().url().describe(`Request URL (http/https only)`),method:L.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:L.record(L.string(),L.string()).optional().describe(`Request headers as key-value pairs`),body:L.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:L.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await st({url:e,method:t,headers:n,body:r,timeout:i}),o=[`## ${t} ${e}`,``,`**Status:** ${a.status} ${a.statusText}`,`**Time:** ${a.durationMs}ms`,`**Size:** ${a.sizeBytes} bytes`,`**Content-Type:** ${a.contentType}`,``,`### Headers`,"```json",JSON.stringify(a.headers),"```",``,`### Body`,a.contentType.includes(`json`)?"```json":"```",a.body,"```"];return a.truncated&&o.push(``,`_Response truncated — total size: ${a.sizeBytes} bytes_`),{content:[{type:`text`,text:o.join(`
2894
+ `)}]}}catch(e){return Kp.error(`HTTP request failed`,I(e)),K(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}})}function Yp(e){let t=U(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:L.string().max(500).describe(`Regex pattern (without delimiters)`),flags:L.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:L.array(L.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:L.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:L.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=Ft({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return K(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
2895
+ `)}]}})}function Xp(e){let t=U(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:L.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:L.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=We({operation:e,input:t});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${t.length>100?`${t.slice(0,100)}...`:t}\`\n**Output:**\n\`\`\`\n${n.output}\n\`\`\``}]}}catch(e){return Kp.error(`Encode failed`,I(e)),K(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}})}function Zp(e){let t=U(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:ho,inputSchema:{path:L.string().describe(`File or directory path to measure`),extensions:L.array(L.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await _t({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r.join(`
2896
+ `)}],structuredContent:i}}catch(e){return Kp.error(`Measure failed`,I(e)),K(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}})}function Qp(e){let t=U(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:L.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:L.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:L.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:L.boolean().default(!0).describe(`Highlight breaking changes`),cwd:L.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Te({from:e,to:t,format:n,includeBreaking:r,cwd:i}),o=`${a.stats.total} commits (${Object.entries(a.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${a.markdown}\n---\n_${o}_`}]}}catch(e){return Kp.error(`Changelog failed`,I(e)),K(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}})}function $p(e){let t=U(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:L.string().max(5e5).describe(`JSON data to validate (as string)`),schema:L.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Gt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
2897
2897
 
2898
2898
  Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${n.errors.length} error(s):**`,``];for(let e of n.errors){let t=e.expected?` (expected: ${e.expected}, got: ${e.received})`:``;r.push(`- \`${e.path}\`: ${e.message}${t}`)}return{content:[{type:`text`,text:r.join(`
2899
- `)}]}}catch(e){return Wp.error(`Schema validation failed`,I(e)),K(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}})}function Qp(e){let t=U(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:go,inputSchema:{include_env:L.boolean().default(!1).describe(`Include environment variables`),filter_env:L.string().optional().describe(`Filter env vars by name substring`),show_sensitive:L.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Ke({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
2900
- `)}],structuredContent:a}})}function $p(e){let t=U(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:_o,inputSchema:{operation:L.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:L.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:L.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:L.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=an({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
2901
- `)}],structuredContent:o}}catch(e){return Wp.error(`Time failed`,I(e)),K(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}})}function em(e){try{let t=N(e,`.flows`);if(!D(t))return null;let n=A(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=N(t,e.name,`meta.json`);if(D(n)&&JSON.parse(k(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function tm(e,t,n,r,i,a,o,s,c,l){let u=new oa,d=n.sources[0]?.path??process.cwd(),f={activeSlug:null};f.activeSlug=em(d);let p=new Ei(N(n.stateDir??``,`flow-context`),()=>f.activeSlug),m=new _i;m.register(mi),m.register(Vr),m.register(di),m.register(Rr),m.register(Pr),m.register(Fr),m.register(gi),m.register(ui(()=>f.activeSlug?{active:!0,slug:f.activeSlug}:null));let h=new Si(m,t.curated,{},p),g=l??lo(n,[...La,...ja],H,Na(n)),_=e=>g.has(e),v=new Set([...g].filter(e=>!Nu.includes(e)&&!Ki.has(e))),y=new Xi;u.use(bi(h),{order:5,name:`auto-knowledge`}),u.use(Ca(),{order:10,name:`replay`}),u.use($i(y,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:v}),{order:94,name:`procedural-memory`}),u.use(Hi(new Bi(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(za(),{order:1,name:`structured-content-guard`}),u.use(Ti(wi(n.tokenBudget)),{order:90,name:`compression`}),Ja(e,u,n.toolPrefix??``);let b=[...g].filter(e=>Ma.has(e)?Aa.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);_(`search`)&&fp(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a,t.stateStore,n.memory?.retention,n.memory?.consolidation);let x={store:t.store,graphStore:t.graphStore,embedder:t.embedder},S=c?e=>{c()?.prioritize(e)}:void 0;_(`lookup`)&&wu(e,t.store,x);let C={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};_(`status`)&&Up(e,t.store,t.graphStore,t.curated,C,n,o,s),_(`config`)&&Xs(e,n),_(`reindex`)&&Kf(e,t.indexer,n,t.curated,t.store,i,o),_(`knowledge`)&&Su(e,t.curated,t.policyStore,t.evolutionCollector,i,p,t.stateStore,n.memory?.retention,n.memory?.supersession,n.memory?.consolidation,n.memory?.lessons),_(`analyze`)&&vs(e,t.store,t.embedder,x),_(`blast_radius`)&&ys(e,t.store,t.embedder,t.graphStore,x),_(`produce_knowledge`)&&Wf(e,n),_(`onboard`)&&zu(e,t.store,t.embedder,n,C,x),_(`graph`)&&pl(e,t.graphStore),_(`audit`)&&ws(e,t.store,t.embedder,n.tokenBudget),_(`compact`)&&sc(e,t.embedder,t.fileCache,d,n.allRoots,x,S),_(`scope_map`)&&cc(e,t.embedder,t.store,x),_(`find`)&&lc(e,t.embedder,t.store,d,x),_(`parse_output`)&&Cc(e),_(`workset`)&&Vu(e),_(`check`)&&bc(e,x,n.tokenBudget),_(`symbol`)&&uc(e,t.embedder,t.store,t.graphStore),_(`eval`)&&xc(e),_(`test_run`)&&Sc(e,x),_(`stash`)&&Hu(e,t.stateStore),_(`signal`)&&jp(e,t.stateStore),_(`git_context`)&&Eu(e),_(`diff_parse`)&&Du(e),_(`rename`)&&Ou(e),_(`codemod`)&&ku(e),_(`restore`)&&Xf(e),_(`file_summary`)&&dc(e,t.fileCache,d,n.allRoots,x,S),_(`checkpoint`)&&Uu(e,t.stateStore),_(`data_transform`)&&Au(e),_(`trace`)&&fc(e,t.embedder,t.store,t.graphStore),_(`process`)&&hl(e),_(`watch`)&&gl(e),_(`dead_symbols`)&&pc(e,t.embedder,t.store,d,n.allRoots,x),_(`delegate`)&&wc(e,a),_(`health`)&&_l(e),_(`lane`)&&Wu(e),_(`queue`)&&Gu(e),_(`web_fetch`)&&vl(e),_(`guide`)&&yl(e,o),Nu.some(e=>_(e))&&Pu(e,n,b),_(`evidence_map`)&&al(e),_(`digest`)&&ol(e,t.embedder),_(`forge_classify`)&&sl(e),_(`stratum_card`)&&cl(e,t.embedder,t.fileCache),_(`forge_ground`)&&ll(e,t.embedder,t.store),_(`present`)&&Hf(e,r),_(`browser`)&&An(e,n),_(`web_search`)&&Gp(e),_(`http`)&&Kp(e),_(`regex_test`)&&qp(e),_(`encode`)&&Jp(e),_(`measure`)&&Yp(e),_(`changelog`)&&Xp(e),_(`schema_validate`)&&Zp(e),_(`env`)&&Qp(e),_(`time`)&&$p(e),_(`flow`)&&rl(e,n,e=>{f.activeSlug=e}),t.bridge&&Aa.some(e=>_(e))&&(Os(e,t.bridge,t.evolutionCollector),ks(e,t.bridge),As(e,t.bridge)),t.policyStore&&_(`er_update_policy`)&&Zu(e,t.policyStore),t.evolutionCollector&&_(`er_evolve_review`)&&vc(e,t.evolutionCollector),ka(e,t.store,t.curated),_(`replay`)&&Jf(e),_(`session_digest`)&&mp(e,t.stateStore,a)}function nm(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&bc(e,void 0,t.tokenBudget),r(`eval`)&&xc(e),r(`test_run`)&&Sc(e),r(`parse_output`)&&Cc(e),r(`delegate`)&&wc(e),r(`git_context`)&&Eu(e),r(`diff_parse`)&&Du(e),r(`rename`)&&Ou(e),r(`codemod`)&&ku(e),r(`data_transform`)&&Au(e),r(`workset`)&&Vu(e),r(`restore`)&&Xf(e),r(`lane`)&&Wu(e),r(`queue`)&&Gu(e),r(`session_digest`)&&mp(e),r(`health`)&&_l(e),r(`process`)&&hl(e),r(`watch`)&&gl(e),r(`web_fetch`)&&vl(e),r(`guide`)&&yl(e),Nu.some(e=>r(e))&&Pu(e,t,[...n??new Set(La)]),r(`evidence_map`)&&al(e),r(`forge_classify`)&&sl(e),r(`present`)&&Hf(e),r(`browser`)&&An(e,t),r(`produce_knowledge`)&&Wf(e),r(`replay`)&&Jf(e),r(`status`)&&Hp(e),r(`flow`)&&rl(e,t),r(`web_search`)&&Gp(e),r(`http`)&&Kp(e),r(`regex_test`)&&qp(e),r(`encode`)&&Jp(e),r(`measure`)&&Yp(e),r(`changelog`)&&Xp(e),r(`schema_validate`)&&Zp(e),r(`env`)&&Qp(e),r(`time`)&&$p(e)}const rm=F(`resource-notifier`);var im=class{mcpServer;constructor(e){this.mcpServer=e}async notifyStatusChanged(){await this.sendUpdate(`aikit://status`)}async notifyFileTreeChanged(){await this.sendUpdate(`aikit://file-tree`)}async notifyCuratedIndexChanged(){await this.sendUpdate(`aikit://curated`)}async notifyCuratedEntryChanged(e){await this.sendUpdate(`aikit://curated/${e}`)}async notifyResourceListChanged(){try{await this.mcpServer.server.sendResourceListChanged()}catch(e){rm.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyAfterReindex(){await Promise.allSettled([this.notifyStatusChanged(),this.notifyFileTreeChanged()])}async notifyAfterCuratedWrite(e){let t=[this.notifyStatusChanged(),this.notifyCuratedIndexChanged()];e&&t.push(this.notifyCuratedEntryChanged(e)),await Promise.allSettled(t)}async sendUpdate(e){try{await this.mcpServer.server.sendResourceUpdated({uri:e})}catch(t){rm.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=F(`server`);async function am(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=null;if(r===`sqlite-vec`){let e=N(i,`aikit.db`);D(i)||O(i,{recursive:!0}),a=await $n(e),Z.info(`SQLite adapter ready`,{type:a.type,vectorCapable:a.vectorCapable,dbPath:e}),a.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
2899
+ `)}]}}catch(e){return Kp.error(`Schema validation failed`,I(e)),K(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}})}function em(e){let t=U(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:go,inputSchema:{include_env:L.boolean().default(!1).describe(`Include environment variables`),filter_env:L.string().optional().describe(`Filter env vars by name substring`),show_sensitive:L.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Ke({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
2900
+ `)}],structuredContent:a}})}function tm(e){let t=U(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:_o,inputSchema:{operation:L.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:L.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:L.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:L.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=an({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
2901
+ `)}],structuredContent:o}}catch(e){return Kp.error(`Time failed`,I(e)),K(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}})}function nm(e){try{let t=N(e,`.flows`);if(!D(t))return null;let n=A(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=N(t,e.name,`meta.json`);if(D(n)&&JSON.parse(k(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function rm(e,t,n,r,i,a,o,s,c,l){let u=new oa,d=n.sources[0]?.path??process.cwd(),f={activeSlug:null};f.activeSlug=nm(d);let p=new Ei(N(n.stateDir??``,`flow-context`),()=>f.activeSlug),m=new _i;m.register(mi),m.register(Vr),m.register(di),m.register(Rr),m.register(Pr),m.register(Fr),m.register(gi),m.register(ui(()=>f.activeSlug?{active:!0,slug:f.activeSlug}:null));let h=new Si(m,t.curated,{},p),g=l??lo(n,[...La,...ja],H,Na(n)),_=e=>g.has(e),v=new Set([...g].filter(e=>!Nu.includes(e)&&!Ki.has(e))),y=new Xi;u.use(bi(h),{order:5,name:`auto-knowledge`}),u.use(Ca(),{order:10,name:`replay`}),u.use($i(y,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:v}),{order:94,name:`procedural-memory`}),u.use(Hi(new Bi(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(za(),{order:1,name:`structured-content-guard`}),u.use(Ti(wi(n.tokenBudget)),{order:90,name:`compression`}),Ja(e,u,n.toolPrefix??``);let b=[...g].filter(e=>Ma.has(e)?Aa.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);_(`search`)&&mp(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a,t.stateStore,n.memory?.retention,n.memory?.consolidation);let x={store:t.store,graphStore:t.graphStore,embedder:t.embedder},S=c?e=>{c()?.prioritize(e)}:void 0;_(`lookup`)&&wu(e,t.store,x);let C={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};_(`status`)&&Gp(e,t.store,t.graphStore,t.curated,C,n,o,s),_(`config`)&&Xs(e,n),_(`reindex`)&&Jf(e,t.indexer,n,t.curated,t.store,i,o),_(`knowledge`)&&Su(e,t.curated,t.policyStore,t.evolutionCollector,i,p,t.stateStore,n.memory?.retention,n.memory?.supersession,n.memory?.consolidation,n.memory?.lessons),_(`analyze`)&&vs(e,t.store,t.embedder,x),_(`blast_radius`)&&ys(e,t.store,t.embedder,t.graphStore,x),_(`produce_knowledge`)&&Kf(e,n),_(`onboard`)&&zu(e,t.store,t.embedder,n,C,x),_(`graph`)&&pl(e,t.graphStore),_(`audit`)&&ws(e,t.store,t.embedder,n.tokenBudget),_(`compact`)&&sc(e,t.embedder,t.fileCache,d,n.allRoots,x,S),_(`scope_map`)&&cc(e,t.embedder,t.store,x),_(`find`)&&lc(e,t.embedder,t.store,d,x),_(`parse_output`)&&Cc(e),_(`workset`)&&Vu(e),_(`check`)&&bc(e,x,n.tokenBudget),_(`symbol`)&&uc(e,t.embedder,t.store,t.graphStore),_(`eval`)&&xc(e),_(`test_run`)&&Sc(e,x),_(`stash`)&&Hu(e,t.stateStore),_(`signal`)&&Np(e,t.stateStore),_(`git_context`)&&Eu(e),_(`diff_parse`)&&Du(e),_(`rename`)&&Ou(e),_(`codemod`)&&ku(e),_(`restore`)&&Qf(e),_(`file_summary`)&&dc(e,t.fileCache,d,n.allRoots,x,S),_(`checkpoint`)&&Uu(e,t.stateStore),_(`data_transform`)&&Au(e),_(`trace`)&&fc(e,t.embedder,t.store,t.graphStore),_(`process`)&&hl(e),_(`watch`)&&gl(e),_(`dead_symbols`)&&pc(e,t.embedder,t.store,d,n.allRoots,x),_(`delegate`)&&wc(e,a),_(`health`)&&_l(e),_(`lane`)&&Wu(e),_(`queue`)&&Gu(e),_(`web_fetch`)&&vl(e),_(`guide`)&&yl(e,o),Nu.some(e=>_(e))&&Pu(e,n,b),_(`evidence_map`)&&al(e),_(`digest`)&&ol(e,t.embedder),_(`forge_classify`)&&sl(e),_(`stratum_card`)&&cl(e,t.embedder,t.fileCache),_(`forge_ground`)&&ll(e,t.embedder,t.store),_(`present`)&&Wf(e,r),_(`browser`)&&An(e,n),_(`web_search`)&&qp(e),_(`http`)&&Jp(e),_(`regex_test`)&&Yp(e),_(`encode`)&&Xp(e),_(`measure`)&&Zp(e),_(`changelog`)&&Qp(e),_(`schema_validate`)&&$p(e),_(`env`)&&em(e),_(`time`)&&tm(e),_(`flow`)&&rl(e,n,e=>{f.activeSlug=e}),t.bridge&&Aa.some(e=>_(e))&&(Os(e,t.bridge,t.evolutionCollector),ks(e,t.bridge),As(e,t.bridge)),t.policyStore&&_(`er_update_policy`)&&Zu(e,t.policyStore),t.evolutionCollector&&_(`er_evolve_review`)&&vc(e,t.evolutionCollector),ka(e,t.store,t.curated),_(`replay`)&&Xf(e),_(`session_digest`)&&gp(e,t.stateStore,a)}function im(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&bc(e,void 0,t.tokenBudget),r(`eval`)&&xc(e),r(`test_run`)&&Sc(e),r(`parse_output`)&&Cc(e),r(`delegate`)&&wc(e),r(`git_context`)&&Eu(e),r(`diff_parse`)&&Du(e),r(`rename`)&&Ou(e),r(`codemod`)&&ku(e),r(`data_transform`)&&Au(e),r(`workset`)&&Vu(e),r(`restore`)&&Qf(e),r(`lane`)&&Wu(e),r(`queue`)&&Gu(e),r(`session_digest`)&&gp(e),r(`health`)&&_l(e),r(`process`)&&hl(e),r(`watch`)&&gl(e),r(`web_fetch`)&&vl(e),r(`guide`)&&yl(e),Nu.some(e=>r(e))&&Pu(e,t,[...n??new Set(La)]),r(`evidence_map`)&&al(e),r(`forge_classify`)&&sl(e),r(`present`)&&Wf(e),r(`browser`)&&An(e,t),r(`produce_knowledge`)&&Kf(e),r(`replay`)&&Xf(e),r(`status`)&&Wp(e),r(`flow`)&&rl(e,t),r(`web_search`)&&qp(e),r(`http`)&&Jp(e),r(`regex_test`)&&Yp(e),r(`encode`)&&Xp(e),r(`measure`)&&Zp(e),r(`changelog`)&&Qp(e),r(`schema_validate`)&&$p(e),r(`env`)&&em(e),r(`time`)&&tm(e)}const am=F(`resource-notifier`);var om=class{mcpServer;constructor(e){this.mcpServer=e}async notifyStatusChanged(){await this.sendUpdate(`aikit://status`)}async notifyFileTreeChanged(){await this.sendUpdate(`aikit://file-tree`)}async notifyCuratedIndexChanged(){await this.sendUpdate(`aikit://curated`)}async notifyCuratedEntryChanged(e){await this.sendUpdate(`aikit://curated/${e}`)}async notifyResourceListChanged(){try{await this.mcpServer.server.sendResourceListChanged()}catch(e){am.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyAfterReindex(){await Promise.allSettled([this.notifyStatusChanged(),this.notifyFileTreeChanged()])}async notifyAfterCuratedWrite(e){let t=[this.notifyStatusChanged(),this.notifyCuratedIndexChanged()];e&&t.push(this.notifyCuratedEntryChanged(e)),await Promise.allSettled(t)}async sendUpdate(e){try{await this.mcpServer.server.sendResourceUpdated({uri:e})}catch(t){am.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Z=F(`server`);async function sm(n){Z.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=null;if(r===`sqlite-vec`){let e=N(i,`aikit.db`);D(i)||O(i,{recursive:!0}),a=await $n(e),Z.info(`SQLite adapter ready`,{type:a.type,vectorCapable:a.vectorCapable,dbPath:e}),a.vectorCapable||Z.warn(`┌──────────────────────────────────────────────────────────────────┐
2902
2902
  │ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
2903
2903
  │ Vector search is disabled. Hybrid search returns FTS only. │
2904
2904
  │ To enable: install/rebuild better-sqlite3 (native module). │
2905
- └──────────────────────────────────────────────────────────────────┘`);let t=N(i,`lance`);D(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let o;if(a)o=a;else{let e=N(i,`aikit-state.db`);D(i)||O(i,{recursive:!0}),o=await $n(e),nr(o,Qn),Z.info(`State store adapter ready`,{type:o.type,dbPath:e})}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new mr({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await tr({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Zn({adapter:a}):new Zn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await Vn();if(e){let e=zn.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=zn.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new gr(s,c),f=er(o),p=new hr(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=Ds(n.er),v=_?new Gn(n.curated.path):void 0;v&&Z.info(`Policy store initialized`,{ruleCount:v.getRules().length});let y=_?new Wn:void 0,b=P(n.sources[0]?.path??process.cwd(),ce.aiContext),x=D(b),S=n.onboardDir?D(n.onboardDir):!1,C=x||S,w,T=x?b:n.onboardDir;if(C&&T)try{w=te(T).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:C,onboardTimestamp:w,aiKbExists:x,onboardDirExists:S}),{embedder:s,store:c,stateStore:f,closeStateStore:o===a?void 0:async()=>o.close(),indexer:d,curated:g,graphStore:l,fileCache:new be,bridge:_,policyStore:v,evolutionCollector:y,onboardComplete:C,onboardTimestamp:w}}function om(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
2906
- `)}const sm=F(`background-task`);var cm=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,sm.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;sm.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;sm.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const lm=F(`idle-timer`);var um=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){lm.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){lm.info(`Skipping idle cleanup — background work in progress`);return}lm.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&lm.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const dm=F(`memory-monitor`);var fm=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),dm.info(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?dm.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?dm.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&dm.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const pm=F(`tool-timeout`),mm=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var hm=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function gm(e){return mm.has(e)?6e5:12e4}function _m(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new hm(n,t);pm.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const Q=F(`server`),vm=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`]);function ym(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function bm(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function xm(e,t,n){let r=[];try{t.statePath&&Ge(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${ym(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>setTimeout(()=>e(null),50))]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${ym(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function Sm(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||vm.has(i))return o;try{r--;let e=a[0],i=await xm(t,n,bm(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function Cm(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`module not found`].some(e=>t.includes(e))}function wm(e){let t=e.indexOf(`node_modules`);return t>0?e.substring(0,t-1):null}async function Tm(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
2907
- `),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??ue.model,n=N(Sn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=N(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=N(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=N(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)){let{fileURLToPath:e}=await import(`node:url`),t=e(import.meta.url);if(t.includes(`_npx`)||t.includes(`npm-cache`)){let e=wm(t);if(e)try{let{execSync:t}=await import(`node:child_process`);t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:e,stdio:`ignore`,timeout:6e4}),Q.info(`Auto-heal: re-ran npm install to restore missing module`,{path:e})}catch{Q.warn(`Auto-heal: npm install failed during module restoration`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}}}}function Em(e,t){let n=lo(e,La,H,Na(e)),r=om(e,n,H),i=new Cn({name:e.serverName??`aikit`,version:b()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${Ia.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
2905
+ └──────────────────────────────────────────────────────────────────┘`);let t=N(i,`lance`);D(t)&&Z.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let o;if(a)o=a;else{let e=N(i,`aikit-state.db`);D(i)||O(i,{recursive:!0}),o=await $n(e),nr(o,Qn),Z.info(`State store adapter ready`,{type:o.type,dbPath:e})}let[s,c,l,u]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new mr({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Z.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Z.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await tr({backend:r,path:i,adapter:a??void 0,embeddingDim:n.embedding.dimensions});return await e.initialize(),Z.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=a?new Zn({adapter:a}):new Zn({path:i});return await e.initialize(),Z.info(`Graph store initialized`,{shared:!!a}),e})(),(async()=>{let e=await Vn();if(e){let e=zn.get();Z.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=zn.get();Z.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),d=new gr(s,c),f=er(o),p=new hr(n.store.path);p.load(),d.setHashCache(p);let m=n.curated.path,h=new e(m);await h.initialize();let g=new t(m,c,s,h);d.setGraphStore(l);let _=Ds(n.er),v=_?new Gn(n.curated.path):void 0;v&&Z.info(`Policy store initialized`,{ruleCount:v.getRules().length});let y=_?new Wn:void 0,b=P(n.sources[0]?.path??process.cwd(),ce.aiContext),x=D(b),S=n.onboardDir?D(n.onboardDir):!1,C=x||S,w,T=x?b:n.onboardDir;if(C&&T)try{w=te(T).mtime.toISOString()}catch{}return Z.info(`Onboard state detected`,{onboardComplete:C,onboardTimestamp:w,aiKbExists:x,onboardDirExists:S}),{embedder:s,store:c,stateStore:f,closeStateStore:o===a?void 0:async()=>o.close(),indexer:d,curated:g,graphStore:l,fileCache:new be,bridge:_,policyStore:v,evolutionCollector:y,onboardComplete:C,onboardTimestamp:w}}function cm(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
2906
+ `)}const lm=F(`background-task`);var um=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,lm.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;lm.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;lm.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const dm=F(`idle-timer`);var fm=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){dm.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){dm.info(`Skipping idle cleanup — background work in progress`);return}dm.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&dm.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const pm=F(`memory-monitor`);var mm=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),pm.info(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?pm.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?pm.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&pm.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const hm=F(`tool-timeout`),gm=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var _m=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function vm(e){return gm.has(e)?6e5:12e4}function ym(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new _m(n,t);hm.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const Q=F(`server`),bm=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`]);function xm(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Sm(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function Cm(e,t,n){let r=[];try{t.statePath&&Ge(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${xm(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>setTimeout(()=>e(null),50))]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${xm(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function wm(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||bm.has(i))return o;try{r--;let e=a[0],i=await Cm(t,n,Sm(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function Tm(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`module not found`].some(e=>t.includes(e))}function Em(e){let t=e.indexOf(`node_modules`);return t>0?e.substring(0,t-1):null}async function Dm(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
2907
+ `),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??ue.model,n=N(Sn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=N(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=N(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=N(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)){let{fileURLToPath:e}=await import(`node:url`),t=e(import.meta.url);if(t.includes(`_npx`)||t.includes(`npm-cache`)){let e=Em(t);if(e)try{let{execSync:t}=await import(`node:child_process`);t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:e,stdio:`ignore`,timeout:6e4}),Q.info(`Auto-heal: re-ran npm install to restore missing module`,{path:e})}catch{Q.warn(`Auto-heal: npm install failed during module restoration`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}}}}function Om(e,t){let n=lo(e,La,H,Na(e)),r=cm(e,n,H),i=new Cn({name:e.serverName??`aikit`,version:b()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${Ia.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
2908
2908
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Ia.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
2909
- `);yr(i);let p=new oa;p.use(za(),{order:1,name:`structured-content-guard`}),Ja(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of La){if(!n.has(e))continue;let t=U(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ia.has(e)?r.remove():h.push(r)}nm(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:On(L.string(),()=>[])}},async()=>({messages:[]})),v,y,x=new Promise((e,t)=>{v=e,y=t}),S,C=new Promise(e=>{S=e}),w=()=>S?.(),T=(async()=>{await C;let n=[];try{let{createRequire:e}=await import(`node:module`),{readFileSync:t}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=i(a(r(import.meta.url)),`..`,`package.json`),c=JSON.parse(t(s,`utf8`)),l=Object.keys(c.dependencies??{}),u=[`@mixmark-io/domino`],d=[...l,...u.filter(e=>!l.includes(e))];for(let e of d)try{o.resolve(e)}catch{n.push(e)}if(n.length>0){Q.warn(`${n.length} dependencies not resolvable — attempting auto-repair`,{missing:n});let e=r(import.meta.url);if(e.includes(`_npx`)||e.includes(`npm-cache`))try{let{execSync:t}=await import(`node:child_process`),r=wm(e);if(r){Q.info(`Auto-heal: running npm install in npx cache to restore missing deps`,{path:r,missing:n}),t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:r,stdio:`ignore`,timeout:6e4});let e=[];for(let t of n)try{o.resolve(t)}catch{e.push(t)}e.length===0?(Q.info(`Auto-heal: all missing dependencies restored successfully`),n=[]):(Q.warn(`Auto-heal: some deps still missing after npm install`,{stillMissing:e,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`}),n=e)}}catch(e){Q.warn(`Auto-heal: npm install failed — server may operate in degraded mode`,{error:e instanceof Error?e.message:String(e),hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}else Q.warn(`Missing dependencies detected in non-npx environment`,{missing:n,hint:`Run: npm install (or pnpm install) to restore missing packages`})}}catch{}let r;try{r=await am(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(Cm(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await Tm(e,n);try{r=await am(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:n}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let f=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let p=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let m=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let b=i._registeredTools??{};for(let e of Ia)b[e]?.remove();let x=new im(i),S=kc(i);tm(i,r,e,_r(i),x,S,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Ar(i,{curated:r.curated,store:r.store,graphStore:r.graphStore,stateStore:r.stateStore},t),i.sendToolListChanged=f,i.sendPromptListChanged=p,i.sendResourceListChanged=m,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let w=i._registeredTools??{};for(let[e,t]of Object.entries(w)){if(Pa.has(e))continue;let n=t.handler;t.handler=async(...i)=>{if(!r.indexer.isIndexing)return n(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${Fa/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:Wa(t.config.outputSchema)}:{}}),Fa));return Promise.race([n(...i),o])}}for(let[e,t]of Object.entries(w)){let n=t.handler,r=gm(e);t.handler=async(...i)=>{try{return await _m(()=>n(...i),r,e)}catch(n){if(n instanceof hm)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:Wa(t.config.outputSchema)}:{}};throw n}}}let T=Object.keys(w).length;T<La.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:La.length,registeredToolCount:T}),Q.info(`MCP server configured`,{toolCount:La.length,resourceCount:4});let E=new fm;E.onPressure((e,t)=>{e===`warning`&&Cr(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Cr())}),E.registerMemoryPressureCallback(()=>r.embedder.shutdown?.()),E.start();let O=new um;l=O,O.onIdle(async()=>{if(D.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),O.touch();return}Q.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{r.store.releaseMemory?.(),r.graphStore.releaseMemory?.()}catch{}}),O.touch();let k=!1;for(let e of Object.values(w)){let t=e.handler;e.handler=async(...e)=>{if(k||(k=!0,O.markSessionActive()),O.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}Sm(w,r,{statePath:e.stateDir??``}),process.stdin.on(`end`,()=>(Q.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>(Q.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=r,v?.(r)})(),E=async()=>{let t;try{t=await x}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,I(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,I(e))}finally{l?.setBusy(!1)}},D=new cm,O=()=>D.schedule({name:`initial-index`,fn:E}),k=process.ppid,A=setInterval(()=>{try{process.kill(k,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:k}),clearInterval(A),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),x.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return A.unref(),{server:i,startInit:w,ready:T,runInitialIndex:O,get aikit(){return c},scheduler:D,setSmartScheduler(e){u=e}}}const $=F(`server`);function Dm(e,t){let n=lo(t,[...La,...ja],H,Na(t)),r=om(t,n,H),i=new Cn({name:t.serverName??`aikit`,version:b()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return yr(i),tm(i,e,t,_r(i),new im(i),kc(i),void 0,null,null,n),Ar(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function Om(e){let t=await am(e),n=Dm(t,e);$.info(`MCP server configured`,{toolCount:La.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,I(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,I(e))}},i=async()=>{$.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{La as ALL_TOOL_NAMES,Em as createLazyServer,Dm as createMcpServer,Om as createServer,am as initializeAikit,tm as registerMcpTools};
2909
+ `);yr(i);let p=new oa;p.use(za(),{order:1,name:`structured-content-guard`}),Ja(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of La){if(!n.has(e))continue;let t=U(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ia.has(e)?r.remove():h.push(r)}im(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:On(L.string(),()=>[])}},async()=>({messages:[]})),v,y,x=new Promise((e,t)=>{v=e,y=t}),S,C=new Promise(e=>{S=e}),w=()=>S?.(),T=(async()=>{await C;let n=[];try{let{createRequire:e}=await import(`node:module`),{readFileSync:t}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=i(a(r(import.meta.url)),`..`,`package.json`),c=JSON.parse(t(s,`utf8`)),l=Object.keys(c.dependencies??{}),u=[`@mixmark-io/domino`],d=[...l,...u.filter(e=>!l.includes(e))];for(let e of d)try{o.resolve(e)}catch{n.push(e)}if(n.length>0){Q.warn(`${n.length} dependencies not resolvable — attempting auto-repair`,{missing:n});let e=r(import.meta.url);if(e.includes(`_npx`)||e.includes(`npm-cache`))try{let{execSync:t}=await import(`node:child_process`),r=Em(e);if(r){Q.info(`Auto-heal: running npm install in npx cache to restore missing deps`,{path:r,missing:n}),t(`npm install --prefer-offline --no-audit --no-fund`,{cwd:r,stdio:`ignore`,timeout:6e4});let e=[];for(let t of n)try{o.resolve(t)}catch{e.push(t)}e.length===0?(Q.info(`Auto-heal: all missing dependencies restored successfully`),n=[]):(Q.warn(`Auto-heal: some deps still missing after npm install`,{stillMissing:e,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`}),n=e)}}catch(e){Q.warn(`Auto-heal: npm install failed — server may operate in degraded mode`,{error:e instanceof Error?e.message:String(e),hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}else Q.warn(`Missing dependencies detected in non-npx environment`,{missing:n,hint:`Run: npm install (or pnpm install) to restore missing packages`})}}catch{}let r;try{r=await sm(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(Tm(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await Dm(e,n);try{r=await sm(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:n}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let f=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let p=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let m=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let b=i._registeredTools??{};for(let e of Ia)b[e]?.remove();let x=new om(i),S=kc(i);rm(i,r,e,_r(i),x,S,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Ar(i,{curated:r.curated,store:r.store,graphStore:r.graphStore,stateStore:r.stateStore},t),i.sendToolListChanged=f,i.sendPromptListChanged=p,i.sendResourceListChanged=m,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let w=i._registeredTools??{};for(let[e,t]of Object.entries(w)){if(Pa.has(e))continue;let n=t.handler;t.handler=async(...i)=>{if(!r.indexer.isIndexing)return n(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${Fa/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:Wa(t.config.outputSchema)}:{}}),Fa));return Promise.race([n(...i),o])}}for(let[e,t]of Object.entries(w)){let n=t.handler,r=vm(e);t.handler=async(...i)=>{try{return await ym(()=>n(...i),r,e)}catch(n){if(n instanceof _m)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:Wa(t.config.outputSchema)}:{}};throw n}}}let T=Object.keys(w).length;T<La.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:La.length,registeredToolCount:T}),Q.info(`MCP server configured`,{toolCount:La.length,resourceCount:4});let E=new mm;E.onPressure((e,t)=>{e===`warning`&&Cr(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Cr())}),E.registerMemoryPressureCallback(()=>r.embedder.shutdown?.()),E.start();let O=new fm;l=O,O.onIdle(async()=>{if(D.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),O.touch();return}Q.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{r.store.releaseMemory?.(),r.graphStore.releaseMemory?.()}catch{}}),O.touch();let k=!1;for(let e of Object.values(w)){let t=e.handler;e.handler=async(...e)=>{if(k||(k=!0,O.markSessionActive()),O.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}wm(w,r,{statePath:e.stateDir??``}),process.stdin.on(`end`,()=>(Q.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>(Q.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=r,v?.(r)})(),E=async()=>{let t;try{t=await x}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,I(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,I(e))}finally{l?.setBusy(!1)}},D=new um,O=()=>D.schedule({name:`initial-index`,fn:E}),k=process.ppid,A=setInterval(()=>{try{process.kill(k,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:k}),clearInterval(A),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),x.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return A.unref(),{server:i,startInit:w,ready:T,runInitialIndex:O,get aikit(){return c},scheduler:D,setSmartScheduler(e){u=e}}}const $=F(`server`);function km(e,t){let n=lo(t,[...La,...ja],H,Na(t)),r=cm(t,n,H),i=new Cn({name:t.serverName??`aikit`,version:b()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return yr(i),rm(i,e,t,_r(i),new om(i),kc(i),void 0,null,null,n),Ar(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function Am(e){let t=await sm(e),n=km(t,e);$.info(`MCP server configured`,{toolCount:La.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,I(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,I(e))}},i=async()=>{$.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{La as ALL_TOOL_NAMES,Om as createLazyServer,km as createMcpServer,Am as createServer,sm as initializeAikit,rm as registerMcpTools};