@vpxa/aikit 0.1.71 → 0.1.73

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.
@@ -595,26 +595,26 @@ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_rad
595
595
  ### Processes`);for(let e of n.processes)r.push(`- **${e.label}** (id: \`${e.id}\`) — ${e.steps.length} step(s)`)}if(n.depthGroups){r.push(`
596
596
  ### Depth Groups`);for(let[e,t]of Object.entries(n.depthGroups))r.push(`- **Depth ${e}**: ${t.map(e=>`${e.name} (${e.type})`).join(`, `)}`)}if(n.cohesionScore!==void 0&&r.push(`\n**Cohesion Score**: ${(n.cohesionScore*100).toFixed(1)}%`),n.symbol360){let e=n.symbol360;r.push(`
597
597
  ### 360° Symbol View`),r.push(`- **Node**: ${e.node.name} (${e.node.type})`),r.push(`- **Community**: ${e.community??`none`}`),r.push(`- **Incoming**: ${e.incoming.length} edge(s)`),r.push(`- **Outgoing**: ${e.outgoing.length} edge(s)`),r.push(`- **Processes**: ${e.processes.length}`)}return r.push("\n---\n_Next: Use `graph(traverse)` to explore connections, `graph(add)` to insert entities, `graph(symbol360)` for full node context, or `graph(detect_communities)` to find clusters._"),{content:[{type:`text`,text:r.join(`
598
- `)}],structuredContent:{nodes:(n.nodes??[]).map(e=>({id:e.id,name:e.name,type:e.type,...e.sourcePath?{sourcePath:e.sourcePath}:{}})),edges:(n.edges??[]).map(e=>({fromId:e.fromId,toId:e.toId,type:e.type})),totalNodes:n.stats?.nodeCount??n.nodes?.length??0,totalEdges:n.stats?.edgeCount??n.edges?.length??0,query:e.action}}}catch(e){return Mo.error(`Graph query failed`,A(e)),{content:[{type:`text`,text:`Graph query failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Io=E(`tools:infra`);function Lo(e){let t=L(`process`);e.registerTool(`process`,{title:t.title,description:`Start, stop, inspect, list, and tail logs for in-memory managed child processes.`,inputSchema:{action:F.enum([`start`,`stop`,`status`,`list`,`logs`]).describe(`Process action to perform`),id:F.string().optional().describe(`Managed process ID`),command:F.string().optional().describe(`Executable to start`),args:F.array(F.string()).optional().describe(`Arguments for start actions`),tail:F.number().min(1).max(500).optional().describe(`Log lines to return for logs actions`)},annotations:t.annotations},async({action:e,id:t,command:n,args:r,tail:i})=>{try{switch(e){case`start`:if(!t||!n)throw Error(`id and command are required for start`);return{content:[{type:`text`,text:JSON.stringify(pt(t,n,r??[]))}]};case`stop`:if(!t)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify(ht(t)??null)}]};case`status`:if(!t)throw Error(`id is required for status`);return{content:[{type:`text`,text:JSON.stringify(mt(t)??null)}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(dt())}]};case`logs`:if(!t)throw Error(`id is required for logs`);return{content:[{type:`text`,text:JSON.stringify(ft(t,i))}]}}}catch(e){return Io.error(`Process action failed`,A(e)),{content:[{type:`text`,text:`Process action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Ro(e){let t=L(`watch`);e.registerTool(`watch`,{title:t.title,description:`Watch a directory for file changes (create/modify/delete). Actions: start (begin watching), stop (by ID), list (show active watchers). Events are emitted as structured JSON with path, event type, and timestamp.`,inputSchema:{action:F.enum([`start`,`stop`,`list`]).describe(`Watch action to perform`),path:F.string().optional().describe(`Directory path to watch for start actions`),id:F.string().optional().describe(`Watcher ID for stop actions`)},annotations:t.annotations},async({action:e,path:t,id:n})=>{try{switch(e){case`start`:if(!t)throw Error(`path is required for start`);return{content:[{type:`text`,text:JSON.stringify(Qt({path:t}))}]};case`stop`:if(!n)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify({stopped:$t(n)})}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(Zt())}]}}}catch(e){return Io.error(`Watch action failed`,A(e)),{content:[{type:`text`,text:`Watch action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function zo(e){let t=L(`health`);e.registerTool(`health`,{title:t.title,description:`Run project health checks — verifies package.json, tsconfig, scripts, lockfile, README, LICENSE, .gitignore.`,outputSchema:mi,inputSchema:{path:F.string().optional().describe(`Root directory to check (defaults to cwd)`)},annotations:t.annotations},async({path:e})=>{try{let t=Qe(e),n={ok:t.checks.every(e=>e.status!==`fail`),checks:t.checks.map(e=>({name:e.name,ok:e.status===`pass`,message:e.message}))};return{content:[{type:`text`,text:JSON.stringify(t)}],structuredContent:n}}catch(e){return Io.error(`Health check failed`,A(e)),{content:[{type:`text`,text:`Health check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Bo(e){let t=L(`web_fetch`);e.registerTool(`web_fetch`,{title:t.title,description:`PREFERRED web fetcher — fetch one or many URLs and convert to LLM-optimized markdown. Pass one URL or multiple for parallel fetching. Supports CSS selectors, 4 output modes (markdown/raw/links/outline), smart paragraph-boundary truncation. Strips scripts/styles/nav automatically.`,inputSchema:{urls:F.array(F.string().url()).min(1).max(10).describe('URLs to fetch (1–10). Single URL: `["https://..."]`. Multiple fetched in parallel.'),mode:F.enum([`markdown`,`raw`,`links`,`outline`]).default(`markdown`).describe(`Output mode: markdown (clean content), raw (HTML), links (extracted URLs), outline (heading hierarchy)`),selector:F.string().optional().describe(`CSS selector to extract a specific element instead of auto-detecting main content`),max_length:F.number().min(500).max(1e5).default(15e3).describe(`Max characters in output — truncates at paragraph boundaries`),include_metadata:F.boolean().default(!0).describe(`Include page title, description, and URL as a header`),include_links:F.boolean().default(!1).describe(`Append extracted links list at the end`),include_images:F.boolean().default(!1).describe(`Include image alt texts inline`),timeout:F.number().min(1e3).max(12e4).default(3e4).describe(`Request timeout in milliseconds`)},annotations:t.annotations},async({urls:e,mode:t,selector:n,max_length:r,include_metadata:i,include_links:a,include_images:o,timeout:s})=>{let c=e,l=async(e,c)=>{let l=await en({url:e,mode:t,selector:n,maxLength:r,includeMetadata:i,includeLinks:a,includeImages:o,timeout:s}),u=[c?`## ${c} ${l.title||`Web Page`}\n> Source: ${e}`:`## ${l.title||`Web Page`}`,``,l.content];return l.truncated&&u.push(``,`_Original length: ${l.originalLength.toLocaleString()} chars_`),u.join(`
599
- `)};if(c.length===1)try{return{content:[{type:`text`,text:await l(c[0])+"\n\n---\n_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"}]}}catch(e){let t=e instanceof Error?e.message:String(e);return/HTTP [45]\d{2}/.test(t)?Io.warn(`Web fetch failed`,{error:t}):Io.error(`Web fetch failed`,A(e)),{content:[{type:`text`,text:`Web fetch failed: ${t}`}],isError:!0}}let u=c.length,d=await Promise.allSettled(c.map((e,t)=>l(e,`[${t+1}/${u}]`))),f=[],p=0;for(let e=0;e<d.length;e++){let t=d[e];if(t.status===`fulfilled`)f.push(t.value);else{p++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);/HTTP [45]\d{2}/.test(n)?Io.warn(`Web fetch failed`,{url:c[e],error:n}):Io.error(`Web fetch failed`,{url:c[e],...A(t.reason)}),f.push(`## ❌ Failed: ${c[e]}\n\n${n}`)}}let m=`_Fetched ${d.length-p}/${d.length} URLs successfully._`;return f.push(``,`---`,m,"_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"),{content:[{type:`text`,text:f.join(`
598
+ `)}],structuredContent:{nodes:(n.nodes??[]).map(e=>({id:e.id,name:e.name,type:e.type,...e.sourcePath?{sourcePath:e.sourcePath}:{}})),edges:(n.edges??[]).map(e=>({fromId:e.fromId,toId:e.toId,type:e.type})),totalNodes:n.stats?.nodeCount??n.nodes?.length??0,totalEdges:n.stats?.edgeCount??n.edges?.length??0,query:e.action}}}catch(e){return Mo.error(`Graph query failed`,A(e)),{content:[{type:`text`,text:`Graph query failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const K=E(`tools:infra`);function Io(e){let t=L(`process`);e.registerTool(`process`,{title:t.title,description:`Start, stop, inspect, list, and tail logs for in-memory managed child processes.`,inputSchema:{action:F.enum([`start`,`stop`,`status`,`list`,`logs`]).describe(`Process action to perform`),id:F.string().optional().describe(`Managed process ID`),command:F.string().optional().describe(`Executable to start`),args:F.array(F.string()).optional().describe(`Arguments for start actions`),tail:F.number().min(1).max(500).optional().describe(`Log lines to return for logs actions`)},annotations:t.annotations},async({action:e,id:t,command:n,args:r,tail:i})=>{try{switch(e){case`start`:if(!t||!n)throw Error(`id and command are required for start`);return{content:[{type:`text`,text:JSON.stringify(pt(t,n,r??[]))}]};case`stop`:if(!t)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify(ht(t)??null)}]};case`status`:if(!t)throw Error(`id is required for status`);return{content:[{type:`text`,text:JSON.stringify(mt(t)??null)}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(dt())}]};case`logs`:if(!t)throw Error(`id is required for logs`);return{content:[{type:`text`,text:JSON.stringify(ft(t,i))}]}}}catch(e){return K.error(`Process action failed`,A(e)),{content:[{type:`text`,text:`Process action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Lo(e){let t=L(`watch`);e.registerTool(`watch`,{title:t.title,description:`Watch a directory for file changes (create/modify/delete). Actions: start (begin watching), stop (by ID), list (show active watchers). Events are emitted as structured JSON with path, event type, and timestamp.`,inputSchema:{action:F.enum([`start`,`stop`,`list`]).describe(`Watch action to perform`),path:F.string().optional().describe(`Directory path to watch for start actions`),id:F.string().optional().describe(`Watcher ID for stop actions`)},annotations:t.annotations},async({action:e,path:t,id:n})=>{try{switch(e){case`start`:if(!t)throw Error(`path is required for start`);return{content:[{type:`text`,text:JSON.stringify(Qt({path:t}))}]};case`stop`:if(!n)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify({stopped:$t(n)})}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(Zt())}]}}}catch(e){return K.error(`Watch action failed`,A(e)),{content:[{type:`text`,text:`Watch action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Ro(e){let t=L(`health`);e.registerTool(`health`,{title:t.title,description:`Run project health checks — verifies package.json, tsconfig, scripts, lockfile, README, LICENSE, .gitignore.`,outputSchema:mi,inputSchema:{path:F.string().optional().describe(`Root directory to check (defaults to cwd)`)},annotations:t.annotations},async({path:e})=>{try{let t=Qe(e),n={ok:t.checks.every(e=>e.status!==`fail`),checks:t.checks.map(e=>({name:e.name,ok:e.status===`pass`,message:e.message}))};return{content:[{type:`text`,text:JSON.stringify(t)}],structuredContent:n}}catch(e){return K.error(`Health check failed`,A(e)),{content:[{type:`text`,text:`Health check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function zo(e){let t=L(`web_fetch`);e.registerTool(`web_fetch`,{title:t.title,description:`PREFERRED web fetcher — fetch one or many URLs and convert to LLM-optimized markdown. Pass one URL or multiple for parallel fetching. Supports CSS selectors, 4 output modes (markdown/raw/links/outline), smart paragraph-boundary truncation. Strips scripts/styles/nav automatically.`,inputSchema:{urls:F.array(F.string().url()).min(1).max(10).describe('URLs to fetch (1–10). Single URL: `["https://..."]`. Multiple fetched in parallel.'),mode:F.enum([`markdown`,`raw`,`links`,`outline`]).default(`markdown`).describe(`Output mode: markdown (clean content), raw (HTML), links (extracted URLs), outline (heading hierarchy)`),selector:F.string().optional().describe(`CSS selector to extract a specific element instead of auto-detecting main content`),max_length:F.number().min(500).max(1e5).default(15e3).describe(`Max characters in output — truncates at paragraph boundaries`),include_metadata:F.boolean().default(!0).describe(`Include page title, description, and URL as a header`),include_links:F.boolean().default(!1).describe(`Append extracted links list at the end`),include_images:F.boolean().default(!1).describe(`Include image alt texts inline`),timeout:F.number().min(1e3).max(12e4).default(3e4).describe(`Request timeout in milliseconds`)},annotations:t.annotations},async({urls:e,mode:t,selector:n,max_length:r,include_metadata:i,include_links:a,include_images:o,timeout:s})=>{let c=e,l=async(e,c)=>{let l=await en({url:e,mode:t,selector:n,maxLength:r,includeMetadata:i,includeLinks:a,includeImages:o,timeout:s}),u=[c?`## ${c} ${l.title||`Web Page`}\n> Source: ${e}`:`## ${l.title||`Web Page`}`,``,l.content];return l.truncated&&u.push(``,`_Original length: ${l.originalLength.toLocaleString()} chars_`),u.join(`
599
+ `)};if(c.length===1)try{return{content:[{type:`text`,text:await l(c[0])+"\n\n---\n_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"}]}}catch(e){let t=e instanceof Error?e.message:String(e);return/HTTP [45]\d{2}/.test(t)?K.warn(`Web fetch failed`,{error:t}):K.error(`Web fetch failed`,A(e)),{content:[{type:`text`,text:`Web fetch failed: ${t}`}],isError:!0}}let u=c.length,d=await Promise.allSettled(c.map((e,t)=>l(e,`[${t+1}/${u}]`))),f=[],p=0;for(let e=0;e<d.length;e++){let t=d[e];if(t.status===`fulfilled`)f.push(t.value);else{p++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);/HTTP [45]\d{2}/.test(n)?K.warn(`Web fetch failed`,{url:c[e],error:n}):K.error(`Web fetch failed`,{url:c[e],...A(t.reason)}),f.push(`## ❌ Failed: ${c[e]}\n\n${n}`)}}let m=`_Fetched ${d.length-p}/${d.length} URLs successfully._`;return f.push(``,`---`,m,"_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"),{content:[{type:`text`,text:f.join(`
600
600
 
601
- `)}],...p===d.length?{isError:!0}:{}}})}function Vo(e,t){let n=L(`guide`);e.registerTool(`guide`,{title:n.title,description:`Tool discovery — given a goal description, recommends which AI Kit tools to use and in what order. Matches against 10 predefined workflows: onboard, audit, bugfix, implement, refactor, search, context, memory, validate, analyze.`,inputSchema:{goal:F.string().describe(`What you want to accomplish (e.g., "audit this monorepo", "fix a failing test")`),max_recommendations:F.number().min(1).max(10).default(5).describe(`Maximum number of tool recommendations`)},annotations:n.annotations},async({goal:e,max_recommendations:n})=>{try{let r=Ze(e,n,t),i=[`## Recommended Workflow: **${r.workflow}**`,r.description,``,`### Tools`,...r.tools.map(e=>{let t=e.suggestedArgs?` — \`${JSON.stringify(e.suggestedArgs)}\``:``;return`${e.order}. **${e.tool}** — ${e.reason}${t}`})];return r.alternativeWorkflows.length>0&&i.push(``,`_Alternative workflows: ${r.alternativeWorkflows.join(`, `)}_`),i.push(``,`---`,"_Next: Run the first recommended tool, or use `guide` again with a more specific goal._"),{content:[{type:`text`,text:i.join(`
602
- `)}]}}catch(e){return Io.error(`Guide failed`,A(e)),{content:[{type:`text`,text:`Guide failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Ho(e,t,n){if(!(!e||typeof e!=`string`)&&!(e.includes(`..`)||e.startsWith(`/`)||e.startsWith(`[`)))return{type:`resource_link`,uri:`aikit://curated/${e}`,name:t??e,mimeType:`text/markdown`,...n?{description:n}:{}}}function Uo(e){let t=new Set,n=[];for(let r of e){let e=Ho(r.path,r.title,r.category?`[${r.category}]`:void 0);e&&!t.has(e.uri)&&(t.add(e.uri),n.push(e))}return n}function Wo(e){if(e.startsWith(`.ai/curated/`))return e.slice(12)}const Go=E(`tools`);function Ko(e,t){let n=L(`list`);e.registerTool(`list`,{title:n.title,description:`List curated knowledge entries stored via remember. Returns path, title, category, tags, and content preview for each entry. Filter by category (decisions, patterns, conventions) or tag.`,outputSchema:pi,inputSchema:{category:F.string().optional().describe(`Filter by category (e.g., "decisions", "patterns")`),tag:F.string().optional().describe(`Filter by tag`)},annotations:n.annotations},async({category:e,tag:n})=>{try{let r=await t.list({category:e,tag:n}),i={entries:r.map(e=>({path:e.path,title:e.title,category:e.category,tags:e.tags,version:e.version,preview:e.contentPreview?.slice(0,120)??``})),totalCount:r.length};if(r.length===0)return{content:[{type:`text`,text:`No curated knowledge entries found.`+(e?` (category: ${e})`:``)+(n?` (tag: ${n})`:``)}],structuredContent:i};let a=r.map(e=>{let t=e.tags.length>0?` [${e.tags.join(`, `)}]`:``;return`- **${e.title}** (v${e.version})${t}\n \`${e.path}\` — ${e.contentPreview.slice(0,80)}…`}).join(`
603
- `),o=Uo(r);return{content:[{type:`text`,text:`## Curated Knowledge (${r.length} entries)\n\n${a}\n\n---\n_Next: Use \`read\` to view full content of any entry, or \`remember\` to store new knowledge._`},...o],structuredContent:i}}catch(e){return Go.error(`List failed`,A(e)),{content:[{type:`text`,text:`List failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const qo=E(`tools`);function Jo(e,t){let n=L(`lookup`);e.registerTool(`lookup`,{title:n.title,description:`Get all indexed content for a known file path, sorted by position. Use when you know the exact file. For discovery across files use search.`,inputSchema:{path:F.string().describe(`Relative file path to look up (e.g., "src/index.ts")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.getBySourcePath(e);if(n.length===0)return{content:[{type:`text`,text:`No indexed content found for: ${e}`}]};n.sort((e,t)=>e.chunkIndex-t.chunkIndex);let r=`## ${e}\n**Chunks**: ${n.length} | **Type**: ${n[0].contentType}\n`,i=n.map(e=>{let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;return`### Chunk ${e.chunkIndex+1}/${e.totalChunks}${t}\n${e.content}`}).join(`
601
+ `)}],...p===d.length?{isError:!0}:{}}})}function Bo(e,t){let n=L(`guide`);e.registerTool(`guide`,{title:n.title,description:`Tool discovery — given a goal description, recommends which AI Kit tools to use and in what order. Matches against 10 predefined workflows: onboard, audit, bugfix, implement, refactor, search, context, memory, validate, analyze.`,inputSchema:{goal:F.string().describe(`What you want to accomplish (e.g., "audit this monorepo", "fix a failing test")`),max_recommendations:F.number().min(1).max(10).default(5).describe(`Maximum number of tool recommendations`)},annotations:n.annotations},async({goal:e,max_recommendations:n})=>{try{let r=Ze(e,n,t),i=[`## Recommended Workflow: **${r.workflow}**`,r.description,``,`### Tools`,...r.tools.map(e=>{let t=e.suggestedArgs?` — \`${JSON.stringify(e.suggestedArgs)}\``:``;return`${e.order}. **${e.tool}** — ${e.reason}${t}`})];return r.alternativeWorkflows.length>0&&i.push(``,`_Alternative workflows: ${r.alternativeWorkflows.join(`, `)}_`),i.push(``,`---`,"_Next: Run the first recommended tool, or use `guide` again with a more specific goal._"),{content:[{type:`text`,text:i.join(`
602
+ `)}]}}catch(e){return K.error(`Guide failed`,A(e)),{content:[{type:`text`,text:`Guide failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Vo(e,t,n){if(!(!e||typeof e!=`string`)&&!(e.includes(`..`)||e.startsWith(`/`)||e.startsWith(`[`)))return{type:`resource_link`,uri:`aikit://curated/${e}`,name:t??e,mimeType:`text/markdown`,...n?{description:n}:{}}}function Ho(e){let t=new Set,n=[];for(let r of e){let e=Vo(r.path,r.title,r.category?`[${r.category}]`:void 0);e&&!t.has(e.uri)&&(t.add(e.uri),n.push(e))}return n}function Uo(e){if(e.startsWith(`.ai/curated/`))return e.slice(12)}const Wo=E(`tools`);function Go(e,t){let n=L(`list`);e.registerTool(`list`,{title:n.title,description:`List curated knowledge entries stored via remember. Returns path, title, category, tags, and content preview for each entry. Filter by category (decisions, patterns, conventions) or tag.`,outputSchema:pi,inputSchema:{category:F.string().optional().describe(`Filter by category (e.g., "decisions", "patterns")`),tag:F.string().optional().describe(`Filter by tag`)},annotations:n.annotations},async({category:e,tag:n})=>{try{let r=await t.list({category:e,tag:n}),i={entries:r.map(e=>({path:e.path,title:e.title,category:e.category,tags:e.tags,version:e.version,preview:e.contentPreview?.slice(0,120)??``})),totalCount:r.length};if(r.length===0)return{content:[{type:`text`,text:`No curated knowledge entries found.`+(e?` (category: ${e})`:``)+(n?` (tag: ${n})`:``)}],structuredContent:i};let a=r.map(e=>{let t=e.tags.length>0?` [${e.tags.join(`, `)}]`:``;return`- **${e.title}** (v${e.version})${t}\n \`${e.path}\` — ${e.contentPreview.slice(0,80)}…`}).join(`
603
+ `),o=Ho(r);return{content:[{type:`text`,text:`## Curated Knowledge (${r.length} entries)\n\n${a}\n\n---\n_Next: Use \`read\` to view full content of any entry, or \`remember\` to store new knowledge._`},...o],structuredContent:i}}catch(e){return Wo.error(`List failed`,A(e)),{content:[{type:`text`,text:`List failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Ko=E(`tools`);function qo(e,t){let n=L(`lookup`);e.registerTool(`lookup`,{title:n.title,description:`Get all indexed content for a known file path, sorted by position. Use when you know the exact file. For discovery across files use search.`,inputSchema:{path:F.string().describe(`Relative file path to look up (e.g., "src/index.ts")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.getBySourcePath(e);if(n.length===0)return{content:[{type:`text`,text:`No indexed content found for: ${e}`}]};n.sort((e,t)=>e.chunkIndex-t.chunkIndex);let r=`## ${e}\n**Chunks**: ${n.length} | **Type**: ${n[0].contentType}\n`,i=n.map(e=>{let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;return`### Chunk ${e.chunkIndex+1}/${e.totalChunks}${t}\n${e.content}`}).join(`
604
604
 
605
- `),a=Wo(e),o=a?Ho(a):void 0;return{content:[{type:`text`,text:`${r}\n${i}\n\n---\n_Next: Use \`search\` to find related content, or \`analyze_dependencies\` to see what this file imports._`},...o?[o]:[]]}}catch(e){return qo.error(`Lookup failed`,A(e)),{content:[{type:`text`,text:`Lookup failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Yo=E(`tools:manipulation`);function Xo(e){let t=L(`git_context`);e.registerTool(`git_context`,{title:t.title,description:`Summarize the current Git branch, working tree state, recent commits, and optional diff statistics for the repository.`,inputSchema:{cwd:F.string().optional().describe(`Repository root or working directory`),commit_count:F.number().min(1).max(50).default(5).optional().describe(`How many recent commits to include`),include_diff:F.boolean().default(!1).optional().describe(`Include diff stat for working tree changes`)},annotations:t.annotations,outputSchema:Li},async({cwd:e,commit_count:t,include_diff:n})=>{try{let r=await Je({cwd:e,commitCount:t,includeDiff:n});return{content:[{type:`text`,text:ts(r)}],structuredContent:{gitRoot:r.gitRoot,branch:r.branch,commitCount:r.recentCommits.length,hasUncommitted:r.status.staged.length>0||r.status.modified.length>0||r.status.untracked.length>0,recentCommits:r.recentCommits.map(e=>({hash:e.hash,message:e.message,author:e.author,date:e.date}))}}}catch(e){return Yo.error(`Git context failed`,A(e)),{content:[{type:`text`,text:`Git context failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Zo(e){let t=L(`diff_parse`);e.registerTool(`diff_parse`,{title:t.title,description:`Parse raw unified diff text into file-level and hunk-level structural changes.`,inputSchema:{diff:F.string().max(1e6).describe(`Raw unified diff text`)},annotations:t.annotations},async({diff:e})=>{try{return{content:[{type:`text`,text:ns(Fe({diff:e.replace(/\\n/g,`
606
- `).replace(/\\t/g,` `)}))}]}}catch(e){return Yo.error(`Diff parse failed`,A(e)),{content:[{type:`text`,text:`Diff parse failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Qo(e){let t=L(`rename`);e.registerTool(`rename`,{title:t.title,description:`Rename a symbol across files using whole-word regex matching for exports, imports, and general usage references.`,inputSchema:{old_name:F.string().describe(`Existing symbol name to replace`),new_name:F.string().describe(`New symbol name to use`),root_path:F.string().describe(`Root directory to search within`),extensions:F.array(F.string()).optional().describe(`Optional file extensions to include, such as .ts,.tsx,.js,.jsx`),dry_run:F.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:t.annotations},async({old_name:e,new_name:t,root_path:n,extensions:r,dry_run:i})=>{try{let a=await Dt({oldName:e,newName:t,rootPath:n,extensions:r,dryRun:i});return{content:[{type:`text`,text:JSON.stringify(a)}]}}catch(e){return Yo.error(`Rename failed`,A(e)),{content:[{type:`text`,text:`Rename failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function $o(e){let t=L(`codemod`);e.registerTool(`codemod`,{title:t.title,description:`Apply regex-based codemod rules across files and return structured before/after changes for each affected line.`,inputSchema:{root_path:F.string().describe(`Root directory to transform within`),rules:F.array(F.object({description:F.string().describe(`What the codemod rule does`),pattern:F.string().describe(`Regex pattern in string form`),replacement:F.string().describe(`Replacement string with optional capture groups`)})).min(1).describe(`Codemod rules to apply`),dry_run:F.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:t.annotations},async({root_path:e,rules:t,dry_run:n})=>{try{let r=await De({rootPath:e,rules:t,dryRun:n});return{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return Yo.error(`Codemod failed`,A(e)),{content:[{type:`text`,text:`Codemod failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function es(e){let t=L(`data_transform`);e.registerTool(`data_transform`,{title:t.title,description:`Apply small jq-like transforms to JSON input for filtering, projection, grouping, and path extraction.`,inputSchema:{input:F.string().max(5e5).describe(`Input JSON string`),expression:F.string().max(1e4).describe(`Transform expression to apply`)},annotations:t.annotations},async({input:e,expression:t})=>{try{return{content:[{type:`text`,text:je({input:e,expression:t}).outputString}]}}catch(e){return Yo.error(`Data transform failed`,A(e)),{content:[{type:`text`,text:`Data transform failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ts(e){let t=[`Git root: ${e.gitRoot}`,`Branch: ${e.branch}`,`Staged: ${e.status.staged.length}`,...e.status.staged.map(e=>` - ${e}`),`Modified: ${e.status.modified.length}`,...e.status.modified.map(e=>` - ${e}`),`Untracked: ${e.status.untracked.length}`,...e.status.untracked.map(e=>` - ${e}`),``,`Recent commits:`];if(e.recentCommits.length===0)t.push(` none`);else for(let n of e.recentCommits)t.push(` - ${n.hash} ${n.message}`),t.push(` ${n.author} @ ${n.date}`);return e.diff&&t.push(``,`Diff stat:`,e.diff),t.join(`
607
- `)}function ns(e){if(e.length===0)return`No diff files found.`;let t=[];for(let n of e){let e=n.oldPath?` (from ${n.oldPath})`:``;t.push(`${n.path}${e} [${n.status}] +${n.additions} -${n.deletions} (${n.hunks.length} hunks)`);for(let e of n.hunks){let n=e.header?` ${e.header}`:``;t.push(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${n}`)}}return t.join(`
608
- `)}const rs=[`list_tools`,`describe_tool`,`search_tools`];function is(e,t,n){let r=[...new Set(n)].sort();e.registerTool(`list_tools`,{title:L(`list_tools`).title,description:`List the available AI Kit tools with names, titles, and categories. Use this before describe_tool when you need to discover the active toolset.`,inputSchema:{category:F.string().optional().describe(`Optional category filter`)},annotations:L(`list_tools`).annotations},async({category:e})=>{let t=e?.trim().toLowerCase();return{content:[{type:`text`,text:r.filter(e=>t?(ur[e]?.category??[]).some(e=>e.toLowerCase()===t):!0).map(e=>{let t=ur[e]??{title:e,category:[]},n=t.category?.join(`, `)||`uncategorized`;return`${e}: ${t.title} [${n}]`}).join(`
605
+ `),a=Uo(e),o=a?Vo(a):void 0;return{content:[{type:`text`,text:`${r}\n${i}\n\n---\n_Next: Use \`search\` to find related content, or \`analyze_dependencies\` to see what this file imports._`},...o?[o]:[]]}}catch(e){return Ko.error(`Lookup failed`,A(e)),{content:[{type:`text`,text:`Lookup failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Jo=E(`tools:manipulation`);function Yo(e){let t=L(`git_context`);e.registerTool(`git_context`,{title:t.title,description:`Summarize the current Git branch, working tree state, recent commits, and optional diff statistics for the repository.`,inputSchema:{cwd:F.string().optional().describe(`Repository root or working directory`),commit_count:F.number().min(1).max(50).default(5).optional().describe(`How many recent commits to include`),include_diff:F.boolean().default(!1).optional().describe(`Include diff stat for working tree changes`)},annotations:t.annotations,outputSchema:Li},async({cwd:e,commit_count:t,include_diff:n})=>{try{let r=await Je({cwd:e,commitCount:t,includeDiff:n});return{content:[{type:`text`,text:es(r)}],structuredContent:{gitRoot:r.gitRoot,branch:r.branch,commitCount:r.recentCommits.length,hasUncommitted:r.status.staged.length>0||r.status.modified.length>0||r.status.untracked.length>0,recentCommits:r.recentCommits.map(e=>({hash:e.hash,message:e.message,author:e.author,date:e.date}))}}}catch(e){return Jo.error(`Git context failed`,A(e)),{content:[{type:`text`,text:`Git context failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Xo(e){let t=L(`diff_parse`);e.registerTool(`diff_parse`,{title:t.title,description:`Parse raw unified diff text into file-level and hunk-level structural changes.`,inputSchema:{diff:F.string().max(1e6).describe(`Raw unified diff text`)},annotations:t.annotations},async({diff:e})=>{try{return{content:[{type:`text`,text:ts(Fe({diff:e.replace(/\\n/g,`
606
+ `).replace(/\\t/g,` `)}))}]}}catch(e){return Jo.error(`Diff parse failed`,A(e)),{content:[{type:`text`,text:`Diff parse failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Zo(e){let t=L(`rename`);e.registerTool(`rename`,{title:t.title,description:`Rename a symbol across files using whole-word regex matching for exports, imports, and general usage references.`,inputSchema:{old_name:F.string().describe(`Existing symbol name to replace`),new_name:F.string().describe(`New symbol name to use`),root_path:F.string().describe(`Root directory to search within`),extensions:F.array(F.string()).optional().describe(`Optional file extensions to include, such as .ts,.tsx,.js,.jsx`),dry_run:F.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:t.annotations},async({old_name:e,new_name:t,root_path:n,extensions:r,dry_run:i})=>{try{let a=await Dt({oldName:e,newName:t,rootPath:n,extensions:r,dryRun:i});return{content:[{type:`text`,text:JSON.stringify(a)}]}}catch(e){return Jo.error(`Rename failed`,A(e)),{content:[{type:`text`,text:`Rename failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Qo(e){let t=L(`codemod`);e.registerTool(`codemod`,{title:t.title,description:`Apply regex-based codemod rules across files and return structured before/after changes for each affected line.`,inputSchema:{root_path:F.string().describe(`Root directory to transform within`),rules:F.array(F.object({description:F.string().describe(`What the codemod rule does`),pattern:F.string().describe(`Regex pattern in string form`),replacement:F.string().describe(`Replacement string with optional capture groups`)})).min(1).describe(`Codemod rules to apply`),dry_run:F.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:t.annotations},async({root_path:e,rules:t,dry_run:n})=>{try{let r=await De({rootPath:e,rules:t,dryRun:n});return{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return Jo.error(`Codemod failed`,A(e)),{content:[{type:`text`,text:`Codemod failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function $o(e){let t=L(`data_transform`);e.registerTool(`data_transform`,{title:t.title,description:`Apply small jq-like transforms to JSON input for filtering, projection, grouping, and path extraction.`,inputSchema:{input:F.string().max(5e5).describe(`Input JSON string`),expression:F.string().max(1e4).describe(`Transform expression to apply`)},annotations:t.annotations},async({input:e,expression:t})=>{try{return{content:[{type:`text`,text:je({input:e,expression:t}).outputString}]}}catch(e){return Jo.error(`Data transform failed`,A(e)),{content:[{type:`text`,text:`Data transform failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function es(e){let t=[`Git root: ${e.gitRoot}`,`Branch: ${e.branch}`,`Staged: ${e.status.staged.length}`,...e.status.staged.map(e=>` - ${e}`),`Modified: ${e.status.modified.length}`,...e.status.modified.map(e=>` - ${e}`),`Untracked: ${e.status.untracked.length}`,...e.status.untracked.map(e=>` - ${e}`),``,`Recent commits:`];if(e.recentCommits.length===0)t.push(` none`);else for(let n of e.recentCommits)t.push(` - ${n.hash} ${n.message}`),t.push(` ${n.author} @ ${n.date}`);return e.diff&&t.push(``,`Diff stat:`,e.diff),t.join(`
607
+ `)}function ts(e){if(e.length===0)return`No diff files found.`;let t=[];for(let n of e){let e=n.oldPath?` (from ${n.oldPath})`:``;t.push(`${n.path}${e} [${n.status}] +${n.additions} -${n.deletions} (${n.hunks.length} hunks)`);for(let e of n.hunks){let n=e.header?` ${e.header}`:``;t.push(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${n}`)}}return t.join(`
608
+ `)}const ns=[`list_tools`,`describe_tool`,`search_tools`];function rs(e,t,n){let r=[...new Set(n)].sort();e.registerTool(`list_tools`,{title:L(`list_tools`).title,description:`List the available AI Kit tools with names, titles, and categories. Use this before describe_tool when you need to discover the active toolset.`,inputSchema:{category:F.string().optional().describe(`Optional category filter`)},annotations:L(`list_tools`).annotations},async({category:e})=>{let t=e?.trim().toLowerCase();return{content:[{type:`text`,text:r.filter(e=>t?(ur[e]?.category??[]).some(e=>e.toLowerCase()===t):!0).map(e=>{let t=ur[e]??{title:e,category:[]},n=t.category?.join(`, `)||`uncategorized`;return`${e}: ${t.title} [${n}]`}).join(`
609
609
  `)||`No tools matched the filter.`}]}}),e.registerTool(`describe_tool`,{title:L(`describe_tool`).title,description:`Describe a specific active AI Kit tool using centralized metadata. Use this after list_tools when you need a tool title, categories, and annotations before calling it directly.`,inputSchema:{tool_name:F.string().describe(`The active tool name to describe`)},annotations:L(`describe_tool`).annotations},async({tool_name:e})=>{if(!r.includes(e))return{content:[{type:`text`,text:`Unknown or inactive tool: ${e}`}],isError:!0};let t=ur[e],n={name:e,title:t?.title??e,categories:t?.category??[],annotations:t?.annotations??{},note:`Call the tool directly after discovery. AI Kit does not expose an execute_tool proxy.`};return{content:[{type:`text`,text:JSON.stringify(n,null,2)}]}}),e.registerTool(`search_tools`,{title:L(`search_tools`).title,description:`Search active AI Kit tools by keyword across tool names, titles, and categories.`,inputSchema:{query:F.string().min(1).describe(`Keyword query to match against active tools`)},annotations:L(`search_tools`).annotations},async({query:e})=>{let t=e.trim().toLowerCase(),n=r.filter(e=>{let n=ur[e];return e.toLowerCase().includes(t)||n?.title.toLowerCase().includes(t)||(n?.category??[]).some(e=>e.toLowerCase().includes(t))}).map(e=>{let t=ur[e]??{title:e,category:[]},n=t.category?.join(`, `)||`uncategorized`;return`${e}: ${t.title} [${n}]`});return{content:[{type:`text`,text:n.length>0?n.join(`
610
- `):`No tools found matching "${e}"`}]}})}const as=E(`tools`);let os=!1;async function ss(e,t,n){for(let r of n.steps)if(!(r.status!==`success`||!r.output))try{let i=j(`sha256`).update(n.path).digest(`hex`).slice(0,12),a=`produced/onboard/${r.name}/${i}.md`,o=j(`sha256`).update(r.output).digest(`hex`).slice(0,16),s=new Date().toISOString(),c=r.output.length>2e3?r.output.split(/(?=^## )/m).filter(e=>e.trim().length>0):[r.output],l=c.map((e,t)=>({id:j(`sha256`).update(`${a}::${t}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:a,contentType:`produced-knowledge`,chunkIndex:t,totalChunks:c.length,startLine:0,endLine:0,fileHash:o,indexedAt:s,origin:`produced`,tags:[`onboard`,r.name],category:`analysis`,version:1})),u=await t.embedBatch(l.map(e=>e.content));await e.upsert(l,u)}catch(e){as.warn(`Auto-persist onboard step failed`,{stepName:r.name,...A(e)})}}async function cs(e,t,n){if(n.autoRemember?.length)for(let r of n.autoRemember)try{let n=j(`sha256`).update(`onboard-remember::${r.title}`).digest(`hex`).slice(0,16),i=new Date().toISOString(),a={id:n,content:`# ${r.title}\n\n${r.content}`,sourcePath:`curated/onboard/${r.category}/${n}.md`,contentType:`curated`,chunkIndex:0,totalChunks:1,startLine:0,endLine:0,fileHash:j(`sha256`).update(r.content).digest(`hex`).slice(0,16),indexedAt:i,origin:`curated`,tags:r.tags,category:r.category,version:1},[o]=await t.embedBatch([a.content]);await e.upsert([a],[o])}catch(e){as.warn(`Auto-persist remember entry failed`,{title:r.title,...A(e)})}}function ls(e,t,n,r,i){let a=L(`onboard`);e.registerTool(`onboard`,{title:a.title,description:`First-time codebase onboarding: runs all analysis tools (structure, dependencies, entry-points, symbols, patterns, diagram) in one command. Results are auto-persisted to KB. Use mode=generate to also write structured output to .ai/context/ directory.`,inputSchema:{path:F.string().describe(`Root path of the codebase to onboard`),mode:F.enum([`memory`,`generate`]).default(`generate`).describe(`Output mode: generate (default) = persist to AI Kit + write .ai/context/ files; memory = AI Kit vector store only`),out_dir:F.string().optional().describe(`Custom output directory for generate mode (default: <path>/.ai/context)`)},annotations:a.annotations},async({path:e,mode:a,out_dir:o},s)=>{try{if(os)return{content:[{type:`text`,text:`Onboard is already running. Please wait for it to complete before starting another.`}]};os=!0,as.info(`Starting onboard`,{path:e,mode:a});let c=await lt({path:e,mode:a,outDir:o??r?.onboardDir}),l=na(s).createTask(`Onboard`,c.steps.length);for(let e=0;e<c.steps.length;e++){let t=c.steps[e];l.progress(e,`${t.name}: ${t.status}`)}l.complete(`Onboard complete: ${c.steps.filter(e=>e.status===`success`).length}/${c.steps.length} steps succeeded`),ss(t,n,c),c.autoRemember?.length&&cs(t,n,c).catch(e=>{as.warn(`Auto-persist autoRemember failed`,A(e))}),i&&(i.onboardComplete=!0,i.onboardTimestamp=new Date().toISOString());let u=[`## Onboard Complete`,``,`**Path:** \`${c.path}\``,`**Mode:** ${c.mode}`,`**Duration:** ${c.totalDurationMs}ms`,``];c.outDir&&(u.push(`**Output directory:** \`${c.outDir}\``),u.push(``)),u.push(`### Analysis Results`,``);let d=[],f=[];for(let e of c.steps)e.status===`success`?d.push(`- ✓ **${e.name}** (${e.durationMs}ms) — ${e.output.length} chars`):f.push(`- ✗ **${e.name}** — ${e.error}`);u.push(...d),f.length>0&&u.push(``,`### Failed`,``,...f),u.push(``,`---`,``);for(let e of c.steps)e.status===`success`&&u.push(`### ${e.name}`,``,e.output,``,`---`,``);return u.push(`_All results auto-saved to KB.`,c.mode===`generate`?` Files written to \`${c.outDir}\`.`:``," Next: Use `search` to query the knowledge, or `remember` to add custom insights._"),{content:[{type:`text`,text:u.join(`
611
- `)}]}}catch(e){return as.error(`Onboard failed`,A(e)),{content:[{type:`text`,text:`Onboard failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}finally{os=!1}})}const us=E(`tools:persistence`);function ds(e){let t=L(`workset`);e.registerTool(`workset`,{title:t.title,description:`Manage named file sets (worksets). Save, load, list, add/remove files. Worksets persist across sessions in .aikit-state/worksets.json.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`delete`,`add`,`remove`]).describe(`Operation to perform`),name:F.string().optional().describe(`Workset name (required for all except list)`),files:F.array(F.string()).optional().describe(`File paths (required for save, add, remove)`),description:F.string().optional().describe(`Description (for save)`)},annotations:t.annotations},async({action:e,name:t,files:n,description:r})=>{try{switch(e){case`save`:{if(!t||!n)throw Error(`name and files required for save`);let e=Nt(t,n,{description:r});return{content:[{type:`text`,text:`Saved workset "${e.name}" with ${e.files.length} files.`}]}}case`get`:{if(!t)throw Error(`name required for get`);let e=qe(t);return e?{content:[{type:`text`,text:JSON.stringify(e)}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}case`list`:{let e=st();return e.length===0?{content:[{type:`text`,text:`No worksets.`}]}:{content:[{type:`text`,text:e.map(e=>`- **${e.name}** (${e.files.length} files) — ${e.description??`no description`}`).join(`
612
- `)}]}}case`delete`:if(!t)throw Error(`name required for delete`);return{content:[{type:`text`,text:Pe(t)?`Deleted workset "${t}".`:`Workset "${t}" not found.`}]};case`add`:{if(!t||!n)throw Error(`name and files required for add`);let e=_e(t,n);return{content:[{type:`text`,text:`Added to workset "${e.name}": now ${e.files.length} files.`}]}}case`remove`:{if(!t||!n)throw Error(`name and files required for remove`);let e=Et(t,n);return e?{content:[{type:`text`,text:`Removed from workset "${e.name}": now ${e.files.length} files.`}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}}}catch(e){return us.error(`Workset operation failed`,A(e)),{content:[{type:`text`,text:`Workset operation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function fs(e){let t=L(`stash`);e.registerTool(`stash`,{title:t.title,description:`Persist and retrieve named values in .aikit-state/stash.json for intermediate results between tool calls.`,inputSchema:{action:F.enum([`set`,`get`,`list`,`delete`,`clear`]).describe(`Operation to perform on the stash`),key:F.string().optional().describe(`Entry key for set/get/delete operations`),value:F.string().optional().describe(`String or JSON value for set operations`)},annotations:t.annotations},async({action:e,key:t,value:n})=>{try{switch(e){case`set`:{if(!t)throw Error(`key required for set`);let e=Ut(t,_s(n??``));return{content:[{type:`text`,text:`Stored stash entry "${e.key}" (${e.type}) at ${e.storedAt}.`}]}}case`get`:{if(!t)throw Error(`key required for get`);let e=Vt(t);return{content:[{type:`text`,text:e?JSON.stringify(e):`Stash entry "${t}" not found.`}]}}case`list`:{let e=Ht();return{content:[{type:`text`,text:e.length===0?`Stash is empty.`:e.map(e=>`- ${e.key} (${e.type}) — ${e.storedAt}`).join(`
613
- `)}]}}case`delete`:if(!t)throw Error(`key required for delete`);return{content:[{type:`text`,text:Bt(t)?`Deleted stash entry "${t}".`:`Stash entry "${t}" not found.`}]};case`clear`:{let e=zt();return{content:[{type:`text`,text:`Cleared ${e} stash entr${e===1?`y`:`ies`}.`}]}}}}catch(e){return us.error(`Stash operation failed`,A(e)),{content:[{type:`text`,text:`Stash operation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ps(e){let t=L(`checkpoint`);e.registerTool(`checkpoint`,{title:t.title,description:`Save and restore lightweight session checkpoints in .aikit-state/checkpoints for cross-session continuity.`,inputSchema:{action:F.enum([`save`,`load`,`list`,`latest`]).describe(`Checkpoint action to perform`),label:F.string().optional().describe(`Checkpoint label for save, or checkpoint id for load`),data:F.string().max(5e5).optional().describe(`JSON object string for save actions`),notes:F.string().max(1e4).optional().describe(`Optional notes for save actions`)},annotations:t.annotations},async({action:e,label:t,data:n,notes:r})=>{try{switch(e){case`save`:if(!t)throw Error(`label required for save`);return{content:[{type:`text`,text:gs(Ee(t,vs(n),{notes:r}))}]};case`load`:{if(!t)throw Error(`label required for load`);let e=Te(t);return{content:[{type:`text`,text:e?gs(e):`Checkpoint "${t}" not found.`}]}}case`list`:{let e=we();return{content:[{type:`text`,text:e.length===0?`No checkpoints saved.`:e.map(e=>`- ${e.id} — ${e.label} (${e.createdAt})`).join(`
614
- `)}]}}case`latest`:{let e=Ce();return{content:[{type:`text`,text:e?gs(e):`No checkpoints saved.`}]}}}}catch(e){return us.error(`Checkpoint failed`,A(e)),{content:[{type:`text`,text:`Checkpoint failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ms(e){let t=L(`lane`);e.registerTool(`lane`,{title:t.title,description:`Manage verified lanes — isolated file copies for parallel exploration. Create a lane, make changes, diff, merge back, or discard.`,inputSchema:{action:F.enum([`create`,`list`,`status`,`diff`,`merge`,`discard`]).describe(`Lane action to perform`),name:F.string().optional().describe(`Lane name (required for create/status/diff/merge/discard)`),files:F.array(F.string()).optional().describe(`File paths to copy into the lane (required for create)`)},annotations:t.annotations},async({action:e,name:t,files:n})=>{try{switch(e){case`create`:{if(!t)throw Error(`name is required for create`);if(!n||n.length===0)throw Error(`files are required for create`);let e=et(t,n);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`list`:return{content:[{type:`text`,text:JSON.stringify(rt())}]};case`status`:if(!t)throw Error(`name is required for status`);return{content:[{type:`text`,text:JSON.stringify(at(t))}]};case`diff`:if(!t)throw Error(`name is required for diff`);return{content:[{type:`text`,text:JSON.stringify(tt(t))}]};case`merge`:if(!t)throw Error(`name is required for merge`);return{content:[{type:`text`,text:JSON.stringify(it(t))}]};case`discard`:if(!t)throw Error(`name is required for discard`);return{content:[{type:`text`,text:JSON.stringify({discarded:nt(t)})}]}}}catch(e){return us.error(`Lane action failed`,A(e)),{content:[{type:`text`,text:`Lane action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function hs(e){let t=L(`queue`);e.registerTool(`queue`,{title:t.title,description:`Manage task queues for sequential agent operations. Push items, take next, mark done/failed, list queues.`,inputSchema:{action:F.enum([`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`]).describe(`Queue action`),name:F.string().optional().describe(`Queue name (required for most actions)`),title:F.string().optional().describe(`Item title (required for push)`),id:F.string().optional().describe(`Item ID (required for done/fail)`),data:F.unknown().optional().describe(`Arbitrary data to attach to a queue item`),error:F.string().optional().describe(`Error message (required for fail)`)},annotations:t.annotations},async({action:e,name:t,title:n,id:r,data:i,error:a})=>{try{switch(e){case`create`:if(!t)throw Error(`name is required for create`);return{content:[{type:`text`,text:JSON.stringify(_t(t))}]};case`push`:if(!t)throw Error(`name is required for push`);if(!n)throw Error(`title is required for push`);return{content:[{type:`text`,text:JSON.stringify(wt(t,n,i))}]};case`next`:{if(!t)throw Error(`name is required for next`);let e=Ct(t);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`done`:if(!t)throw Error(`name is required for done`);if(!r)throw Error(`id is required for done`);return{content:[{type:`text`,text:JSON.stringify(yt(t,r))}]};case`fail`:if(!t)throw Error(`name is required for fail`);if(!r)throw Error(`id is required for fail`);if(!a)throw Error(`error is required for fail`);return{content:[{type:`text`,text:JSON.stringify(bt(t,r,a))}]};case`get`:if(!t)throw Error(`name is required for get`);return{content:[{type:`text`,text:JSON.stringify(xt(t))}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(St())}]};case`clear`:if(!t)throw Error(`name is required for clear`);return{content:[{type:`text`,text:JSON.stringify({cleared:gt(t)})}]};case`delete`:if(!t)throw Error(`name is required for delete`);return{content:[{type:`text`,text:JSON.stringify({deleted:vt(t)})}]}}}catch(e){return us.error(`Queue action failed`,A(e)),{content:[{type:`text`,text:`Queue action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function gs(e){let t=[e.id,`Label: ${e.label}`,`Created: ${e.createdAt}`];if(e.notes&&t.push(`Notes: ${e.notes}`),e.files?.length){t.push(`Files: ${e.files.length}`);for(let n of e.files)t.push(` - ${n}`)}return t.push(``,`Data:`,JSON.stringify(e.data)),t.join(`
615
- `)}function _s(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function vs(e){let t=e?.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{throw Error(`data must be a valid JSON object string`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`data must be a JSON object string`);return n}const ys=E(`tools`);function bs(e){let t=[`## Rule: ${e.id}`,``,`- **Status**: ${e.enabled?`enabled`:`disabled`}`,`- **Description**: ${e.description??`—`}`,`- **Category**: ${e.category??`—`}`,`- **Push weight**: ${e.pushWeight??`—`}`];return e.patterns?.length&&t.push(`- **Patterns**: ${e.patterns.join(`, `)}`),e.examples?.length&&t.push(`- **Examples**: ${e.examples.join(`, `)}`),t.join(`
616
- `)}function xs(e,t){let n=L(`er_update_policy`);e.registerTool(`er_update_policy`,{title:n.title,description:`Manage ER push classification rules. Supports listing, updating, creating, and deleting rules that determine when knowledge should be pushed to Enterprise RAG.`,inputSchema:{action:F.enum([`list`,`get`,`update`,`create`,`delete`]).describe(`Action to perform on classification rules`),rule_id:F.string().optional().describe(`Rule ID (required for get, update, delete)`),changes:F.object({patterns:F.array(F.string()).optional(),category:F.string().optional(),pushWeight:F.number().min(0).max(1).optional(),description:F.string().optional(),examples:F.array(F.string()).optional(),enabled:F.boolean().optional()}).optional().describe(`Changes to apply (for update action)`),new_rule:F.object({id:F.string().regex(/^[a-z][a-z0-9-]*$/),patterns:F.array(F.string()).min(1),category:F.string(),pushWeight:F.number().min(0).max(1),description:F.string(),examples:F.array(F.string()).default([]),enabled:F.boolean().default(!0)}).optional().describe(`New rule definition (for create action)`)},annotations:n.annotations},async({action:e,rule_id:n,changes:r,new_rule:i})=>{try{if(e===`list`){let e=t.getRules();return{content:[{type:`text`,text:`## Classification Rules\n\n${e.map(e=>`- **${e.id}** (${e.enabled?`enabled`:`disabled`}) — ${e.description}\n Category: ${e.category} | Weight: ${e.pushWeight} | Patterns: ${e.patterns.join(`, `)}`).join(`
617
- `)}\n\n---\n_${e.length} rules total. Use \`action: "update"\` to modify a rule._`}]}}if(e===`get`){if(!n)return{content:[{type:`text`,text:'`rule_id` is required for "get" action.'}],isError:!0};let e=t.getRule(n);return e?{content:[{type:`text`,text:bs(e)}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}}if(e===`update`){if(!n||!r)return{content:[{type:`text`,text:'`rule_id` and `changes` are required for "update" action.'}],isError:!0};let e=t.updateRule(n,r);return e?{content:[{type:`text`,text:`${bs(e)}\n\n---\n_Updated. Next: Use \`action: "list"\` to verify._`}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}}return e===`create`?i?{content:[{type:`text`,text:`${bs(t.addRule(i))}\n\n---\n_Created. Next: Test classification with \`remember\`._`}]}:{content:[{type:`text`,text:'`new_rule` is required for "create" action.'}],isError:!0}:e===`delete`?n?t.deleteRule(n)?{content:[{type:`text`,text:`Deleted rule **${n}**.\n\n---\n_Next: Use \`action: "list"\` to verify._`}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}:{content:[{type:`text`,text:'`rule_id` is required for "delete" action.'}],isError:!0}:{content:[{type:`text`,text:`Unknown action: ${e}`}],isError:!0}}catch(e){return ys.error(`Policy update failed`,A(e)),{content:[{type:`text`,text:`Policy update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Ss(){return`
610
+ `):`No tools found matching "${e}"`}]}})}const is=E(`tools`);let as=!1;async function os(e,t,n){for(let r of n.steps)if(!(r.status!==`success`||!r.output))try{let i=j(`sha256`).update(n.path).digest(`hex`).slice(0,12),a=`produced/onboard/${r.name}/${i}.md`,o=j(`sha256`).update(r.output).digest(`hex`).slice(0,16),s=new Date().toISOString(),c=r.output.length>2e3?r.output.split(/(?=^## )/m).filter(e=>e.trim().length>0):[r.output],l=c.map((e,t)=>({id:j(`sha256`).update(`${a}::${t}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:a,contentType:`produced-knowledge`,chunkIndex:t,totalChunks:c.length,startLine:0,endLine:0,fileHash:o,indexedAt:s,origin:`produced`,tags:[`onboard`,r.name],category:`analysis`,version:1})),u=await t.embedBatch(l.map(e=>e.content));await e.upsert(l,u)}catch(e){is.warn(`Auto-persist onboard step failed`,{stepName:r.name,...A(e)})}}async function ss(e,t,n){if(n.autoRemember?.length)for(let r of n.autoRemember)try{let n=j(`sha256`).update(`onboard-remember::${r.title}`).digest(`hex`).slice(0,16),i=new Date().toISOString(),a={id:n,content:`# ${r.title}\n\n${r.content}`,sourcePath:`curated/onboard/${r.category}/${n}.md`,contentType:`curated`,chunkIndex:0,totalChunks:1,startLine:0,endLine:0,fileHash:j(`sha256`).update(r.content).digest(`hex`).slice(0,16),indexedAt:i,origin:`curated`,tags:r.tags,category:r.category,version:1},[o]=await t.embedBatch([a.content]);await e.upsert([a],[o])}catch(e){is.warn(`Auto-persist remember entry failed`,{title:r.title,...A(e)})}}function cs(e,t,n,r,i){let a=L(`onboard`);e.registerTool(`onboard`,{title:a.title,description:`First-time codebase onboarding: runs all analysis tools (structure, dependencies, entry-points, symbols, patterns, diagram) in one command. Results are auto-persisted to KB. Use mode=generate to also write structured output to .ai/context/ directory.`,inputSchema:{path:F.string().describe(`Root path of the codebase to onboard`),mode:F.enum([`memory`,`generate`]).default(`generate`).describe(`Output mode: generate (default) = persist to AI Kit + write .ai/context/ files; memory = AI Kit vector store only`),out_dir:F.string().optional().describe(`Custom output directory for generate mode (default: <path>/.ai/context)`)},annotations:a.annotations},async({path:e,mode:a,out_dir:o},s)=>{try{if(as)return{content:[{type:`text`,text:`Onboard is already running. Please wait for it to complete before starting another.`}]};as=!0,is.info(`Starting onboard`,{path:e,mode:a});let c=await lt({path:e,mode:a,outDir:o??r?.onboardDir}),l=na(s).createTask(`Onboard`,c.steps.length);for(let e=0;e<c.steps.length;e++){let t=c.steps[e];l.progress(e,`${t.name}: ${t.status}`)}l.complete(`Onboard complete: ${c.steps.filter(e=>e.status===`success`).length}/${c.steps.length} steps succeeded`),os(t,n,c),c.autoRemember?.length&&ss(t,n,c).catch(e=>{is.warn(`Auto-persist autoRemember failed`,A(e))}),i&&(i.onboardComplete=!0,i.onboardTimestamp=new Date().toISOString());let u=[`## Onboard Complete`,``,`**Path:** \`${c.path}\``,`**Mode:** ${c.mode}`,`**Duration:** ${c.totalDurationMs}ms`,``];c.outDir&&(u.push(`**Output directory:** \`${c.outDir}\``),u.push(``)),u.push(`### Analysis Results`,``);let d=[],f=[];for(let e of c.steps)e.status===`success`?d.push(`- ✓ **${e.name}** (${e.durationMs}ms) — ${e.output.length} chars`):f.push(`- ✗ **${e.name}** — ${e.error}`);u.push(...d),f.length>0&&u.push(``,`### Failed`,``,...f),u.push(``,`---`,``);for(let e of c.steps)e.status===`success`&&u.push(`### ${e.name}`,``,e.output,``,`---`,``);return u.push(`_All results auto-saved to KB.`,c.mode===`generate`?` Files written to \`${c.outDir}\`.`:``," Next: Use `search` to query the knowledge, or `remember` to add custom insights._"),{content:[{type:`text`,text:u.join(`
611
+ `)}]}}catch(e){return is.error(`Onboard failed`,A(e)),{content:[{type:`text`,text:`Onboard failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}finally{as=!1}})}const ls=E(`tools:persistence`);function us(e){let t=L(`workset`);e.registerTool(`workset`,{title:t.title,description:`Manage named file sets (worksets). Save, load, list, add/remove files. Worksets persist across sessions in .aikit-state/worksets.json.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`delete`,`add`,`remove`]).describe(`Operation to perform`),name:F.string().optional().describe(`Workset name (required for all except list)`),files:F.array(F.string()).optional().describe(`File paths (required for save, add, remove)`),description:F.string().optional().describe(`Description (for save)`)},annotations:t.annotations},async({action:e,name:t,files:n,description:r})=>{try{switch(e){case`save`:{if(!t||!n)throw Error(`name and files required for save`);let e=Nt(t,n,{description:r});return{content:[{type:`text`,text:`Saved workset "${e.name}" with ${e.files.length} files.`}]}}case`get`:{if(!t)throw Error(`name required for get`);let e=qe(t);return e?{content:[{type:`text`,text:JSON.stringify(e)}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}case`list`:{let e=st();return e.length===0?{content:[{type:`text`,text:`No worksets.`}]}:{content:[{type:`text`,text:e.map(e=>`- **${e.name}** (${e.files.length} files) — ${e.description??`no description`}`).join(`
612
+ `)}]}}case`delete`:if(!t)throw Error(`name required for delete`);return{content:[{type:`text`,text:Pe(t)?`Deleted workset "${t}".`:`Workset "${t}" not found.`}]};case`add`:{if(!t||!n)throw Error(`name and files required for add`);let e=_e(t,n);return{content:[{type:`text`,text:`Added to workset "${e.name}": now ${e.files.length} files.`}]}}case`remove`:{if(!t||!n)throw Error(`name and files required for remove`);let e=Et(t,n);return e?{content:[{type:`text`,text:`Removed from workset "${e.name}": now ${e.files.length} files.`}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}}}catch(e){return ls.error(`Workset operation failed`,A(e)),{content:[{type:`text`,text:`Workset operation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ds(e){let t=L(`stash`);e.registerTool(`stash`,{title:t.title,description:`Persist and retrieve named values in .aikit-state/stash.json for intermediate results between tool calls.`,inputSchema:{action:F.enum([`set`,`get`,`list`,`delete`,`clear`]).describe(`Operation to perform on the stash`),key:F.string().optional().describe(`Entry key for set/get/delete operations`),value:F.string().optional().describe(`String or JSON value for set operations`)},annotations:t.annotations},async({action:e,key:t,value:n})=>{try{switch(e){case`set`:{if(!t)throw Error(`key required for set`);let e=Ut(t,gs(n??``));return{content:[{type:`text`,text:`Stored stash entry "${e.key}" (${e.type}) at ${e.storedAt}.`}]}}case`get`:{if(!t)throw Error(`key required for get`);let e=Vt(t);return{content:[{type:`text`,text:e?JSON.stringify(e):`Stash entry "${t}" not found.`}]}}case`list`:{let e=Ht();return{content:[{type:`text`,text:e.length===0?`Stash is empty.`:e.map(e=>`- ${e.key} (${e.type}) — ${e.storedAt}`).join(`
613
+ `)}]}}case`delete`:if(!t)throw Error(`key required for delete`);return{content:[{type:`text`,text:Bt(t)?`Deleted stash entry "${t}".`:`Stash entry "${t}" not found.`}]};case`clear`:{let e=zt();return{content:[{type:`text`,text:`Cleared ${e} stash entr${e===1?`y`:`ies`}.`}]}}}}catch(e){return ls.error(`Stash operation failed`,A(e)),{content:[{type:`text`,text:`Stash operation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function fs(e){let t=L(`checkpoint`);e.registerTool(`checkpoint`,{title:t.title,description:`Save and restore lightweight session checkpoints in .aikit-state/checkpoints for cross-session continuity.`,inputSchema:{action:F.enum([`save`,`load`,`list`,`latest`]).describe(`Checkpoint action to perform`),label:F.string().optional().describe(`Checkpoint label for save, or checkpoint id for load`),data:F.string().max(5e5).optional().describe(`JSON object string for save actions`),notes:F.string().max(1e4).optional().describe(`Optional notes for save actions`)},annotations:t.annotations},async({action:e,label:t,data:n,notes:r})=>{try{switch(e){case`save`:if(!t)throw Error(`label required for save`);return{content:[{type:`text`,text:hs(Ee(t,_s(n),{notes:r}))}]};case`load`:{if(!t)throw Error(`label required for load`);let e=Te(t);return{content:[{type:`text`,text:e?hs(e):`Checkpoint "${t}" not found.`}]}}case`list`:{let e=we();return{content:[{type:`text`,text:e.length===0?`No checkpoints saved.`:e.map(e=>`- ${e.id} — ${e.label} (${e.createdAt})`).join(`
614
+ `)}]}}case`latest`:{let e=Ce();return{content:[{type:`text`,text:e?hs(e):`No checkpoints saved.`}]}}}}catch(e){return ls.error(`Checkpoint failed`,A(e)),{content:[{type:`text`,text:`Checkpoint failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ps(e){let t=L(`lane`);e.registerTool(`lane`,{title:t.title,description:`Manage verified lanes — isolated file copies for parallel exploration. Create a lane, make changes, diff, merge back, or discard.`,inputSchema:{action:F.enum([`create`,`list`,`status`,`diff`,`merge`,`discard`]).describe(`Lane action to perform`),name:F.string().optional().describe(`Lane name (required for create/status/diff/merge/discard)`),files:F.array(F.string()).optional().describe(`File paths to copy into the lane (required for create)`)},annotations:t.annotations},async({action:e,name:t,files:n})=>{try{switch(e){case`create`:{if(!t)throw Error(`name is required for create`);if(!n||n.length===0)throw Error(`files are required for create`);let e=et(t,n);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`list`:return{content:[{type:`text`,text:JSON.stringify(rt())}]};case`status`:if(!t)throw Error(`name is required for status`);return{content:[{type:`text`,text:JSON.stringify(at(t))}]};case`diff`:if(!t)throw Error(`name is required for diff`);return{content:[{type:`text`,text:JSON.stringify(tt(t))}]};case`merge`:if(!t)throw Error(`name is required for merge`);return{content:[{type:`text`,text:JSON.stringify(it(t))}]};case`discard`:if(!t)throw Error(`name is required for discard`);return{content:[{type:`text`,text:JSON.stringify({discarded:nt(t)})}]}}}catch(e){return ls.error(`Lane action failed`,A(e)),{content:[{type:`text`,text:`Lane action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function ms(e){let t=L(`queue`);e.registerTool(`queue`,{title:t.title,description:`Manage task queues for sequential agent operations. Push items, take next, mark done/failed, list queues.`,inputSchema:{action:F.enum([`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`]).describe(`Queue action`),name:F.string().optional().describe(`Queue name (required for most actions)`),title:F.string().optional().describe(`Item title (required for push)`),id:F.string().optional().describe(`Item ID (required for done/fail)`),data:F.unknown().optional().describe(`Arbitrary data to attach to a queue item`),error:F.string().optional().describe(`Error message (required for fail)`)},annotations:t.annotations},async({action:e,name:t,title:n,id:r,data:i,error:a})=>{try{switch(e){case`create`:if(!t)throw Error(`name is required for create`);return{content:[{type:`text`,text:JSON.stringify(_t(t))}]};case`push`:if(!t)throw Error(`name is required for push`);if(!n)throw Error(`title is required for push`);return{content:[{type:`text`,text:JSON.stringify(wt(t,n,i))}]};case`next`:{if(!t)throw Error(`name is required for next`);let e=Ct(t);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`done`:if(!t)throw Error(`name is required for done`);if(!r)throw Error(`id is required for done`);return{content:[{type:`text`,text:JSON.stringify(yt(t,r))}]};case`fail`:if(!t)throw Error(`name is required for fail`);if(!r)throw Error(`id is required for fail`);if(!a)throw Error(`error is required for fail`);return{content:[{type:`text`,text:JSON.stringify(bt(t,r,a))}]};case`get`:if(!t)throw Error(`name is required for get`);return{content:[{type:`text`,text:JSON.stringify(xt(t))}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(St())}]};case`clear`:if(!t)throw Error(`name is required for clear`);return{content:[{type:`text`,text:JSON.stringify({cleared:gt(t)})}]};case`delete`:if(!t)throw Error(`name is required for delete`);return{content:[{type:`text`,text:JSON.stringify({deleted:vt(t)})}]}}}catch(e){return ls.error(`Queue action failed`,A(e)),{content:[{type:`text`,text:`Queue action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function hs(e){let t=[e.id,`Label: ${e.label}`,`Created: ${e.createdAt}`];if(e.notes&&t.push(`Notes: ${e.notes}`),e.files?.length){t.push(`Files: ${e.files.length}`);for(let n of e.files)t.push(` - ${n}`)}return t.push(``,`Data:`,JSON.stringify(e.data)),t.join(`
615
+ `)}function gs(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function _s(e){let t=e?.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{throw Error(`data must be a valid JSON object string`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`data must be a JSON object string`);return n}const vs=E(`tools`);function ys(e){let t=[`## Rule: ${e.id}`,``,`- **Status**: ${e.enabled?`enabled`:`disabled`}`,`- **Description**: ${e.description??`—`}`,`- **Category**: ${e.category??`—`}`,`- **Push weight**: ${e.pushWeight??`—`}`];return e.patterns?.length&&t.push(`- **Patterns**: ${e.patterns.join(`, `)}`),e.examples?.length&&t.push(`- **Examples**: ${e.examples.join(`, `)}`),t.join(`
616
+ `)}function bs(e,t){let n=L(`er_update_policy`);e.registerTool(`er_update_policy`,{title:n.title,description:`Manage ER push classification rules. Supports listing, updating, creating, and deleting rules that determine when knowledge should be pushed to Enterprise RAG.`,inputSchema:{action:F.enum([`list`,`get`,`update`,`create`,`delete`]).describe(`Action to perform on classification rules`),rule_id:F.string().optional().describe(`Rule ID (required for get, update, delete)`),changes:F.object({patterns:F.array(F.string()).optional(),category:F.string().optional(),pushWeight:F.number().min(0).max(1).optional(),description:F.string().optional(),examples:F.array(F.string()).optional(),enabled:F.boolean().optional()}).optional().describe(`Changes to apply (for update action)`),new_rule:F.object({id:F.string().regex(/^[a-z][a-z0-9-]*$/),patterns:F.array(F.string()).min(1),category:F.string(),pushWeight:F.number().min(0).max(1),description:F.string(),examples:F.array(F.string()).default([]),enabled:F.boolean().default(!0)}).optional().describe(`New rule definition (for create action)`)},annotations:n.annotations},async({action:e,rule_id:n,changes:r,new_rule:i})=>{try{if(e===`list`){let e=t.getRules();return{content:[{type:`text`,text:`## Classification Rules\n\n${e.map(e=>`- **${e.id}** (${e.enabled?`enabled`:`disabled`}) — ${e.description}\n Category: ${e.category} | Weight: ${e.pushWeight} | Patterns: ${e.patterns.join(`, `)}`).join(`
617
+ `)}\n\n---\n_${e.length} rules total. Use \`action: "update"\` to modify a rule._`}]}}if(e===`get`){if(!n)return{content:[{type:`text`,text:'`rule_id` is required for "get" action.'}],isError:!0};let e=t.getRule(n);return e?{content:[{type:`text`,text:ys(e)}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}}if(e===`update`){if(!n||!r)return{content:[{type:`text`,text:'`rule_id` and `changes` are required for "update" action.'}],isError:!0};let e=t.updateRule(n,r);return e?{content:[{type:`text`,text:`${ys(e)}\n\n---\n_Updated. Next: Use \`action: "list"\` to verify._`}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}}return e===`create`?i?{content:[{type:`text`,text:`${ys(t.addRule(i))}\n\n---\n_Created. Next: Test classification with \`remember\`._`}]}:{content:[{type:`text`,text:'`new_rule` is required for "create" action.'}],isError:!0}:e===`delete`?n?t.deleteRule(n)?{content:[{type:`text`,text:`Deleted rule **${n}**.\n\n---\n_Next: Use \`action: "list"\` to verify._`}]}:{content:[{type:`text`,text:`Rule "${n}" not found.`}],isError:!0}:{content:[{type:`text`,text:'`rule_id` is required for "delete" action.'}],isError:!0}:{content:[{type:`text`,text:`Unknown action: ${e}`}],isError:!0}}catch(e){return vs.error(`Policy update failed`,A(e)),{content:[{type:`text`,text:`Policy update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function xs(){return`
618
618
  /* ── Reset ────────────────────────────────────────────────────────── */
619
619
  *{box-sizing:border-box;margin:0;padding:0}
620
620
 
@@ -1009,52 +1009,52 @@ li{margin:4px 0}
1009
1009
  ::-webkit-scrollbar-track{background:var(--card)}
1010
1010
  ::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
1011
1011
  ::-webkit-scrollbar-thumb:hover{background:var(--muted-foreground)}
1012
- `}const K=B;function Cs(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="timeline">${t.items.map(e=>{let t=e.status??`pending`,n=e.phase?`<div class="timeline-phase">${K(e.phase)}</div>`:``,r=e.description?`<div class="timeline-desc">${K(e.description)}</div>`:``;return`<div class="timeline-item">
1012
+ `}const q=B;function Ss(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="timeline">${t.items.map(e=>{let t=e.status??`pending`,n=e.phase?`<div class="timeline-phase">${q(e.phase)}</div>`:``,r=e.description?`<div class="timeline-desc">${q(e.description)}</div>`:``;return`<div class="timeline-item">
1013
1013
  <div class="timeline-dot ${t}"></div>
1014
1014
  ${n}
1015
- <div class="timeline-title">${K(e.title)}</div>
1015
+ <div class="timeline-title">${q(e.title)}</div>
1016
1016
  ${r}
1017
- </div>`}).join(``)}</div>`}function ws(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="checklist">${t.items.map(e=>{let t=e.checked?`checked`:``,n=e.checked?`✓`:``,r=e.note?`<div class="checklist-note">${K(e.note)}</div>`:``;return`<div class="checklist-item ${t}">
1017
+ </div>`}).join(``)}</div>`}function Cs(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="checklist">${t.items.map(e=>{let t=e.checked?`checked`:``,n=e.checked?`✓`:``,r=e.note?`<div class="checklist-note">${q(e.note)}</div>`:``;return`<div class="checklist-item ${t}">
1018
1018
  <div class="checklist-check ${t}">${n}</div>
1019
1019
  <div>
1020
- <div class="checklist-label">${K(e.label)}</div>
1020
+ <div class="checklist-label">${q(e.label)}</div>
1021
1021
  ${r}
1022
1022
  </div>
1023
- </div>`}).join(``)}</div>`}function Ts(e){let t=e;if(t?.left&&t?.right)return Ts({columns:[{title:t.left.label??`Left`,items:t.left.items??[]},{title:t.right.label??`Right`,items:t.right.items??[]}]});if(!t?.columns||!Array.isArray(t.columns)||t.columns.length===0)return``;let n=t.columns.length,r=Math.max(...t.columns.map(e=>e.items?.length??0));return`<div class="comparison-grid" style="grid-template-columns:repeat(${n},1fr)">${t.columns.map(e=>{let t=`<div class="comparison-header">${K(e.title)}</div>`,n=[];for(let t=0;t<r;t++){let r=e.items?.[t]??``;n.push(`<div class="comparison-item">${K(r)}</div>`)}return`<div class="comparison-col">${t}${n.join(``)}</div>`}).join(``)}</div>`}function Es(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="status-board">${t.items.map(e=>{let t=e.detail?`<span class="status-detail">${K(e.detail)}</span>`:``;return`<div class="status-row">
1023
+ </div>`}).join(``)}</div>`}function ws(e){let t=e;if(t?.left&&t?.right)return ws({columns:[{title:t.left.label??`Left`,items:t.left.items??[]},{title:t.right.label??`Right`,items:t.right.items??[]}]});if(!t?.columns||!Array.isArray(t.columns)||t.columns.length===0)return``;let n=t.columns.length,r=Math.max(...t.columns.map(e=>e.items?.length??0));return`<div class="comparison-grid" style="grid-template-columns:repeat(${n},1fr)">${t.columns.map(e=>{let t=`<div class="comparison-header">${q(e.title)}</div>`,n=[];for(let t=0;t<r;t++){let r=e.items?.[t]??``;n.push(`<div class="comparison-item">${q(r)}</div>`)}return`<div class="comparison-col">${t}${n.join(``)}</div>`}).join(``)}</div>`}function Ts(e){let t=e;return!t?.items||!Array.isArray(t.items)?``:`<div class="status-board">${t.items.map(e=>{let t=e.detail?`<span class="status-detail">${q(e.detail)}</span>`:``;return`<div class="status-row">
1024
1024
  <div class="status-indicator ${e.status??`pending`}"></div>
1025
- <span class="status-label">${K(e.label)}</span>
1025
+ <span class="status-label">${q(e.label)}</span>
1026
1026
  ${t}
1027
- </div>`}).join(``)}</div>`}function Ds(e){let t=e;if(!t?.question)return``;let n=t.context?`<div class="prompt-context">${K(t.context)}</div>`:``,r=t.placeholder?`<div class="prompt-placeholder">${K(t.placeholder)}</div>`:``;return`<div class="prompt-block">
1028
- <div class="prompt-question">${K(t.question)}</div>
1027
+ </div>`}).join(``)}</div>`}function Es(e){let t=e;if(!t?.question)return``;let n=t.context?`<div class="prompt-context">${q(t.context)}</div>`:``,r=t.placeholder?`<div class="prompt-placeholder">${q(t.placeholder)}</div>`:``;return`<div class="prompt-block">
1028
+ <div class="prompt-question">${q(t.question)}</div>
1029
1029
  ${n}${r}
1030
- </div>`}function Os(e){let t=e;if(!t?.items||!Array.isArray(t.items))return``;let n=e=>e>=100?`var(--success)`:e>=60?`var(--primary)`:e>=30?`var(--warning)`:`var(--error)`;return`<div class="progress-list">${t.items.map(e=>{let t=e.max??100,r=t>0?Math.min(100,e.value/t*100):0,i=e.color??n(r);return`<div class="progress-item">
1030
+ </div>`}function Ds(e){let t=e;if(!t?.items||!Array.isArray(t.items))return``;let n=e=>e>=100?`var(--success)`:e>=60?`var(--primary)`:e>=30?`var(--warning)`:`var(--error)`;return`<div class="progress-list">${t.items.map(e=>{let t=e.max??100,r=t>0?Math.min(100,e.value/t*100):0,i=e.color??n(r);return`<div class="progress-item">
1031
1031
  <div class="progress-header">
1032
- <span class="progress-label">${K(e.label)}</span>
1032
+ <span class="progress-label">${q(e.label)}</span>
1033
1033
  <span class="progress-value">${e.value}/${t}</span>
1034
1034
  </div>
1035
1035
  <div class="progress-track">
1036
1036
  <div class="progress-fill" style="width:${r.toFixed(1)}%;background:${i}"></div>
1037
1037
  </div>
1038
- </div>`}).join(``)}</div>`}const q=B;function ks(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:Number.isInteger(e)?String(e):e.toFixed(1)}function As(e){return`var(--chart-${e%12+1})`}let js=0;function Ms(e){let t=e.value;if(!t?.data?.length||!t.chartType)return`<pre>${q(JSON.stringify(e.value,null,2))}</pre>`;js++;let n=e.title||t.title?`<div class="chart-title">${q(String(e.title||t.title))}</div>`:``,r;switch(t.chartType){case`line`:r=Bs(t,!1);break;case`area`:r=Bs(t,!0);break;case`bar`:r=Vs(t,!1);break;case`horizontal-bar`:r=Vs(t,!0);break;case`pie`:r=Hs(t,!1);break;case`donut`:r=Hs(t,!0);break;case`sparkline`:r=Us(t);break;case`heatmap`:r=Ws(t);break;default:r=`<pre>${q(JSON.stringify(t,null,2))}</pre>`}let i=t.showLegend!==!1&&t.yKeys.length>1&&t.chartType!==`sparkline`?Ns(t.yKeys):``;return`<div class="chart-container">${n}${r}${i}</div>`}function Ns(e){return`<div class="chart-legend">${e.map((e,t)=>`<span class="chart-legend-item"><span class="chart-legend-swatch" style="background:${As(t)}"></span>${q(e)}</span>`).join(``)}</div>`}const J={top:20,right:20,bottom:35,left:55};function Ps(e,t){return e.map(e=>Number(e[t])||0)}function Fs(e,t){return e.map(e=>String(e[t]??``))}function Is(e){let t=1/0,n=-1/0;for(let r of e)r<t&&(t=r),r>n&&(n=r);return t===n&&(t=t===0?0:t*.9,n=n===0?1:n*1.1),[t,n]}function Ls(e){return e>=0?0:e}function Rs(e,t,n,r=5){let i=[];for(let a=0;a<=r;a++){let o=a/r,s=J.top+n-o*n,c=e+o*(t-e);i.push(`<line class="chart-grid-line" x1="${J.left}" x2="${600-J.right}" y1="${s}" y2="${s}"/>`),i.push(`<text class="chart-axis-label" x="${J.left-8}" y="${s+4}" text-anchor="end">${ks(c)}</text>`)}return i.join(``)}function zs(e,t,n,r){let i=Math.floor(t/50),a=Math.max(1,Math.ceil(e.length/i));return e.map((e,t)=>t%a===0?`<text class="chart-axis-label" x="${J.left+t*r+r/2}" y="${J.top+n+18}" text-anchor="middle">${q(e.length>10?`${e.slice(0,9)}…`:e)}</text>`:``).join(``)}function Bs(e,t){let n=(e.height??300)-J.top-J.bottom,r=600-J.left-J.right,i=Fs(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=r/Math.max(a-1,1),s=1/0,c=-1/0;for(let t of e.yKeys){let[n,r]=Is(Ps(e.data,t));n<s&&(s=n),r>c&&(c=r)}s=Ls(s);let l=c-s||1,u=e=>J.top+n-(e-s)/l*n,d=e=>J.left+e*o,f=``,p=[];for(let r=0;r<e.yKeys.length;r++){let i=Ps(e.data,e.yKeys[r]),o=As(r),s=`M${i.map((e,t)=>`${d(t).toFixed(1)},${u(e).toFixed(1)}`).join(`L`)}`;if(t){let e=`ag${js}_${r}`;f+=`<linearGradient id="${e}" x1="0" y1="0" x2="0" y2="1">
1038
+ </div>`}).join(``)}</div>`}const J=B;function Os(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:Number.isInteger(e)?String(e):e.toFixed(1)}function ks(e){return`var(--chart-${e%12+1})`}let As=0;function js(e){let t=e.value;if(!t?.data?.length||!t.chartType)return`<pre>${J(JSON.stringify(e.value,null,2))}</pre>`;As++;let n=e.title||t.title?`<div class="chart-title">${J(String(e.title||t.title))}</div>`:``,r;switch(t.chartType){case`line`:r=zs(t,!1);break;case`area`:r=zs(t,!0);break;case`bar`:r=Bs(t,!1);break;case`horizontal-bar`:r=Bs(t,!0);break;case`pie`:r=Vs(t,!1);break;case`donut`:r=Vs(t,!0);break;case`sparkline`:r=Hs(t);break;case`heatmap`:r=Us(t);break;default:r=`<pre>${J(JSON.stringify(t,null,2))}</pre>`}let i=t.showLegend!==!1&&t.yKeys.length>1&&t.chartType!==`sparkline`?Ms(t.yKeys):``;return`<div class="chart-container">${n}${r}${i}</div>`}function Ms(e){return`<div class="chart-legend">${e.map((e,t)=>`<span class="chart-legend-item"><span class="chart-legend-swatch" style="background:${ks(t)}"></span>${J(e)}</span>`).join(``)}</div>`}const Y={top:20,right:20,bottom:35,left:55};function Ns(e,t){return e.map(e=>Number(e[t])||0)}function Ps(e,t){return e.map(e=>String(e[t]??``))}function Fs(e){let t=1/0,n=-1/0;for(let r of e)r<t&&(t=r),r>n&&(n=r);return t===n&&(t=t===0?0:t*.9,n=n===0?1:n*1.1),[t,n]}function Is(e){return e>=0?0:e}function Ls(e,t,n,r=5){let i=[];for(let a=0;a<=r;a++){let o=a/r,s=Y.top+n-o*n,c=e+o*(t-e);i.push(`<line class="chart-grid-line" x1="${Y.left}" x2="${600-Y.right}" y1="${s}" y2="${s}"/>`),i.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${s+4}" text-anchor="end">${Os(c)}</text>`)}return i.join(``)}function Rs(e,t,n,r){let i=Math.floor(t/50),a=Math.max(1,Math.ceil(e.length/i));return e.map((e,t)=>t%a===0?`<text class="chart-axis-label" x="${Y.left+t*r+r/2}" y="${Y.top+n+18}" text-anchor="middle">${J(e.length>10?`${e.slice(0,9)}…`:e)}</text>`:``).join(``)}function zs(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=Ps(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=r/Math.max(a-1,1),s=1/0,c=-1/0;for(let t of e.yKeys){let[n,r]=Fs(Ns(e.data,t));n<s&&(s=n),r>c&&(c=r)}s=Is(s);let l=c-s||1,u=e=>Y.top+n-(e-s)/l*n,d=e=>Y.left+e*o,f=``,p=[];for(let r=0;r<e.yKeys.length;r++){let i=Ns(e.data,e.yKeys[r]),o=ks(r),s=`M${i.map((e,t)=>`${d(t).toFixed(1)},${u(e).toFixed(1)}`).join(`L`)}`;if(t){let e=`ag${As}_${r}`;f+=`<linearGradient id="${e}" x1="0" y1="0" x2="0" y2="1">
1039
1039
  <stop offset="0%" stop-color="${o}" stop-opacity="0.3"/>
1040
1040
  <stop offset="100%" stop-color="${o}" stop-opacity="0"/>
1041
- </linearGradient>`;let t=`${s}L${d(a-1).toFixed(1)},${(J.top+n).toFixed(1)}L${d(0).toFixed(1)},${(J.top+n).toFixed(1)}Z`;p.push(`<path d="${t}" fill="url(#${e})" stroke="none"/>`)}p.push(`<path d="${s}" fill="none" stroke="${o}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);for(let e=0;e<i.length;e++)p.push(`<circle cx="${d(e).toFixed(1)}" cy="${u(i[e]).toFixed(1)}" r="3" fill="${o}" stroke="var(--card)" stroke-width="1.5"/>`)}let m=e.height??300,h=e.showGrid===!1?``:Rs(s,c,n),g=zs(i,r,n,a>1?o:r);return`<svg class="chart-svg" viewBox="0 0 600 ${m}" preserveAspectRatio="xMidYMid meet">
1041
+ </linearGradient>`;let t=`${s}L${d(a-1).toFixed(1)},${(Y.top+n).toFixed(1)}L${d(0).toFixed(1)},${(Y.top+n).toFixed(1)}Z`;p.push(`<path d="${t}" fill="url(#${e})" stroke="none"/>`)}p.push(`<path d="${s}" fill="none" stroke="${o}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);for(let e=0;e<i.length;e++)p.push(`<circle cx="${d(e).toFixed(1)}" cy="${u(i[e]).toFixed(1)}" r="3" fill="${o}" stroke="var(--card)" stroke-width="1.5"/>`)}let m=e.height??300,h=e.showGrid===!1?``:Ls(s,c,n),g=Rs(i,r,n,a>1?o:r);return`<svg class="chart-svg" viewBox="0 0 600 ${m}" preserveAspectRatio="xMidYMid meet">
1042
1042
  ${f?`<defs>${f}</defs>`:``}
1043
1043
  ${h}${g}${p.join(``)}
1044
- </svg>`}function Vs(e,t){let n=(e.height??300)-J.top-J.bottom,r=600-J.left-J.right,i=Fs(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=e.yKeys.length,s=0;for(let t of e.yKeys)for(let n of Ps(e.data,t))n>s&&(s=n);s===0&&(s=1);let c=e.height??300,l=[];if(t){let t=Math.min(24,(n-(a-1)*4)/(a*o)),u=t*o+4,d=e.showGrid===!1?``:Rs(0,s,n),f=i.map((e,t)=>{let n=J.top+t*u+u/2,r=e.length>15?`${e.slice(0,14)}…`:e;return`<text class="chart-axis-label" x="${J.left-8}" y="${n+4}" text-anchor="end">${q(r)}</text>`}).join(``);for(let n=0;n<a;n++)for(let i=0;i<o;i++){let a=Number(e.data[n][e.yKeys[i]])||0,o=a/s*r,c=J.top+n*u+i*t;l.push(`<rect x="${J.left}" y="${c}" width="${o.toFixed(1)}" height="${t-2}" rx="3" fill="${As(i)}" opacity="0.85">
1045
- <title>${q(e.yKeys[i])}: ${ks(a)}</title>
1046
- </rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${Math.max(c,a*u+J.top+J.bottom)}" preserveAspectRatio="xMidYMid meet">
1044
+ </svg>`}function Bs(e,t){let n=(e.height??300)-Y.top-Y.bottom,r=600-Y.left-Y.right,i=Ps(e.data,e.xKey),a=e.data.length;if(a===0)return``;let o=e.yKeys.length,s=0;for(let t of e.yKeys)for(let n of Ns(e.data,t))n>s&&(s=n);s===0&&(s=1);let c=e.height??300,l=[];if(t){let t=Math.min(24,(n-(a-1)*4)/(a*o)),u=t*o+4,d=e.showGrid===!1?``:Ls(0,s,n),f=i.map((e,t)=>{let n=Y.top+t*u+u/2,r=e.length>15?`${e.slice(0,14)}…`:e;return`<text class="chart-axis-label" x="${Y.left-8}" y="${n+4}" text-anchor="end">${J(r)}</text>`}).join(``);for(let n=0;n<a;n++)for(let i=0;i<o;i++){let a=Number(e.data[n][e.yKeys[i]])||0,o=a/s*r,c=Y.top+n*u+i*t;l.push(`<rect x="${Y.left}" y="${c}" width="${o.toFixed(1)}" height="${t-2}" rx="3" fill="${ks(i)}" opacity="0.85">
1045
+ <title>${J(e.yKeys[i])}: ${Os(a)}</title>
1046
+ </rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${Math.max(c,a*u+Y.top+Y.bottom)}" preserveAspectRatio="xMidYMid meet">
1047
1047
  ${d}${f}${l.join(``)}
1048
- </svg>`}else{let t=r/a,u=Math.min(40,(t-8)/o),d=e.showGrid===!1?``:Rs(0,s,n),f=zs(i,r,n,t);for(let r=0;r<a;r++)for(let i=0;i<o;i++){let a=Number(e.data[r][e.yKeys[i]])||0,c=a/s*n,d=J.left+r*t+(t-u*o)/2+i*u,f=J.top+n-c;l.push(`<rect x="${d.toFixed(1)}" y="${f.toFixed(1)}" width="${(u-2).toFixed(1)}" height="${c.toFixed(1)}" rx="3" fill="${As(i)}" opacity="0.85">
1049
- <title>${q(e.yKeys[i])}: ${ks(a)}</title>
1048
+ </svg>`}else{let t=r/a,u=Math.min(40,(t-8)/o),d=e.showGrid===!1?``:Ls(0,s,n),f=Rs(i,r,n,t);for(let r=0;r<a;r++)for(let i=0;i<o;i++){let a=Number(e.data[r][e.yKeys[i]])||0,c=a/s*n,d=Y.left+r*t+(t-u*o)/2+i*u,f=Y.top+n-c;l.push(`<rect x="${d.toFixed(1)}" y="${f.toFixed(1)}" width="${(u-2).toFixed(1)}" height="${c.toFixed(1)}" rx="3" fill="${ks(i)}" opacity="0.85">
1049
+ <title>${J(e.yKeys[i])}: ${Os(a)}</title>
1050
1050
  </rect>`)}return`<svg class="chart-svg" viewBox="0 0 600 ${c}" preserveAspectRatio="xMidYMid meet">
1051
1051
  ${d}${f}${l.join(``)}
1052
- </svg>`}}function Hs(e,t){let n=e.height??300,r=n/2,i=n/2,a=n/2-10,o=t?a*.55:0,s=e.yKeys[0]||`value`,c=e.data.map(e=>Math.max(0,Number(e[s])||0)),l=Fs(e.data,e.xKey),u=c.reduce((e,t)=>e+t,0);if(u===0)return`<div style="color:var(--muted-foreground);text-align:center;padding:20px">No data</div>`;let d=[],f=-Math.PI/2;for(let e=0;e<c.length;e++){let t=c[e]/u;if(t===0)continue;let n=t*Math.PI*2,s=f,p=f+n,m=r+a*Math.cos(s),h=i+a*Math.sin(s),g=r+a*Math.cos(p),_=i+a*Math.sin(p),v=+(n>Math.PI),y;if(o>0){let e=r+o*Math.cos(s),t=i+o*Math.sin(s),n=r+o*Math.cos(p),c=i+o*Math.sin(p);y=`M${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)} L${n.toFixed(2)},${c.toFixed(2)} A${o},${o} 0 ${v},0 ${e.toFixed(2)},${t.toFixed(2)}Z`}else y=`M${r},${i} L${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)}Z`;d.push(`<path d="${y}" fill="${As(e)}" stroke="var(--background)" stroke-width="2" opacity="0.9">
1053
- <title>${q(l[e]||`Item ${e+1}`)}: ${ks(c[e])} (${(t*100).toFixed(1)}%)</title>
1054
- </path>`),f=p}let p=t?`<text x="${r}" y="${i-6}" text-anchor="middle" fill="var(--foreground)" font-size="18" font-weight="700">${ks(u)}</text>
1055
- <text x="${r}" y="${i+12}" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">Total</text>`:``,m=Ns(l.filter((e,t)=>c[t]>0));return`<svg class="chart-svg" viewBox="0 0 ${n} ${n}" preserveAspectRatio="xMidYMid meet">
1052
+ </svg>`}}function Vs(e,t){let n=e.height??300,r=n/2,i=n/2,a=n/2-10,o=t?a*.55:0,s=e.yKeys[0]||`value`,c=e.data.map(e=>Math.max(0,Number(e[s])||0)),l=Ps(e.data,e.xKey),u=c.reduce((e,t)=>e+t,0);if(u===0)return`<div style="color:var(--muted-foreground);text-align:center;padding:20px">No data</div>`;let d=[],f=-Math.PI/2;for(let e=0;e<c.length;e++){let t=c[e]/u;if(t===0)continue;let n=t*Math.PI*2,s=f,p=f+n,m=r+a*Math.cos(s),h=i+a*Math.sin(s),g=r+a*Math.cos(p),_=i+a*Math.sin(p),v=+(n>Math.PI),y;if(o>0){let e=r+o*Math.cos(s),t=i+o*Math.sin(s),n=r+o*Math.cos(p),c=i+o*Math.sin(p);y=`M${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)} L${n.toFixed(2)},${c.toFixed(2)} A${o},${o} 0 ${v},0 ${e.toFixed(2)},${t.toFixed(2)}Z`}else y=`M${r},${i} L${m.toFixed(2)},${h.toFixed(2)} A${a},${a} 0 ${v},1 ${g.toFixed(2)},${_.toFixed(2)}Z`;d.push(`<path d="${y}" fill="${ks(e)}" stroke="var(--background)" stroke-width="2" opacity="0.9">
1053
+ <title>${J(l[e]||`Item ${e+1}`)}: ${Os(c[e])} (${(t*100).toFixed(1)}%)</title>
1054
+ </path>`),f=p}let p=t?`<text x="${r}" y="${i-6}" text-anchor="middle" fill="var(--foreground)" font-size="18" font-weight="700">${Os(u)}</text>
1055
+ <text x="${r}" y="${i+12}" text-anchor="middle" fill="var(--muted-foreground)" font-size="11">Total</text>`:``,m=Ms(l.filter((e,t)=>c[t]>0));return`<svg class="chart-svg" viewBox="0 0 ${n} ${n}" preserveAspectRatio="xMidYMid meet">
1056
1056
  ${d.join(``)}${p}
1057
- </svg>${m}`}function Us(e){let t=e.height??40,n=e.yKeys[0]||`value`,r=Ps(e.data,n),i=r.length;if(i===0)return``;let[a,o]=Is(r),s=o-a||1,c=200/Math.max(i-1,1),l=r.map((e,n)=>`${(n*c).toFixed(1)},${(t-4-(e-a)/s*(t-8)).toFixed(1)}`),u=`spk${js}`,d=As(0);return`<svg class="chart-svg" viewBox="0 0 200 ${t}" preserveAspectRatio="xMidYMid meet" style="max-width:200px;height:${t}px">
1057
+ </svg>${m}`}function Hs(e){let t=e.height??40,n=e.yKeys[0]||`value`,r=Ns(e.data,n),i=r.length;if(i===0)return``;let[a,o]=Fs(r),s=o-a||1,c=200/Math.max(i-1,1),l=r.map((e,n)=>`${(n*c).toFixed(1)},${(t-4-(e-a)/s*(t-8)).toFixed(1)}`),u=`spk${As}`,d=ks(0);return`<svg class="chart-svg" viewBox="0 0 200 ${t}" preserveAspectRatio="xMidYMid meet" style="max-width:200px;height:${t}px">
1058
1058
  <defs>
1059
1059
  <linearGradient id="${u}" x1="0" y1="0" x2="0" y2="1">
1060
1060
  <stop offset="0%" stop-color="${d}" stop-opacity="0.2"/>
@@ -1064,11 +1064,14 @@ li{margin:4px 0}
1064
1064
  <path d="M${l.join(`L`)}L${((i-1)*c).toFixed(1)},${t}L0,${t}Z" fill="url(#${u})" stroke="none"/>
1065
1065
  <polyline points="${l.join(` `)}" fill="none" stroke="${d}" stroke-width="1.5" stroke-linejoin="round"/>
1066
1066
  <circle cx="${((i-1)*c).toFixed(1)}" cy="${l[i-1].split(`,`)[1]}" r="2.5" fill="${d}"/>
1067
- </svg>`}function Ws(e){let t=Fs(e.data,e.xKey),n=e.data.length,r=e.yKeys.length;if(n===0||r===0)return``;let i=1/0,a=-1/0;for(let t of e.yKeys)for(let n of Ps(e.data,t))n<i&&(i=n),n>a&&(a=n);let o=a-i||1,s=Math.min(50,(600-J.left-J.right)/n),c=Math.min(30,200/r),l=J.left+n*s+J.right,u=J.top+r*c+J.bottom,d=[];for(let t=0;t<r;t++){let n=J.top+t*c+c/2+4,r=e.yKeys[t].length>8?`${e.yKeys[t].slice(0,7)}…`:e.yKeys[t];d.push(`<text class="chart-axis-label" x="${J.left-8}" y="${n}" text-anchor="end">${q(r)}</text>`)}let f=Math.floor((l-J.left)/40),p=Math.max(1,Math.ceil(n/f));for(let e=0;e<n;e++){if(e%p!==0)continue;let n=J.left+e*s+s/2,r=t[e].length>6?`${t[e].slice(0,5)}…`:t[e];d.push(`<text class="chart-axis-label" x="${n}" y="${u-8}" text-anchor="middle">${q(r)}</text>`)}for(let a=0;a<n;a++)for(let n=0;n<r;n++){let r=Number(e.data[a][e.yKeys[n]])||0,l=(r-i)/o,u=J.left+a*s,f=J.top+n*c;d.push(`<rect x="${u}" y="${f}" width="${s-1}" height="${c-1}" rx="2" fill="var(--primary)" opacity="${(.1+l*.8).toFixed(2)}">
1068
- <title>${q(t[a])} / ${q(e.yKeys[n])}: ${ks(r)}</title>
1067
+ </svg>`}function Us(e){let t=Ps(e.data,e.xKey),n=e.data.length,r=e.yKeys.length;if(n===0||r===0)return``;let i=1/0,a=-1/0;for(let t of e.yKeys)for(let n of Ns(e.data,t))n<i&&(i=n),n>a&&(a=n);let o=a-i||1,s=Math.min(50,(600-Y.left-Y.right)/n),c=Math.min(30,200/r),l=Y.left+n*s+Y.right,u=Y.top+r*c+Y.bottom,d=[];for(let t=0;t<r;t++){let n=Y.top+t*c+c/2+4,r=e.yKeys[t].length>8?`${e.yKeys[t].slice(0,7)}…`:e.yKeys[t];d.push(`<text class="chart-axis-label" x="${Y.left-8}" y="${n}" text-anchor="end">${J(r)}</text>`)}let f=Math.floor((l-Y.left)/40),p=Math.max(1,Math.ceil(n/f));for(let e=0;e<n;e++){if(e%p!==0)continue;let n=Y.left+e*s+s/2,r=t[e].length>6?`${t[e].slice(0,5)}…`:t[e];d.push(`<text class="chart-axis-label" x="${n}" y="${u-8}" text-anchor="middle">${J(r)}</text>`)}for(let a=0;a<n;a++)for(let n=0;n<r;n++){let r=Number(e.data[a][e.yKeys[n]])||0,l=(r-i)/o,u=Y.left+a*s,f=Y.top+n*c;d.push(`<rect x="${u}" y="${f}" width="${s-1}" height="${c-1}" rx="2" fill="var(--primary)" opacity="${(.1+l*.8).toFixed(2)}">
1068
+ <title>${J(t[a])} / ${J(e.yKeys[n])}: ${Os(r)}</title>
1069
1069
  </rect>`)}return`<svg class="chart-svg" viewBox="0 0 ${l} ${u}" preserveAspectRatio="xMidYMid meet">
1070
1070
  ${d.join(``)}
1071
- </svg>`}function Gs(e){if(e==null)return`null`;if(Array.isArray(e))return`[${e.map(Gs).join(`, `)}]`;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function Ks(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function qs(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return new Set([`separator`,`actions`]).has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function Js(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Ys(e){let t=e,n=e;if(`value`in n||(typeof t.text==`string`?n={...n,value:t.text}:typeof t.content==`string`?n={...n,value:t.content}:typeof t.markdown==`string`?n={...n,value:t.markdown}:typeof t.description==`string`?n={...n,value:t.description}:typeof t.code==`string`?n={...n,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?n={...n,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?n={...n,value:{items:t.items}}:Array.isArray(t.metrics)?n={...n,value:t.metrics}:Array.isArray(t.cards)?n={...n,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?n={...n,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?n={...n,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:(`chartType`in t||Array.isArray(t.data))&&(n={...n,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}})),n.type===`chart`){let e=n.value;if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e,r=t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:null,i=Array.isArray(t.labels)?t.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(t.datasets)?t.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof t.type==`string`?t.type:typeof t.chartType==`string`?t.chartType:null;if(o&&i&&a&&!Array.isArray(t.data)){let e=a.map((e,t)=>String(e.label??`series${t+1}`)),t=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});n={...n,value:{chartType:String(o),data:t,xKey:`label`,yKeys:e}}}}}let r=n;if(n.type===`text`||n.type===`paragraph`)return{...n,type:`markdown`};if(n.type===`heading`)return{...n,type:`markdown`,value:`## ${String(r.value??``)}`};if(n.type===`kv`){let e=t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)?t.entries:r.value&&typeof r.value==`object`&&!Array.isArray(r.value)?r.value:null;if(e)return{...n,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(e).map(([e,t])=>[e,t])}}}if(n.type===`comparison`){let e=Js(t.columns??(r.value&&typeof r.value==`object`?r.value.columns:void 0))??Js(r.value);if(e)return{...n,type:`table`,value:e};let i=r.value;if(i&&typeof i==`object`&&!Array.isArray(i)){let e=i;if(Array.isArray(e.headers)&&Array.isArray(e.rows))return{...n,type:`table`}}}if(n.type===`timeline`){let e=r.value;if(Array.isArray(e)){let t=e.map(e=>{if(e&&typeof e==`object`){let t=e;return[String(t.status??t.state??``),String(t.time??t.date??t.timestamp??``),String(t.label??t.description??t.title??t.text??``)]}return[``,``,String(e)]});return{...n,type:`table`,value:{headers:[`Status`,`Time`,`Description`],rows:t}}}}return n}function Xs(e,t){let n=e=>{if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(typeof e==`object`)try{let t=JSON.stringify(e);return typeof t==`string`?t:String(e)}catch{return String(e)}return String(e)};if(e==null)return null;if(typeof e==`string`)return{type:`markdown`,title:t,value:e};if(typeof e==`number`||typeof e==`boolean`)return{type:`markdown`,title:t,value:String(e)};if(Array.isArray(e)){if(e.every(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`))return{type:`markdown`,title:t,value:e.map(e=>`- ${String(e)}`).join(`
1071
+ </svg>`}function Ws(e){if(e==null)return`null`;if(Array.isArray(e))return`[${e.map(Ws).join(`, `)}]`;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function Gs(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function Ks(e){if(typeof e!=`string`)return e;let t=e.trim();if(t.startsWith(`[`)&&t.endsWith(`]`)||t.startsWith(`{`)&&t.endsWith(`}`))try{return JSON.parse(t)}catch{return e}return e}function qs(e){if(typeof e!=`object`||!e||!(`type`in e))return!1;let t=e,n=typeof t.type==`string`?t.type:``;return new Set([`separator`,`actions`]).has(n)?!0:`value`in t||typeof t.text==`string`||Array.isArray(t.headers)&&Array.isArray(t.rows)||typeof t.code==`string`||Array.isArray(t.items)||!!t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)||!!t.columns&&typeof t.columns==`object`||`chartType`in t||Array.isArray(t.data)||typeof t.content==`string`||typeof t.markdown==`string`||typeof t.description==`string`||Array.isArray(t.metrics)||Array.isArray(t.cards)||Array.isArray(t.nodes)||typeof t.question==`string`}function Js(e){if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e),n=t.map(e=>String(e.title??``)),r=Math.max(0,...t.map(e=>Array.isArray(e.items)?e.items.length:0));return{headers:n,rows:Array.from({length:r},(e,n)=>t.map(e=>Array.isArray(e.items)?e.items[n]??``:``))}}if(!e||typeof e!=`object`)return null;let t=e,n=Object.keys(t),r=Math.max(0,...n.map(e=>Array.isArray(t[e])?t[e].length:0));return{headers:n,rows:Array.from({length:r},(e,r)=>n.map(e=>Array.isArray(t[e])?t[e][r]??``:``))}}function Ys(e){let t=e,n=e;if(`value`in n||(typeof t.text==`string`?n={...n,value:t.text}:typeof t.content==`string`?n={...n,value:t.content}:typeof t.markdown==`string`?n={...n,value:t.markdown}:typeof t.description==`string`?n={...n,value:t.description}:typeof t.code==`string`?n={...n,value:t.code}:Array.isArray(t.headers)&&Array.isArray(t.rows)?n={...n,value:{headers:t.headers,rows:t.rows}}:Array.isArray(t.items)?n={...n,value:{items:t.items}}:Array.isArray(t.metrics)?n={...n,value:t.metrics}:Array.isArray(t.cards)?n={...n,value:t.cards}:Array.isArray(t.nodes)&&Array.isArray(t.edges)?n={...n,value:{nodes:t.nodes,edges:t.edges}}:typeof t.question==`string`?n={...n,value:{question:t.question,context:t.context,placeholder:t.placeholder}}:(`chartType`in t||Array.isArray(t.data))&&(n={...n,value:{chartType:t.chartType,data:t.data,xKey:t.xKey??`label`,yKeys:t.yKeys??[`value`]}})),n.type===`chart`){let e=n.value;if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e,r=t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:null,i=Array.isArray(t.labels)?t.labels:Array.isArray(r?.labels)?r.labels:null,a=Array.isArray(t.datasets)?t.datasets:Array.isArray(r?.datasets)?r.datasets:null,o=typeof t.type==`string`?t.type:typeof t.chartType==`string`?t.chartType:null;if(o&&i&&a&&!Array.isArray(t.data)){let e=a.map((e,t)=>String(e.label??`series${t+1}`)),t=i.map((e,t)=>{let n={label:String(e)};for(let[e,r]of a.entries()){let i=r,a=String(i.label??`series${e+1}`);n[a]=i.data?.[t]??0}return n});n={...n,value:{chartType:String(o),data:t,xKey:`label`,yKeys:e}}}}}let r=n;if(n.type===`text`||n.type===`paragraph`)return{...n,type:`markdown`};if(n.type===`heading`)return{...n,type:`markdown`,value:`## ${String(r.value??``)}`};if(n.type===`header`){let e=Math.min(Math.max(Number(n.level)||2,1),6);return{...n,type:`markdown`,value:`${`#`.repeat(e)} ${String(r.value??``)}`}}if(n.type===`section`)return{...n,type:`markdown`};if(n.type===`list`||n.type===`bullet`||n.type===`bullets`){let e=Array.isArray(r.value)?r.value:r.value&&typeof r.value==`object`&&Array.isArray(r.value.items)?r.value.items:void 0;return Array.isArray(e)?{...n,type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
1072
+ `)}:{...n,type:`markdown`}}if(n.type===`note`||n.type===`info`||n.type===`warning`||n.type===`alert`||n.type===`callout`){let e=n.type===`warning`?`⚠️`:n.type===`alert`?`🚨`:`ℹ️`;return{...n,type:`markdown`,value:`> ${e} ${String(r.value??``)}`}}if(n.type===`quote`||n.type===`blockquote`){let e=String(r.value??``).split(`
1073
+ `);return{...n,type:`markdown`,value:e.map(e=>`> ${e}`).join(`
1074
+ `)}}if(n.type===`divider`||n.type===`hr`)return{...n,type:`separator`};if(n.type===`image`||n.type===`img`){let e=n,t=String(e.src??e.url??e.value??``),r=String(e.alt??e.label??e.title??`image`);return{...n,type:`markdown`,value:`![${r}](${t})`}}if(n.type===`link`||n.type===`url`){let e=n,t=String(e.href??e.url??e.value??``),r=String(e.label??e.text??e.title??t);return{...n,type:`markdown`,value:`[${r}](${t})`}}if(n.type===`kv`){let e=t.entries&&typeof t.entries==`object`&&!Array.isArray(t.entries)?t.entries:r.value&&typeof r.value==`object`&&!Array.isArray(r.value)?r.value:null;if(e)return{...n,type:`table`,value:{headers:[`Key`,`Value`],rows:Object.entries(e).map(([e,t])=>[e,t])}}}if(n.type===`comparison`){let e=Js(t.columns??(r.value&&typeof r.value==`object`?r.value.columns:void 0))??Js(r.value);if(e)return{...n,type:`table`,value:e};let i=r.value;if(i&&typeof i==`object`&&!Array.isArray(i)){let e=i;if(Array.isArray(e.headers)&&Array.isArray(e.rows))return{...n,type:`table`}}}if(n.type===`timeline`){let e=r.value;if(Array.isArray(e)){let t=e.map(e=>{if(e&&typeof e==`object`){let t=e;return[String(t.status??t.state??``),String(t.time??t.date??t.timestamp??``),String(t.label??t.description??t.title??t.text??``)]}return[``,``,String(e)]});return{...n,type:`table`,value:{headers:[`Status`,`Time`,`Description`],rows:t}}}}return n}function Xs(e,t){let n=e=>{if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(typeof e==`object`)try{let t=JSON.stringify(e);return typeof t==`string`?t:String(e)}catch{return String(e)}return String(e)};if(e==null)return null;if(typeof e==`string`)return{type:`markdown`,title:t,value:e};if(typeof e==`number`||typeof e==`boolean`)return{type:`markdown`,title:t,value:String(e)};if(Array.isArray(e)){if(e.every(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`))return{type:`markdown`,title:t,value:e.map(e=>`- ${String(e)}`).join(`
1072
1075
  `)};let n=e.filter(e=>typeof e==`object`&&!!e);if(n.length===e.length){let e={success:`✅`,done:`✅`,warning:`⚠️`,"at-risk":`⚠️`,error:`❌`,info:`ℹ️`,pending:`⏳`};if(n.every(e=>typeof e.category==`string`&&Array.isArray(e.items))){let r=n.map(t=>{let n=typeof t.category==`string`?t.category:null,r=Array.isArray(t.items)?t.items:null;if(!n||!r)return null;let i=r.map(t=>{if(!t||typeof t!=`object`)return null;let n=t,r=n.label??n.title??n.name,i=typeof r==`string`||typeof r==`number`||typeof r==`boolean`?String(r):null;if(!i)return null;let a=typeof n.status==`string`?`${e[n.status.toLowerCase()]??`●`} `:``,o=n.detail??n.description;return`- ${a}${i}${typeof o==`string`&&o.length>0?` — ${o}`:typeof o==`number`||typeof o==`boolean`?` — ${String(o)}`:``}`}).filter(e=>typeof e==`string`);return i.length===0?null:`### ${n}\n${i.join(`
1073
1076
  `)}`}).filter(e=>typeof e==`string`);if(r.length>0)return{type:`markdown`,title:t,value:r.join(`
1074
1077
 
@@ -1084,9 +1087,9 @@ li{margin:4px 0}
1084
1087
 
1085
1088
  `)}}let i=n.map(e=>{if(!e||typeof e!=`object`)return null;let n=e,r=typeof n.label==`string`?n.label:typeof n.title==`string`?n.title:null;return r?`- ${typeof n.status==`string`?`${t[n.status.toLowerCase()]??`●`} `:``}${r}${typeof n.description==`string`&&n.description.length>0?` — ${n.description}`:``}`:null}).filter(Boolean);if(i.length>0)return{type:`markdown`,title:e.title,value:i.join(`
1086
1089
  `)}}}return e.type===`table`&&typeof t==`string`?{type:`markdown`,title:e.title,value:t}:new Set([`markdown`,`table`,`code`,`chart`,`metrics`,`tree`,`graph`,`mermaid`]).has(e.type)?e:Xs(e.value,e.title)||{type:`code`,title:e.title,value:typeof e.value==`string`?e.value:JSON.stringify(e.value,null,2)}}function Qs(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;return Array.isArray(t.blocks)&&t.blocks.length>0?Qs(t.blocks):e}return Array.isArray(e)?e.map(e=>qs(e)?Zs(Ys(e)):e):e}Cn.setOptions({async:!1,gfm:!0,breaks:!0}),Cn.use({renderer:{html(e){return B(e.text)}}});function $s(e){return e.replace(/<table\b/g,`<div class="table-wrap"><table`).replace(/<\/table>/g,`</table></div>`)}function ec(e){if(typeof e!=`object`||!e)return`<p>${B(String(e))}</p>`;let t=e;return typeof t.type==`string`?nc(Ys(t)):`<pre>${B(JSON.stringify(e,null,2))}</pre>`}function tc(e,t){let n=[];if(e&&n.push(`<h1>${B(e)}</h1>`),typeof t==`string`)n.push(`<div class="md-content">${$s(Cn.parse(t))}</div>`);else if(Array.isArray(t))if(t.length===0)n.push(`<p><em>empty</em></p>`);else if(qs(t[0]))for(let e of t)n.push(ec(e));else typeof t[0]==`object`&&t[0]!==null?n.push(rc(t)):n.push(`<ul>${t.map(e=>`<li>${B(String(e))}</li>`).join(``)}</ul>`);else if(typeof t==`object`&&t){let e=t;if(Array.isArray(e.blocks)&&e.blocks.length>0)for(let t of e.blocks)n.push(ec(t));else Array.isArray(e.metrics)?n.push(ic(e.metrics)):Array.isArray(e.nodes)&&Array.isArray(e.edges)?(n.push(`<pre class="mermaid">${B(cc(e))}</pre>`),n.push(`<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"><\/script>`),n.push(`<script>mermaid.run();<\/script>`)):n.push(oc(e))}else n.push(`<p>${B(String(t))}</p>`);return n.join(`
1087
- `)}function nc(e){let t=[];switch(e.title&&t.push(`<h2>${B(e.title)}</h2>`),e.type){case`markdown`:t.push(`<div class="md-content">${$s(Cn.parse(String(e.value??``)))}</div>`);break;case`code`:t.push(`<pre><code>${B(String(e.value??``))}</code></pre>`);break;case`mermaid`:t.push(`<pre class="mermaid">${B(String(e.value??``))}</pre>`);break;case`table`:if(Array.isArray(e.value)){let n=e.value;if(n.length>0&&Array.isArray(n[0])){let e=n,r=e[0].map(String),i=e.slice(1).map(e=>Object.fromEntries(r.map((t,n)=>[t,e[n]])));t.push(rc(i))}else t.push(rc(n))}else if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:n,rows:r}=e.value,i=r.map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]])));t.push(rc(i))}break;case`metrics`:{let n;Array.isArray(e.value)?n=e.value:e.value&&typeof e.value==`object`&&(n=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),n&&t.push(ic(n));break}case`cards`:Array.isArray(e.value)&&t.push(ac(e.value));break;case`tree`:e.value&&typeof e.value==`object`&&t.push(oc(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&t.push(`<pre class="mermaid">${B(cc(e.value))}</pre>`);break;case`chart`:t.push(Ms(e));break;case`timeline`:{let n=e.value;Array.isArray(n)&&(n={items:n.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),n&&t.push(Cs(n));break}case`checklist`:e.value&&t.push(ws(e.value));break;case`comparison`:e.value&&t.push(Ts(e.value));break;case`status-board`:e.value&&t.push(Es(e.value));break;case`prompt`:e.value&&t.push(Ds(e.value));break;case`progress`:e.value&&t.push(Os(e.value));break;case`text`:t.push(`<div class="md-content">${Cn.parse(String(e.value??``))}</div>`);break;case`heading`:{let n=Math.min(Math.max(Number(e.level)||2,1),6);t.push(`<h${n}>${B(String(e.value??``))}</h${n}>`);break}case`paragraph`:t.push(`<p>${B(String(e.value??``))}</p>`);break;case`separator`:t.push(`<hr class="separator">`);break;case`actions`:{let n=(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${B(String(e.value??e.label??``))}">${B(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${B(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${B(String(e.label??``))}</button>`}).join(``);t.push(`<div class="action-bar">${n}</div>`);break}default:t.push(`<pre>${B(JSON.stringify(e.value,null,2))}</pre>`)}return t.join(`
1090
+ `)}function nc(e){let t=[];switch(e.title&&t.push(`<h2>${B(e.title)}</h2>`),e.type){case`markdown`:t.push(`<div class="md-content">${$s(Cn.parse(String(e.value??``)))}</div>`);break;case`code`:t.push(`<pre><code>${B(String(e.value??``))}</code></pre>`);break;case`mermaid`:t.push(`<pre class="mermaid">${B(String(e.value??``))}</pre>`);break;case`table`:if(Array.isArray(e.value)){let n=e.value;if(n.length>0&&Array.isArray(n[0])){let e=n,r=e[0].map(String),i=e.slice(1).map(e=>Object.fromEntries(r.map((t,n)=>[t,e[n]])));t.push(rc(i))}else t.push(rc(n))}else if(e.value&&typeof e.value==`object`&&`headers`in e.value&&`rows`in e.value){let{headers:n,rows:r}=e.value,i=r.map(e=>Object.fromEntries(n.map((t,n)=>[t,e[n]])));t.push(rc(i))}break;case`metrics`:{let n;Array.isArray(e.value)?n=e.value:e.value&&typeof e.value==`object`&&(n=Object.entries(e.value).map(([e,t])=>({label:e,value:String(t)}))),n&&t.push(ic(n));break}case`cards`:Array.isArray(e.value)&&t.push(ac(e.value));break;case`tree`:e.value&&typeof e.value==`object`&&t.push(oc(e.value));break;case`graph`:e.value&&typeof e.value==`object`&&t.push(`<pre class="mermaid">${B(cc(e.value))}</pre>`);break;case`chart`:t.push(js(e));break;case`timeline`:{let n=e.value;Array.isArray(n)&&(n={items:n.map(e=>({title:String(e.event??e.title??``),phase:e.date==null?e.phase==null?void 0:String(e.phase):String(e.date),description:e.description==null?void 0:String(e.description),status:e.status??`done`}))}),n&&t.push(Ss(n));break}case`checklist`:e.value&&t.push(Cs(e.value));break;case`comparison`:e.value&&t.push(ws(e.value));break;case`status-board`:e.value&&t.push(Ts(e.value));break;case`prompt`:e.value&&t.push(Es(e.value));break;case`progress`:e.value&&t.push(Ds(e.value));break;case`text`:t.push(`<div class="md-content">${Cn.parse(String(e.value??``))}</div>`);break;case`heading`:{let n=Math.min(Math.max(Number(e.level)||2,1),6);t.push(`<h${n}>${B(String(e.value??``))}</h${n}>`);break}case`paragraph`:t.push(`<p>${B(String(e.value??``))}</p>`);break;case`separator`:t.push(`<hr class="separator">`);break;case`actions`:{let n=(Array.isArray(e.value)?e.value:[]).map(e=>{if(e.type===`select`){let t=Array.isArray(e.options)?e.options.map(e=>`<option value="${B(String(e.value??e.label??``))}">${B(String(e.label??e.value??``))}</option>`).join(``):``;return`<select class="action-select"><option value="">${B(String(e.label??`Select...`))}</option>${t}</select>`}return`<button class="action-btn action-${String(e.variant??`secondary`)}">${B(String(e.label??``))}</button>`}).join(``);t.push(`<div class="action-bar">${n}</div>`);break}default:t.push(`<pre>${B(JSON.stringify(e.value,null,2))}</pre>`)}return t.join(`
1088
1091
  `)}function rc(e){if(e.length===0)return`<p><em>empty table</em></p>`;let t=Object.keys(e[0]);return`<div class="table-wrap"><table><thead><tr>${t.map(e=>`<th>${B(e)}</th>`).join(``)}</tr></thead><tbody>${e.map(e=>`<tr>${t.map(t=>`<td>${B(String(e[t]??``))}</td>`).join(``)}</tr>`).join(`
1089
- `)}</tbody></table></div>`}function ic(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${B(String(e.value))}</div><div class="metric-label">${B(e.label)}</div></div>`).join(``)}</div>`}function ac(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${B(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${B(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${B(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function oc(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return sc(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${B(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span><div class="tree-children">${oc(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span> ${B(Gs(r))}</div>`);return t.join(``)}function sc(e){let t=B(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?sc(e):`<div class="tree-node"><span class="tree-key">${B(String(e))}</span></div>`).join(``)}</div></div>`}function cc(e){let t=[`graph LR`];for(let n of e.nodes){let e=Ks(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ks(String(n.source??n.from??``)),r=Ks(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
1092
+ `)}</tbody></table></div>`}function ic(e){return`<div class="metric-grid">${e.map(e=>`<div class="metric"><div class="metric-value">${B(String(e.value))}</div><div class="metric-label">${B(e.label)}</div></div>`).join(``)}</div>`}function ac(e){return`<div class="card-grid">${e.map(e=>{let t=[`<div class="card">`];return e.title&&t.push(`<div class="card-title">${B(String(e.title))}</div>`),(e.body||e.description)&&t.push(`<div class="card-body">${B(String(e.body??e.description))}</div>`),(e.badge||e.status)&&t.push(`<span class="badge">${B(String(e.badge??e.status))}</span>`),t.push(`</div>`),t.join(``)}).join(``)}</div>`}function oc(e){if(`name`in e&&`children`in e&&Array.isArray(e.children))return sc(e);if(`name`in e&&!(`children`in e))return`<div class="tree-node"><span class="tree-key">${B(String(e.name))}</span></div>`;let t=[];for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span><div class="tree-children">${oc(r)}</div></div>`):t.push(`<div class="tree-node"><span class="tree-key">${B(n)}:</span> ${B(Ws(r))}</div>`);return t.join(``)}function sc(e){let t=B(String(e.name));return!e.children||e.children.length===0?`<div class="tree-node"><span class="tree-key">${t}</span></div>`:`<div class="tree-node"><span class="tree-key">${t}</span><div class="tree-children">${e.children.map(e=>typeof e==`object`&&e?sc(e):`<div class="tree-node"><span class="tree-key">${B(String(e))}</span></div>`).join(``)}</div></div>`}function cc(e){let t=[`graph LR`];for(let n of e.nodes){let e=Gs(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Gs(String(n.source??n.from??``)),r=Gs(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.join(`
1090
1093
  `)}function lc(e,t,n,r){let i=r&&r!==`auto`?ma(r,t):tc(e,t);return`<!DOCTYPE html>
1091
1094
  <html lang="en">
1092
1095
  <head>
@@ -1094,7 +1097,7 @@ li{margin:4px 0}
1094
1097
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
1095
1098
  <title>${B(e??`AI Kit Dashboard`)}</title>
1096
1099
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
1097
- <style>${Ss()}</style>
1100
+ <style>${xs()}</style>
1098
1101
  </head>
1099
1102
  <body>
1100
1103
  <div class="dashboard">
@@ -1187,8 +1190,8 @@ document.querySelectorAll('.table-wrap').forEach(wrap=>{
1187
1190
  `)}function pc(e,t){if(e.length===0)return`*(empty table)*`;let n=Object.keys(e[0]),r=[];t&&r.push(`**${t}**\n`);for(let t=0;t<e.length;t++){let i=e[t],a=String(i[n[0]]??``);if(n.length===1)r.push(`${t+1}. **${a}**`);else{let e=n.slice(1).map(e=>`${e}: ${String(i[e]??``)}`).join(` · `);r.push(`${t+1}. **${a}** — ${e}`)}}return r.join(`
1188
1191
  `)}function mc(e,t){let n=[];t&&n.push(`**${t}**\n`);for(let t of e){if(n.push(`**${t.title}**`),t.items&&t.items.length>0)for(let e of t.items)n.push(`- ${e}`);else n.push(`- *(none)*`);n.push(``)}return n.join(`
1189
1192
  `)}function hc(e){return e.map(e=>`- **${e.label}**: ${e.value}`).join(`
1190
- `)}function gc(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Ks(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Ks(String(n.source??n.from??``)),r=Ks(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
1191
- `)}function _c(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(_c(a,t+1))):r.push(`${n}- **${i}**: ${Gs(a)}`);return r.join(`
1193
+ `)}function gc(e){let t=["```mermaid",`graph LR`];for(let n of e.nodes){let e=Gs(String(n.id??n.name??``)),r=String(n.label??n.name??e);t.push(` ${e}["${r}"]`)}for(let n of e.edges){let e=Gs(String(n.source??n.from??``)),r=Gs(String(n.target??n.to??``)),i=n.label?`|${String(n.label)}|`:``;t.push(` ${e} -->${i} ${r}`)}return t.push("```"),t.join(`
1194
+ `)}function _c(e,t=0){let n=` `.repeat(t),r=[];for(let[i,a]of Object.entries(e))typeof a==`object`&&a&&!Array.isArray(a)?(r.push(`${n}- **${i}**:`),r.push(_c(a,t+1))):r.push(`${n}- **${i}**: ${Ws(a)}`);return r.join(`
1192
1195
  `)}const vc=import.meta.dirname??m(v(import.meta.url));function yc(e){let t=e;for(let e=0;e<10;e++){try{let e=g(t,`package.json`);if(a(e)&&JSON.parse(s(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=m(t);if(e===t)break;t=e}return _(e,`..`,`..`,`..`)}const bc=`ui://aikit/present.html`,xc=F.object({type:F.enum([`button`,`select`]).describe(`Action type`),id:F.string().describe(`Unique action identifier`),label:F.string().describe(`Display label`),variant:F.enum([`primary`,`danger`,`default`]).optional().describe(`Button style variant`),options:F.array(F.union([F.string(),F.object({label:F.string(),value:F.string()})])).optional().describe(`Select options (for type=select)`)}),Sc={format:F.enum([`html`,`browser`]).default(`html`).describe(`Output format.
1193
1196
  - "html" (default): Rich markdown in chat + embedded UIResource for MCP-UI hosts. Actions shown as numbered choices.
1194
1197
  - "browser": Rich markdown in chat + opens beautiful themed dashboard in the browser. When actions are provided, the browser shows interactive buttons and the tool blocks until user clicks, returning their selection.`),title:F.string().optional().describe(`Optional heading`),content:F.any().describe(`Content to present. Accepts these shapes:
@@ -1222,16 +1225,16 @@ IMPORTANT: For charts, use the ChartValue format above. Do NOT use Chart.js form
1222
1225
  - kanban: drag-drop board — content: { columns: [{id, label, color?}], cards: [{id, title, column, tags?[], priority?}] }
1223
1226
  - tree: collapsible tree view — content: { root: {label, children?:[...]} | [...] }
1224
1227
  - diff-view: side-by-side diff — content: { files: [{path, status, additions, deletions, hunks:[{header, changes:[{type, content}]}]}] }
1225
- - dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let Cc,wc=!1,Y=null;process.on(`exit`,()=>{if(Y){try{Y.close()}catch{}Y=null}});function Tc(){return g(yc(vc),`packages`,`present`,`dist`,`index.html`)}function Ec(){if(!Cc)try{Cc=s(Tc(),`utf-8`)}catch{Cc=``}return Cc}function Dc(e,t){let n=L(`present`),r=Ec(),i=`Present content to the user in the best format. Two modes:
1228
+ - dashboard: metric cards grid — content: { metrics: [{label, value, trend?, status?, type?}] }`)};let Cc,wc=!1,Tc=null;process.on(`exit`,()=>{if(Tc){try{Tc.close()}catch{}Tc=null}});function Ec(){return g(yc(vc),`packages`,`present`,`dist`,`index.html`)}function Dc(){if(!Cc)try{Cc=s(Ec(),`utf-8`)}catch{Cc=``}return Cc}function Oc(e,t){let n=L(`present`),r=Dc(),i=`Present content to the user in the best format. Two modes:
1226
1229
  - "html" (default): Rich markdown in chat + embedded UIResource. Use for display-only content (tables, charts, reports, status boards) where no user interaction is needed.
1227
1230
  - "browser": Serves a themed dashboard on a local URL. Use ONLY when you need user interaction back (confirmations, selections, form input). The tool blocks until user clicks an action button, then returns their selection.
1228
1231
  FORMAT RULE: If no user interaction is needed → use "html". If you need user input back → use "browser".
1229
1232
  CONTENT GUIDE: Pass typed blocks [{ type, title?, value }] for structured content. See the \`content\` parameter description for all supported block types and their value shapes. For charts: use {chartType, data:Record[], xKey, yKeys} — NOT Chart.js format.
1230
- BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await Oc(n,r,i,t,a):kc(n,r,i,a);if(r){wc||=(_n(e,`AI Kit Present App`,bc,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:bc,mimeType:gn,text:r}]})),!0),vn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:Sc,_meta:{ui:{resourceUri:bc}}},a);return}e.tool(`present`,i,Sc,n.annotations,a)}async function Oc(e,t,n,r,i){let a=uc(e,t,{compactTables:!0}),o=lc(e,t,n,i),s=Sn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:o},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),c,l,u=Array.isArray(n)?n:[],d=``,f;try{Y&&=(Y.close(),null),u.length>0&&(c=new Promise(e=>{l=e}));let e=!1;d=await new Promise((t,n)=>{let r=xn((t,n)=>{if(e||(e=!0,f&&clearTimeout(f)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);l?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(o)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Y=r;let n=`http://127.0.0.1:${i.port}`;f=setTimeout(()=>{if(!e)try{yn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),f.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Y===r&&(Y=null)},300*1e3).unref()})}catch{}let p=d?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${d}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(u.length>0&&r?.available&&c)try{let e=await Promise.race([c,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${p}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},s]}}catch{return{content:[{type:`text`,text:`${p}\n\n⚠️ *No selection received (timed out).*`},s]}}return{content:[{type:`text`,text:p},s]}}function kc(e,t,n,r){let i=Array.isArray(n)?n:[],a=uc(e,t,{compactTables:!0}),o=Sn({uri:`ui://aikit/present-static.html`,content:{type:`rawHtml`,htmlString:lc(e,t,n,r)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:a},o],structuredContent:{title:e,content:Qs(t),actions:i}}}const Ac=E(`tools`);function jc(e,t){let n=new fn({structure:new mn,dependencies:new ln,symbols:new hn,patterns:new pn,entryPoints:new dn,diagrams:new un}),r=L(`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:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.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??`.`;Ac.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??g(i,`.ai`,`context`);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`&&f(g(e,`${t}.md`),n+r,`utf-8`);Ac.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){Ac.warn(`Failed to persist knowledge to .ai/context/`,{error:A(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
1233
+ BROWSER WORKFLOW: After calling present with format "browser", you MUST extract the URL from the response and call openBrowserPage({ url }) tool - PlayWright MCP to open it in VS Code Simple Browser. A system browser fallback also opens automatically, but always call openBrowserPage tool - PlayWright MCP yourself.`,a=async({format:e,title:n,content:r,actions:i,template:a})=>{let o=Ks(r);return(e??`html`)===`browser`||Array.isArray(i)&&i.length>0?await kc(n,o,i,t,a):Ac(n,o,i,a)};if(r){wc||=(_n(e,`AI Kit Present App`,bc,{description:`Rich interactive content viewer for AI Kit tools`},async()=>({contents:[{uri:bc,mimeType:gn,text:r}]})),!0),vn(e,`present`,{title:n.title,description:i,annotations:n.annotations,inputSchema:Sc,_meta:{ui:{resourceUri:bc}}},a);return}e.tool(`present`,i,Sc,n.annotations,a)}async function kc(e,t,n,r,i){let a=uc(e,t,{compactTables:!0}),o=lc(e,t,n,i),s=Sn({uri:`ui://aikit/present-browser.html`,content:{type:`rawHtml`,htmlString:o},encoding:`text`,adapters:{mcpApps:{enabled:!0}}}),c,l,u=Array.isArray(n)?n:[],d=``,f;try{Tc&&=(Tc.close(),null),u.length>0&&(c=new Promise(e=>{l=e}));let e=!1;d=await new Promise((t,n)=>{let r=xn((t,n)=>{if(e||(e=!0,f&&clearTimeout(f)),t.method===`POST`&&t.url===`/callback`){let e=``;t.on(`data`,t=>{e+=t.toString()}),t.on(`end`,()=>{n.writeHead(200,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":`*`}),n.end(`{"ok":true}`);try{let t=JSON.parse(e);l?.(t)}catch{}});return}if(t.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}n.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),n.end(o)});r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i){Tc=r;let n=`http://127.0.0.1:${i.port}`;f=setTimeout(()=>{if(!e)try{yn(process.platform===`win32`?`start "" "${n}"`:process.platform===`darwin`?`open "${n}"`:`xdg-open "${n}"`)}catch{}},8e3),f.unref(),t(n)}else n(Error(`Failed to start present server`))}),setTimeout(()=>{r.close(),Tc===r&&(Tc=null)},300*1e3).unref()})}catch{}let p=d?`${a}\n\n---\n🌐 **Dashboard opened in browser:** ${d}\n\n**IMPORTANT:** You MUST now open this URL using the \`openBrowserPage\` tool - PlayWright MCP. If that tool is unavailable, open the URL in the system browser as a fallback. If neither works, ask the user to open the URL manually.`:a;if(u.length>0&&r?.available&&c)try{let e=await Promise.race([c,new Promise((e,t)=>setTimeout(()=>t(Error(`timeout`)),300*1e3))]);return{content:[{type:`text`,text:`${p}\n\n✅ **Selected:** ${e.actionId} = \`${e.value}\``},s]}}catch{return{content:[{type:`text`,text:`${p}\n\n⚠️ *No selection received (timed out).*`},s]}}return{content:[{type:`text`,text:p},s]}}function Ac(e,t,n,r){let i=Array.isArray(n)?n:[],a=uc(e,t,{compactTables:!0}),o=Sn({uri:`ui://aikit/present-static.html`,content:{type:`rawHtml`,htmlString:lc(e,t,n,r)},encoding:`text`,adapters:{mcpApps:{enabled:!0}}});return{content:[{type:`text`,text:a},o],structuredContent:{title:e,content:Qs(t),actions:i}}}const jc=E(`tools`);function Mc(e,t){let n=new fn({structure:new mn,dependencies:new ln,symbols:new hn,patterns:new pn,entryPoints:new dn,diagrams:new un}),r=L(`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:F.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:F.array(F.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??`.`;jc.info(`Running knowledge production`,{rootPath:i,aspects:r});let a=await n.runExtraction(i,r);try{let e=t?.onboardDir??g(i,`.ai`,`context`);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`&&f(g(e,`${t}.md`),n+r,`utf-8`);jc.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(a).length})}catch(e){jc.warn(`Failed to persist knowledge to .ai/context/`,{error:A(e)})}return{content:[{type:`text`,text:n.buildSynthesisInstructions(a,r)+`
1231
1234
 
1232
1235
  ---
1233
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return Ac.error(`Knowledge production failed`,A(e)),{content:[{type:`text`,text:`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Mc=E(`tools`);function Nc(e,t){let n=L(`read`);e.registerTool(`read`,{title:n.title,description:`Read the full content of a specific curated knowledge entry by its path. Use list first to discover available entries.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.read(e),r=[`## ${n.title}`,`- **Path**: .ai/curated/${e}`,`- **Category**: ${n.category}`,n.tags.length?`- **Tags**: ${n.tags.join(`, `)}`:null,`- **Version**: ${n.version}`,`- **Created**: ${n.created}`,n.updated===n.created?null:`- **Updated**: ${n.updated}`,``].filter(e=>e!==null).join(`
1234
- `),i=Ho(e,n.title,`[${n.category}]`);return{content:[{type:`text`,text:`${r}\n${n.content}\n\n---\n_Next: Use \`update\` to modify this entry, or \`search\` to find related entries._`},...i?[i]:[]]}}catch(e){return Mc.error(`Read failed`,A(e)),{content:[{type:`text`,text:`Read failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const X=E(`tools`);function Pc(e,t,n,r,i,a,o){let s=L(`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:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.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
1236
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return jc.error(`Knowledge production failed`,A(e)),{content:[{type:`text`,text:`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Nc=E(`tools`);function Pc(e,t){let n=L(`read`);e.registerTool(`read`,{title:n.title,description:`Read the full content of a specific curated knowledge entry by its path. Use list first to discover available entries.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`)},annotations:n.annotations},async({path:e})=>{try{let n=await t.read(e),r=[`## ${n.title}`,`- **Path**: .ai/curated/${e}`,`- **Category**: ${n.category}`,n.tags.length?`- **Tags**: ${n.tags.join(`, `)}`:null,`- **Version**: ${n.version}`,`- **Created**: ${n.created}`,n.updated===n.created?null:`- **Updated**: ${n.updated}`,``].filter(e=>e!==null).join(`
1237
+ `),i=Vo(e,n.title,`[${n.category}]`);return{content:[{type:`text`,text:`${r}\n${n.content}\n\n---\n_Next: Use \`update\` to modify this entry, or \`search\` to find related entries._`},...i?[i]:[]]}}catch(e){return Nc.error(`Read failed`,A(e)),{content:[{type:`text`,text:`Read failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const X=E(`tools`);function Fc(e,t,n,r,i,a,o){let s=L(`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:F.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:F.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
1235
1238
 
1236
1239
  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
1237
1240
 
@@ -1239,36 +1242,36 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
1239
1242
 
1240
1243
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
1241
1244
 
1242
- Use \`status({})\` to check smart indexing queue status.`}]};let l=na(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.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(X.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(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,A(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,A(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,A(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,A(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 X.error(`Reindex failed`,A(e)),{content:[{type:`text`,text:`Reindex failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Fc=E(`tools`);function Ic(e,t,n,r,i){let a=L(`remember`);e.registerTool(`remember`,{title:a.title,description:`Store a new piece of curated knowledge. Use this to persist decisions, patterns, conventions, or any insight worth remembering across sessions.`,inputSchema:{title:F.string().min(3).max(120).describe(`Short descriptive title for the knowledge entry`),content:F.string().min(10).max(1e5).describe(`The markdown content to store`),category:F.string().regex(/^[a-z][a-z0-9-]*$/).describe(`Category slug (e.g., "decisions", "patterns", "conventions", "api-contracts")`),tags:F.array(F.string()).default([]).describe(`Optional tags for filtering`)},annotations:a.annotations},async({title:e,content:a,category:o,tags:s})=>{try{let c=await t.remember(e,a,o,s),l=``;if(n){let t=n.classify(e,a,s);r&&r.recordClassification(e,t.matchingRules.map(e=>e.ruleId),t.pushRecommended),t.matchingRules.length>0&&(l=`\n\n### Classification Signals\n${t.matchingRules.map(e=>` - **${e.ruleId}** (${e.category}, weight: ${e.pushWeight}) — matched: ${e.matchedPatterns.join(`, `)}`).join(`
1245
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=na(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),X.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&X.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(X.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(),X.info(`FTS index rebuilt after reindex`)}catch(e){X.warn(`FTS index rebuild failed`,A(e))}try{let e=await r.reindexAll();X.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){X.warn(`Curated re-index failed`,A(e))}if(a)try{await a.notifyAfterReindex()}catch(e){X.warn(`Post-reindex resource notification failed`,A(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),X.error(`Background reindex failed`,A(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 X.error(`Reindex failed`,A(e)),{content:[{type:`text`,text:`Reindex failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Ic=E(`tools`);function Lc(e,t,n,r,i){let a=L(`remember`);e.registerTool(`remember`,{title:a.title,description:`Store a new piece of curated knowledge. Use this to persist decisions, patterns, conventions, or any insight worth remembering across sessions.`,inputSchema:{title:F.string().min(3).max(120).describe(`Short descriptive title for the knowledge entry`),content:F.string().min(10).max(1e5).describe(`The markdown content to store`),category:F.string().regex(/^[a-z][a-z0-9-]*$/).describe(`Category slug (e.g., "decisions", "patterns", "conventions", "api-contracts")`),tags:F.array(F.string()).default([]).describe(`Optional tags for filtering`)},annotations:a.annotations},async({title:e,content:a,category:o,tags:s})=>{try{let c=await t.remember(e,a,o,s),l=``;if(n){let t=n.classify(e,a,s);r&&r.recordClassification(e,t.matchingRules.map(e=>e.ruleId),t.pushRecommended),t.matchingRules.length>0&&(l=`\n\n### Classification Signals\n${t.matchingRules.map(e=>` - **${e.ruleId}** (${e.category}, weight: ${e.pushWeight}) — matched: ${e.matchedPatterns.join(`, `)}`).join(`
1243
1246
  `)}\n- **Push recommended**: ${t.pushRecommended?`yes`:`no`} (max weight: ${t.maxPushWeight})`,t.pushRecommended&&(l+=`
1244
1247
 
1245
- > 💡 This entry matches push rules. Consider \`er_push\` to share with Enterprise RAG.`))}i&&i.notifyAfterCuratedWrite(c.path).catch(()=>{});let u=Ho(c.path,e,`[${o}]`);return{content:[{type:`text`,text:`Remembered: **${e}**\n\nStored at \`.ai/curated/${c.path}\` and indexed for semantic search.${l}\n\n---\n_Next: Use \`search\` to verify the entry is findable, or \`list\` to see all curated entries._`},...u?[u]:[]]}}catch(e){return Fc.error(`Remember failed`,A(e)),{content:[{type:`text`,text:`Remember failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Lc=E(`tools`);function Rc(e){let t=L(`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:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.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 kt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=At({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 jt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
1248
+ > 💡 This entry matches push rules. Consider \`er_push\` to share with Enterprise RAG.`))}i&&i.notifyAfterCuratedWrite(c.path).catch(()=>{});let u=Vo(c.path,e,`[${o}]`);return{content:[{type:`text`,text:`Remembered: **${e}**\n\nStored at \`.ai/curated/${c.path}\` and indexed for semantic search.${l}\n\n---\n_Next: Use \`search\` to verify the entry is findable, or \`list\` to see all curated entries._`},...u?[u]:[]]}}catch(e){return Ic.error(`Remember failed`,A(e)),{content:[{type:`text`,text:`Remember failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Rc=E(`tools`);function zc(e){let t=L(`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:F.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:F.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:F.string().optional().describe(`Filter by tool name (list only)`),source:F.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:F.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 kt(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=At({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 jt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
1246
1249
 
1247
- `)}`}]}}catch(e){return Lc.error(`Replay failed`,A(e)),{content:[{type:`text`,text:`Replay failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const zc=E(`tools`);function Bc(e){let t=L(`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:F.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:F.string().optional().describe(`Restore point ID (required for action=restore)`),limit:F.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=ot().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(`
1250
+ `)}`}]}}catch(e){return Rc.error(`Replay failed`,A(e)),{content:[{type:`text`,text:`Replay failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Bc=E(`tools`);function Vc(e){let t=L(`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:F.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:F.string().optional().describe(`Restore point ID (required for action=restore)`),limit:F.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=ot().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(`
1248
1251
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Mt(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
1249
- `)}`}]}}catch(e){return zc.error(`Restore failed`,A(e)),{content:[{type:`text`,text:`Restore failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Vc=/<\/?curated-context>/gi;function Hc(e){return e.replace(Vc,``)}function Uc(e){return`<curated-context>\n${Hc(e)}\n</curated-context>`}const Wc=E(`tools`);function Gc(e){let t=[],n=p(process.cwd());n&&t.push(`[project: ${n}]`);let r=Vt(`__context_boost`);return r&&t.push(`[focus: ${r.value}]`),t.length===0?e:`${t.join(` `)} ${e}`}async function Kc(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:de(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 Wc.warn(`ER fallback failed`,A(e)),{results:n,triggered:!0,cacheHit:a}}}function qc(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function Jc(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 Yc(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&&!Xc.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 Xc=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 Zc(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 ne(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 Qc(e,t,n,r,i,a,o){let s=L(`search`);e.registerTool(`search`,{title:s.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:Si,inputSchema:{query:F.string().max(5e3).describe(`Natural language search query`),limit:F.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:F.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:F.enum(b).optional().describe(`Filter by content type`),source_type:F.enum(C).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:F.enum(S).optional().describe(`Filter by knowledge origin`),category:F.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:F.array(F.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:F.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:F.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:F.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:F.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:F.array(F.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:s.annotations},async({query:e,limit:s,search_mode:c,content_type:l,source_type:u,origin:d,category:f,tags:p,min_score:m,graph_hops:h,max_tokens:g,dedup:_,workspaces:v})=>{try{let y={limit:s,minScore:m,contentType:l,sourceType:u,origin:d,category:f,tags:p},b,x=!1,S=!1,C=``,w=Gc(e);if(c===`keyword`)b=await n.ftsSearch(e,y),b=b.slice(0,s);else if(c===`semantic`){let r=await t.embedQuery(w);b=await n.search(r,y);let a=await Kc(i,b[0]?.score??0,b,e,s);b=a.results,x=a.triggered,S=a.cacheHit}else{let r=await t.embedQuery(w),[a,o]=await Promise.all([n.search(r,{...y,limit:s*2}),n.ftsSearch(e,{...y,limit:s*2}).catch(()=>[])]);b=qc(a,o).slice(0,s);let c=await Kc(i,a[0]?.score??0,b,e,s);b=c.results,x=c.triggered,S=c.cacheHit}a&&a.recordSearch(e,x,S),b.length>1&&(b=Jc(b,e));let E=``;if(v&&v.length>0){let n=Ua(v,T(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await Wa(n);try{let i;i=c===`keyword`?await Ka(r,e,{...y,limit:s}):await Ga(r,await t.embedQuery(e),{...y,limit:s});for(let e of i)b.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});b=b.sort((e,t)=>t.score-e.score).slice(0,s),E=` + ${n.length} workspace(s)`}finally{await i()}}}if(_===`file`&&b.length>1){let e=new Map;for(let t of b){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}]})}b=[...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(b.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(`
1250
- `)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,y);a.length>0&&(b=a,C=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,Wc.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){Wc.debug(`Smart search fallback failed`,{error:String(e)})}if(b.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:c,query:e}}}let D,O;if(h>0&&!r&&(O="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),h>0&&r)try{let e=await Ye(r,b.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:h,maxPerHit:5});D=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(`
1252
+ `)}`}]}}catch(e){return Bc.error(`Restore failed`,A(e)),{content:[{type:`text`,text:`Restore failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Hc=/<\/?curated-context>/gi;function Uc(e){return e.replace(Hc,``)}function Wc(e){return`<curated-context>\n${Uc(e)}\n</curated-context>`}const Gc=E(`tools`);function Kc(e){let t=[],n=p(process.cwd());n&&t.push(`[project: ${n}]`);let r=Vt(`__context_boost`);return r&&t.push(`[focus: ${r.value}]`),t.length===0?e:`${t.join(` `)} ${e}`}async function qc(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:de(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 Gc.warn(`ER fallback failed`,A(e)),{results:n,triggered:!0,cacheHit:a}}}function Jc(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function Yc(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 Xc(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&&!Zc.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 Zc=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 Qc(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 ne(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 $c(e,t,n,r,i,a,o){let s=L(`search`);e.registerTool(`search`,{title:s.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:Si,inputSchema:{query:F.string().max(5e3).describe(`Natural language search query`),limit:F.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:F.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:F.enum(b).optional().describe(`Filter by content type`),source_type:F.enum(C).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:F.enum(S).optional().describe(`Filter by knowledge origin`),category:F.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:F.array(F.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:F.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:F.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:F.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:F.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:F.array(F.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:s.annotations},async({query:e,limit:s,search_mode:c,content_type:l,source_type:u,origin:d,category:f,tags:p,min_score:m,graph_hops:h,max_tokens:g,dedup:_,workspaces:v})=>{try{let y={limit:s,minScore:m,contentType:l,sourceType:u,origin:d,category:f,tags:p},b,x=!1,S=!1,C=``,w=Kc(e);if(c===`keyword`)b=await n.ftsSearch(e,y),b=b.slice(0,s);else if(c===`semantic`){let r=await t.embedQuery(w);b=await n.search(r,y);let a=await qc(i,b[0]?.score??0,b,e,s);b=a.results,x=a.triggered,S=a.cacheHit}else{let r=await t.embedQuery(w),[a,o]=await Promise.all([n.search(r,{...y,limit:s*2}),n.ftsSearch(e,{...y,limit:s*2}).catch(()=>[])]);b=Jc(a,o).slice(0,s);let c=await qc(i,a[0]?.score??0,b,e,s);b=c.results,x=c.triggered,S=c.cacheHit}a&&a.recordSearch(e,x,S),b.length>1&&(b=Yc(b,e));let E=``;if(v&&v.length>0){let n=Ua(v,T(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await Wa(n);try{let i;i=c===`keyword`?await Ka(r,e,{...y,limit:s}):await Ga(r,await t.embedQuery(e),{...y,limit:s});for(let e of i)b.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});b=b.sort((e,t)=>t.score-e.score).slice(0,s),E=` + ${n.length} workspace(s)`}finally{await i()}}}if(_===`file`&&b.length>1){let e=new Map;for(let t of b){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}]})}b=[...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(b.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(`
1253
+ `)[0].slice(0,500);if(r&&r!==e){let i=await t.embedQuery(r),a=await n.search(i,y);a.length>0&&(b=a,C=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,Gc.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:a.length}))}}catch(e){Gc.debug(`Smart search fallback failed`,{error:String(e)})}if(b.length===0)return{content:[{type:`text`,text:`No results found for the given query.`}],structuredContent:{results:[],totalResults:0,searchMode:c,query:e}}}let D,O;if(h>0&&!r&&(O="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),h>0&&r)try{let e=await Ye(r,b.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:h,maxPerHit:5});D=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(`
1251
1254
  `),n=t.graphContext.edges.slice(0,5).map(e=>` - ${e.fromId} —[${e.type}]→ ${e.toId}`).join(`
1252
1255
  `),r=[`- **Graph Context** (${h} hop${h>1?`s`:``}):`];e&&r.push(` Entities:\n${e}`),n&&r.push(` Relationships:\n${n}`),D.set(t.recordId,r.join(`
1253
- `))}}catch(e){Wc.warn(`Graph augmentation failed`,A(e)),O=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let k=Date.now();for(let e of b)if(e.record.origin===`curated`&&e.record.indexedAt){let t=k-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}b.sort((e,t)=>t.score-e.score),b=be(b);let ee=b.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,D?.get(n.id)??null].filter(Boolean).join(`
1254
- `)}\n\n${n.origin===`curated`?Uc(n.content):n.content}`}).join(`
1256
+ `))}}catch(e){Gc.warn(`Graph augmentation failed`,A(e)),O=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let k=Date.now();for(let e of b)if(e.record.origin===`curated`&&e.record.indexedAt){let t=k-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}b.sort((e,t)=>t.score-e.score),b=be(b);let ee=b.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,D?.get(n.id)??null].filter(Boolean).join(`
1257
+ `)}\n\n${n.origin===`curated`?Wc(n.content):n.content}`}).join(`
1255
1258
 
1256
1259
  ---
1257
1260
 
1258
- `),j=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+E,M=Yc(b,e),te=M.length>0?`\n_Distinctive terms: ${M.map(e=>`\`${e}\``).join(`, `)}_`:``,ne=await Zc(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[O?`${O}\n\n`:``,ne?`${ne}\n\n`:``,ee,`\n\n---\n_Search mode: ${j} | ${b.length} results_${te}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Xt(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Wo(e.record.sourcePath);if(!t)continue;let n=Ho(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.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:b.length,searchMode:c,query:e}}}catch(e){return Wc.error(`Search failed`,A(e)),{content:[{type:`text`,text:`Search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const $c=E(`tools`);function el(e,t){let n=L(`session_digest`);e.registerTool(`session_digest`,{title:n.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:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await Lt(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):It(c)).digest}]}}catch(e){return $c.error(`Session digest failed`,A(e)),{content:[{type:`text`,text:`Session digest failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const tl=E(`tools`);function nl(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{tl.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),tl.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}const rl=5*6e4;let il=null,al=null;function ol(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 sl(){let e=Date.now();if(il&&e-il.ts<rl)return il.value;try{let t=_(N(),`.copilot`,`.aikit-scaffold.json`);if(!a(t))return il={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return il={value:n,ts:e},n}catch{return il={value:null,ts:e},null}}function cl(){let e=Date.now();if(al&&e-al.ts<rl)return al.value;try{let t=_(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!a(t))return al={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return al={value:n,ts:e},n}catch{return al={value:null,ts:e},null}}function ll(e){let t=L(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:t.annotations},async()=>{let e=r(),t=sl(),a=cl(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!re.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
1259
- `)}],structuredContent:l}})}function ul(e,t,o,s,c,l,u,f){let p=L(`status`);e.registerTool(`status`,{title:p.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:p.annotations},async()=>{let e=[];try{let[p,m]=await Promise.all([nl(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),nl(t.listSourcePaths(),[],`store.listSourcePaths`)]),h=p.value;p.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let g=m.value;m.timedOut&&e.push(`⚠ File listing timed out`);let v=null,b=0,x=[`## AI Kit Status`,``,`- **Total Records**: ${h.totalRecords}`,`- **Total Files**: ${h.totalFiles}`,`- **Last Indexed**: ${h.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(h.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(o)try{let t=await nl(o.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),x.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;v={nodes:e.nodeCount,edges:e.edgeCount},x.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await nl(o.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||x.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&x.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{x.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let S=l?.onboardDir??_(process.cwd(),y.aiContext),C=a(S),w=c?.onboardComplete||C;if(x.push(``,`### Onboard Status`,w?`- ✅ Complete${c?.onboardTimestamp?` (last: ${c.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${S}\``),s)try{let t=await nl(s.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),x.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;b=e.length,x.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:"- Empty — use `remember()` to persist decisions")}}catch{x.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let T=ol(h.totalRecords,v?.nodes??0,v?.edges??0,b);x.push(``),x.push(`## 📊 Context Pressure: ${T}/100`),T>=80?x.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):T>=50?x.push(`ℹ️ Moderate pressure — knowledge base is well-populated.`):x.push(`✅ Low pressure — plenty of headroom for more content.`);let E=0;if(h.lastIndexedAt){E=new Date(h.lastIndexedAt).getTime();let e=(Date.now()-E)/(1e3*60*60);x.push(``,`### Index Freshness`,e>24?u===`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`)}if(u===`smart`)if(x.push(``,`### Smart Indexing`),f){let e=f();e?x.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}`):x.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else x.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=_(process.cwd(),y.data,`stash`);if(a(e)){let t=d(e).mtimeMs;t>E&&(E=t)}}catch{}let e=[];if(s)try{let t=b>0?await s.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>E&&(E=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=E>0?Date.now()-E:0;if(t>=144e5){let n=Math.floor(t/36e5);if(x.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){x.push(`**Recent decisions/notes:**`);for(let t of e)x.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}x.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint","- `list()` — browse all stored knowledge")}}x.push(``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`);let D=sl(),O=cl(),k=r(),ee=D!=null&&D!==k,A=O!=null&&O!==k;if(ee||A){let e=i(),t=[];ee&&t.push(`user scaffold v${D}`),A&&t.push(`workspace scaffold v${O}`);let r=t.join(`, `);e.state===`success`?x.push(``,`### ✅ Upgrade Applied`,`- Server v${k} — ${r} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?x.push(``,`### ⏳ Upgrade In Progress`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(n(),x.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${k} ≠ ${r}`,`- Error: ${e.error??`unknown`}`)):(n(),x.push(``,`### ⬆ Upgrade Available`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&x.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let j=Br();if(j.length>0){let e=j.sort((e,t)=>t.callCount-e.callCount);x.push(``,`### Tool Usage This Session`,``),x.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),x.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);x.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=Nr();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;x.push(``,`### Auto-GC: ${e} ${M.state}`),x.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&x.push(`- GC cycles triggered: ${M.gcCount}`)}let te=x.join(`
1260
- `),ne={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!re.get(),graphStats:v,curatedCount:b,serverVersion:k,scaffoldVersion:D??null,workspaceScaffoldVersion:O??null,upgradeAvailable:ee||A,contextPressure:T};return{content:[{type:`text`,text:te+(u===`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:ne}}catch(e){return tl.error(`Status failed`,A(e)),{content:[{type:`text`,text:`Status check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const dl=E(`tools`);function fl(e,t,n){let r=L(`update`);e.registerTool(`update`,{title:r.title,description:`Update an existing curated knowledge entry. Increments version and records the reason in the changelog.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`),content:F.string().min(10).max(1e5).describe(`New markdown content to replace existing content`),reason:F.string().min(3).max(1e3).describe(`Why this update is being made (recorded in changelog)`)},annotations:r.annotations},async({path:e,content:r,reason:i})=>{try{let a=await t.update(e,r,i);return n&&n.notifyAfterCuratedWrite(e).catch(()=>{}),{content:[{type:`text`,text:`Updated: \`.ai/curated/${a.path}\` → version ${a.version}\n\nReason: ${i}\n\n---\n_Next: Use \`read\` to verify the updated content, or \`search\` to test searchability._`}]}}catch(e){return dl.error(`Update failed`,A(e)),{content:[{type:`text`,text:`Update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Z=E(`tools`);function pl(e){let t=L(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — search the web via DuckDuckGo (no API key). Pass one query or multiple for parallel searching. Returns structured results with title, URL, and snippet.`,inputSchema:{queries:F.array(F.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:F.number().min(1).max(20).default(5).describe(`Max results per query`),site:F.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`)},annotations:t.annotations},async({queries:e,limit:t,site:n})=>{let r=e,i=async e=>{let r=await tn({query:e,limit:t,site:n}),i=[`## Search: ${r.query}`,``];if(r.results.length===0)i.push(`No results found.`);else for(let e of r.results)i.push(`### [${e.title}](${e.url})`,e.snippet,``);return i.join(`
1261
+ `),j=(c===`hybrid`?`hybrid (vector + keyword RRF)`:c===`keyword`?`keyword (FTS)`:`semantic (vector)`)+E,M=Xc(b,e),te=M.length>0?`\n_Distinctive terms: ${M.map(e=>`\`${e}\``).join(`, `)}_`:``,ne=await Qc(n,b),N=[];if(b.length===0)N.push("`reindex` — no results found, index may be stale"),N.push("`find` — try federated search with glob/regex");else{let e=b[0]?.record.sourcePath;e&&N.push(`\`lookup\` — see all chunks from \`${e}\``),N.push("`symbol` — resolve a specific symbol from the results"),N.push("`compact` — compress a result file for focused reading")}let re=[O?`${O}\n\n`:``,ne?`${ne}\n\n`:``,ee,`\n\n---\n_Search mode: ${j} | ${b.length} results_${te}`,`\n_Next: ${N.join(` | `)}_`],ie=C+re.join(``);g&&(ie=Xt(ie,g));let ae=new Set,oe=[];for(let e of b){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Uo(e.record.sourcePath);if(!t)continue;let n=Vo(t,e.record.headingPath??t);n&&!ae.has(n.uri)&&(ae.add(n.uri),oe.push(n))}return{content:[{type:`text`,text:ie},...oe],structuredContent:{results:b.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:b.length,searchMode:c,query:e}}}catch(e){return Gc.error(`Search failed`,A(e)),{content:[{type:`text`,text:`Search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const el=E(`tools`);function tl(e,t){let n=L(`session_digest`);e.registerTool(`session_digest`,{title:n.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:F.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:F.string().optional().describe(`ISO timestamp — only include activity after this time`),last:F.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:F.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:F.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:F.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:F.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:n.annotations},async({scope:e,since:n,last:r,focus:i,mode:a,token_budget:o,persist:s})=>{try{let c={scope:e,since:n,last:r,focus:i,mode:a,tokenBudget:o,persist:s};return{content:[{type:`text`,text:(a===`sampling`&&t?.available?await Lt(c,async(e,n,r)=>(await t.createMessage({prompt:e,systemPrompt:n,maxTokens:r})).text):It(c)).digest}]}}catch(e){return el.error(`Session digest failed`,A(e)),{content:[{type:`text`,text:`Session digest failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const nl=E(`tools`);function rl(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{nl.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),nl.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}const il=5*6e4;let al=null,ol=null;function sl(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 cl(){let e=Date.now();if(al&&e-al.ts<il)return al.value;try{let t=_(N(),`.copilot`,`.aikit-scaffold.json`);if(!a(t))return al={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return al={value:n,ts:e},n}catch{return al={value:null,ts:e},null}}function ll(){let e=Date.now();if(ol&&e-ol.ts<il)return ol.value;try{let t=_(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!a(t))return ol={value:null,ts:e},null;let n=JSON.parse(s(t,`utf-8`)).version??null;return ol={value:n,ts:e},n}catch{return ol={value:null,ts:e},null}}function ul(e){let t=L(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:t.annotations},async()=>{let e=r(),t=cl(),a=ll(),o=t!=null&&t!==e,s=a!=null&&a!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${a??`not installed`}`];if(o||s){let r=i(),l=[];o&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${a}`);let u=l.join(`, `);r.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):r.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):r.state===`failed`?(n(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${r.error??`unknown`}`)):(n(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!re.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:a??null,upgradeAvailable:o||s,contextPressure:0};return{content:[{type:`text`,text:c.join(`
1262
+ `)}],structuredContent:l}})}function dl(e,t,o,s,c,l,u,f){let p=L(`status`);e.registerTool(`status`,{title:p.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:fi,annotations:p.annotations},async()=>{let e=[];try{let[p,m]=await Promise.all([rl(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),rl(t.listSourcePaths(),[],`store.listSourcePaths`)]),h=p.value;p.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let g=m.value;m.timedOut&&e.push(`⚠ File listing timed out`);let v=null,b=0,x=[`## AI Kit Status`,``,`- **Total Records**: ${h.totalRecords}`,`- **Total Files**: ${h.totalFiles}`,`- **Last Indexed**: ${h.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(h.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(o)try{let t=await rl(o.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),x.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;v={nodes:e.nodeCount,edges:e.edgeCount},x.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await rl(o.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||x.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&x.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{x.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let S=l?.onboardDir??_(process.cwd(),y.aiContext),C=a(S),w=c?.onboardComplete||C;if(x.push(``,`### Onboard Status`,w?`- ✅ Complete${c?.onboardTimestamp?` (last: ${c.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${S}\``),s)try{let t=await rl(s.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),x.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;b=e.length,x.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:"- Empty — use `remember()` to persist decisions")}}catch{x.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let T=sl(h.totalRecords,v?.nodes??0,v?.edges??0,b);x.push(``),x.push(`## 📊 Context Pressure: ${T}/100`),T>=80?x.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):T>=50?x.push(`ℹ️ Moderate pressure — knowledge base is well-populated.`):x.push(`✅ Low pressure — plenty of headroom for more content.`);let E=0;if(h.lastIndexedAt){E=new Date(h.lastIndexedAt).getTime();let e=(Date.now()-E)/(1e3*60*60);x.push(``,`### Index Freshness`,e>24?u===`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`)}if(u===`smart`)if(x.push(``,`### Smart Indexing`),f){let e=f();e?x.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}`):x.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else x.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=_(process.cwd(),y.data,`stash`);if(a(e)){let t=d(e).mtimeMs;t>E&&(E=t)}}catch{}let e=[];if(s)try{let t=b>0?await s.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>E&&(E=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=E>0?Date.now()-E:0;if(t>=144e5){let n=Math.floor(t/36e5);if(x.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){x.push(`**Recent decisions/notes:**`);for(let t of e)x.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}x.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint","- `list()` — browse all stored knowledge")}}x.push(``,`### Runtime`,`- **Tree-sitter (WASM)**: ${re.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`);let D=cl(),O=ll(),k=r(),ee=D!=null&&D!==k,A=O!=null&&O!==k;if(ee||A){let e=i(),t=[];ee&&t.push(`user scaffold v${D}`),A&&t.push(`workspace scaffold v${O}`);let r=t.join(`, `);e.state===`success`?x.push(``,`### ✅ Upgrade Applied`,`- Server v${k} — ${r} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?x.push(``,`### ⏳ Upgrade In Progress`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(n(),x.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${k} ≠ ${r}`,`- Error: ${e.error??`unknown`}`)):(n(),x.push(``,`### ⬆ Upgrade Available`,`- Server v${k} ≠ ${r}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&x.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let j=Br();if(j.length>0){let e=j.sort((e,t)=>t.callCount-e.callCount);x.push(``,`### Tool Usage This Session`,``),x.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),x.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);x.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let M=Nr();if(M.bufferSize>=10){let e=M.state===`healthy`?`🟢`:M.state===`degraded`?`🔴`:`🟡`;x.push(``,`### Auto-GC: ${e} ${M.state}`),x.push(`- p95 latency: ${M.p95}ms | buffer: ${M.bufferSize} samples`),M.gcCount>0&&x.push(`- GC cycles triggered: ${M.gcCount}`)}let te=x.join(`
1263
+ `),ne={totalRecords:h.totalRecords,totalFiles:h.totalFiles,lastIndexedAt:h.lastIndexedAt??null,onboarded:w,onboardDir:S,contentTypes:h.contentTypeBreakdown,wasmAvailable:!!re.get(),graphStats:v,curatedCount:b,serverVersion:k,scaffoldVersion:D??null,workspaceScaffoldVersion:O??null,upgradeAvailable:ee||A,contextPressure:T};return{content:[{type:`text`,text:te+(u===`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:ne}}catch(e){return nl.error(`Status failed`,A(e)),{content:[{type:`text`,text:`Status check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const fl=E(`tools`);function pl(e,t,n){let r=L(`update`);e.registerTool(`update`,{title:r.title,description:`Update an existing curated knowledge entry. Increments version and records the reason in the changelog.`,inputSchema:{path:F.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`),content:F.string().min(10).max(1e5).describe(`New markdown content to replace existing content`),reason:F.string().min(3).max(1e3).describe(`Why this update is being made (recorded in changelog)`)},annotations:r.annotations},async({path:e,content:r,reason:i})=>{try{let a=await t.update(e,r,i);return n&&n.notifyAfterCuratedWrite(e).catch(()=>{}),{content:[{type:`text`,text:`Updated: \`.ai/curated/${a.path}\` → version ${a.version}\n\nReason: ${i}\n\n---\n_Next: Use \`read\` to verify the updated content, or \`search\` to test searchability._`}]}}catch(e){return fl.error(`Update failed`,A(e)),{content:[{type:`text`,text:`Update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Z=E(`tools`);function ml(e){let t=L(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — search the web via DuckDuckGo (no API key). Pass one query or multiple for parallel searching. Returns structured results with title, URL, and snippet.`,inputSchema:{queries:F.array(F.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:F.number().min(1).max(20).default(5).describe(`Max results per query`),site:F.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`)},annotations:t.annotations},async({queries:e,limit:t,site:n})=>{let r=e,i=async e=>{let r=await tn({query:e,limit:t,site:n}),i=[`## Search: ${r.query}`,``];if(r.results.length===0)i.push(`No results found.`);else for(let e of r.results)i.push(`### [${e.title}](${e.url})`,e.snippet,``);return i.join(`
1261
1264
  `)};if(r.length===1)try{return{content:[{type:`text`,text:`${await i(r[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return Z.error(`Web search failed`,A(e)),{content:[{type:`text`,text:`Web search failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}let a=await Promise.allSettled(r.map(e=>i(e))),o=[],s=0;for(let e=0;e<a.length;e++){let t=a[e];if(t.status===`fulfilled`)o.push(t.value);else{s++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Z.error(`Web search failed`,{query:r[e],error:n}),o.push(`## ❌ Search failed: ${r[e]}\n\n${n}`)}}let c=`_Searched ${a.length-s}/${a.length} queries successfully._`;return o.push(``,`---`,c,"_Next: Use `web_fetch` to read any of these pages in full._"),{content:[{type:`text`,text:o.join(`
1262
1265
 
1263
- `)}],...s===a.length?{isError:!0}:{}}})}function ml(e){let t=L(`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:F.string().url().describe(`Request URL (http/https only)`),method:F.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:F.record(F.string(),F.string()).optional().describe(`Request headers as key-value pairs`),body:F.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:F.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 $e({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(`
1264
- `)}]}}catch(e){return Z.error(`HTTP request failed`,A(e)),{content:[{type:`text`,text:`HTTP request failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function hl(e){let t=L(`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:F.string().max(500).describe(`Regex pattern (without delimiters)`),flags:F.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:F.array(F.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:F.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:F.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=Tt({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return{content:[{type:`text`,text:`Invalid regex: ${a.error}`}],isError:!0};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(`
1265
- `)}]}})}function gl(e){let t=L(`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:F.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:F.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=Le({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 Z.error(`Encode failed`,A(e)),{content:[{type:`text`,text:`Encode failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function _l(e){let t=L(`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:hi,inputSchema:{path:F.string().describe(`File or directory path to measure`),extensions:F.array(F.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await ct({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(`
1266
- `)}],structuredContent:i}}catch(e){return Z.error(`Measure failed`,A(e)),{content:[{type:`text`,text:`Measure failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function vl(e){let t=L(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:F.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:F.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:F.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:F.boolean().default(!0).describe(`Highlight breaking changes`),cwd:F.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=xe({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 Z.error(`Changelog failed`,A(e)),{content:[{type:`text`,text:`Changelog failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function yl(e){let t=L(`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:F.string().max(5e5).describe(`JSON data to validate (as string)`),schema:F.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Pt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
1266
+ `)}],...s===a.length?{isError:!0}:{}}})}function hl(e){let t=L(`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:F.string().url().describe(`Request URL (http/https only)`),method:F.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:F.record(F.string(),F.string()).optional().describe(`Request headers as key-value pairs`),body:F.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:F.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 $e({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(`
1267
+ `)}]}}catch(e){return Z.error(`HTTP request failed`,A(e)),{content:[{type:`text`,text:`HTTP request failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function gl(e){let t=L(`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:F.string().max(500).describe(`Regex pattern (without delimiters)`),flags:F.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:F.array(F.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:F.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:F.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=Tt({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return{content:[{type:`text`,text:`Invalid regex: ${a.error}`}],isError:!0};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(`
1268
+ `)}]}})}function _l(e){let t=L(`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:F.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:F.string().max(1e6).describe(`Input text`)},annotations:t.annotations},async({operation:e,input:t})=>{try{let n=Le({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 Z.error(`Encode failed`,A(e)),{content:[{type:`text`,text:`Encode failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function vl(e){let t=L(`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:hi,inputSchema:{path:F.string().describe(`File or directory path to measure`),extensions:F.array(F.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:t.annotations},async({path:e,extensions:t})=>{try{let n=await ct({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(`
1269
+ `)}],structuredContent:i}}catch(e){return Z.error(`Measure failed`,A(e)),{content:[{type:`text`,text:`Measure failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function yl(e){let t=L(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:F.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:F.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:F.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:F.boolean().default(!0).describe(`Highlight breaking changes`),cwd:F.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=xe({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 Z.error(`Changelog failed`,A(e)),{content:[{type:`text`,text:`Changelog failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function bl(e){let t=L(`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:F.string().max(5e5).describe(`JSON data to validate (as string)`),schema:F.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},async({data:e,schema:t})=>{try{let n=Pt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
1267
1270
 
1268
1271
  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(`
1269
- `)}]}}catch(e){return Z.error(`Schema validation failed`,A(e)),{content:[{type:`text`,text:`Schema validation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function bl(e){let t=L(`snippet`);e.registerTool(`snippet`,{title:t.title,description:`Save, retrieve, search, and manage persistent code snippets/templates.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`search`,`delete`]).describe(`Operation to perform`),name:F.string().optional().describe(`Snippet name (required for save/get/delete)`),language:F.string().optional().describe(`Language tag (for save)`),code:F.string().max(1e5).optional().describe(`Code content (for save)`),tags:F.array(F.string()).optional().describe(`Tags for categorization (for save)`),query:F.string().optional().describe(`Search query (for search)`)},annotations:t.annotations},async({action:e,name:t,language:n,code:r,tags:i,query:a})=>{try{let o=Rt({action:e,name:t,language:n,code:r,tags:i,query:a});if(`deleted`in o)return{content:[{type:`text`,text:o.deleted?`Snippet "${t}" deleted.`:`Snippet "${t}" not found.`}]};if(`snippets`in o){if(o.snippets.length===0)return{content:[{type:`text`,text:`No snippets found.`}]};let e=[`## Snippets`,``];for(let t of o.snippets){let n=t.tags.length>0?` [${t.tags.join(`, `)}]`:``;e.push(`- **${t.name}** (${t.language})${n}`)}return{content:[{type:`text`,text:e.join(`
1270
- `)}]}}let s=o,c=s.tags.length>0?`\nTags: ${s.tags.join(`, `)}`:``;return{content:[{type:`text`,text:`## ${s.name} (${s.language})${c}\n\n\`\`\`${s.language}\n${s.code}\n\`\`\``}]}}catch(e){return Z.error(`Snippet failed`,A(e)),{content:[{type:`text`,text:`Snippet failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function xl(e){let t=L(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:gi,inputSchema:{include_env:F.boolean().default(!1).describe(`Include environment variables`),filter_env:F.string().optional().describe(`Filter env vars by name substring`),show_sensitive:F.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=Re({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(`
1271
- `)}],structuredContent:a}})}function Sl(e){let t=L(`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:_i,inputSchema:{operation:F.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:F.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:F.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:F.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=Jt({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(`
1272
- `)}],structuredContent:o}}catch(e){return Z.error(`Time failed`,A(e)),{content:[{type:`text`,text:`Time failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Q=E(`server`);function Cl(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`].some(e=>t.includes(e))}async function wl(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??x.model,n=g(N(),`.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=g(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=g(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}async function Tl(n){Q.info(`Initializing AI Kit components`);let[r,i,o,s]=await Promise.all([(async()=>{let e=new ae({model:n.embedding.model,dimensions:n.embedding.dimensions});return await e.initialize(),Q.info(`Embedder loaded`,{modelId:e.modelId,dimensions:e.dimensions}),e})(),(async()=>{let e=await he({backend:n.store.backend,path:n.store.path});return await e.initialize(),Q.info(`Store initialized`),e})(),(async()=>{let e=new me({path:n.store.path});return await e.initialize(),Q.info(`Graph store initialized`),e})(),(async()=>{let e=await ie();return e?Q.info(`WASM tree-sitter enabled for AST analysis`):Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),c=new pe(r,i),l=new fe(n.store.path);l.load(),c.setHashCache(l);let u=n.curated.path,f=new e(u);await f.initialize();let p=new t(u,i,r,f);c.setGraphStore(o);let m=ua(n.er),h=m?new le(n.curated.path):void 0;h&&Q.info(`Policy store initialized`,{ruleCount:h.getRules().length});let g=m?new ce:void 0,v=_(n.sources[0]?.path??process.cwd(),y.aiContext),b=a(v),x=n.onboardDir?a(n.onboardDir):!1,S=b||x,C,w=b?v:n.onboardDir;if(S&&w)try{C=d(w).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:S,onboardTimestamp:C,aiKbExists:b,onboardDirExists:x}),{embedder:r,store:i,indexer:c,curated:p,graphStore:o,fileCache:new ge,bridge:m,policyStore:h,evolutionCollector:g,onboardComplete:S,onboardTimestamp:C}}function El(e,t){let n=new nn({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}});return Cr(n),Ml(n,e,t,vr(n),new Wr(n),Xr(n)),Er(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Dl(e){return e.toolProfiles}const Ol=[`flow_list`,`flow_info`,`flow_start`,`flow_step`,`flow_status`,`flow_reset`,`flow_runs`,`flow_read_instruction`,`flow_add`,`flow_remove`,`flow_update`],kl=[`er_push`,`er_pull`,`er_sync_status`],Al=[...kl,`er_update_policy`,`er_evolve_review`],jl=new Set(Al);function Ml(e,t,n,r,i,a,o,s){let c=new lr,l=new Vn;l.register(Rn),l.register(Pn),l.register(Fn),l.register(jn),l.register(Dn),l.register(On),l.register(Bn);let u=new Kn(l,t.curated);c.use(Wn(u),{order:5,name:`auto-knowledge`}),c.use(Hr(),{order:10,name:`replay`}),c.use(Zr(),{order:50,name:`structured-content-guard`}),c.use(_r(),{order:90,name:`compression`}),mr(e,c,n.toolPrefix??``);let d=oi(process.env.AIKIT_TOOLSET||n.toolProfile||`full`,[...$,...Al],ur,Dl(n)),f=e=>d.has(e),p=[...d].filter(e=>jl.has(e)?kl.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);f(`search`)&&Qc(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a),f(`lookup`)&&Jo(e,t.store);let m={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};f(`status`)&&ul(e,t.store,t.graphStore,t.curated,m,n,o,s),f(`config`)&&Va(e,n),f(`reindex`)&&Pc(e,t.indexer,n,t.curated,t.store,i,o),f(`remember`)&&Ic(e,t.curated,t.policyStore,t.evolutionCollector,i),f(`update`)&&fl(e,t.curated,i),f(`forget`)&&jo(e,t.curated,i),f(`read`)&&Nc(e,t.curated),f(`list`)&&Ko(e,t.curated),f(`analyze_structure`)&&qi(e,t.store,t.embedder),f(`analyze_dependencies`)&&Ji(e,t.store,t.embedder),f(`analyze_symbols`)&&Yi(e,t.store,t.embedder),f(`analyze_patterns`)&&Xi(e,t.store,t.embedder),f(`analyze_entry_points`)&&Zi(e,t.store,t.embedder),f(`analyze_diagram`)&&Qi(e,t.store,t.embedder),f(`blast_radius`)&&$i(e,t.store,t.embedder,t.graphStore),f(`produce_knowledge`)&&jc(e,n),f(`onboard`)&&ls(e,t.store,t.embedder,n,m),f(`graph`)&&Fo(e,t.graphStore),f(`audit`)&&ia(e,t.store,t.embedder);let h=n.sources[0]?.path??process.cwd();f(`compact`)&&Ja(e,t.embedder,t.fileCache,h),f(`scope_map`)&&Ya(e,t.embedder,t.store),f(`find`)&&Xa(e,t.embedder,t.store),f(`parse_output`)&&fo(e),f(`workset`)&&ds(e),f(`check`)&&so(e),f(`batch`)&&co(e,t.embedder,t.store),f(`symbol`)&&Za(e,t.embedder,t.store,t.graphStore),f(`eval`)&&lo(e),f(`test_run`)&&uo(e),f(`stash`)&&fs(e),f(`git_context`)&&Xo(e),f(`diff_parse`)&&Zo(e),f(`rename`)&&Qo(e),f(`codemod`)&&$o(e),f(`restore`)&&Bc(e),f(`file_summary`)&&Qa(e,t.fileCache,h),f(`checkpoint`)&&ps(e),f(`data_transform`)&&es(e),f(`trace`)&&$a(e,t.embedder,t.store,t.graphStore),f(`process`)&&Lo(e),f(`watch`)&&Ro(e),f(`dead_symbols`)&&eo(e,t.embedder,t.store),f(`delegate`)&&po(e,a),f(`health`)&&zo(e),f(`lane`)&&ms(e),f(`queue`)&&hs(e),f(`web_fetch`)&&Bo(e),f(`guide`)&&Vo(e,o),rs.some(e=>f(e))&&is(e,n,p),f(`evidence_map`)&&To(e),f(`digest`)&&Eo(e,t.embedder),f(`forge_classify`)&&Do(e),f(`stratum_card`)&&Oo(e,t.embedder,t.fileCache),f(`forge_ground`)&&ko(e,t.embedder,t.store),f(`present`)&&Dc(e,r),r&&f(`brainstorm`)&&oa(e,r),f(`web_search`)&&pl(e),f(`http`)&&ml(e),f(`regex_test`)&&hl(e),f(`encode`)&&gl(e),f(`measure`)&&_l(e),f(`changelog`)&&vl(e),f(`schema_validate`)&&yl(e),f(`snippet`)&&bl(e),f(`env`)&&xl(e),f(`time`)&&Sl(e),Ol.some(e=>f(e))&&Co(e,n),t.bridge&&kl.some(e=>f(e))&&(da(e,t.bridge,t.evolutionCollector),fa(e,t.bridge),pa(e,t.bridge)),t.policyStore&&f(`er_update_policy`)&&xs(e,t.policyStore),t.evolutionCollector&&f(`er_evolve_review`)&&ao(e,t.evolutionCollector),Kr(e,t.store,t.curated),Rc(e),f(`session_digest`)&&el(e,a)}async function Nl(e){let t=await Tl(e),n=El(t,e);Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{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}))});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`,A(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`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}},i=async()=>{Q.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),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{Q.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const Pl=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.session_digest.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),Fl=5e3,Il=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.describe_tool.list_tools.search_tools.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.session_digest.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function Ll(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&so(e),r(`eval`)&&lo(e),r(`test_run`)&&uo(e),r(`parse_output`)&&fo(e),r(`delegate`)&&po(e),r(`git_context`)&&Xo(e),r(`diff_parse`)&&Zo(e),r(`rename`)&&Qo(e),r(`codemod`)&&$o(e),r(`data_transform`)&&es(e),r(`workset`)&&ds(e),r(`stash`)&&fs(e),r(`checkpoint`)&&ps(e),r(`restore`)&&Bc(e),r(`lane`)&&ms(e),r(`queue`)&&hs(e),r(`session_digest`)&&el(e),r(`health`)&&zo(e),r(`process`)&&Lo(e),r(`watch`)&&Ro(e),r(`web_fetch`)&&Bo(e),r(`guide`)&&Vo(e),rs.some(e=>r(e))&&is(e,t,[...n??new Set($)]),r(`evidence_map`)&&To(e),r(`forge_classify`)&&Do(e),r(`present`)&&Dc(e),r(`brainstorm`)&&oa(e,yr),r(`produce_knowledge`)&&jc(e),r(`replay`)&&Rc(e),r(`status`)&&ll(e),Ol.some(e=>r(e))&&Co(e,t),r(`web_search`)&&pl(e),r(`http`)&&ml(e),r(`regex_test`)&&hl(e),r(`encode`)&&gl(e),r(`measure`)&&_l(e),r(`changelog`)&&vl(e),r(`schema_validate`)&&yl(e),r(`snippet`)&&bl(e),r(`env`)&&xl(e),r(`time`)&&Sl(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.describe_tool.list_tools.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.search_tools.session_digest.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function Rl(e,t){let n=new nn({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}}),i=`initializing`,a=``,o=!1,s=null,c=oi(process.env.AIKIT_TOOLSET||e.toolProfile||`full`,$,ur,Dl(e)),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=()=>i===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,a?`Error: ${a}`:``,``,`**${Il.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, 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(`
1273
- `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Il.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, 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(`
1274
- `);Cr(n),hr(n,e.toolPrefix??``);let p=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let m=[];for(let e of $){if(!c.has(e))continue;let t=L(e),r=n.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Il.has(e)?r.remove():m.push(r)}Ll(n,e,c),n.sendToolListChanged=p;let h=n.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`}]})),g=n.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:P(F.string(),()=>[])}},async()=>({messages:[]})),_,v=new Promise(e=>{_=e}),y,b=new Promise(e=>{y=e}),x=()=>y?.(),S=(async()=>{await b;let r;try{r=await Tl(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(Cl(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await wl(e,n);try{r=await Tl(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){i=`failed`,a=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:a,originalError:n});return}}else{i=`failed`,a=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:a});return}}let c=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let f=n.sendPromptListChanged.bind(n);n.sendPromptListChanged=()=>{};let p=n.sendResourceListChanged.bind(n);n.sendResourceListChanged=()=>{};for(let e of m)e.remove();h.remove(),g.remove();let v=n._registeredTools??{};for(let e of Il)v[e]?.remove();let y=new Wr(n),x=Xr(n);Ml(n,r,e,vr(n),y,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null),Er(n,{curated:r.curated,store:r.store,graphStore:r.graphStore},t),n.sendToolListChanged=c,n.sendPromptListChanged=f,n.sendResourceListChanged=p,Promise.resolve(n.sendToolListChanged()).catch(()=>{}),Promise.resolve(n.sendPromptListChanged()).catch(()=>{}),Promise.resolve(n.sendResourceListChanged()).catch(()=>{});let S=n._registeredTools??{};for(let[e,t]of Object.entries(S)){if(Pl.has(e))continue;let n=t.handler;t.handler=async(...t)=>{if(!r.indexer.isIndexing)return n(...t);let i=o?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${e}" timed out waiting for index data (${Fl/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Fl));return Promise.race([n(...t),a])}}for(let[e,t]of Object.entries(S)){let n=t.handler,r=ui(e);t.handler=async(...t)=>{try{return await di(()=>n(...t),r,e)}catch(t){if(t instanceof li)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.`}]};throw t}}}let C=Object.keys(S).length;C<$.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:C}),Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:4});let T=new Tr;T.onPressure((e,t)=>{e===`warning`&&Qn(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Qn())}),T.start();let E=new xr;l=E,E.onIdle(async()=>{if(w.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),E.touch();return}Q.info(`Idle cleanup: closing store and graph connections`);try{await Promise.all([r.store.close().catch(()=>{}),r.graphStore.close().catch(()=>{})])}catch{}}),E.touch();for(let e of Object.values(S)){let t=e.handler;e.handler=async(...e)=>{if(E.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}s=r,_?.(r)})(),C=async()=>{let t=await v;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}))});o=!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`,A(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`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}finally{l?.setBusy(!1)}},w=new Jn,T=()=>w.schedule({name:`initial-index`,fn:C}),E=process.ppid,D=setInterval(()=>{try{process.kill(E,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:E}),clearInterval(D),v.then(async e=>{await Promise.all([e.embedder.shutdown().catch(()=>{}),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return D.unref(),{server:n,startInit:x,ready:S,runInitialIndex:T,get kb(){return s},scheduler:w,setSmartScheduler(e){u=e}}}export{$ as ALL_TOOL_NAMES,Rl as createLazyServer,El as createMcpServer,Nl as createServer,Tl as initializeKnowledgeBase,Ml as registerMcpTools};
1272
+ `)}]}}catch(e){return Z.error(`Schema validation failed`,A(e)),{content:[{type:`text`,text:`Schema validation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function xl(e){let t=L(`snippet`);e.registerTool(`snippet`,{title:t.title,description:`Save, retrieve, search, and manage persistent code snippets/templates.`,inputSchema:{action:F.enum([`save`,`get`,`list`,`search`,`delete`]).describe(`Operation to perform`),name:F.string().optional().describe(`Snippet name (required for save/get/delete)`),language:F.string().optional().describe(`Language tag (for save)`),code:F.string().max(1e5).optional().describe(`Code content (for save)`),tags:F.array(F.string()).optional().describe(`Tags for categorization (for save)`),query:F.string().optional().describe(`Search query (for search)`)},annotations:t.annotations},async({action:e,name:t,language:n,code:r,tags:i,query:a})=>{try{let o=Rt({action:e,name:t,language:n,code:r,tags:i,query:a});if(`deleted`in o)return{content:[{type:`text`,text:o.deleted?`Snippet "${t}" deleted.`:`Snippet "${t}" not found.`}]};if(`snippets`in o){if(o.snippets.length===0)return{content:[{type:`text`,text:`No snippets found.`}]};let e=[`## Snippets`,``];for(let t of o.snippets){let n=t.tags.length>0?` [${t.tags.join(`, `)}]`:``;e.push(`- **${t.name}** (${t.language})${n}`)}return{content:[{type:`text`,text:e.join(`
1273
+ `)}]}}let s=o,c=s.tags.length>0?`\nTags: ${s.tags.join(`, `)}`:``;return{content:[{type:`text`,text:`## ${s.name} (${s.language})${c}\n\n\`\`\`${s.language}\n${s.code}\n\`\`\``}]}}catch(e){return Z.error(`Snippet failed`,A(e)),{content:[{type:`text`,text:`Snippet failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function Sl(e){let t=L(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:gi,inputSchema:{include_env:F.boolean().default(!1).describe(`Include environment variables`),filter_env:F.string().optional().describe(`Filter env vars by name substring`),show_sensitive:F.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=Re({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(`
1274
+ `)}],structuredContent:a}})}function Cl(e){let t=L(`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:_i,inputSchema:{operation:F.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:F.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:F.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:F.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=Jt({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(`
1275
+ `)}],structuredContent:o}}catch(e){return Z.error(`Time failed`,A(e)),{content:[{type:`text`,text:`Time failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const Q=E(`server`);function wl(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`].some(e=>t.includes(e))}async function Tl(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??x.model,n=g(N(),`.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=g(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=g(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}async function El(n){Q.info(`Initializing AI Kit components`);let[r,i,o,s]=await Promise.all([(async()=>{let e=new ae({model:n.embedding.model,dimensions:n.embedding.dimensions});return await e.initialize(),Q.info(`Embedder loaded`,{modelId:e.modelId,dimensions:e.dimensions}),e})(),(async()=>{let e=await he({backend:n.store.backend,path:n.store.path});return await e.initialize(),Q.info(`Store initialized`),e})(),(async()=>{let e=new me({path:n.store.path});return await e.initialize(),Q.info(`Graph store initialized`),e})(),(async()=>{let e=await ie();return e?Q.info(`WASM tree-sitter enabled for AST analysis`):Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),c=new pe(r,i),l=new fe(n.store.path);l.load(),c.setHashCache(l);let u=n.curated.path,f=new e(u);await f.initialize();let p=new t(u,i,r,f);c.setGraphStore(o);let m=ua(n.er),h=m?new le(n.curated.path):void 0;h&&Q.info(`Policy store initialized`,{ruleCount:h.getRules().length});let g=m?new ce:void 0,v=_(n.sources[0]?.path??process.cwd(),y.aiContext),b=a(v),x=n.onboardDir?a(n.onboardDir):!1,S=b||x,C,w=b?v:n.onboardDir;if(S&&w)try{C=d(w).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:S,onboardTimestamp:C,aiKbExists:b,onboardDirExists:x}),{embedder:r,store:i,indexer:c,curated:p,graphStore:o,fileCache:new ge,bridge:m,policyStore:h,evolutionCollector:g,onboardComplete:S,onboardTimestamp:C}}function Dl(e,t){let n=new nn({name:t.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}});return Cr(n),Nl(n,e,t,vr(n),new Wr(n),Xr(n)),Er(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Ol(e){return e.toolProfiles}const kl=[`flow_list`,`flow_info`,`flow_start`,`flow_step`,`flow_status`,`flow_reset`,`flow_runs`,`flow_read_instruction`,`flow_add`,`flow_remove`,`flow_update`],Al=[`er_push`,`er_pull`,`er_sync_status`],jl=[...Al,`er_update_policy`,`er_evolve_review`],Ml=new Set(jl);function Nl(e,t,n,r,i,a,o,s){let c=new lr,l=new Vn;l.register(Rn),l.register(Pn),l.register(Fn),l.register(jn),l.register(Dn),l.register(On),l.register(Bn);let u=new Kn(l,t.curated);c.use(Wn(u),{order:5,name:`auto-knowledge`}),c.use(Hr(),{order:10,name:`replay`}),c.use(Zr(),{order:50,name:`structured-content-guard`}),c.use(_r(),{order:90,name:`compression`}),mr(e,c,n.toolPrefix??``);let d=oi(process.env.AIKIT_TOOLSET||n.toolProfile||`full`,[...$,...jl],ur,Ol(n)),f=e=>d.has(e),p=[...d].filter(e=>Ml.has(e)?Al.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);f(`search`)&&$c(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a),f(`lookup`)&&qo(e,t.store);let m={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};f(`status`)&&dl(e,t.store,t.graphStore,t.curated,m,n,o,s),f(`config`)&&Va(e,n),f(`reindex`)&&Fc(e,t.indexer,n,t.curated,t.store,i,o),f(`remember`)&&Lc(e,t.curated,t.policyStore,t.evolutionCollector,i),f(`update`)&&pl(e,t.curated,i),f(`forget`)&&jo(e,t.curated,i),f(`read`)&&Pc(e,t.curated),f(`list`)&&Go(e,t.curated),f(`analyze_structure`)&&qi(e,t.store,t.embedder),f(`analyze_dependencies`)&&Ji(e,t.store,t.embedder),f(`analyze_symbols`)&&Yi(e,t.store,t.embedder),f(`analyze_patterns`)&&Xi(e,t.store,t.embedder),f(`analyze_entry_points`)&&Zi(e,t.store,t.embedder),f(`analyze_diagram`)&&Qi(e,t.store,t.embedder),f(`blast_radius`)&&$i(e,t.store,t.embedder,t.graphStore),f(`produce_knowledge`)&&Mc(e,n),f(`onboard`)&&cs(e,t.store,t.embedder,n,m),f(`graph`)&&Fo(e,t.graphStore),f(`audit`)&&ia(e,t.store,t.embedder);let h=n.sources[0]?.path??process.cwd();f(`compact`)&&Ja(e,t.embedder,t.fileCache,h),f(`scope_map`)&&Ya(e,t.embedder,t.store),f(`find`)&&Xa(e,t.embedder,t.store),f(`parse_output`)&&fo(e),f(`workset`)&&us(e),f(`check`)&&so(e),f(`batch`)&&co(e,t.embedder,t.store),f(`symbol`)&&Za(e,t.embedder,t.store,t.graphStore),f(`eval`)&&lo(e),f(`test_run`)&&uo(e),f(`stash`)&&ds(e),f(`git_context`)&&Yo(e),f(`diff_parse`)&&Xo(e),f(`rename`)&&Zo(e),f(`codemod`)&&Qo(e),f(`restore`)&&Vc(e),f(`file_summary`)&&Qa(e,t.fileCache,h),f(`checkpoint`)&&fs(e),f(`data_transform`)&&$o(e),f(`trace`)&&$a(e,t.embedder,t.store,t.graphStore),f(`process`)&&Io(e),f(`watch`)&&Lo(e),f(`dead_symbols`)&&eo(e,t.embedder,t.store),f(`delegate`)&&po(e,a),f(`health`)&&Ro(e),f(`lane`)&&ps(e),f(`queue`)&&ms(e),f(`web_fetch`)&&zo(e),f(`guide`)&&Bo(e,o),ns.some(e=>f(e))&&rs(e,n,p),f(`evidence_map`)&&To(e),f(`digest`)&&Eo(e,t.embedder),f(`forge_classify`)&&Do(e),f(`stratum_card`)&&Oo(e,t.embedder,t.fileCache),f(`forge_ground`)&&ko(e,t.embedder,t.store),f(`present`)&&Oc(e,r),r&&f(`brainstorm`)&&oa(e,r),f(`web_search`)&&ml(e),f(`http`)&&hl(e),f(`regex_test`)&&gl(e),f(`encode`)&&_l(e),f(`measure`)&&vl(e),f(`changelog`)&&yl(e),f(`schema_validate`)&&bl(e),f(`snippet`)&&xl(e),f(`env`)&&Sl(e),f(`time`)&&Cl(e),kl.some(e=>f(e))&&Co(e,n),t.bridge&&Al.some(e=>f(e))&&(da(e,t.bridge,t.evolutionCollector),fa(e,t.bridge),pa(e,t.bridge)),t.policyStore&&f(`er_update_policy`)&&bs(e,t.policyStore),t.evolutionCollector&&f(`er_evolve_review`)&&ao(e,t.evolutionCollector),Kr(e,t.store,t.curated),zc(e),f(`session_digest`)&&tl(e,a)}async function Pl(e){let t=await El(e),n=Dl(t,e);Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{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}))});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`,A(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`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}},i=async()=>{Q.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),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{Q.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const Fl=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.session_digest.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),Il=5e3,Ll=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.describe_tool.list_tools.search_tools.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.session_digest.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function Rl(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&so(e),r(`eval`)&&lo(e),r(`test_run`)&&uo(e),r(`parse_output`)&&fo(e),r(`delegate`)&&po(e),r(`git_context`)&&Yo(e),r(`diff_parse`)&&Xo(e),r(`rename`)&&Zo(e),r(`codemod`)&&Qo(e),r(`data_transform`)&&$o(e),r(`workset`)&&us(e),r(`stash`)&&ds(e),r(`checkpoint`)&&fs(e),r(`restore`)&&Vc(e),r(`lane`)&&ps(e),r(`queue`)&&ms(e),r(`session_digest`)&&tl(e),r(`health`)&&Ro(e),r(`process`)&&Io(e),r(`watch`)&&Lo(e),r(`web_fetch`)&&zo(e),r(`guide`)&&Bo(e),ns.some(e=>r(e))&&rs(e,t,[...n??new Set($)]),r(`evidence_map`)&&To(e),r(`forge_classify`)&&Do(e),r(`present`)&&Oc(e),r(`brainstorm`)&&oa(e,yr),r(`produce_knowledge`)&&Mc(e),r(`replay`)&&zc(e),r(`status`)&&ul(e),kl.some(e=>r(e))&&Co(e,t),r(`web_search`)&&ml(e),r(`http`)&&hl(e),r(`regex_test`)&&gl(e),r(`encode`)&&_l(e),r(`measure`)&&vl(e),r(`changelog`)&&yl(e),r(`schema_validate`)&&bl(e),r(`snippet`)&&xl(e),r(`env`)&&Sl(e),r(`time`)&&Cl(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_runs.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.describe_tool.list_tools.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.search_tools.session_digest.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function zl(e,t){let n=new nn({name:e.serverName??`aikit`,version:r()},{capabilities:{logging:{},completions:{},prompts:{}}}),i=`initializing`,a=``,o=!1,s=null,c=oi(process.env.AIKIT_TOOLSET||e.toolProfile||`full`,$,ur,Ol(e)),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=()=>i===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,a?`Error: ${a}`:``,``,`**${Ll.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, 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(`
1276
+ `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Ll.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, 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(`
1277
+ `);Cr(n),hr(n,e.toolPrefix??``);let p=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let m=[];for(let e of $){if(!c.has(e))continue;let t=L(e),r=n.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));Ll.has(e)?r.remove():m.push(r)}Rl(n,e,c),n.sendToolListChanged=p;let h=n.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`}]})),g=n.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:P(F.string(),()=>[])}},async()=>({messages:[]})),_,v=new Promise(e=>{_=e}),y,b=new Promise(e=>{y=e}),x=()=>y?.(),S=(async()=>{await b;let r;try{r=await El(e)}catch(t){let n=t instanceof Error?t.message:String(t);if(wl(n)){Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:n}),await Tl(e,n);try{r=await El(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){i=`failed`,a=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:a,originalError:n});return}}else{i=`failed`,a=n,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:a});return}}let c=n.sendToolListChanged.bind(n);n.sendToolListChanged=()=>{};let f=n.sendPromptListChanged.bind(n);n.sendPromptListChanged=()=>{};let p=n.sendResourceListChanged.bind(n);n.sendResourceListChanged=()=>{};for(let e of m)e.remove();h.remove(),g.remove();let v=n._registeredTools??{};for(let e of Ll)v[e]?.remove();let y=new Wr(n),x=Xr(n);Nl(n,r,e,vr(n),y,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null),Er(n,{curated:r.curated,store:r.store,graphStore:r.graphStore},t),n.sendToolListChanged=c,n.sendPromptListChanged=f,n.sendResourceListChanged=p,Promise.resolve(n.sendToolListChanged()).catch(()=>{}),Promise.resolve(n.sendPromptListChanged()).catch(()=>{}),Promise.resolve(n.sendResourceListChanged()).catch(()=>{});let S=n._registeredTools??{};for(let[e,t]of Object.entries(S)){if(Fl.has(e))continue;let n=t.handler;t.handler=async(...t)=>{if(!r.indexer.isIndexing)return n(...t);let i=o?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${e}" timed out waiting for index data (${Il/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Il));return Promise.race([n(...t),a])}}for(let[e,t]of Object.entries(S)){let n=t.handler,r=ui(e);t.handler=async(...t)=>{try{return await di(()=>n(...t),r,e)}catch(t){if(t instanceof li)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.`}]};throw t}}}let C=Object.keys(S).length;C<$.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:C}),Q.info(`MCP server configured`,{toolCount:$.length,resourceCount:4});let T=new Tr;T.onPressure((e,t)=>{e===`warning`&&Qn(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Qn())}),T.start();let E=new xr;l=E,E.onIdle(async()=>{if(w.isRunning||r.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),E.touch();return}Q.info(`Idle cleanup: closing store and graph connections`);try{await Promise.all([r.store.close().catch(()=>{}),r.graphStore.close().catch(()=>{})])}catch{}}),E.touch();for(let e of Object.values(S)){let t=e.handler;e.handler=async(...e)=>{if(E.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}s=r,_?.(r)})(),C=async()=>{let t=await v;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}))});o=!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`,A(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`,A(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,A(e))}finally{l?.setBusy(!1)}},w=new Jn,T=()=>w.schedule({name:`initial-index`,fn:C}),E=process.ppid,D=setInterval(()=>{try{process.kill(E,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:E}),clearInterval(D),v.then(async e=>{await Promise.all([e.embedder.shutdown().catch(()=>{}),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return D.unref(),{server:n,startInit:x,ready:S,runInitialIndex:T,get kb(){return s},scheduler:w,setSmartScheduler(e){u=e}}}export{$ as ALL_TOOL_NAMES,zl as createLazyServer,Dl as createMcpServer,Pl as createServer,El as initializeKnowledgeBase,Nl as registerMcpTools};