@vpxa/aikit 0.1.222 → 0.1.223

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.
@@ -24,7 +24,7 @@ import{r as e,t}from"./curated-manager-CxKwx3Ym.js";import{a as n,i as r,n as i,
24
24
  `),r=await this.curatedStore.remember(t,n,`context`,[`observation`,`source-${e.source}`,`type-${e.type}`]);this.stateStore.memoryMetaCreate(r.path,`working`)}};function Ua(e){let t=[e.cwd,e.workspace,e.root_path,e.path];for(let e of t)if(typeof e==`string`&&e.length>0)return e}function Wa(e){return async(t,n)=>{let r=await n();try{await e.processToolResult(t.toolName,r,{workspace:Ua(t.args),args:t.args})}catch(e){ka.warn(`Observation capture failed`,{toolName:t.toolName,requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}return r}}const Ga=F(`procedural-memory`),Ka=`Use when these user-facing tools are run in this order within a single session.`,qa={minSequenceLength:3,minRepetitions:3,maxSequenceLength:10,confidenceIncrement:10,confidenceDecrement:20},Ja=new Set([`status`,`guide`,`health`,`onboard`,`reindex`,`replay`,`session_digest`,`process`,`watch`,`produce_knowledge`,`list_tools`,`describe_tool`,`search_tools`]);function Ya(e){return e.join(`→`)}function Xa(e){return{...e,steps:[...e.steps]}}function Za(e){return e.every(e=>e.success)}var Qa=class{config;history=[];sequences=new Map;procedures=new Map;pendingProcedures=new Map;constructor(e=qa){this.config=e}record(e,t){let n=new Date().toISOString();this.history.push({toolName:e,timestamp:n,success:t}),this.history.length>100&&(this.history=this.history.slice(-100));let r=this.detectSequences(n);this.updateMatchedProcedures(n,r)}getExtractableSequences(){return[...this.sequences.entries()].filter(([,e])=>e.count>=this.config.minRepetitions).map(([e,t])=>({steps:e.split(`→`),count:t.count,lastSeen:t.lastSeen})).sort((e,t)=>t.count===e.count?t.steps.length-e.steps.length:t.count-e.count)}listProcedures(){return[...this.procedures.values()].map(e=>Xa(e)).sort((e,t)=>t.occurrences===e.occurrences?t.steps.length-e.steps.length:t.occurrences-e.occurrences)}drainNewProcedures(){let e=[...this.pendingProcedures.values()].map(e=>Xa(e));return this.pendingProcedures.clear(),e}requeueProcedures(e){for(let t of e)this.pendingProcedures.set(Ya(t.steps),Xa(t))}extractProcedure(e,t){return{id:ce(),steps:[...e],occurrences:t,confidence:Math.min(50+(t-this.config.minRepetitions)*this.config.confidenceIncrement,100),lastSeen:new Date().toISOString(),conditions:Ka}}adjustConfidence(e,t){return e.confidence=t?Math.min(100,e.confidence+this.config.confidenceIncrement):Math.max(0,e.confidence-this.config.confidenceDecrement),e.confidence}getHistoryLength(){return this.history.length}clear(){this.history=[],this.sequences.clear(),this.procedures.clear(),this.pendingProcedures.clear()}detectSequences(e){let t=this.history.map(e=>e.toolName),n=Math.min(this.config.maxSequenceLength,t.length),r=new Set,i=Math.max(1,Math.min(2,this.config.minRepetitions));for(let a=this.config.minSequenceLength;a<=n;a+=1){let n=t.slice(-a),o=Ya(n),s=0;for(let e=0;e<=t.length-a;e+=1)Ya(t.slice(e,e+a))===o&&(s+=1);if(!(s<i)&&(this.sequences.set(o,{count:s,lastSeen:e}),s>=this.config.minRepetitions&&!this.procedures.has(o))){let t=this.extractProcedure(n,s);t.lastSeen=e,this.procedures.set(o,t),this.pendingProcedures.set(o,Xa(t)),r.add(o)}}return r}updateMatchedProcedures(e,t){for(let[n,r]of this.procedures.entries()){if(t.has(n))continue;let i=n.split(`→`);if(this.history.length<i.length)continue;let a=this.history.slice(-i.length);Ya(a.map(e=>e.toolName))===n&&(r.occurrences+=1,r.lastSeen=e,this.adjustConfidence(r,Za(a)))}}};async function $a(e,t,n){let r=await t.remember(`Procedure: ${n.steps.join(` → `)}`,eo(n),`patterns`,[`procedure`,`auto-extracted`]);return e.memoryMetaCreate(r.path,`procedural`),r.path}function eo(e){return[`## Procedure: ${e.steps.join(` → `)}`,``,`**Confidence:** ${e.confidence}/100`,`**Occurrences:** ${e.occurrences}`,`**Last Seen:** ${e.lastSeen}`,``,`### Steps`,...e.steps.map((e,t)=>`${t+1}. \`${e}\``),``,`### When to Use`,e.conditions??Ka].join(`
25
25
  `)}function to(e,t,n={}){return async(r,i)=>{if(!no(r.toolName,n))return i();try{let n=await i();return e.record(r.toolName,n.isError!==!0),await ro(e,t,r.toolName),n}catch(n){throw e.record(r.toolName,!1),await ro(e,t,r.toolName),n}}}function no(e,t){return t.trackedTools&&!t.trackedTools.has(e)?!1:!(t.ignoredTools??Ja).has(e)}async function ro(e,t,n){if(Ee.instance().isDegraded(`embedder`)){Ga.debug?.(`Skipping procedural memory persist — embedder degraded`);return}let r=e.drainNewProcedures();if(r.length===0)return;let i=[];for(let e of r)try{await $a(t.stateStore,t.curatedStore,e)}catch(t){let r=t instanceof Error?t.message:String(t),a=/circuit breaker|timed out|worker.*killed|respawn/i.test(r);Ga.warn(`Failed to store procedural memory`,{toolName:n,sequence:e.steps.join(` -> `),error:r}),a||i.push(e)}i.length>0&&e.requeueProcedures(i)}const io=F(`tool-pipeline`);function ao(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oo(e,t){return e.tools?(Array.isArray(e.tools)?e.tools:[e.tools]).includes(t):!0}function so(e){return e.middleware.critical===!0}var co=class{entries=[];use(e,t){this.entries.push({middleware:e,order:t?.order??100,tools:t?.tools,name:t?.name??e.name??`anonymous`})}useFor(e,t,n){this.use(t,{order:n?.order,tools:e,name:n?.name})}wrap(e,t,n,r){let i=this.entries.filter(t=>oo(t,e)).sort((e,t)=>e.order-t.order);return async(a,o)=>{let s={toolName:e,args:ao(a)?a:{},requestId:ce(),meta:r,extra:o,toolConfig:n},c=async n=>{let r=i[n];if(!r)return await t(s.args,o);let a=!1,l=!1,u,d=async()=>{a=!0;let e=await c(n+1);return l=!0,u=e,e};try{return await r.middleware(s,d)}catch(t){if(so(r))throw t;if(io.warn(`Middleware failed for tool`,{middleware:r.name,tool:e,error:String(t)}),a){if(l&&u)return u;throw t}return c(n+1)}};return c(0)}}getMiddlewareNames(){return this.entries.map(e=>e.name)}};const lo=F(`auto-gc`);let uo=`warming`,fo=null,po=0;function mo(){let e=[...To()];if(e.length<10)return 0;e.sort((e,t)=>e-t);let t=Math.floor(e.length*.95);return e[Math.min(t,e.length-1)]}function ho(e){let t=mo();if(t===0){uo=`warming`;return}if(t>500){uo=`degraded`;let n=Date.now();if(fo&&n-fo<36e5){lo.debug(`GC cooldown active — skipping`,{lastGcAgoMs:n-fo});return}fo=n,po++,lo.warn(`p95 latency exceeds threshold, triggering GC`,{p95:t,cycle:po}),e&&e().catch(e=>lo.error(`GC callback failed`,{err:String(e)}))}else t<200&&(uo=`healthy`)}function go(){return{state:uo,p95:mo(),lastGcAt:fo,gcCount:po,bufferSize:To().length}}const _o=/key|token|secret|auth|password|bearer/i,vo=new Set([`eval`,`env`]);function yo(e){if(typeof e==`string`)return/^(Bearer |sk-|ghp_|glpat-|ghu_|ghs_|github_pat_)/i.test(e)?`[REDACTED]`:e;if(Array.isArray(e))return e.map(yo);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))/(?:token|secret|password|passphrase|key|auth|credential|api.?key)/i.test(n)?t[n]=`[REDACTED]`:t[n]=yo(r);return t}return e}function bo(e,t){if(vo.has(e))return JSON.stringify({_redacted:!0,tool:e});let n=yo(t);if(e===`http`&&n.headers&&typeof n.headers==`object`){let e={};for(let[t,r]of Object.entries(n.headers))e[t]=_o.test(t)?`[REDACTED]`:r;return n.headers=e,JSON.stringify(n).slice(0,2e3)}return JSON.stringify(n).slice(0,2e3)}const xo=new Map,So=[];function Co(e,t,n,r,i){let a=xo.get(e);a||(a={callCount:0,totalDurationMs:0,totalInputChars:0,totalOutputChars:0,errorCount:0},xo.set(e,a)),a.callCount++,a.totalDurationMs+=t,a.totalInputChars+=n,a.totalOutputChars+=r,i&&a.errorCount++,So.push(t),So.length>100&&So.shift(),So.length>=10&&So.length%20==0&&ho()}function wo(){return Array.from(xo.entries()).map(([e,t])=>({tool:e,...t}))}function To(){return So}function Eo(){return async(e,t)=>{let n=Date.now(),r=JSON.stringify(e.args??{}).length;try{let i=await t(),a=Date.now()-n,o=JSON.stringify(i);return rn({ts:new Date().toISOString(),source:`mcp`,tool:e.toolName,input:bo(e.toolName,e.args),durationMs:a,status:`ok`,output:o,traceId:e.requestId,outputChars:o.length}),Co(e.toolName,a,r,o.length,!1),i}catch(t){let i=Date.now()-n,a=t instanceof Error?t.message:String(t);throw rn({ts:new Date().toISOString(),source:`mcp`,tool:e.toolName,input:bo(e.toolName,e.args),durationMs:i,status:`error`,output:a,traceId:e.requestId,outputChars:0}),Co(e.toolName,i,r,0,!0),t}}}function Do(e,t){e.registerResource(`aikit-curated-index`,`aikit://curated`,{description:`Index of all curated knowledge entries`,mimeType:`text/markdown`},async()=>{let e=(await t.list()).map(e=>`- [${e.title}](aikit://curated/${e.path}) — ${e.category}`);return{contents:[{uri:`aikit://curated`,text:`# Curated Knowledge Index\n\n${e.length>0?e.join(`
26
26
  `):`_No curated entries yet._`}`,mimeType:`text/markdown`}]}});let n=new Un(`aikit://curated/{+path}`,{list:async()=>({resources:(await t.list()).map(e=>({uri:`aikit://curated/${e.path}`,name:e.title,description:`[${e.category}] ${e.contentPreview?.slice(0,80)??``}`,mimeType:`text/markdown`}))})});e.registerResource(`aikit-curated-entry`,n,{description:`A curated knowledge entry`,mimeType:`text/markdown`},async(e,n)=>{let r=n.path;if(!r)throw Error(`Missing path variable in curated resource URI`);let i=await t.read(r);return{contents:[{uri:e.toString(),text:`---\ntitle: ${i.title}\ncategory: ${i.category}\ntags: ${i.tags?.join(`, `)??``}\nversion: ${i.version??1}\n---\n\n${i.content??i.contentPreview??``}`,mimeType:`text/markdown`}]}})}const Oo=`aikit://schemas/channel-surface`,ko=new URL(`../../../blocks-core/schemas/channel-surface.schema.json`,import.meta.url);let Ao;function jo(){return Ao??=Mn(ko,`utf8`),Ao}function Mo(e,t,n){e.registerResource(`aikit-status`,`aikit://status`,{description:`Current AI Kit status and statistics`,mimeType:`text/plain`},async()=>{let e=await t.getStats();return{contents:[{uri:`aikit://status`,text:`AI Kit: ${e.totalRecords} records from ${e.totalFiles} files. Last indexed: ${e.lastIndexedAt??`Never`}`,mimeType:`text/plain`}]}}),e.registerResource(`aikit-file-tree`,`aikit://file-tree`,{description:`List of all indexed source files`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://file-tree`,text:(await t.listSourcePaths()).sort().join(`
27
- `),mimeType:`text/plain`}]})),e.registerResource(`aikit-channel-surface-schema`,Oo,{description:`JSON Schema for the ChannelSurface communication contract`,mimeType:`application/schema+json`},async()=>({contents:[{uri:Oo,text:await jo(),mimeType:`application/schema+json`}]})),Do(e,n)}const No=[`er_push`,`er_pull`,`er_sync_status`],Po=[...No,`er_update_policy`,`er_evolve_review`],Fo=new Set(Po);function Io(e){return e.toolProfiles}const Lo=new Set(`browser.changelog.check.compliance_score.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.knowledge.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.regex_test.reindex.rename.replay.restore.schema_validate.session_digest.scope_map.stash.status.stratum_card.signal.test_run.time.watch.web_fetch.web_search.workset`.split(`.`)),Ro=5e3,zo=new Set(`browser.changelog.check.compliance_score.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow.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.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`)),Bo=`analyze.audit.blast_radius.browser.changelog.check.compliance_score.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow.forge_classify.forge_ground.git_context.graph.guide.health.http.knowledge.lane.describe_tool.list_tools.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.regex_test.reindex.rename.replay.restore.schema_validate.scope_map.search.search_tools.signal.session_digest.stash.status.stratum_card.symbol.test_run.time.trace.watch.web_fetch.web_search.workset`.split(`.`),Vo=F(`structured-content-guard`);function Ho(){let e=(async(e,t)=>{let n;try{n=await t()}catch(e){n={content:[{type:`text`,text:`[ERROR:INTERNAL] ${e instanceof Error?e.message:String(e)}`}],isError:!0}}let r=(e.toolConfig??{}).outputSchema;if(r==null)return n;let i=null;if(n.structuredContent==null){let t=Uo(r);n.structuredContent=t,i=`synthesize`,n.structuredContent??(n.structuredContent={},i=`synthesize-null-fallback`,Vo.error(`synthesizeStructuredContent returned null/undefined — using empty fallback`,{tool:e.toolName}))}let a=Wo(r,n.structuredContent);if(a.action!=null&&(n.structuredContent=a.structuredContent,i=a.action),Ko(n.structuredContent)||(n.isError=!0,n.structuredContent={},i=`fallback-error`),Go(r,n.structuredContent)===!1){let e=Uo(r);n.structuredContent=e??{},Go(r,n.structuredContent)===!1?(n.structuredContent=Ko(n.structuredContent)?n.structuredContent:{},i=`final-validation-failed`):i??=`final-heal`}return Ko(n.structuredContent)||(n.isError=!0,n.structuredContent={},i=`fallback-error`),i!=null&&Vo.warn(`Structured content guard activated`,{tool:e.toolName,action:i}),n});return e.critical=!0,e}function Uo(e){try{return qo(e)??{}}catch{return{}}}function Wo(e,t){if(Go(e,t)!==!1)return{structuredContent:t,action:null};try{let n=Uo(e);if(Ko(n)&&Ko(t)){let r={...n,...t};if(Go(e,r)!==!1)return{structuredContent:r,action:`heal`}}return{structuredContent:n,action:`fallback-zero-value`}}catch{return{structuredContent:t,action:null}}}function Go(e,t){let n=e.safeParse;if(typeof n==`function`)try{return n(t).success}catch{return}}function Ko(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qo(e){if(!e)return{};if(e.anyOf){let t=e.anyOf.find(e=>e.type!==`null`);return t?qo(t):null}let t=e._def?.typeName;if(t&&!e.type)switch(t){case`ZodObject`:{let t={},n=null;try{n=e.shape??(typeof e._def?.shape==`function`?e._def.shape():e._def?.shape)}catch{n=null}if(n)for(let[e,r]of Object.entries(n))try{t[e]=qo(r)}catch{t[e]=null}return t}case`ZodArray`:return[];case`ZodString`:return``;case`ZodNumber`:return 0;case`ZodBoolean`:return!1;case`ZodNullable`:return null;case`ZodOptional`:return;case`ZodRecord`:return{};case`ZodEnum`:return e._def?.values?.[0]??``;default:return{}}switch(e.type){case`object`:{let t={},n=e.properties??e.shape;if(n)for(let[e,r]of Object.entries(n))t[e]=qo(r);return t}case`array`:return[];case`string`:return``;case`number`:case`integer`:return 0;case`boolean`:return!1;case`nullable`:return null;case`optional`:return;case`record`:return{};case`enum`:return e.options?.[0]??Object.values(e.enum??e._def?.entries??{})[0]??``;default:return{}}}function Jo(e){if(!e)return{};try{let t=qo(e);return Ko(t)?t:{}}catch{return{}}}const W={search:{title:`Hybrid Search`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},find:{title:`Federated Find`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},symbol:{title:`Symbol Resolver — Cross-Module Definitions & References`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},trace:{title:`Data Flow Tracer — Cross-Module Call & Import Chains`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},scope_map:{title:`Task Scope Map`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},lookup:{title:`Chunk Lookup`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},dead_symbols:{title:`Dead Symbol Finder`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},file_summary:{title:`File Summary`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},analyze:{title:`Analyze`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`analysis`]},blast_radius:{title:`Blast Radius`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`analysis`,`search`]},knowledge:{title:`Knowledge`,annotations:{readOnlyHint:!1},category:[`knowledge`]},produce_knowledge:{title:`Produce Knowledge`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`knowledge`]},compact:{title:`Semantic Compactor`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`compression`]},digest:{title:`Multi-Source Digest`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`compression`]},stratum_card:{title:`Stratum Card`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`compression`]},forge_ground:{title:`FORGE Ground`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`forge`]},forge_classify:{title:`FORGE Classify`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`forge`]},evidence_map:{title:`Evidence Map`,annotations:{readOnlyHint:!1},category:[`forge`]},present:{title:`Rich Content Presenter`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`presentation`]},check:{title:`Typecheck & Lint`,annotations:{readOnlyHint:!0,openWorldHint:!0},category:[`execution`]},test_run:{title:`Run Tests`,annotations:{readOnlyHint:!0,openWorldHint:!0},category:[`execution`]},eval:{title:`Evaluate Code`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`execution`]},audit:{title:`Project Audit`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`execution`]},browser:{title:`Browser Automation`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`web`]},rename:{title:`Rename Symbol`,annotations:{readOnlyHint:!1,destructiveHint:!0},category:[`manipulation`]},restore:{title:`Restore`,annotations:{readOnlyHint:!1},category:[`manipulation`]},codemod:{title:`Codemod`,annotations:{readOnlyHint:!1,destructiveHint:!0},category:[`manipulation`]},data_transform:{title:`Data Transform`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`manipulation`]},stash:{title:`Stash Values`,annotations:{readOnlyHint:!1},category:[`session`]},signal:{title:`Inter-Agent Signaling`,annotations:{readOnlyHint:!1},category:[`session`]},checkpoint:{title:`Session Checkpoint`,annotations:{readOnlyHint:!1},category:[`session`]},session_digest:{title:`Session Digest`,annotations:{readOnlyHint:!0,idempotentHint:!1},category:[`session`]},compliance_score:{title:`Compliance Score`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`session`]},workset:{title:`Workset Manager`,annotations:{readOnlyHint:!1},category:[`session`]},lane:{title:`Exploration Lane`,annotations:{readOnlyHint:!1},category:[`session`]},git_context:{title:`Git Context`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`git`]},diff_parse:{title:`Diff Parser`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`git`]},parse_output:{title:`Parse Build Output`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`git`]},process:{title:`Process Manager`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`process`]},watch:{title:`File Watcher`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`process`]},delegate:{title:`Delegate Task`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`process`]},config:{title:`Configuration Manager`,annotations:{readOnlyHint:!1},category:[`system`]},status:{title:`AI Kit Status`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},health:{title:`Health Check`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},reindex:{title:`Reindex`,annotations:{readOnlyHint:!1},category:[`system`]},onboard:{title:`Onboard Codebase`,annotations:{readOnlyHint:!1},category:[`system`]},graph:{title:`Code Knowledge Graph — Module & Symbol Relationships`,annotations:{readOnlyHint:!1},category:[`system`]},guide:{title:`Tool Guide`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},replay:{title:`Replay History`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},list_tools:{title:`List Available Tools`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`meta`]},describe_tool:{title:`Describe Tool`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`meta`]},search_tools:{title:`Search Tools`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`meta`]},changelog:{title:`Generate Changelog`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},regex_test:{title:`Regex Tester`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},encode:{title:`Encode / Decode`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},measure:{title:`Code Metrics`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},schema_validate:{title:`Schema Validator`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},env:{title:`Environment Info`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},time:{title:`Date & Time`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},web_fetch:{title:`Web Fetch`,annotations:{readOnlyHint:!0,openWorldHint:!0},category:[`web`]},web_search:{title:`Web Search`,annotations:{readOnlyHint:!0,openWorldHint:!0},category:[`web`]},http:{title:`HTTP Request`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`web`]},queue:{title:`Operation Queue`,annotations:{readOnlyHint:!1},category:[`queue`]},bridge_push:{title:`Bridge Push`,annotations:{readOnlyHint:!1},category:[`system`]},bridge_pull:{title:`Bridge Pull`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},bridge_sync:{title:`Bridge Sync Status`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},er_push:{title:`Enterprise Push`,annotations:{readOnlyHint:!1},category:[`system`]},er_pull:{title:`Enterprise Pull`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},er_sync_status:{title:`Enterprise Sync Status`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},er_update_policy:{title:`Enterprise Update Policy`,annotations:{readOnlyHint:!1},category:[`system`]},er_evolve_review:{title:`Enterprise Evolution Review`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},evolution_state:{title:`Evolution State`,annotations:{readOnlyHint:!1},category:[`system`]},policy_check:{title:`Policy Check`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},flow:{title:`Flow`,annotations:{readOnlyHint:!1},category:[`flow`]}};function G(e){return W[e]??{title:e,annotations:{readOnlyHint:!1},category:[]}}const Yo=Symbol(`toolPipelineState`);function Xo(e){return e[Yo]}function Zo(e,t){e[Yo]=t}function Qo(e,t){return t?async(...n)=>{let r=await e(...n);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=Jo(t),i.structuredContent??={},r)}:e}function $o(e,t,n=``){let r=Xo(e);if(r){r.pipeline=t,r.prefix=n;return}Zo(e,{originalRegisterTool:e.registerTool.bind(e),pipeline:t,prefix:n}),e.registerTool=(n,r,i)=>{let a=Xo(e),o=a?.prefix?`${a.prefix}${n}`:n;if(!i)return a?.originalRegisterTool(o,r);let s=r?.outputSchema;if((a?.pipeline??t).getMiddlewareNames().length===0){let e=Qo(i,s);return a?.originalRegisterTool(o,r,e)}let c=G(n),l=Qo((a?.pipeline??t).wrap(n,i,r,c),s);return a?.originalRegisterTool(o,r,l)}}const es={analyze:1,audit:1,blast_radius:1,changelog:1,check:2,checkpoint:2,codemod:2,compact:1,config:0,data_transform:1,dead_symbols:1,delegate:3,describe_tool:1,diff_parse:1,digest:1,encode:1,env:0,eval:2,evidence_map:2,file_summary:1,find:1,flow:3,forge_classify:1,forge_ground:2,git_context:1,graph:1,guide:0,health:0,http:1,lane:2,list_tools:1,lookup:1,measure:1,onboard:3,parse_output:1,present:1,process:3,produce_knowledge:3,queue:3,regex_test:1,reindex:3,rename:2,replay:1,restore:2,schema_validate:1,scope_map:1,search:1,search_tools:1,signal:2,session_digest:2,stash:2,status:0,stratum_card:1,symbol:1,test_run:2,time:0,trace:1,watch:3,web_fetch:1,web_search:1,workset:2};function ts(e,t){return e.filter(e=>(es[e]??0)<=t)}const ns=new Set([`status`,`config`,`guide`,`health`]),rs={full:{description:`All tools enabled (default)`,includeCategories:[]},safe:{description:`Read-only tools — no file/state modifications`,includeCategories:[`search`,`analysis`,`compression`,`utilities`,`system`,`git`,`flow`],excludeTools:[`reindex`,`onboard`]},research:{description:`Search, analysis, knowledge, and web access`,includeCategories:[`search`,`analysis`,`knowledge`,`compression`,`web`,`system`,`flow`]},minimal:{description:`Essential tools only — search, status, basic operations`,includeCategories:[`search`,`system`],includeTools:[`compact`,`file_summary`,`check`,`test_run`]},discovery:{description:`Full toolset plus discovery-oriented meta-tools for guided tool exploration`,includeCategories:[],includeTools:[`list_tools`,`describe_tool`,`search_tools`]}};function is(e,t){let n=rs[e];if(n)return n;let r=t?.[e];if(r)return r;throw Error(`Unknown tool profile: ${e}`)}function as(e,t,n){return t.includes(`*`)?!0:(n[e]?.category??[]).some(e=>t.includes(e))}function os(e,t,n,r){if(t.includes(`*`)){for(let t of n)e.add(t);return}for(let i of n)as(i,t,r)&&e.add(i)}function ss(e,t,n){if(t.includes(`*`)){e.clear();return}for(let r of[...e])as(r,t,n)&&e.delete(r)}function cs(e,t,n){if(!e||e.length===0||e.includes(`*`))return new Set(t);let r=new Set;return os(r,e,t,n),r}function ls(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function us(e,t){for(let n of[...e])t[n]?.annotations?.readOnlyHint===!1&&e.delete(n)}function ds(e,t,n=0,r=[]){if(n>10)throw Error(`Tool profile inheritance exceeded max depth 10: ${[...r,e].join(` -> `)}`);if(r.includes(e))throw Error(`Tool profile inheritance cycle detected: ${[...r,e].join(` -> `)}`);let i=is(e,t);return ls(i.extends?ds(i.extends,t,n+1,[...r,e]):void 0,i.maxTier)}function fs(e,t,n,r){let i=(e,a,o)=>{if(a>10)throw Error(`Tool profile inheritance exceeded max depth 10: ${[...o,e].join(` -> `)}`);if(o.includes(e))throw Error(`Tool profile inheritance cycle detected: ${[...o,e].join(` -> `)}`);let s=is(e,r),c=[...o,e],l=s.extends?i(s.extends,a+1,c):cs(s.includeCategories,t,n);s.extends&&s.includeCategories?.length&&os(l,s.includeCategories,t,n),s.excludeCategories?.length&&ss(l,s.excludeCategories,n);for(let e of s.includeTools??[])l.add(e);for(let e of s.excludeTools??[])l.delete(e);return l},a=i(e,0,[]),o=ds(e,r);if(o!==void 0){let e=ts([...a],o);a.clear();for(let t of e)a.add(t)}for(let e of ns)a.add(e);return e===`safe`&&us(a,n),a}const ps=new Set([`search`,`analysis`,`knowledge`,`compression`,`forge`,`presentation`,`execution`,`manipulation`,`session`,`git`,`process`,`system`,`meta`,`utilities`,`web`,`queue`,`flow`]);function ms(e,t,n,r){let i=process.env.AIKIT_TOOLSET||e.toolProfile||`full`,a=fs(i,t,n,r);if(e.features&&e.features.length>0){let i=e.features.filter(e=>!ps.has(e));if(i.length>0)throw Error(`Unknown feature group(s): ${i.join(`, `)}. Valid categories: ${[...ps].join(`, `)}`);let o={description:`Synthetic profile from features config`,includeCategories:e.features},s=fs(`_features`,t,n,{...r,_features:o});for(let e of a)!s.has(e)&&!ns.has(e)&&a.delete(e)}if(e.readOnly)for(let e of[...a])n[e]?.annotations?.readOnlyHint===!1&&!ns.has(e)&&a.delete(e);for(let e of ns)a.add(e);return i===`safe`&&us(a,n),a}const hs=R.object({mode:R.enum([`wasm`,`regex`,`unknown`]),reason:R.string(),pathsChecked:R.array(R.object({path:R.string(),exists:R.boolean()})),os:R.string(),arch:R.string(),nodeVersion:R.string(),webTreeSitterImportable:R.boolean(),healAttempted:R.boolean(),healSuccess:R.boolean(),healError:R.string().nullable(),initError:R.string().nullable(),wasmDir:R.string().nullable(),grammarCount:R.number()}),gs=R.object({kind:R.enum([`onboard`,`reindex`,`handoff`,`proceed`]),reason:R.string()}),_s=R.object({title:R.string(),insight:R.string(),confidence:R.number()}),vs=R.object({lessons:R.array(_s),conventions:R.array(R.object({title:R.string(),preview:R.string()})),checkpoint:R.string().nullable()}),ys=R.object({totalRecords:R.number(),totalFiles:R.number(),lastIndexedAt:R.string().nullable(),onboarded:R.boolean(),onboardDir:R.string(),contentTypes:R.record(R.string(),R.number()),wasmAvailable:R.boolean(),wasmDiagnostics:hs,graphStats:R.object({nodes:R.number(),edges:R.number()}).nullable(),curatedCount:R.number(),serverVersion:R.string(),scaffoldVersion:R.string().nullable(),workspaceScaffoldVersion:R.string().nullable(),upgradeAvailable:R.boolean(),storeBackend:R.string().optional(),storeDiagnostics:R.object({adapterType:R.string(),vectorSearchEnabled:R.boolean(),ftsEnabled:R.boolean(),degradedMode:R.boolean(),dbPath:R.string(),dbSizeBytes:R.number().nullable(),embeddingDim:R.number(),vectorDtype:R.string()}).nullable().optional(),contextPressure:R.number().min(0).max(100).describe(`0–100 score indicating AI Kit saturation`),nextAction:gs,prelude:vs.nullable().optional()});R.object({entries:R.array(R.object({path:R.string(),title:R.string(),category:R.string(),tags:R.array(R.string()),version:R.number(),preview:R.string()})),totalCount:R.number()});const bs=R.object({ok:R.boolean(),checks:R.array(R.object({name:R.string(),ok:R.boolean(),message:R.string().optional()}))}),xs=R.object({summary:R.object({totalFiles:R.number(),totalLines:R.number(),totalCodeLines:R.number(),totalFunctions:R.number(),avgComplexity:R.number(),maxComplexity:R.object({value:R.number(),file:R.string()})}),files:R.array(R.object({path:R.string(),lines:R.number(),code:R.number(),complexity:R.number(),functions:R.number()}))}),Ss=R.object({platform:R.string(),arch:R.string(),nodeVersion:R.string(),cwd:R.string(),cpus:R.number(),memoryFreeGb:R.number(),memoryTotalGb:R.number()}),Cs=R.object({iso:R.string(),unix:R.number(),timezone:R.string(),formatted:R.string()}),ws=R.object({passed:R.boolean(),errorCount:R.number(),warningCount:R.number(),topErrors:R.array(R.string())}),Ts=R.object({passed:R.boolean(),tsc:ws,biome:ws}),Es=R.object({name:R.string(),definedIn:R.object({path:R.string(),line:R.number(),kind:R.string(),signature:R.string().optional()}).nullable(),importedBy:R.array(R.object({path:R.string(),line:R.number(),importStatement:R.string()})),referencedIn:R.array(R.object({path:R.string(),line:R.number(),context:R.string(),scope:R.string().optional()})),graphContext:R.object({definingModule:R.string().optional(),importedByModules:R.array(R.string()),siblingSymbols:R.array(R.string())}).nullable()}),Ds=R.object({sourcePath:R.string(),contentType:R.string(),score:R.number(),headingPath:R.string().optional(),startLine:R.number().optional(),endLine:R.number().optional(),origin:R.string().optional(),category:R.string().optional(),tags:R.array(R.string()).optional()}),Os=R.object({results:R.array(Ds),totalResults:R.number(),searchMode:R.string(),query:R.string()}),ks=R.object({path:R.string(),line:R.number().optional(),matchType:R.string(),preview:R.string()}),As=R.object({matches:R.array(ks),totalMatches:R.number(),pattern:R.string(),truncated:R.boolean()}),js=R.object({path:R.string(),relevance:R.number(),estimatedTokens:R.number(),focusLines:R.array(R.string()).optional()}),Ms=R.object({files:R.array(js),totalFiles:R.number(),totalEstimatedTokens:R.number(),task:R.string()}),Ns=R.object({path:R.string(),impact:R.string(),reason:R.string()}),Ps=R.object({changedFiles:R.array(R.string()),affectedFiles:R.array(Ns),totalAffected:R.number(),riskLevel:R.string()}),Fs=R.object({name:R.string(),passed:R.boolean(),message:R.string().optional(),severity:R.string().optional()}),Is=R.object({passed:R.boolean(),score:R.number(),checks:R.array(Fs),summary:R.string()}),Ls=R.object({id:R.string(),name:R.string(),type:R.string(),sourcePath:R.string().optional()}),Rs=R.object({fromId:R.string(),toId:R.string(),type:R.string()}),zs=R.object({nodes:R.array(Ls),edges:R.array(Rs),totalNodes:R.number(),totalEdges:R.number(),query:R.string()}),Bs=R.object({symbols:R.array(R.object({name:R.string(),path:R.string(),line:R.number().optional(),kind:R.string()})),totalDead:R.number()});R.object({files:R.number(),packages:R.number(),languages:R.record(R.string(),R.number()),tree:R.string()});const Vs=R.object({path:R.string(),language:R.string(),lines:R.number(),imports:R.number(),exports:R.number(),functions:R.number(),classes:R.number()}),Hs=R.object({gitRoot:R.string(),branch:R.string(),commitCount:R.number(),hasUncommitted:R.boolean(),recentCommits:R.array(R.object({hash:R.string(),message:R.string(),author:R.string(),date:R.string()}))}),Us=R.object({text:R.string().describe(`The compressed text output`),originalChars:R.number(),compressedChars:R.number(),ratio:R.number(),segmentsKept:R.number(),segmentsTotal:R.number()}),Ws=R.object({passed:R.boolean(),totalTests:R.number(),passedTests:R.number(),failedTests:R.number(),skippedTests:R.number(),duration:R.number().describe(`Duration in milliseconds`),failures:R.array(R.object({name:R.string(),message:R.string(),file:R.string().optional()}))}),Gs=F(`utils:enrich`);async function K(e,t){let n={curated:[],graph:[]},r=t.limit??3,[i,a]=await Promise.allSettled([Ks(e,t.query,r),qs(e,t.filePath)]);return i.status===`fulfilled`?n.curated=i.value:Gs.debug(`Curated enrichment failed`,{error:i.reason}),a.status===`fulfilled`?n.graph=a.value:Gs.debug(`Graph enrichment failed`,{error:a.reason}),n}async function Ks(e,t,n){if(!e.store||!t)return[];try{let r=await e.store.ftsSearch(t,{origin:`curated`,limit:n});if(r.length>0)return r.map(e=>Js(e.record));if(e.embedder){let r=await e.embedder.embedQuery(t);return(await e.store.search(r,{origin:`curated`,limit:n,minScore:.3})).map(e=>Js(e.record))}return[]}catch(e){return Gs.debug(`Curated enrichment failed`,{error:e}),[]}}async function qs(e,t){if(!e.graphStore||!t)return[];try{let n=await e.graphStore.findNodes({sourcePath:t,limit:1});if(n.length===0){let r=t.split(/[/\\]/).pop()?.replace(/\.\w+$/,``)||``;if(!r)return[];let i=await e.graphStore.findNodes({namePattern:r,type:`module`,limit:1});if(i.length===0)return[];n.push(i[0])}let r=n[0],i=await e.graphStore.getNeighbors(r.id,{direction:`both`,limit:10}),a=[];for(let e of i.edges){let t=e.fromId===r.id?e.toId:e.fromId,n=i.nodes.find(e=>e.id===t);if(!n)continue;let o=e.fromId===r.id?`->`:`<-`;a.push(`${o} ${e.type}: ${n.name} (${n.type})`)}return a}catch(e){return Gs.debug(`Graph enrichment failed`,{error:e}),[]}}function q(e){let t=[];if(e.curated.length>0){t.push(`**Curated Knowledge:**`);for(let n of e.curated)t.push(`- ${n}`)}if(e.graph.length>0){t.push(`**Graph Context:**`);for(let n of e.graph)t.push(`- ${n}`)}return t.length===0?``:`\n\n---\n## Enrichment\n${t.join(`
27
+ `),mimeType:`text/plain`}]})),e.registerResource(`aikit-channel-surface-schema`,Oo,{description:`JSON Schema for the ChannelSurface communication contract`,mimeType:`application/schema+json`},async()=>({contents:[{uri:Oo,text:await jo(),mimeType:`application/schema+json`}]})),Do(e,n)}const No=[`er_push`,`er_pull`,`er_sync_status`],Po=[...No,`er_update_policy`,`er_evolve_review`],Fo=new Set(Po);function Io(e){return e.toolProfiles}const Lo=new Set(`browser.changelog.check.compliance_score.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.knowledge.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.regex_test.reindex.rename.replay.restore.schema_validate.session_digest.scope_map.stash.status.stratum_card.signal.test_run.time.watch.web_fetch.web_search.workset`.split(`.`)),Ro=5e3,zo=new Set(`browser.changelog.check.compliance_score.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow.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.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`)),Bo=`analyze.audit.blast_radius.browser.changelog.check.compliance_score.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow.forge_classify.forge_ground.git_context.graph.guide.health.http.knowledge.lane.describe_tool.list_tools.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.regex_test.reindex.rename.replay.restore.schema_validate.scope_map.search.search_tools.signal.session_digest.stash.status.stratum_card.symbol.test_run.time.trace.watch.web_fetch.web_search.workset`.split(`.`),Vo=F(`structured-content-guard`);function Ho(){let e=(async(e,t)=>{let n;try{n=await t()}catch(e){n={content:[{type:`text`,text:`[ERROR:INTERNAL] ${e instanceof Error?e.message:String(e)}`}],isError:!0}}let r=(e.toolConfig??{}).outputSchema;if(r==null)return n;let i=null;if(n.structuredContent==null){let t=Uo(r);n.structuredContent=t,i=`synthesize`,n.structuredContent??(n.structuredContent={},i=`synthesize-null-fallback`,Vo.error(`synthesizeStructuredContent returned null/undefined — using empty fallback`,{tool:e.toolName}))}let a=Wo(r,n.structuredContent);if(a.action!=null&&(n.structuredContent=a.structuredContent,i=a.action),Ko(n.structuredContent)||(n.isError=!0,n.structuredContent={},i=`fallback-error`),Go(r,n.structuredContent)===!1){let e=Uo(r);n.structuredContent=e??{},Go(r,n.structuredContent)===!1?(n.structuredContent=Ko(n.structuredContent)?n.structuredContent:{},i=`final-validation-failed`):i??=`final-heal`}return Ko(n.structuredContent)||(n.isError=!0,n.structuredContent={},i=`fallback-error`),i!=null&&Vo.warn(`Structured content guard activated`,{tool:e.toolName,action:i}),n});return e.critical=!0,e}function Uo(e){try{return qo(e)??{}}catch{return{}}}function Wo(e,t){if(Go(e,t)!==!1)return{structuredContent:t,action:null};try{let n=Uo(e);if(Ko(n)&&Ko(t)){let r={...n,...t};if(Go(e,r)!==!1)return{structuredContent:r,action:`heal`}}return{structuredContent:n,action:`fallback-zero-value`}}catch{return{structuredContent:t,action:null}}}function Go(e,t){let n=e.safeParse;if(typeof n==`function`)try{return n(t).success}catch{return}}function Ko(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qo(e){if(!e)return{};if(e.anyOf){let t=e.anyOf.find(e=>e.type!==`null`);return t?qo(t):null}let t=e._def?.typeName;if(t&&!e.type)switch(t){case`ZodObject`:{let t={},n=null;try{n=e.shape??(typeof e._def?.shape==`function`?e._def.shape():e._def?.shape)}catch{n=null}if(n)for(let[e,r]of Object.entries(n))try{t[e]=qo(r)}catch{t[e]=null}return t}case`ZodArray`:return[];case`ZodString`:return``;case`ZodNumber`:return 0;case`ZodBoolean`:return!1;case`ZodNullable`:return null;case`ZodOptional`:return;case`ZodRecord`:return{};case`ZodEnum`:return e._def?.values?.[0]??``;default:return{}}switch(e.type){case`object`:{let t={},n=e.properties??e.shape;if(n)for(let[e,r]of Object.entries(n))t[e]=qo(r);return t}case`array`:return[];case`string`:return``;case`number`:case`integer`:return 0;case`boolean`:return!1;case`nullable`:return null;case`optional`:return;case`record`:return{};case`enum`:return e.options?.[0]??Object.values(e.enum??e._def?.entries??{})[0]??``;default:return{}}}function Jo(e){if(!e)return{};try{let t=qo(e);return Ko(t)?t:{}}catch{return{}}}const W={search:{title:`Hybrid Search`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},find:{title:`Federated Find`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},symbol:{title:`Symbol Resolver — Cross-Module Definitions & References`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},trace:{title:`Data Flow Tracer — Cross-Module Call & Import Chains`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},scope_map:{title:`Task Scope Map`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},lookup:{title:`Chunk Lookup`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},dead_symbols:{title:`Dead Symbol Finder`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},file_summary:{title:`File Summary`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`search`]},analyze:{title:`Analyze`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`analysis`]},blast_radius:{title:`Blast Radius`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`analysis`,`search`]},knowledge:{title:`Knowledge`,annotations:{readOnlyHint:!1},category:[`knowledge`]},produce_knowledge:{title:`Produce Knowledge`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`knowledge`]},compact:{title:`Semantic Compactor`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`compression`]},digest:{title:`Multi-Source Digest`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`compression`]},stratum_card:{title:`Stratum Card`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`compression`]},forge_ground:{title:`FORGE Ground`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`forge`]},forge_classify:{title:`FORGE Classify`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`forge`]},evidence_map:{title:`Evidence Map`,annotations:{readOnlyHint:!1},category:[`forge`]},present:{title:`Rich Content Presenter`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`presentation`]},check:{title:`Typecheck & Lint`,annotations:{readOnlyHint:!0,openWorldHint:!0},category:[`execution`]},test_run:{title:`Run Tests`,annotations:{readOnlyHint:!0,openWorldHint:!0},category:[`execution`]},eval:{title:`Evaluate Code`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`execution`]},audit:{title:`Project Audit`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`execution`]},browser:{title:`Browser Automation`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`web`]},rename:{title:`Rename Symbol`,annotations:{readOnlyHint:!1,destructiveHint:!0},category:[`manipulation`]},restore:{title:`Restore`,annotations:{readOnlyHint:!1},category:[`manipulation`]},codemod:{title:`Codemod`,annotations:{readOnlyHint:!1,destructiveHint:!0},category:[`manipulation`]},data_transform:{title:`Data Transform`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`manipulation`]},stash:{title:`Stash Values`,annotations:{readOnlyHint:!1},category:[`session`]},signal:{title:`Inter-Agent Signaling`,annotations:{readOnlyHint:!1},category:[`session`]},checkpoint:{title:`Session Checkpoint`,annotations:{readOnlyHint:!1},category:[`session`]},session_digest:{title:`Session Digest`,annotations:{readOnlyHint:!0,idempotentHint:!1},category:[`session`]},compliance_score:{title:`Compliance Score`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`session`]},workset:{title:`Workset Manager`,annotations:{readOnlyHint:!1},category:[`session`]},lane:{title:`Exploration Lane`,annotations:{readOnlyHint:!1},category:[`session`]},git_context:{title:`Git Context`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`git`]},diff_parse:{title:`Diff Parser`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`git`]},parse_output:{title:`Parse Build Output`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`git`]},process:{title:`Process Manager`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`process`]},watch:{title:`File Watcher`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`process`]},delegate:{title:`Delegate Task`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`process`]},config:{title:`Configuration Manager`,annotations:{readOnlyHint:!1},category:[`system`]},status:{title:`AI Kit Status`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},health:{title:`Health Check`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},reindex:{title:`Reindex`,annotations:{readOnlyHint:!1},category:[`system`]},onboard:{title:`Onboard Codebase`,annotations:{readOnlyHint:!1},category:[`system`]},graph:{title:`Code Knowledge Graph — Module & Symbol Relationships`,annotations:{readOnlyHint:!1},category:[`system`]},guide:{title:`Tool Guide`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},replay:{title:`Replay History`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},list_tools:{title:`List Available Tools`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`meta`]},describe_tool:{title:`Describe Tool`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`meta`]},search_tools:{title:`Search Tools`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`meta`]},changelog:{title:`Generate Changelog`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},regex_test:{title:`Regex Tester`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},encode:{title:`Encode / Decode`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},measure:{title:`Code Metrics`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},schema_validate:{title:`Schema Validator`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},env:{title:`Environment Info`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},time:{title:`Date & Time`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`utilities`]},web_fetch:{title:`Web Fetch`,annotations:{readOnlyHint:!0,openWorldHint:!0},category:[`web`]},web_search:{title:`Web Search`,annotations:{readOnlyHint:!0,openWorldHint:!0},category:[`web`]},http:{title:`HTTP Request`,annotations:{readOnlyHint:!1,openWorldHint:!0},category:[`web`]},queue:{title:`Operation Queue`,annotations:{readOnlyHint:!1},category:[`queue`]},bridge_push:{title:`Bridge Push`,annotations:{readOnlyHint:!1},category:[`system`]},bridge_pull:{title:`Bridge Pull`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},bridge_sync:{title:`Bridge Sync Status`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},er_push:{title:`Enterprise Push`,annotations:{readOnlyHint:!1},category:[`system`]},er_pull:{title:`Enterprise Pull`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},er_sync_status:{title:`Enterprise Sync Status`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},er_update_policy:{title:`Enterprise Update Policy`,annotations:{readOnlyHint:!1},category:[`system`]},er_evolve_review:{title:`Enterprise Evolution Review`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},evolution_state:{title:`Evolution State`,annotations:{readOnlyHint:!1},category:[`system`]},policy_check:{title:`Policy Check`,annotations:{readOnlyHint:!0,idempotentHint:!0},category:[`system`]},flow:{title:`Flow`,annotations:{readOnlyHint:!1},category:[`flow`]}};function G(e){return W[e]??{title:e,annotations:{readOnlyHint:!1},category:[]}}const Yo=Symbol(`toolPipelineState`);function Xo(e){return e[Yo]}function Zo(e,t){e[Yo]=t}function Qo(e,t){return t?async(...n)=>{let r=await e(...n);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=Jo(t),i.structuredContent??={},r)}:e}function $o(e,t,n=``){let r=Xo(e);if(r){r.pipeline=t,r.prefix=n;return}Zo(e,{originalRegisterTool:e.registerTool.bind(e),pipeline:t,prefix:n}),e.registerTool=(n,r,i)=>{let a=Xo(e),o=a?.prefix?`${a.prefix}${n}`:n;if(!i)return a?.originalRegisterTool(o,r);let s=r?.outputSchema;if((a?.pipeline??t).getMiddlewareNames().length===0){let e=Qo(i,s);return a?.originalRegisterTool(o,r,e)}let c=G(n),l=Qo((a?.pipeline??t).wrap(n,i,r,c),s);return a?.originalRegisterTool(o,r,l)}}const es={analyze:1,audit:1,blast_radius:1,changelog:1,check:2,checkpoint:2,codemod:2,compact:1,config:0,data_transform:1,dead_symbols:1,delegate:3,describe_tool:1,diff_parse:1,digest:1,encode:1,env:0,eval:2,evidence_map:2,file_summary:1,find:1,flow:3,forge_classify:1,forge_ground:2,git_context:1,graph:1,guide:0,health:0,http:1,lane:2,list_tools:1,lookup:1,measure:1,onboard:3,parse_output:1,present:1,process:3,produce_knowledge:3,queue:3,regex_test:1,reindex:3,rename:2,replay:1,restore:2,schema_validate:1,scope_map:1,search:1,search_tools:1,signal:2,session_digest:2,stash:2,status:0,stratum_card:1,symbol:1,test_run:2,time:0,trace:1,watch:3,web_fetch:1,web_search:1,workset:2};function ts(e,t){return e.filter(e=>(es[e]??0)<=t)}const ns=new Set([`status`,`config`,`guide`,`health`]),rs={full:{description:`All tools enabled (default)`,includeCategories:[]},safe:{description:`Read-only tools — no file/state modifications`,includeCategories:[`search`,`analysis`,`compression`,`utilities`,`system`,`git`,`flow`],excludeTools:[`reindex`,`onboard`]},research:{description:`Search, analysis, knowledge, and web access`,includeCategories:[`search`,`analysis`,`knowledge`,`compression`,`web`,`system`,`flow`]},minimal:{description:`Essential tools only — search, status, basic operations`,includeCategories:[`search`,`system`],includeTools:[`compact`,`file_summary`,`check`,`test_run`]},discovery:{description:`Full toolset plus discovery-oriented meta-tools for guided tool exploration`,includeCategories:[],includeTools:[`list_tools`,`describe_tool`,`search_tools`]}};function is(e,t){let n=rs[e];if(n)return n;let r=t?.[e];if(r)return r;throw Error(`Unknown tool profile: ${e}`)}function as(e,t,n){return t.includes(`*`)?!0:(n[e]?.category??[]).some(e=>t.includes(e))}function os(e,t,n,r){if(t.includes(`*`)){for(let t of n)e.add(t);return}for(let i of n)as(i,t,r)&&e.add(i)}function ss(e,t,n){if(t.includes(`*`)){e.clear();return}for(let r of[...e])as(r,t,n)&&e.delete(r)}function cs(e,t,n){if(!e||e.length===0||e.includes(`*`))return new Set(t);let r=new Set;return os(r,e,t,n),r}function ls(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function us(e,t){for(let n of[...e])t[n]?.annotations?.readOnlyHint===!1&&e.delete(n)}function ds(e,t,n=0,r=[]){if(n>10)throw Error(`Tool profile inheritance exceeded max depth 10: ${[...r,e].join(` -> `)}`);if(r.includes(e))throw Error(`Tool profile inheritance cycle detected: ${[...r,e].join(` -> `)}`);let i=is(e,t);return ls(i.extends?ds(i.extends,t,n+1,[...r,e]):void 0,i.maxTier)}function fs(e,t,n,r){let i=(e,a,o)=>{if(a>10)throw Error(`Tool profile inheritance exceeded max depth 10: ${[...o,e].join(` -> `)}`);if(o.includes(e))throw Error(`Tool profile inheritance cycle detected: ${[...o,e].join(` -> `)}`);let s=is(e,r),c=[...o,e],l=s.extends?i(s.extends,a+1,c):cs(s.includeCategories,t,n);s.extends&&s.includeCategories?.length&&os(l,s.includeCategories,t,n),s.excludeCategories?.length&&ss(l,s.excludeCategories,n);for(let e of s.includeTools??[])l.add(e);for(let e of s.excludeTools??[])l.delete(e);return l},a=i(e,0,[]),o=ds(e,r);if(o!==void 0){let e=ts([...a],o);a.clear();for(let t of e)a.add(t)}for(let e of ns)a.add(e);return e===`safe`&&us(a,n),a}const ps=new Set([`search`,`analysis`,`knowledge`,`compression`,`forge`,`presentation`,`execution`,`manipulation`,`session`,`git`,`process`,`system`,`meta`,`utilities`,`web`,`queue`,`flow`]);function ms(e,t,n,r){let i=process.env.AIKIT_TOOLSET||e.toolProfile||`full`,a=fs(i,t,n,r);if(e.features&&e.features.length>0){let i=e.features.filter(e=>!ps.has(e));if(i.length>0)throw Error(`Unknown feature group(s): ${i.join(`, `)}. Valid categories: ${[...ps].join(`, `)}`);let o={description:`Synthetic profile from features config`,includeCategories:e.features},s=fs(`_features`,t,n,{...r,_features:o});for(let e of a)!s.has(e)&&!ns.has(e)&&a.delete(e)}if(e.readOnly)for(let e of[...a])n[e]?.annotations?.readOnlyHint===!1&&!ns.has(e)&&a.delete(e);for(let e of ns)a.add(e);return i===`safe`&&us(a,n),a}const hs=R.object({mode:R.enum([`wasm`,`regex`,`unknown`]),reason:R.string(),pathsChecked:R.array(R.object({path:R.string(),exists:R.boolean()})),os:R.string(),arch:R.string(),nodeVersion:R.string(),webTreeSitterImportable:R.boolean(),healAttempted:R.boolean(),healSuccess:R.boolean(),healError:R.string().nullable(),initError:R.string().nullable(),wasmDir:R.string().nullable(),grammarCount:R.number()}),gs=R.object({kind:R.enum([`onboard`,`reindex`,`handoff`,`proceed`]),reason:R.string()}),_s=R.object({title:R.string(),insight:R.string(),confidence:R.number()}),vs=R.object({lessons:R.array(_s),conventions:R.array(R.object({title:R.string(),preview:R.string()})),checkpoint:R.string().nullable()}),ys=R.object({totalRecords:R.number(),totalFiles:R.number(),lastIndexedAt:R.string().nullable(),onboarded:R.boolean(),onboardDir:R.string(),contentTypes:R.record(R.string(),R.number()),wasmAvailable:R.boolean(),wasmDiagnostics:hs,graphStats:R.object({nodes:R.number(),edges:R.number()}).nullable(),curatedCount:R.number(),serverVersion:R.string(),scaffoldVersion:R.string().nullable(),workspaceScaffoldVersion:R.string().nullable(),upgradeAvailable:R.boolean(),storeBackend:R.string().optional(),storeDiagnostics:R.object({adapterType:R.string(),vectorSearchEnabled:R.boolean(),ftsEnabled:R.boolean(),degradedMode:R.boolean(),dbPath:R.string(),dbSizeBytes:R.number().nullable(),embeddingDim:R.number(),vectorDtype:R.string()}).nullable().optional(),contextPressure:R.number().min(0).max(100).describe(`0–100 score indicating AI Kit saturation`),nextAction:gs,prelude:vs.nullable().optional()});R.object({entries:R.array(R.object({path:R.string(),title:R.string(),category:R.string(),tags:R.array(R.string()),version:R.number(),preview:R.string()})),totalCount:R.number()});const bs=R.object({ok:R.boolean(),checks:R.array(R.object({name:R.string(),ok:R.boolean(),message:R.string().optional()}))}),xs=R.object({summary:R.object({totalFiles:R.number(),totalLines:R.number(),totalCodeLines:R.number(),totalFunctions:R.number(),avgComplexity:R.number(),maxComplexity:R.object({value:R.number(),file:R.string()})}),files:R.array(R.object({path:R.string(),lines:R.number(),code:R.number(),complexity:R.number(),functions:R.number()}))}),Ss=R.object({platform:R.string(),arch:R.string(),nodeVersion:R.string(),cwd:R.string(),cpus:R.number(),memoryFreeGb:R.number(),memoryTotalGb:R.number()}),Cs=R.object({iso:R.string(),unix:R.number(),timezone:R.string(),formatted:R.string()}),ws=R.object({passed:R.boolean(),errorCount:R.number(),warningCount:R.number(),topErrors:R.array(R.string())}),Ts=R.object({passed:R.boolean(),tsc:ws,biome:ws}),Es=R.object({name:R.string(),definedIn:R.object({path:R.string(),line:R.number(),kind:R.string(),signature:R.string().optional()}).nullable(),importedBy:R.array(R.object({path:R.string(),line:R.number(),importStatement:R.string()})),referencedIn:R.array(R.object({path:R.string(),line:R.number(),context:R.string(),scope:R.string().optional()})),graphContext:R.object({definingModule:R.string().optional(),importedByModules:R.array(R.string()),siblingSymbols:R.array(R.string())}).nullable()}),Ds=R.object({sourcePath:R.string(),contentType:R.string(),score:R.number(),headingPath:R.string().optional(),startLine:R.number().optional(),endLine:R.number().optional(),origin:R.string().optional(),category:R.string().optional(),tags:R.array(R.string()).optional()}),Os=R.object({results:R.array(Ds),totalResults:R.number(),searchMode:R.string(),query:R.string()}),ks=R.object({path:R.string(),line:R.number().optional(),matchType:R.string(),preview:R.string()}),As=R.object({matches:R.array(ks),totalMatches:R.number(),pattern:R.string(),truncated:R.boolean()}),js=R.object({path:R.string(),relevance:R.number(),estimatedTokens:R.number(),focusLines:R.array(R.string()).optional()}),Ms=R.object({files:R.array(js),totalFiles:R.number(),totalEstimatedTokens:R.number(),task:R.string()}),Ns=R.object({path:R.string(),impact:R.string(),reason:R.string()}),Ps=R.object({changedFiles:R.array(R.string()),affectedFiles:R.array(Ns),totalAffected:R.number(),riskLevel:R.string()}),Fs=R.object({name:R.string(),passed:R.boolean(),message:R.string().optional(),severity:R.string().optional()}),Is=R.object({passed:R.boolean(),score:R.number(),checks:R.array(Fs),summary:R.string()}),Ls=R.object({id:R.string(),name:R.string(),type:R.string(),sourcePath:R.string().optional()}),Rs=R.object({fromId:R.string(),toId:R.string(),type:R.string()}),zs=R.object({nodes:R.array(Ls),edges:R.array(Rs),totalNodes:R.number(),totalEdges:R.number(),query:R.string()}),Bs=R.object({symbols:R.array(R.object({name:R.string(),path:R.string(),line:R.number().optional(),kind:R.string()})),totalDead:R.number()});R.object({files:R.number(),packages:R.number(),languages:R.record(R.string(),R.number()),tree:R.string()});const Vs=R.object({path:R.string(),language:R.string(),lines:R.number(),imports:R.number(),exports:R.number(),functions:R.number(),classes:R.number()}),Hs=R.object({gitRoot:R.string(),branch:R.string(),commitCount:R.number(),hasUncommitted:R.boolean(),recentCommits:R.array(R.object({hash:R.string(),message:R.string(),author:R.string(),date:R.string()}))}),Us=R.object({text:R.string().describe(`The compressed text output`),originalChars:R.number(),compressedChars:R.number(),ratio:R.number(),segmentsKept:R.number(),segmentsTotal:R.number()}),Ws=R.object({passed:R.boolean(),totalTests:R.number(),passedTests:R.number(),failedTests:R.number(),skippedTests:R.number(),duration:R.number().describe(`Duration in milliseconds`),failures:R.array(R.object({name:R.string(),message:R.string(),file:R.string().optional()}))}),Gs=F(`utils:enrich`);async function K(e,t){let n={curated:[],graph:[]},r=t.limit??3,[i,a]=await Promise.allSettled([Ks(e,t.query,r),qs(e,t.filePath)]);return i.status===`fulfilled`?n.curated=i.value:Gs.debug(`Curated enrichment failed`,{error:i.reason}),a.status===`fulfilled`?n.graph=a.value:Gs.debug(`Graph enrichment failed`,{error:a.reason}),n}async function Ks(e,t,n){if(!e.store||!t)return[];try{let r=await e.store.ftsSearch(t,{origin:`curated`,limit:n});if(r.length>0)return r.map(e=>Js(e.record));if(e.embedder){let r=await e.embedder.embedQuery(t);return(await e.store.search(r,{origin:`curated`,limit:n,minScore:.3})).map(e=>Js(e.record))}return[]}catch(e){return Gs.debug(`Curated enrichment failed`,{error:e}),[]}}async function qs(e,t){if(!e.graphStore||!t)return[];try{let n=await e.graphStore.findNodes({sourcePath:t,limit:1});if(n.length===0){let r=t.split(/[/\\]/).pop()?.replace(/\.\w+$/,``)||``;if(!r)return[];let i=await e.graphStore.findNodes({namePattern:r,type:`module`,limit:1});if(i.length===0)return[];n.push(i[0])}let r=n[0],i=await e.graphStore.getNeighbors(r.id,{direction:`both`,limit:10}),a=[];for(let e of i.edges){let t=e.fromId===r.id?e.toId:e.fromId,n=i.nodes.find(e=>e.id===t);if(!n)continue;let o=e.fromId===r.id?`->`:`<-`;a.push(`${o} ${e.type}: ${n.name} (${n.type})`)}return a}catch(e){return Gs.debug(`Graph enrichment failed`,{error:e}),[]}}function q(e){let t=[];if(e.curated.length>0){t.push(`**Curated Knowledge:**`);for(let n of e.curated)t.push(`- ${n}`)}if(e.graph.length>0){t.push(`**Graph Context:**`);for(let n of e.graph)t.push(`- ${n}`)}return t.length===0?``:`\n\n---\n### Enrichment\n${t.join(`
28
28
  `)}`}function Js(e){let t=Ys(e.metadata,`title`)||e.sourcePath||`Untitled`;return`[${Ys(e.metadata,`category`)}] ${t}: ${e.content.slice(0,200)}`}function Ys(e,t){let n=e?.[t];return typeof n==`string`?n:``}function J(e,t,n){return{content:[{type:`text`,text:`[ERROR:${e}] ${t}`}],isError:!0,...n==null?{}:{structuredContent:n}}}function Y(e,t){return async(n,r)=>{let i=Date.now(),a=await t(n,r),o=Date.now()-i;return a._meta={...a._meta??{},durationMs:o,toolName:e},a}}const Xs=F(`tools`),Zs=R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`);function Qs(e,t){return t?L(e,t):e}function $s(){let e=[];return ar.get()||e.push(`Tree-sitter unavailable — using regex fallback, symbol/pattern confidence reduced`),e.length===0?``:`\n\n> **⚠ Caveats:** ${e.join(`; `)}`}function ec(e){return(e??[]).map(e=>{if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`path`in e)return typeof e.path==`string`?e.path:void 0}).filter(e=>!!e)}function tc(e){let t=[],n=e.filter(e=>/\.(ts|tsx|js|jsx)$/.test(e)&&/(service|store|model|schema|migration)/i.test(e)),r=e.filter(e=>/\.(ts|tsx|js|jsx)$/.test(e)&&!n.includes(e)),i=e.filter(e=>!/\.(ts|tsx|js|jsx)$/.test(e));return(n.length>0||r.length>0||i.length>0)&&(t.push(`
29
29
 
30
30
  ### Risk Assessment`),n.length>0&&t.push(`- 🔴 **High risk** (${n.length}): ${n.slice(0,5).map(e=>`\`${e}\``).join(`, `)}`),r.length>0&&t.push(`- 🟡 **Medium risk** (${r.length}): source files`),i.length>0&&t.push(`- 🟢 **Low risk** (${i.length}): non-source files`)),t.join(`
@@ -2887,7 +2887,7 @@ window.addEventListener('message', function(e) {
2887
2887
  }
2888
2888
  });
2889
2889
  <\/script>
2890
- </body>`)}function Em(){let e=Z;e&&(Z=null,setTimeout(()=>{try{e.close()}catch{}},2e3))}function Dm(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Om(e,t){if(Nm(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=un({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2890
+ </body>`)}function Em(){let e=Z;e&&(Z=null,setTimeout(()=>{try{e.close()}catch{}},2e3))}function Dm(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Om(e,t){if(Pm(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`),e.data!=null&&t.inputSchema){let n=un({data:e.data,schema:t.inputSchema});if(!n.valid){let e=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2891
2891
  `);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=Tm(Ip(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=Cr({title:e.title,html:[_m(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2892
2892
  (function() {
2893
2893
  const iframe = document.querySelector('.present-viewer-iframe');
@@ -2904,11 +2904,11 @@ window.addEventListener('message', function(e) {
2904
2904
  })();
2905
2905
  <\/script>`,`</div>`].join(`
2906
2906
  `),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: calc(100vh - 12rem);`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
2907
- `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{Em(),i=await new Promise((e,t)=>{let i=Mr((e,t)=>{try{if(e.url===`/viewer`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(n);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(r)}catch{Dm(t)}});i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}Z=i,e(`http://127.0.0.1:${n.port}`)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}await bm(i);let a=Z;return a&&setTimeout(()=>{Z===a&&(a.close(),Z=null)},mm),{content:[{type:`text`,text:xm(e,i,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function km(e){Nm(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=jr(e,{transport:`browser`,registry:am,blockVendorScripts:hp()}),n=Op(t.surfaceId,t.actions),r=fm(t.vendorScripts,`browser`),i=pm(),a=Cr({title:e.title,html:[_m(e),t.html,vm(t.actions,n.nonce)].filter(Boolean).join(`
2908
- `),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``,c=!1;try{let e=Z;e&&(e.close(),Z=null),o=await new Promise((e,t)=>{let r=Mr((e,t)=>{try{if(c=!0,e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s).catch(()=>{Dm(t)});return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}let o=wm(e.url);if(o)try{let e=M(o,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(e);return}catch{}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)}catch{Dm(t)}});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}Z=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}let l=await bm(o);if(!Sm(t.actions)){let t=Z;return t&&(n.promise.finally(()=>{Z===t&&(t.close(),Z=null)}),setTimeout(()=>{Z===t&&(t.close(),Z=null)},mm)),{content:[{type:`text`,text:xm(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let u=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>{c||(Em(),e(n.settleError(`BROWSER_CONNECT_TIMEOUT`,l?`No browser client connected within ${hm}ms.`:`Fell back to system browser, but no browser client connected within ${hm}ms.`)))},hm)}),new Promise(e=>{setTimeout(()=>e(n.settleTimeout(mm)),mm)})]),d=Z;d&&setTimeout(()=>{Z===d&&(d.close(),Z=null)},mm);let f=u.kind===`result`?`Selected action: ${u.result.actionId}`:u.kind===`timeout`?`Timed out after ${u.waitedMs}ms.`:u.kind===`cancelled`?`Cancelled: ${u.reason}.`:u.kind===`error`?`Error: ${u.error.message}`:`Rendered.`;return{content:[{type:`text`,text:xm(e,o,f)}],structuredContent:u,isError:u.kind===`error`}}const Am=`ui://aikit/present.html`;let jm=``;function Mm(){return jm}function Nm(e){jm=e}function Pm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Fm=/\\u[0-9a-fA-F]{4}/,Im=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Lm=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,Rm=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function zm(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function Bm(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(Im.test(t[e])&&Lm.test(t[e+1]))return!0;return!1}function Vm(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function Hm(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Vm(n).length===t:!1}function Um(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2909
- `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Im.test(e)&&Lm.test(o)){let r=Vm(e),o=[];i();let s=a+2;for(;s<t.length&&Hm(t[s],r.length);)o.push(Vm(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Wm(e){let t=zm(e);return!t||!Bm(t)?[e]:Um(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function Gm(e){if(typeof e==`string`)return Rm.test(e);if(Array.isArray(e))return e.some(e=>Gm(e));if(!Pm(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Gm(n):!1)}function Km(e,t){return{preferBrowser:[t,e._meta,Pm(e.metadata)?e.metadata.source:void 0].some(e=>Gm(e))}}function qm(e){if(!e.template)return!0;let t=Np(e.template);return t?t.supportedTransports.includes(`browser`):om(e)?.supportedTransports.includes(`browser`)??!1}function Jm(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${X(e.description)}</p>`:``;return[`<section class="present-surface-header">`,` <h1>${X(e.title)}</h1>`,t,`</section>`,`<style>`,` .present-surface-header { display: grid; gap: 0.75rem; margin-bottom: 1.5rem; }`,` .present-surface-header h1 { margin: 0; font-size: 1.875rem; }`,` .present-surface-description { margin: 0; color: var(--dt-text-secondary, #475467); }`,`</style>`].filter(Boolean).join(`
2910
- `)}function Ym(e,t){let n=[e.title];return e.description&&n.push(e.description),Or(t)?n.push(``,`Selected action: ${t.result.actionId}`):Dr(t)?n.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?n.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`&&n.push(``,`Cancelled: ${t.reason}.`),n.join(`
2911
- `)}const Xm={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Zm(e){if((e.actions?.length??0)>0||!e.template)return e;let t=om(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[Xm]}:e}function Qm(e){return e.replace(`</head>`,`<style>
2907
+ `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{Em(),i=await new Promise((e,t)=>{let i=Mr((e,t)=>{try{if(e.url===`/viewer`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(n);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(r)}catch{Dm(t)}});i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}Z=i,e(`http://127.0.0.1:${n.port}`)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:{kind:`error`,error:{code:`BROWSER_START_FAILED`,message:t instanceof Error?t.message:`Unable to start browser transport`}},isError:!0}}await bm(i);let a=Z;return a&&setTimeout(()=>{Z===a&&(a.close(),Z=null)},mm),{content:[{type:`text`,text:xm(e,i,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function km(e){Pm(`<html><body style="font-family:system-ui;padding:2rem;color:#888;text-align:center"><p>Content opened in browser window.</p></body></html>`);let t=jr(e,{transport:`browser`,registry:am,blockVendorScripts:hp()}),n=Op(t.surfaceId,t.actions),r=fm(t.vendorScripts,`browser`),i=pm(),a=Cr({title:e.title,html:[_m(e),t.html,vm(t.actions,n.nonce)].filter(Boolean).join(`
2908
+ `),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:t.exportPolicy,headScripts:r}),o=``,s=``,c=!1;try{let e=Z;e&&(e.close(),Z=null),o=await new Promise((e,t)=>{let r=Mr((e,t)=>{try{if(c=!0,e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":s||`*`,"Access-Control-Allow-Methods":`POST`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(e.method===`POST`&&e.url===`/callback`){n.handle(e,t,s).catch(()=>{Dm(t)});return}let r=i.find(t=>e.url===t.route);if(r){let e=r.getSource();if(e){t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`,"Cache-Control":`public, max-age=86400`}),t.end(e);return}t.writeHead(302,{Location:r.cdn}),t.end();return}let o=wm(e.url);if(o)try{let e=M(o,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(e);return}catch{}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(a)}catch{Dm(t)}});r.listen(0,`127.0.0.1`,()=>{let n=r.address();if(typeof n!=`object`||!n){t(Error(`Failed to resolve local browser address`));return}Z=r,s=`http://127.0.0.1:${n.port}`,e(s)})})}catch(t){return{content:[{type:`text`,text:`${e.title}\n\nUnable to start local browser transport.`}],structuredContent:n.settleError(`BROWSER_START_FAILED`,t instanceof Error?t.message:`Unable to start browser transport`),isError:!0}}let l=await bm(o);if(!Sm(t.actions)){let t=Z;return t&&(n.promise.finally(()=>{Z===t&&(t.close(),Z=null)}),setTimeout(()=>{Z===t&&(t.close(),Z=null)},mm)),{content:[{type:`text`,text:xm(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let u=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>{c||(Em(),e(n.settleError(`BROWSER_CONNECT_TIMEOUT`,l?`No browser client connected within ${hm}ms.`:`Fell back to system browser, but no browser client connected within ${hm}ms.`)))},hm)}),new Promise(e=>{setTimeout(()=>e(n.settleTimeout(mm)),mm)})]),d=Z;d&&setTimeout(()=>{Z===d&&(d.close(),Z=null)},mm);let f=u.kind===`result`?`Selected action: ${u.result.actionId}`:u.kind===`timeout`?`Timed out after ${u.waitedMs}ms.`:u.kind===`cancelled`?`Cancelled: ${u.reason}.`:u.kind===`error`?`Error: ${u.error.message}`:`Rendered.`;return{content:[{type:`text`,text:xm(e,o,f)}],structuredContent:u,isError:u.kind===`error`}}const Am=`ui://aikit/present.html`,jm=`Install AI Kit with <code>${X(`npx -y @vpxa/aikit init --user`)}</code>.`;let Mm=``;function Nm(){return Mm}function Pm(e){Mm=e}function Fm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Im=/\\u[0-9a-fA-F]{4}/,Lm=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Rm=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,zm=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function Bm(e){let t=[e.value,e.markdown,e.text,e.content];for(let e of t)if(typeof e==`string`&&e.trim().length>0)return e}function Vm(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(Lm.test(t[e])&&Rm.test(t[e+1]))return!0;return!1}function Hm(e){let t=e.trim().split(`|`),n=+(t[0]?.trim()===``),r=t.at(-1)?.trim()===``?t.length-1:t.length;return t.slice(n,r).map(e=>e.trim())}function Um(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Hm(n).length===t:!1}function Wm(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2909
+ `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Lm.test(e)&&Rm.test(o)){let r=Hm(e),o=[];i();let s=a+2;for(;s<t.length&&Um(t[s],r.length);)o.push(Hm(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Gm(e){let t=Bm(e);return!t||!Vm(t)?[e]:Wm(t).flatMap(e=>{if(e.type===`text`){let t=e.content.trim();return t.length>0?[{type:`markdown`,value:t}]:[]}return[{type:`table`,value:{headers:e.headers,rows:e.rows}}]})}function Km(e){if(typeof e==`string`)return zm.test(e);if(Array.isArray(e))return e.some(e=>Km(e));if(!Fm(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Km(n):!1)}function qm(e,t){return{preferBrowser:[t,e._meta,Fm(e.metadata)?e.metadata.source:void 0].some(e=>Km(e))}}function Jm(e){if(!e.template)return!0;let t=Np(e.template);return t?t.supportedTransports.includes(`browser`):om(e)?.supportedTransports.includes(`browser`)??!1}function Ym(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${X(e.description)}</p>`:``;return[`<section class="present-surface-header">`,` <h1>${X(e.title)}</h1>`,t,`</section>`,`<style>`,` .present-surface-header { display: grid; gap: 0.75rem; margin-bottom: 1.5rem; }`,` .present-surface-header h1 { margin: 0; font-size: 1.875rem; }`,` .present-surface-description { margin: 0; color: var(--dt-text-secondary, #475467); }`,`</style>`].filter(Boolean).join(`
2910
+ `)}function Xm(e,t){let n=[e.title];return e.description&&n.push(e.description),Or(t)?n.push(``,`Selected action: ${t.result.actionId}`):Dr(t)?n.push(``,`Error: ${t.error.message}`):t.kind===`timeout`?n.push(``,`Timed out after ${t.waitedMs}ms.`):t.kind===`cancelled`&&n.push(``,`Cancelled: ${t.reason}.`),n.join(`
2911
+ `)}const Zm={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Qm(e){if((e.actions?.length??0)>0||!e.template)return e;let t=om(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[Zm]}:e}function $m(e){return e.replace(`</head>`,`<style>
2912
2912
  .toolbar, .badge, body > header, body > footer { display: none !important; }
2913
2913
  body { padding-top: 0 !important; margin-top: 0 !important; }
2914
2914
  </style>
@@ -2930,7 +2930,7 @@ window.addEventListener('message', function(e) {
2930
2930
  }
2931
2931
  });
2932
2932
  <\/script>
2933
- </body>`)}function $m(e){let t=`<script>
2933
+ </body>`)}function eh(e){let t=`<script>
2934
2934
  (function(){
2935
2935
  var last=0;
2936
2936
  function notify(){
@@ -2941,9 +2941,9 @@ window.addEventListener('message', function(e) {
2941
2941
  if(typeof ResizeObserver!=="undefined"){new ResizeObserver(notify).observe(document.documentElement)}
2942
2942
  else{setInterval(notify,500)}
2943
2943
  })();
2944
- <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function eh(e,t){return[`<!DOCTYPE html>`,`<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`,`<title>Error — ${X(e)}</title>`,`<style>`,` * { box-sizing: border-box; margin: 0; padding: 0; }`,` body { font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; background: #fafafa; color: #333; }`,` .error-card { max-width: 560px; width: 100%; padding: 2.5rem; border-radius: 1rem; background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }`,` .error-badge { display: inline-block; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.375rem; padding: 0.25rem 0.625rem; margin-bottom: 1rem; }`,` .error-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.75rem; color: #111; }`,` .error-message { font-size: 0.875rem; line-height: 1.6; color: #6b7280; white-space: pre-wrap; word-break: break-word; }`,`</style></head><body>`,`<div class="error-card">`,` <span class="error-badge">Render Error</span>`,` <h1 class="error-title">${X(e)}</h1>`,` <p class="error-message">${X(t)}</p>`,`</div>`,`</body></html>`].join(`
2945
- `)}function th(e,t,n,r){return Nm(eh(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function nh(e,t){if(!Pm(e)||!(`schemaVersion`in e))return{ok:!1,response:th(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:th(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Fm.test(e.title))return{ok:!1,response:th(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!Pm(e)||e.type!==`markdown`)return[e];let t=zm(e);return!t||!Bm(t)?[e]:Wm(e)})}:e;return{ok:!0,surface:n,options:Km(n,t)}}async function rh(e,t={}){let n=Zm(e);if(e.template){let r=Np(e.template);if(r)return await ih(n,r,t)}return sm(n)||t.preferBrowser&&qm(n)?await km(n):ah(n)}async function ih(e,t,n={}){if(e.data!=null&&t.inputSchema){let n=un({data:e.data,schema:t.inputSchema});if(!n.valid){let r=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2946
- `);return th(`VIEWER_DATA_INVALID`,`Template "${t.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`,void 0,e.title)}}let r=t.supportedTransports.includes(`browser`),i=t.supportedTransports.includes(`mcp-app`);if(n.preferBrowser&&r||r&&!i)return await Om(e,t);if(!i)return th(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${t.id}" does not support an available transport`,void 0,e.title);try{let n=Qm(Ip(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`);return Nm($m(Cr({title:e.title,html:[Jm(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2944
+ <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function th(e,t){return[`<!DOCTYPE html>`,`<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`,`<title>Error — ${X(e)}</title>`,`<style>`,` * { box-sizing: border-box; margin: 0; padding: 0; }`,` body { font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; background: #fafafa; color: #333; }`,` .error-card { max-width: 560px; width: 100%; padding: 2.5rem; border-radius: 1rem; background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }`,` .error-badge { display: inline-block; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.375rem; padding: 0.25rem 0.625rem; margin-bottom: 1rem; }`,` .error-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.75rem; color: #111; }`,` .error-message { font-size: 0.875rem; line-height: 1.6; color: #6b7280; white-space: pre-wrap; word-break: break-word; }`,`</style></head><body>`,`<div class="error-card">`,` <span class="error-badge">Render Error</span>`,` <h1 class="error-title">${X(e)}</h1>`,` <p class="error-message">${X(t)}</p>`,`</div>`,`</body></html>`].join(`
2945
+ `)}function nh(e,t,n,r){return Pm(th(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function rh(e,t){if(!Fm(e)||!(`schemaVersion`in e))return{ok:!1,response:nh(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:nh(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Im.test(e.title))return{ok:!1,response:nh(`TITLE_UNICODE_ESCAPE_NOT_ALLOWED`,`Use actual Unicode characters in title, not escape sequences.`)};let n=Array.isArray(e.blocks)?{...e,blocks:e.blocks.flatMap(e=>{if(!Fm(e)||e.type!==`markdown`)return[e];let t=Bm(e);return!t||!Vm(t)?[e]:Gm(e)})}:e;return{ok:!0,surface:n,options:qm(n,t)}}async function ih(e,t={}){let n=Qm(e);if(e.template){let r=Np(e.template);if(r)return await ah(n,r,t)}return sm(n)||t.preferBrowser&&Jm(n)?await km(n):oh(n)}async function ah(e,t,n={}){if(e.data!=null&&t.inputSchema){let n=un({data:e.data,schema:t.inputSchema});if(!n.valid){let r=n.errors.map(e=>` ${e.path}: ${e.message}${e.expected?` (expected: ${e.expected}, got: ${e.received})`:``}`).join(`
2946
+ `);return nh(`VIEWER_DATA_INVALID`,`Template "${t.id}" data validation failed:\n${r}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`,void 0,e.title)}}let r=t.supportedTransports.includes(`browser`),i=t.supportedTransports.includes(`mcp-app`);if(n.preferBrowser&&r||r&&!i)return await Om(e,t);if(!i)return nh(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${t.id}" does not support an available transport`,void 0,e.title);try{let n=$m(Ip(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`);return Pm(eh(Cr({title:e.title,html:[Ym(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2947
2947
  (function() {
2948
2948
  const iframe = document.querySelector('.present-viewer-iframe');
2949
2949
  if (!iframe) return;
@@ -2966,12 +2966,12 @@ window.addEventListener('message', function(e) {
2966
2966
  });
2967
2967
  <\/script>`,`</div>`].join(`
2968
2968
  `),css:[[`.present-viewer-container {`,` flex: 1;`,` min-height: 640px;`,` position: relative;`,` border-radius: 0.75rem;`,` overflow: hidden;`,` border: none;`,`}`,`.present-viewer-iframe {`,` border: none;`,` width: 100%;`,` height: 100%;`,` position: absolute;`,` inset: 0;`,` border-radius: inherit;`,`}`].join(`
2969
- `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`}))),{content:[{type:`text`,text:Ym(e,{kind:`rendered`,reason:`no-response-required`})}],ui:{type:`resource`,uri:Am}}}catch(t){return th(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}function ah(e){try{let t=jr(e,{transport:`mcp-app`,registry:am,blockVendorScripts:hp()}),n=fm(t.vendorScripts,`mcp-app`);return jm=$m(Cr({title:e.title,html:[Jm(e),t.html].filter(Boolean).join(`
2970
- `),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,headScripts:n})),{content:[{type:`text`,text:Ym(e,{kind:`rendered`,reason:`no-response-required`})}],ui:{type:`resource`,uri:Am}}}catch(t){return th(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const oh=R.object({label:R.string(),value:R.string(),description:R.string().optional()}),sh=R.object({id:R.string().describe(`Unique action identifier`),type:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:R.string().describe(`Visible action label`),variant:R.enum([`primary`,`danger`,`default`]).optional(),options:R.array(oh).optional(),schema:R.record(R.string(),R.unknown()).optional()}),ch=R.object({type:R.string(),title:R.string().optional(),value:R.unknown().optional(),language:R.string().optional()}).catchall(R.unknown()),lh={schemaVersion:R.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:R.string().describe(`Surface title shown to the user.`),description:R.string().optional().describe(`Optional supporting copy for the surface.`),template:R.string().optional().describe(`Optional template id such as report@1.`),layout:R.object({maxWidth:R.string().optional(),padding:R.string().optional(),columns:R.number().optional()}).optional(),blocks:R.array(ch).optional().describe(`Typed block content for the surface.`),data:R.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:R.array(sh).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:R.object({timeout:R.number().optional(),required:R.boolean().optional()}).optional(),metadata:R.object({surfaceId:R.string().optional(),createdAt:R.string().optional(),source:R.string().optional()}).optional(),colorScheme:R.enum([`light`,`dark`,`auto`]).optional(),lang:R.string().optional(),dir:R.enum([`ltr`,`rtl`,`auto`]).optional()};R.object({surfaceId:R.string(),actionId:R.string(),actionType:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:R.unknown().optional(),formData:R.record(R.string(),R.unknown()).optional(),selection:R.union([R.string(),R.array(R.string())]).optional(),label:R.string().optional(),timestamp:R.string(),sourceTransport:R.enum([`mcp-app`,`browser`,`export`])});function uh(e,t){let n=G(`present`),r=[`Render a ChannelSurface for the user.`,`Quick ref:`,`- Full schema: aikit://schemas/channel-surface`,`- Required: schemaVersion: 1, title`,`- Content: blocks[] for direct rendering, or template + data for registry-backed rendering`,`- Actions: actions[] of SurfaceAction; interactive surfaces use browser transport and return ChannelOutcome`,`- Optional fields: description, layout, response, metadata, colorScheme, lang, dir`,`- Transports: mcp-app, browser, export`,`- Use schema resource for block enums and action details.`].join(`
2971
- `);hr(e,`present`,{title:n.title,description:r,inputSchema:lh,annotations:n.annotations,_meta:{ui:{resourceUri:Am}}},Y(`present`,async(e,t)=>{let n=nh(e,t);return n.ok?await rh(n.surface,n.options):n.response}));try{mr(e,`Present View`,Am,{description:`AI Kit present tool viewer`},async()=>({contents:[{uri:Am,mimeType:pr,text:Mm()||`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=Fp().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}}const dh=F(`tools`);function fh(e,t){let n=new er({structure:new nr,dependencies:new Zn,symbols:new rr,patterns:new tr,entryPoints:new $n,diagrams:new Qn}),r=G(`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:R.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:R.array(R.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},Y(`produce_knowledge`,async({scope:e,aspects:r},i)=>{let a;try{a=Oc(i).createTask(`Produce Knowledge`,3),a.progress(0,`Running analyzers`);let o=e??`.`;dh.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=t?.onboardDir??``;if(!e)throw dh.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);j(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(s))r&&typeof r==`string`&&he(N(e,`${t}.md`),n+r,`utf-8`);dh.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){dh.warn(`Failed to persist knowledge to .ai/context/`,{error:I(e)})}a.progress(1,`Synthesizing results`);let c=n.buildSynthesisInstructions(s,r);return a.complete(`Knowledge production complete`),{content:[{type:`text`,text:c+`
2969
+ `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),footerContentHtml:jm,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:`local-interactive`}))),{content:[{type:`text`,text:Xm(e,{kind:`rendered`,reason:`no-response-required`})}],ui:{type:`resource`,uri:Am}}}catch(t){return nh(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}function oh(e){try{let t=jr(e,{transport:`mcp-app`,registry:am,blockVendorScripts:hp()}),n=fm(t.vendorScripts,`mcp-app`);return Mm=eh(Cr({title:e.title,html:[Ym(e),t.html].filter(Boolean).join(`
2970
+ `),css:t.css,islands:t.islands,payload:t.payload,nonce:t.nonce,colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`mcp-app`,exportPolicy:t.exportPolicy,footerContentHtml:jm,headScripts:n})),{content:[{type:`text`,text:Xm(e,{kind:`rendered`,reason:`no-response-required`})}],ui:{type:`resource`,uri:Am}}}catch(t){return nh(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const sh=R.object({label:R.string(),value:R.string(),description:R.string().optional()}),ch=R.object({id:R.string().describe(`Unique action identifier`),type:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:R.string().describe(`Visible action label`),variant:R.enum([`primary`,`danger`,`default`]).optional(),options:R.array(sh).optional(),schema:R.record(R.string(),R.unknown()).optional()}),lh=R.object({type:R.string(),title:R.string().optional(),value:R.unknown().optional(),language:R.string().optional()}).catchall(R.unknown()),uh={schemaVersion:R.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:R.string().describe(`Surface title shown to the user.`),description:R.string().optional().describe(`Optional supporting copy for the surface.`),template:R.string().optional().describe(`Optional template id such as report@1.`),layout:R.object({maxWidth:R.string().optional(),padding:R.string().optional(),columns:R.number().optional()}).optional(),blocks:R.array(lh).optional().describe(`Typed block content for the surface.`),data:R.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:R.array(ch).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:R.object({timeout:R.number().optional(),required:R.boolean().optional()}).optional(),metadata:R.object({surfaceId:R.string().optional(),createdAt:R.string().optional(),source:R.string().optional()}).optional(),colorScheme:R.enum([`light`,`dark`,`auto`]).optional(),lang:R.string().optional(),dir:R.enum([`ltr`,`rtl`,`auto`]).optional()};R.object({surfaceId:R.string(),actionId:R.string(),actionType:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:R.unknown().optional(),formData:R.record(R.string(),R.unknown()).optional(),selection:R.union([R.string(),R.array(R.string())]).optional(),label:R.string().optional(),timestamp:R.string(),sourceTransport:R.enum([`mcp-app`,`browser`,`export`])});function dh(e,t){let n=G(`present`),r=[`Render a ChannelSurface for the user.`,`Quick ref:`,`- Full schema: aikit://schemas/channel-surface`,`- Required: schemaVersion: 1, title`,`- Content: blocks[] for direct rendering, or template + data for registry-backed rendering`,`- Actions: actions[] of SurfaceAction; interactive surfaces use browser transport and return ChannelOutcome`,`- Optional fields: description, layout, response, metadata, colorScheme, lang, dir`,`- Transports: mcp-app, browser, export`,`- Use schema resource for block enums and action details.`].join(`
2971
+ `);hr(e,`present`,{title:n.title,description:r,inputSchema:uh,annotations:n.annotations,_meta:{ui:{resourceUri:Am}}},Y(`present`,async(e,t)=>{let n=rh(e,t);return n.ok?await ih(n.surface,n.options):n.response}));try{mr(e,`Present View`,Am,{description:`AI Kit present tool viewer`},async()=>({contents:[{uri:Am,mimeType:pr,text:Nm()||`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=Fp().map(e=>({id:e.id,label:e.label,description:e.description,transports:e.supportedTransports,inputSchema:e.inputSchema}));return{contents:[{uri:`aikit://present/templates`,mimeType:`application/json`,text:JSON.stringify(e,null,2)}]}})}catch{}}const fh=F(`tools`);function ph(e,t){let n=new er({structure:new nr,dependencies:new Zn,symbols:new rr,patterns:new tr,entryPoints:new $n,diagrams:new Qn}),r=G(`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:R.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:R.array(R.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},Y(`produce_knowledge`,async({scope:e,aspects:r},i)=>{let a;try{a=Oc(i).createTask(`Produce Knowledge`,3),a.progress(0,`Running analyzers`);let o=e??`.`;fh.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=t?.onboardDir??``;if(!e)throw fh.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);j(e,{recursive:!0});let n=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,r]of Object.entries(s))r&&typeof r==`string`&&he(N(e,`${t}.md`),n+r,`utf-8`);fh.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){fh.warn(`Failed to persist knowledge to .ai/context/`,{error:I(e)})}a.progress(1,`Synthesizing results`);let c=n.buildSynthesisInstructions(s,r);return a.complete(`Knowledge production complete`),{content:[{type:`text`,text:c+`
2972
2972
 
2973
2973
  ---
2974
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),dh.error(`Knowledge production failed`,I(e)),J(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const ph=F(`tools`);function mh(e,t,n,r,i,a,o){let s=G(`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:R.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:R.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},Y(`reindex`,async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
2974
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),fh.error(`Knowledge production failed`,I(e)),J(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const mh=F(`tools`);function hh(e,t,n,r,i,a,o){let s=G(`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:R.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:R.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},Y(`reindex`,async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
2975
2975
 
2976
2976
  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
2977
2977
 
@@ -2979,45 +2979,45 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
2979
2979
 
2980
2980
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
2981
2981
 
2982
- Use \`status({})\` to check smart indexing queue status.`}]};let l=Oc(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),ph.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&ph.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(ph.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(),ph.info(`FTS index rebuilt after reindex`)}catch(e){ph.warn(`FTS index rebuild failed`,I(e))}try{let e=await r.reindexAll();ph.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){ph.warn(`Curated re-index failed`,I(e))}if(a)try{await a.notifyAfterReindex()}catch(e){ph.warn(`Post-reindex resource notification failed`,I(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),ph.error(`Background reindex failed`,I(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return ph.error(`Reindex failed`,I(e)),J(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const hh=F(`tools`);function gh(e){let t=G(`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:R.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:R.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:R.string().optional().describe(`Filter by tool name (list only)`),source:R.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:R.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},Y(`replay`,async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return an(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=on({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 sn().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
2982
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=Oc(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),mh.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&mh.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(mh.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(),mh.info(`FTS index rebuilt after reindex`)}catch(e){mh.warn(`FTS index rebuild failed`,I(e))}try{let e=await r.reindexAll();mh.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){mh.warn(`Curated re-index failed`,I(e))}if(a)try{await a.notifyAfterReindex()}catch(e){mh.warn(`Post-reindex resource notification failed`,I(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),mh.error(`Background reindex failed`,I(e))}),{content:[{type:`text`,text:`## Reindex Started (Background)\n\n- **Mode**: ${e?`Full`:`Incremental`}\n- Search and other tools continue to work with existing data during reindex.\n- Completion will be logged. Use \`status({})\` to check index stats afterward.\n\n---\n_Next: Continue working — the reindex runs in the background._`}]}}catch(e){return mh.error(`Reindex failed`,I(e)),J(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const gh=F(`tools`);function _h(e){let t=G(`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:R.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:R.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:R.string().optional().describe(`Filter by tool name (list only)`),source:R.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:R.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},Y(`replay`,async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return an(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=on({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 sn().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
2983
2983
 
2984
- `)}`}]}}catch(e){return hh.error(`Replay failed`,I(e)),J(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const _h=F(`tools`);function vh(e){let t=G(`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:R.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:R.string().optional().describe(`Restore point ID (required for action=restore)`),limit:R.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=Nt().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(`
2984
+ `)}`}]}}catch(e){return gh.error(`Replay failed`,I(e)),J(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const vh=F(`tools`);function yh(e){let t=G(`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:R.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:R.string().optional().describe(`Restore point ID (required for action=restore)`),limit:R.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=Nt().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(`
2985
2985
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await cn(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
2986
- `)}`}]}}catch(e){return _h.error(`Restore failed`,I(e)),J(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const yh=/<\/?curated-context>/gi;function bh(e){return e.replace(yh,``)}function xh(e){return`<curated-context>\n${bh(e)}\n</curated-context>`}const Sh=F(`tools`);function Ch(e,t,i,c){r(e,t,i);let l=e.memoryMetaGet(t);if(!l)return;let u=a(l,{...n,...c});u&&(s(e,t,u),o(e,t,i))}function wh(e,t){let n=[],r=ge(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?_n(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function Th(e,t,n){return n?e:t===`curated`?e*1.2:e}function Eh(e,t){return t?e:e.map(e=>({record:e.record,score:Th(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}async function Dh(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:fr(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 Sh.warn(`ER fallback failed`,I(e)),{results:n,triggered:!0,cacheHit:a}}}function Oh(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function kh(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 Ah(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function jh(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&&!Mh.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 Mh=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 Nh(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 Fn(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 Ph(e,t,n,r,i,a,o,s,c,l){let u=G(`search`);e.registerTool(`search`,{title:u.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:Os,inputSchema:{query:R.string().max(5e3).describe(`Natural language search query`),limit:R.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:R.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:R.enum(Ce).optional().describe(`Filter by content type`),source_type:R.enum(Oe).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:R.enum(De).optional().describe(`Filter by knowledge origin`),category:R.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:R.array(R.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:R.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:R.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:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:R.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:R.array(R.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:u.annotations},async({query:e,limit:u,search_mode:d,content_type:f,source_type:p,origin:m,category:h,tags:g,min_score:_,graph_hops:v,max_tokens:y,dedup:b,workspaces:x})=>{let S=Date.now();try{let C={limit:u,minScore:_,contentType:f,sourceType:p,origin:m,category:h,tags:g},w,T=!1,E=!1,D=``,O=d!==`keyword`,ee=wh(e,s);if(d===`keyword`)w=await n.ftsSearch(e,C),w=w.slice(0,u);else if(d===`semantic`)try{let r=await t.embedQuery(ee);w=await n.search(r,C);let a=await Dh(i,w[0]?.score??0,w,e,u);w=a.results,T=a.triggered,E=a.cacheHit}catch(t){O=!1,Sh.warn(`Embedder unavailable in semantic mode, falling back to FTS`,I(t)),w=await n.ftsSearch(e,{...C,limit:u}),D=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
2986
+ `)}`}]}}catch(e){return vh.error(`Restore failed`,I(e)),J(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const bh=/<\/?curated-context>/gi;function xh(e){return e.replace(bh,``)}function Sh(e){return`<curated-context>\n${xh(e)}\n</curated-context>`}const Ch=F(`tools`);function wh(e,t,i,c){r(e,t,i);let l=e.memoryMetaGet(t);if(!l)return;let u=a(l,{...n,...c});u&&(s(e,t,u),o(e,t,i))}function Th(e,t){let n=[],r=ge(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?_n(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function Eh(e,t,n){return n?e:t===`curated`?e*1.2:e}function Dh(e,t){return t?e:e.map(e=>({record:e.record,score:Eh(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}async function Oh(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:fr(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 Ch.warn(`ER fallback failed`,I(e)),{results:n,triggered:!0,cacheHit:a}}}function kh(e,t,n=60){let r=new Map,i=e[0]?.score||1,a=t[0]?.score||1;for(let t=0;t<e.length;t++){let a=e[t],o=a.score/i;r.set(a.record.id,{record:a.record,score:1/(n+t+1)*o})}for(let e=0;e<t.length;e++){let i=t[e],o=i.score/a,s=r.get(i.record.id);s?s.score+=1/(n+e+1)*o:r.set(i.record.id,{record:i.record,score:1/(n+e+1)*o})}return[...r.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function Ah(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 jh(e){if(e.length<=1)return e;let t=new Set;return e.filter(e=>{let n=e.record.contentHash;return n?t.has(n)?!1:(t.add(n),!0):!0})}function Mh(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&&!Nh.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 Nh=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 Ph(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 Fn(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 Fh(e,t,n,r,i,a,o,s,c,l){let u=G(`search`);e.registerTool(`search`,{title:u.title,description:`Search AI Kit for code, docs, and prior decisions. Default choice for discovery. Modes: hybrid (default), semantic, keyword. For multi-strategy precision queries use find; for a known file path use lookup.`,outputSchema:Os,inputSchema:{query:R.string().max(5e3).describe(`Natural language search query`),limit:R.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:R.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:R.enum(Ce).optional().describe(`Filter by content type`),source_type:R.enum(Oe).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:R.enum(De).optional().describe(`Filter by knowledge origin`),category:R.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:R.array(R.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:R.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:R.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:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:R.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:R.array(R.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:u.annotations},async({query:e,limit:u,search_mode:d,content_type:f,source_type:p,origin:m,category:h,tags:g,min_score:_,graph_hops:v,max_tokens:y,dedup:b,workspaces:x})=>{let S=Date.now();try{let C={limit:u,minScore:_,contentType:f,sourceType:p,origin:m,category:h,tags:g},w,T=!1,E=!1,D=``,O=d!==`keyword`,ee=Th(e,s);if(d===`keyword`)w=await n.ftsSearch(e,C),w=w.slice(0,u);else if(d===`semantic`)try{let r=await t.embedQuery(ee);w=await n.search(r,C);let a=await Oh(i,w[0]?.score??0,w,e,u);w=a.results,T=a.triggered,E=a.cacheHit}catch(t){O=!1,Ch.warn(`Embedder unavailable in semantic mode, falling back to FTS`,I(t)),w=await n.ftsSearch(e,{...C,limit:u}),D=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
2987
2987
 
2988
- `}else{let r=[],a=[];try{let i=await t.embedQuery(ee),o=n.coarseSearch,s=o?o.bind(n):n.search.bind(n);[r,a]=await Promise.all([s(i,{...C,limit:u*2}),n.ftsSearch(e,{...C,limit:u*2}).catch(()=>[])])}catch(t){O=!1,Sh.warn(`Embedder unavailable, falling back to FTS-only`,I(t)),a=await n.ftsSearch(e,{...C,limit:u*2}),D=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
2988
+ `}else{let r=[],a=[];try{let i=await t.embedQuery(ee),o=n.coarseSearch,s=o?o.bind(n):n.search.bind(n);[r,a]=await Promise.all([s(i,{...C,limit:u*2}),n.ftsSearch(e,{...C,limit:u*2}).catch(()=>[])])}catch(t){O=!1,Ch.warn(`Embedder unavailable, falling back to FTS-only`,I(t)),a=await n.ftsSearch(e,{...C,limit:u*2}),D=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
2989
2989
 
2990
- `}if(O?r.length===0&&a.length>0?(w=a.slice(0,u),D=` (FTS-only: vector index rebuilding)`):w=a.length===0&&r.length>0?r.slice(0,u):Oh(r,a).slice(0,u):w=a.slice(0,u),O){let t=await Dh(i,r[0]?.score??0,w,e,u);w=t.results,T=t.triggered,E=t.cacheHit}}w=Eh(w,m).slice(0,u),a&&a.recordSearch(e,T,E),w.length>1&&(w=kh(w,e)),w=Ah(w);let te=``;if(x&&x.length>0){let n=cl(x,je(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await ll(n);try{let i;i=d===`keyword`||!O?await dl(r,e,{...C,limit:u}):await ul(r,await t.embedQuery(e),{...C,limit:u});for(let e of i)w.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});w=w.sort((e,t)=>t.score-e.score).slice(0,u),te=` + ${n.length} workspace(s)`}finally{await i()}}}if(b===`file`&&w.length>1){let e=new Map;for(let t of w){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}]})}w=[...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(w.length>1){let e=w[0].score,t=Math.max(e*.4,.1);w=w.filter(e=>e.score>=t)}if(w.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(`
2991
- `)[0].slice(0,500);if(r&&r!==e){let i=d===`keyword`||!O?await n.ftsSearch(r,C):await n.search(await t.embedQuery(r),C);i.length>0&&(w=i,D=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,Sh.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){Sh.debug(`Smart search fallback failed`,{error:String(e)})}if(w.length===0){let t=tt({text:`No results found for the given query.`,query:e,searchMode:d,limit:u,results:[],durationMs:Date.now()-S});return{content:[{type:`text`,text:t.summary}],isError:!t.ok,structuredContent:t.data??{results:[],totalResults:0,searchMode:d,query:e}}}}let ne,re;if(v>0&&!r&&(re="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),v>0&&r)try{let e=await xt(r,w.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:v,maxPerHit:5});ne=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(`
2990
+ `}if(O?r.length===0&&a.length>0?(w=a.slice(0,u),D=` (FTS-only: vector index rebuilding)`):w=a.length===0&&r.length>0?r.slice(0,u):kh(r,a).slice(0,u):w=a.slice(0,u),O){let t=await Oh(i,r[0]?.score??0,w,e,u);w=t.results,T=t.triggered,E=t.cacheHit}}w=Dh(w,m).slice(0,u),a&&a.recordSearch(e,T,E),w.length>1&&(w=Ah(w,e)),w=jh(w);let te=``;if(x&&x.length>0){let n=cl(x,je(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await ll(n);try{let i;i=d===`keyword`||!O?await dl(r,e,{...C,limit:u}):await ul(r,await t.embedQuery(e),{...C,limit:u});for(let e of i)w.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});w=w.sort((e,t)=>t.score-e.score).slice(0,u),te=` + ${n.length} workspace(s)`}finally{await i()}}}if(b===`file`&&w.length>1){let e=new Map;for(let t of w){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}]})}w=[...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(w.length>1){let e=w[0].score,t=Math.max(e*.4,.1);w=w.filter(e=>e.score>=t)}if(w.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(`
2991
+ `)[0].slice(0,500);if(r&&r!==e){let i=d===`keyword`||!O?await n.ftsSearch(r,C):await n.search(await t.embedQuery(r),C);i.length>0&&(w=i,D=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,Ch.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){Ch.debug(`Smart search fallback failed`,{error:String(e)})}if(w.length===0){let t=tt({text:`No results found for the given query.`,query:e,searchMode:d,limit:u,results:[],durationMs:Date.now()-S});return{content:[{type:`text`,text:t.summary}],isError:!t.ok,structuredContent:t.data??{results:[],totalResults:0,searchMode:d,query:e}}}}let ne,re;if(v>0&&!r&&(re="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),v>0&&r)try{let e=await xt(r,w.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:v,maxPerHit:5});ne=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(`
2992
2992
  `),n=new Map;for(let e of t.graphContext.nodes)n.set(e.id,e.name);let r=t.graphContext.edges.slice(0,5).map(e=>` - ${n.get(e.fromId)??e.fromId} —[${e.type}]→ ${n.get(e.toId)??e.toId}`).join(`
2993
2993
  `),i=[`- **Graph Context** (${v} hop${v>1?`s`:``}):`];e&&i.push(` Entities:\n${e}`),r&&i.push(` Relationships:\n${r}`),ne.set(t.recordId,i.join(`
2994
- `))}}catch(e){Sh.warn(`Graph augmentation failed`,I(e)),re=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let ie=Date.now();for(let e of w)if(e.record.origin===`curated`&&e.record.indexedAt){let t=ie-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(w.sort((e,t)=>t.score-e.score),w=Be(w),s)for(let e of w){if(e.record.origin!==`curated`)continue;let t=Cd(e.record.sourcePath);t&&Ch(s,t,c,l)}let ae=w.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,ne?.get(n.id)??null].filter(Boolean).join(`
2995
- `)}\n\n${n.origin===`curated`?xh(n.content):n.content}`}).join(`
2994
+ `))}}catch(e){Ch.warn(`Graph augmentation failed`,I(e)),re=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let ie=Date.now();for(let e of w)if(e.record.origin===`curated`&&e.record.indexedAt){let t=ie-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(w.sort((e,t)=>t.score-e.score),w=Be(w),s)for(let e of w){if(e.record.origin!==`curated`)continue;let t=Cd(e.record.sourcePath);t&&wh(s,t,c,l)}let ae=w.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,ne?.get(n.id)??null].filter(Boolean).join(`
2995
+ `)}\n\n${n.origin===`curated`?Sh(n.content):n.content}`}).join(`
2996
2996
 
2997
2997
  ---
2998
2998
 
2999
- `),oe=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+te,k=jh(w,e),se=k.length>0?`\n_Distinctive terms: ${k.map(e=>`\`${e}\``).join(`, `)}_`:``,ce=await Nh(n,w),le=[];if(w.length===0)le.push("`reindex` — no results found, index may be stale"),le.push("`find` — try federated search with glob/regex");else{let e=w[0]?.record.sourcePath;e&&le.push(`\`lookup\` — see all chunks from \`${e}\``),le.push("`symbol` — resolve a specific symbol from the results"),le.push("`compact` — compress a result file for focused reading")}let A=[re?`${re}\n\n`:``,ce?`${ce}\n\n`:``,ae,`\n\n---\n_Search mode: ${oe} | ${w.length} results_${se}`,`\n_Next: ${le.join(` | `)}_`],j=D+A.join(``),M=!1;if(y){let e=L(j,y);M=e!==j,j=e}let ue=w.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}:{}})),de=[re,ce].filter(e=>!!e),fe=tt({text:j,query:e,searchMode:d,limit:u,results:ue,durationMs:Date.now()-S,truncated:M,caveats:de}),pe=new Set,me=[];for(let e of w){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Cd(e.record.sourcePath);if(!t)continue;let n=xd(t,e.record.headingPath??t);n&&!pe.has(n.uri)&&(pe.add(n.uri),me.push(n))}return{content:[{type:`text`,text:fe.summary},...me],isError:!fe.ok,structuredContent:fe.data??{results:[],totalResults:0,searchMode:d,query:e}}}catch(t){Sh.error(`Search failed`,I(t));let n=et(`Search failed: ${t instanceof Error?t.message:String(t)}`,Date.now()-S);return J(`INTERNAL`,n.error?.message??n.summary,{results:[],totalResults:0,searchMode:d??`hybrid`,query:e??``})}})}const Fh=F(`tools`);function Ih(e,t,n){let r=G(`session_digest`);e.registerTool(`session_digest`,{title:r.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:R.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:R.string().optional().describe(`ISO timestamp — only include activity after this time`),last:R.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:R.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:R.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:R.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:R.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},Y(`session_digest`,async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await mn(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):pn(l,u)).digest}]}}catch(e){return Fh.error(`Session digest failed`,I(e)),J(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Lh=1e4,Rh={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function zh(e){return e??Rh}function Bh(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function Vh(e,t,n){let r=Bh(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function Hh(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function Uh(e,t=!1,n){Bh(e,`workspace`);let r=zh(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function Wh(e,t,n){let r=zh(n),i=Uh(t.workspace,t.global??!1,r),a=Vh(t.key,`key`,500),o=Vh(t.value,`value`,Lh),s=t.agent?Vh(t.agent,`agent`,500):void 0,c=Hh(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Gh(e,t,n){let r=Bh(t,`workspace`),i=Vh(n,`key`,500);return e.signalGet(r,i)}function Kh(e,t){let n=Bh(t,`workspace`);return e.signalList(n)}function qh(e,t,n){let r=Bh(t,`workspace`),i=n===void 0?void 0:Vh(n,`key`,500);return e.signalClear(r,i)}function Jh(e,t,n){let r=zh(n),i=Vh(t.resource,`resource`,500),a=Vh(t.holder,`holder`,500),o=Bh(t.workspace,`workspace`),s=t.intent?Vh(t.intent,`intent`,Lh):void 0,c=Hh(t.ttlMinutes??r.defaultLeaseTtlMinutes,`ttlMinutes`);if(c>60)throw Error(`ttlMinutes exceeds max of 60`);let l=e.leaseAcquire(i,a,o,s,c),u=e.leaseGet(i,o);return u?{acquired:l,holder:u.holder,expiresAt:u.expiresAt}:{acquired:l}}function Yh(e,t,n,r){let i=Bh(t,`workspace`),a=Vh(n,`resource`,500),o=Vh(r,`holder`,500);return e.leaseRelease(a,o,i)}function Xh(e,t){let n=Bh(t,`workspace`);return e.leaseList(n)}const Zh=F(`tools:signal`);function Qh(e){return JSON.stringify(e,null,2)}function $h(e,t,n){let r=G(`signal`),i={...Rh,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:R.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:R.string().describe(`Workspace identifier (required)`),key:R.string().optional().describe(`Signal key (for post/get/clear)`),value:R.string().optional().describe(`Signal value (for post)`),agent:R.string().optional().describe(`Agent identifier`),resource:R.string().optional().describe(`Resource path (for lease/unlease)`),holder:R.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:R.string().optional().describe(`What the holder plans to do`),ttl:R.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:R.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},Y(`signal`,async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=Wh(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:Qh({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Gh(t,Uh(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:Qh(e)}],structuredContent:{signals:e}}}case`list`:{let e=Kh(t,Uh(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:Qh(e)}],structuredContent:{signals:e}}}case`clear`:{let e=qh(t,Uh(n,d??!1,i),r);return{content:[{type:`text`,text:Qh({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=Jh(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:Qh(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=Yh(t,n,s,c);return{content:[{type:`text`,text:Qh({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=Xh(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:Qh(e)}],structuredContent:{leases:e}}}}}catch(e){return Zh.error(`Signal operation failed`,I(e)),J(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function eg(e,t){return e.length<=t?e:e.slice(0,t)}function tg(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}async function ng(e,t,n=_){if(!e||!t)return null;try{let[r,i,a]=await Promise.all([e.list({category:`lessons`}),e.list({category:`conventions`}),e.list({category:`session`})]),o=r.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:m(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3);return{lessons:await Promise.all(o.map(async({entry:t,confidence:n})=>{let r=d((await e.read(t.path)).content);return{title:t.title,insight:eg(r.insight??``,150),confidence:n}})),conventions:i.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>tg(t.lastAccessedAt)-tg(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),checkpoint:a.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>tg(t.lastAccessedAt)-tg(e.lastAccessedAt)).map(({entry:e})=>eg(e.contentPreview,200))[0]??null}}catch{return null}}const rg=F(`tools`),ig=14400*1e3,ag={includePrelude:R.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function og(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{rg.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),rg.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function sg(e){return e.onboarded?e.indexStale?{kind:`reindex`,reason:`Index stale. Run reindex() to update.`}:e.contextPressure>70?{kind:`handoff`,reason:`Context pressure high. Consider session handoff.`}:{kind:`proceed`,reason:`Ready to work.`}:{kind:`onboard`,reason:`Index not initialized. Run onboard({ path: "." }) first.`}}function cg(){let e=ar.get(),t=ir.get();if(e)return`- **Tree-sitter (WASM)**: ✅ Available (${t.grammarCount} grammars, dir: ${t.wasmDir})`;let n=t.pathsChecked.length?t.pathsChecked.map(e=>` ${e.exists?`✓`:`✗`} ${e.path}`).join(`
2999
+ `),oe=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+te,k=Mh(w,e),se=k.length>0?`\n_Distinctive terms: ${k.map(e=>`\`${e}\``).join(`, `)}_`:``,ce=await Ph(n,w),le=[];if(w.length===0)le.push("`reindex` — no results found, index may be stale"),le.push("`find` — try federated search with glob/regex");else{let e=w[0]?.record.sourcePath;e&&le.push(`\`lookup\` — see all chunks from \`${e}\``),le.push("`symbol` — resolve a specific symbol from the results"),le.push("`compact` — compress a result file for focused reading")}let A=[re?`${re}\n\n`:``,ce?`${ce}\n\n`:``,ae,`\n\n---\n_Search mode: ${oe} | ${w.length} results_${se}`,`\n_Next: ${le.join(` | `)}_`],j=D+A.join(``),M=!1;if(y){let e=L(j,y);M=e!==j,j=e}let ue=w.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}:{}})),de=[re,ce].filter(e=>!!e),fe=tt({text:j,query:e,searchMode:d,limit:u,results:ue,durationMs:Date.now()-S,truncated:M,caveats:de}),pe=new Set,me=[];for(let e of w){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Cd(e.record.sourcePath);if(!t)continue;let n=xd(t,e.record.headingPath??t);n&&!pe.has(n.uri)&&(pe.add(n.uri),me.push(n))}return{content:[{type:`text`,text:fe.summary},...me],isError:!fe.ok,structuredContent:fe.data??{results:[],totalResults:0,searchMode:d,query:e}}}catch(t){Ch.error(`Search failed`,I(t));let n=et(`Search failed: ${t instanceof Error?t.message:String(t)}`,Date.now()-S);return J(`INTERNAL`,n.error?.message??n.summary,{results:[],totalResults:0,searchMode:d??`hybrid`,query:e??``})}})}const Ih=F(`tools`);function Lh(e,t,n){let r=G(`session_digest`);e.registerTool(`session_digest`,{title:r.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:R.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:R.string().optional().describe(`ISO timestamp — only include activity after this time`),last:R.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:R.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:R.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:R.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:R.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},Y(`session_digest`,async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await mn(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):pn(l,u)).digest}]}}catch(e){return Ih.error(`Session digest failed`,I(e)),J(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Rh=1e4,zh={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function Bh(e){return e??zh}function Vh(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function Hh(e,t,n){let r=Vh(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function Uh(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function Wh(e,t=!1,n){Vh(e,`workspace`);let r=Bh(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function Gh(e,t,n){let r=Bh(n),i=Wh(t.workspace,t.global??!1,r),a=Hh(t.key,`key`,500),o=Hh(t.value,`value`,Rh),s=t.agent?Hh(t.agent,`agent`,500):void 0,c=Uh(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Kh(e,t,n){let r=Vh(t,`workspace`),i=Hh(n,`key`,500);return e.signalGet(r,i)}function qh(e,t){let n=Vh(t,`workspace`);return e.signalList(n)}function Jh(e,t,n){let r=Vh(t,`workspace`),i=n===void 0?void 0:Hh(n,`key`,500);return e.signalClear(r,i)}function Yh(e,t,n){let r=Bh(n),i=Hh(t.resource,`resource`,500),a=Hh(t.holder,`holder`,500),o=Vh(t.workspace,`workspace`),s=t.intent?Hh(t.intent,`intent`,Rh):void 0,c=Uh(t.ttlMinutes??r.defaultLeaseTtlMinutes,`ttlMinutes`);if(c>60)throw Error(`ttlMinutes exceeds max of 60`);let l=e.leaseAcquire(i,a,o,s,c),u=e.leaseGet(i,o);return u?{acquired:l,holder:u.holder,expiresAt:u.expiresAt}:{acquired:l}}function Xh(e,t,n,r){let i=Vh(t,`workspace`),a=Hh(n,`resource`,500),o=Hh(r,`holder`,500);return e.leaseRelease(a,o,i)}function Zh(e,t){let n=Vh(t,`workspace`);return e.leaseList(n)}const Qh=F(`tools:signal`);function $h(e){return JSON.stringify(e,null,2)}function eg(e,t,n){let r=G(`signal`),i={...zh,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:R.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:R.string().describe(`Workspace identifier (required)`),key:R.string().optional().describe(`Signal key (for post/get/clear)`),value:R.string().optional().describe(`Signal value (for post)`),agent:R.string().optional().describe(`Agent identifier`),resource:R.string().optional().describe(`Resource path (for lease/unlease)`),holder:R.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:R.string().optional().describe(`What the holder plans to do`),ttl:R.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:R.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},Y(`signal`,async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=Gh(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:$h({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Kh(t,Wh(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:$h(e)}],structuredContent:{signals:e}}}case`list`:{let e=qh(t,Wh(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:$h(e)}],structuredContent:{signals:e}}}case`clear`:{let e=Jh(t,Wh(n,d??!1,i),r);return{content:[{type:`text`,text:$h({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=Yh(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:$h(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=Xh(t,n,s,c);return{content:[{type:`text`,text:$h({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=Zh(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:$h(e)}],structuredContent:{leases:e}}}}}catch(e){return Qh.error(`Signal operation failed`,I(e)),J(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function tg(e,t){return e.length<=t?e:e.slice(0,t)}function ng(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}async function rg(e,t,n=_){if(!e||!t)return null;try{let[r,i,a]=await Promise.all([e.list({category:`lessons`}),e.list({category:`conventions`}),e.list({category:`session`})]),o=r.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:m(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3);return{lessons:await Promise.all(o.map(async({entry:t,confidence:n})=>{let r=d((await e.read(t.path)).content);return{title:t.title,insight:tg(r.insight??``,150),confidence:n}})),conventions:i.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>ng(t.lastAccessedAt)-ng(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),checkpoint:a.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>ng(t.lastAccessedAt)-ng(e.lastAccessedAt)).map(({entry:e})=>tg(e.contentPreview,200))[0]??null}}catch{return null}}const ig=F(`tools`),ag=14400*1e3,og={includePrelude:R.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function sg(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{ig.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),ig.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function cg(e){return e.onboarded?e.indexStale?{kind:`reindex`,reason:`Index stale. Run reindex() to update.`}:e.contextPressure>70?{kind:`handoff`,reason:`Context pressure high. Consider session handoff.`}:{kind:`proceed`,reason:`Ready to work.`}:{kind:`onboard`,reason:`Index not initialized. Run onboard({ path: "." }) first.`}}function lg(){let e=ar.get(),t=ir.get();if(e)return`- **Tree-sitter (WASM)**: ✅ Available (${t.grammarCount} grammars, dir: ${t.wasmDir})`;let n=t.pathsChecked.length?t.pathsChecked.map(e=>` ${e.exists?`✓`:`✗`} ${e.path}`).join(`
3000
3000
  `):` none`,r=t.healAttempted?` Auto-heal: ${t.healSuccess?`✓ succeeded`:`✗ failed (${t.healError??`unknown`})`}`:` Auto-heal: not attempted`;return[`- **Tree-sitter (WASM)**: ⚠ Unavailable (regex fallback)`,` Reason: ${t.reason||`unknown`}`,` Paths checked:`,n,r,` OS: ${t.os} ${t.arch} | Node: ${t.nodeVersion}`,` Fix: Reinstall package or run vendor:wasm script`].join(`
3001
- `)}const lg=5*6e4;let ug=null,dg=null;function fg(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 pg(){let e=Date.now();if(ug&&e-ug.ts<lg)return ug.value;try{let t=P(Bn(),`.copilot`,`.aikit-scaffold.json`);if(!A(t))return ug={value:null,ts:e},null;let n=JSON.parse(M(t,`utf-8`)).version??null;return ug={value:n,ts:e},n}catch{return ug={value:null,ts:e},null}}function mg(){let e=Date.now();if(dg&&e-dg.ts<lg)return dg.value;try{let t=P(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!A(t))return dg={value:null,ts:e},null;let n=JSON.parse(M(t,`utf-8`)).version??null;return dg={value:n,ts:e},n}catch{return dg={value:null,ts:e},null}}function hg(e){let t=G(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:ag,outputSchema:ys,annotations:t.annotations},Y(`status`,async()=>{let e=ie(),t=pg(),n=mg(),r=t!=null&&t!==e,i=n!=null&&n!==e,a=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${ar.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||i){let o=ae(),s=[];r&&s.push(`user scaffold v${t}`),i&&s.push(`workspace scaffold v${n}`);let c=s.join(`, `);o.state===`success`?a.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${c} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):o.state===`pending`?a.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade is running in the background…`):o.state===`failed`?(re(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(re(),a.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade triggered — check again shortly.`))}let o={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!ar.get(),wasmDiagnostics:ir.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:sg({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3002
- `)}],structuredContent:o}}))}function gg(e,t,n,r,i,a,o,s,c){let l=G(`status`);e.registerTool(`status`,{title:l.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:ag,outputSchema:ys,annotations:l.annotations},Y(`status`,async({includePrelude:e=!1})=>{let l=[];try{let[u,d]=await Promise.all([og(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),og(t.listSourcePaths(),[],`store.listSourcePaths`)]),f=u.value;u.timedOut&&l.push(`⚠ Index stats timed out — values may be incomplete`);let p=d.value;d.timedOut&&l.push(`⚠ File listing timed out`);let m=null,h=0,g=[`## AI Kit Status`,``,`- **Total Records**: ${f.totalRecords}`,`- **Total Files**: ${f.totalFiles}`,`- **Last Indexed**: ${f.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(f.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...p.slice(0,50).map(e=>`- ${e}`),p.length>50?`\n... and ${p.length-50} more files`:``];if(n)try{let e=await og(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)l.push(`⚠ Graph stats timed out`),g.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;m={nodes:t.nodeCount,edges:t.edgeCount},g.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await og(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||g.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&g.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{g.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let _=a?.onboardDir??``,v=A(_),y=i?.onboardComplete||v;if(g.push(``,`### Onboard Status`,y?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${_}\``),r)try{let e=await og(r.list(),[],`curated.list`);if(e.timedOut)l.push(`⚠ Curated knowledge listing timed out`),g.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let t=e.value;h=t.length,g.push(``,`### Curated Knowledge`,t.length>0?`- ${t.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{g.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let b=fg(f.totalRecords,m?.nodes??0,m?.edges??0,h),x=f.lastIndexedAt?new Date(f.lastIndexedAt).getTime():0,S=x>0?Date.now()-x:1/0,C=sg({onboarded:y,indexStale:y&&S>1440*60*1e3,contextPressure:b});g.push(``),g.push(`## 📊 Context Pressure: ${b}/100`),b>=80?g.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):b>=50?g.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):g.push(`✅ Low pressure — plenty of headroom for more content.`);let w=0;if(f.lastIndexedAt){w=new Date(f.lastIndexedAt).getTime();let e=(Date.now()-w)/(1e3*60*60);g.push(``,`### Index Freshness`,e>24?o===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}g.push(``,`### Next Action`,`- **${C.kind}**: ${C.reason}`);let T=null,E=t;if(typeof E.getDiagnostics==`function`)try{T=E.getDiagnostics(),g.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${T.adapterType}`,`- **Vector search**: ${T.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,T.dbPath?`- **DB**: ${T.dbPath}`:``,T.dbSizeBytes==null?``:`- **DB size**: ${(T.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${T.embeddingDim}`,`- **Vector dtype**: ${T.vectorDtype}`)}catch{}if(o===`smart`)if(g.push(``,`### Smart Indexing`),s){let e=s();e?g.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}`):g.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else g.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);let D=0;{try{let e=a?.stateDir?N(a.stateDir,`stash`):null;if(e&&A(e)){let t=pe(e).mtimeMs;t>w&&(w=t)}}catch{}let e=[];if(r)try{let t=h>0?await r.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>w&&(w=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}if(D=w>0?Date.now()-w:0,D>=ig){let t=Math.floor(D/36e5);if(g.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){g.push(`**Recent decisions/notes:**`);for(let t of e)g.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}g.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}g.push(``,`### Runtime`,cg());let O=Ee.instance().getAll(),ee=O.filter(e=>e.status!==`healthy`);if(ee.length>0){g.push(``,`### ⚠️ Subsystem Health`);for(let e of ee){let t=Math.round((Date.now()-e.since)/1e3);g.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else O.length>0&&g.push(``,`### ✅ Subsystem Health`,`- All ${O.length} subsystems healthy`);let te=we.getAll();if(te.size>0){g.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of te){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}g.push(r)}}let ne=pg(),oe=mg(),k=ie(),se=ne!=null&&ne!==k,ce=oe!=null&&oe!==k;if(se||ce){let e=ae(),t=[];se&&t.push(`user scaffold v${ne}`),ce&&t.push(`workspace scaffold v${oe}`);let n=t.join(`, `);e.state===`success`?g.push(``,`### ✅ Upgrade Applied`,`- Server v${k} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?g.push(``,`### ⏳ Upgrade In Progress`,`- Server v${k} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(re(),g.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${k} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(re(),g.push(``,`### ⬆ Upgrade Available`,`- Server v${k} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}l.length>0&&g.push(``,`### ⚠ Warnings`,...l.map(e=>`- ${e}`));let le=wo();if(le.length>0){let e=le.sort((e,t)=>t.callCount-e.callCount);g.push(``,`### Tool Usage This Session`,``),g.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),g.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);g.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let j=go();if(j.bufferSize>=10){let e=j.state===`healthy`?`🟢`:j.state===`degraded`?`🔴`:`🟡`;g.push(``,`### Auto-GC: ${e} ${j.state}`),g.push(`- p95 latency: ${j.p95}ms | buffer: ${j.bufferSize} samples`),j.gcCount>0&&g.push(`- GC cycles triggered: ${j.gcCount}`)}let M=g.join(`
3003
- `),ue=e||D>=ig?await ng(r,c):void 0,de={totalRecords:f.totalRecords,totalFiles:f.totalFiles,lastIndexedAt:f.lastIndexedAt??null,onboarded:y,onboardDir:_,contentTypes:f.contentTypeBreakdown,wasmAvailable:!!ar.get(),wasmDiagnostics:ir.get(),graphStats:m,curatedCount:h,serverVersion:k,scaffoldVersion:ne??null,workspaceScaffoldVersion:oe??null,upgradeAvailable:se||ce,storeBackend:a?.store?.backend,storeDiagnostics:T??null,contextPressure:b,nextAction:C,...ue===void 0?{}:{prelude:ue}};return{content:[{type:`text`,text:M+(o===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:de}}catch(e){return rg.error(`Status failed`,I(e)),J(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const _g=F(`tools`);function vg(e){let t=G(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:R.array(R.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:R.number().min(1).max(20).default(5).describe(`Max results per query`),site:R.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:R.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},Y(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await An({query:e,limit:t,site:n,provider:r}),a=[`## Search: ${i.query} _(via ${i.provider})_`,``];if(i.results.length===0)a.push(`No results found.`);else for(let e of i.results)a.push(`### [${e.title}](${e.url})`,e.snippet,``);return a.join(`
3004
- `)};if(i.length===1)try{return{content:[{type:`text`,text:`${await a(i[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return _g.error(`Web search failed`,I(e)),J(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);_g.error(`Web search failed`,{query:i[e],error:n}),s.push(`## ❌ Search failed: ${i[e]}\n\n${n}`)}}let l=`_Searched ${o.length-c}/${o.length} queries successfully._`;s.push(``,`---`,l,"_Next: Use `web_fetch` to read any of these pages in full._");let u=s.join(`
3005
-
3006
- `);return c===o.length?J(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function yg(e){let t=G(`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:R.string().url().describe(`Request URL (http/https only)`),method:R.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:R.record(R.string(),R.string()).optional().describe(`Request headers as key-value pairs`),body:R.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:R.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},Y(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Tt({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(`
3007
- `)}]}}catch(e){return _g.error(`HTTP request failed`,I(e)),J(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function bg(e){let t=G(`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:R.string().max(500).describe(`Regex pattern (without delimiters)`),flags:R.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:R.array(R.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:R.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:R.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},Y(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=$t({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return J(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
3008
- `)}]}}))}function xg(e){let t=G(`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:R.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:R.string().max(1e6).describe(`Input text`)},annotations:t.annotations},Y(`encode`,async({operation:e,input:t})=>{try{let n=ct({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 _g.error(`Encode failed`,I(e)),J(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Sg(e){let t=G(`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:xs,inputSchema:{path:R.string().describe(`File or directory path to measure`),extensions:R.array(R.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),max_tokens:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},Y(`measure`,async({path:e,extensions:t,max_tokens:n})=>{try{let r=await Ft({path:e,extensions:t}),i=[`## Code Metrics`,``,`**Files:** ${r.summary.totalFiles}`,`**Total lines:** ${r.summary.totalLines} (${r.summary.totalCodeLines} code)`,`**Functions:** ${r.summary.totalFunctions}`,`**Avg complexity:** ${r.summary.avgComplexity}`,`**Max complexity:** ${r.summary.maxComplexity.value} (${r.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of r.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);i.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}r.files.length>20&&i.push(``,`_...and ${r.files.length-20} more files_`);let a={summary:{totalFiles:r.summary.totalFiles,totalLines:r.summary.totalLines,totalCodeLines:r.summary.totalCodeLines,totalFunctions:r.summary.totalFunctions,avgComplexity:r.summary.avgComplexity,maxComplexity:{value:r.summary.maxComplexity.value,file:r.summary.maxComplexity.file}},files:r.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:n?L(i.join(`
3001
+ `)}const ug=5*6e4;let dg=null,fg=null;function pg(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 mg(){let e=Date.now();if(dg&&e-dg.ts<ug)return dg.value;try{let t=P(Bn(),`.copilot`,`.aikit-scaffold.json`);if(!A(t))return dg={value:null,ts:e},null;let n=JSON.parse(M(t,`utf-8`)).version??null;return dg={value:n,ts:e},n}catch{return dg={value:null,ts:e},null}}function hg(){let e=Date.now();if(fg&&e-fg.ts<ug)return fg.value;try{let t=P(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!A(t))return fg={value:null,ts:e},null;let n=JSON.parse(M(t,`utf-8`)).version??null;return fg={value:n,ts:e},n}catch{return fg={value:null,ts:e},null}}function gg(e){let t=G(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:og,outputSchema:ys,annotations:t.annotations},Y(`status`,async()=>{let e=ie(),t=mg(),n=hg(),r=t!=null&&t!==e,i=n!=null&&n!==e,a=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${ar.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||i){let o=ae(),s=[];r&&s.push(`user scaffold v${t}`),i&&s.push(`workspace scaffold v${n}`);let c=s.join(`, `);o.state===`success`?a.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${c} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):o.state===`pending`?a.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade is running in the background…`):o.state===`failed`?(re(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(re(),a.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${c}`,`- Auto-upgrade triggered — check again shortly.`))}let o={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!ar.get(),wasmDiagnostics:ir.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:cg({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3002
+ `)}],structuredContent:o}}))}function _g(e,t,n,r,i,a,o,s,c){let l=G(`status`);e.registerTool(`status`,{title:l.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:og,outputSchema:ys,annotations:l.annotations},Y(`status`,async({includePrelude:e=!1})=>{let l=[];try{let[u,d]=await Promise.all([sg(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),sg(t.listSourcePaths(),[],`store.listSourcePaths`)]),f=u.value;u.timedOut&&l.push(`⚠ Index stats timed out — values may be incomplete`);let p=d.value;d.timedOut&&l.push(`⚠ File listing timed out`);let m=null,h=0,g=[`## AI Kit Status`,``,`- **Total Records**: ${f.totalRecords}`,`- **Total Files**: ${f.totalFiles}`,`- **Last Indexed**: ${f.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(f.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...p.slice(0,50).map(e=>`- ${e}`),p.length>50?`\n... and ${p.length-50} more files`:``];if(n)try{let e=await sg(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)l.push(`⚠ Graph stats timed out`),g.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;m={nodes:t.nodeCount,edges:t.edgeCount},g.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await sg(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||g.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&g.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{g.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let _=a?.onboardDir??``,v=A(_),y=i?.onboardComplete||v;if(g.push(``,`### Onboard Status`,y?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${_}\``),r)try{let e=await sg(r.list(),[],`curated.list`);if(e.timedOut)l.push(`⚠ Curated knowledge listing timed out`),g.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let t=e.value;h=t.length,g.push(``,`### Curated Knowledge`,t.length>0?`- ${t.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{g.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let b=pg(f.totalRecords,m?.nodes??0,m?.edges??0,h),x=f.lastIndexedAt?new Date(f.lastIndexedAt).getTime():0,S=x>0?Date.now()-x:1/0,C=cg({onboarded:y,indexStale:y&&S>1440*60*1e3,contextPressure:b});g.push(``),g.push(`## 📊 Context Pressure: ${b}/100`),b>=80?g.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):b>=50?g.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):g.push(`✅ Low pressure — plenty of headroom for more content.`);let w=0;if(f.lastIndexedAt){w=new Date(f.lastIndexedAt).getTime();let e=(Date.now()-w)/(1e3*60*60);g.push(``,`### Index Freshness`,e>24?o===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}g.push(``,`### Next Action`,`- **${C.kind}**: ${C.reason}`);let T=null,E=t;if(typeof E.getDiagnostics==`function`)try{T=E.getDiagnostics(),g.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${T.adapterType}`,`- **Vector search**: ${T.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,T.dbPath?`- **DB**: ${T.dbPath}`:``,T.dbSizeBytes==null?``:`- **DB size**: ${(T.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${T.embeddingDim}`,`- **Vector dtype**: ${T.vectorDtype}`)}catch{}if(o===`smart`)if(g.push(``,`### Smart Indexing`),s){let e=s();e?g.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}`):g.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else g.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);let D=0;{try{let e=a?.stateDir?N(a.stateDir,`stash`):null;if(e&&A(e)){let t=pe(e).mtimeMs;t>w&&(w=t)}}catch{}let e=[];if(r)try{let t=h>0?await r.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>w&&(w=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}if(D=w>0?Date.now()-w:0,D>=ag){let t=Math.floor(D/36e5);if(g.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){g.push(`**Recent decisions/notes:**`);for(let t of e)g.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}g.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}g.push(``,`### Runtime`,lg());let O=Ee.instance().getAll(),ee=O.filter(e=>e.status!==`healthy`);if(ee.length>0){g.push(``,`### ⚠️ Subsystem Health`);for(let e of ee){let t=Math.round((Date.now()-e.since)/1e3);g.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else O.length>0&&g.push(``,`### ✅ Subsystem Health`,`- All ${O.length} subsystems healthy`);let te=we.getAll();if(te.size>0){g.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of te){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}g.push(r)}}let ne=mg(),oe=hg(),k=ie(),se=ne!=null&&ne!==k,ce=oe!=null&&oe!==k;if(se||ce){let e=ae(),t=[];se&&t.push(`user scaffold v${ne}`),ce&&t.push(`workspace scaffold v${oe}`);let n=t.join(`, `);e.state===`success`?g.push(``,`### ✅ Upgrade Applied`,`- Server v${k} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?g.push(``,`### ⏳ Upgrade In Progress`,`- Server v${k} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(re(),g.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${k} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(re(),g.push(``,`### ⬆ Upgrade Available`,`- Server v${k} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}l.length>0&&g.push(``,`### ⚠ Warnings`,...l.map(e=>`- ${e}`));let le=wo();if(le.length>0){let e=le.sort((e,t)=>t.callCount-e.callCount);g.push(``,`### Tool Usage This Session`,``),g.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),g.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);g.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let j=go();if(j.bufferSize>=10){let e=j.state===`healthy`?`🟢`:j.state===`degraded`?`🔴`:`🟡`;g.push(``,`### Auto-GC: ${e} ${j.state}`),g.push(`- p95 latency: ${j.p95}ms | buffer: ${j.bufferSize} samples`),j.gcCount>0&&g.push(`- GC cycles triggered: ${j.gcCount}`)}let M=g.join(`
3003
+ `),ue=e||D>=ag?await rg(r,c):void 0,de={totalRecords:f.totalRecords,totalFiles:f.totalFiles,lastIndexedAt:f.lastIndexedAt??null,onboarded:y,onboardDir:_,contentTypes:f.contentTypeBreakdown,wasmAvailable:!!ar.get(),wasmDiagnostics:ir.get(),graphStats:m,curatedCount:h,serverVersion:k,scaffoldVersion:ne??null,workspaceScaffoldVersion:oe??null,upgradeAvailable:se||ce,storeBackend:a?.store?.backend,storeDiagnostics:T??null,contextPressure:b,nextAction:C,...ue===void 0?{}:{prelude:ue}};return{content:[{type:`text`,text:M+(o===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph({action:'find_nodes', name_pattern:'<top-level-module>'})` → then `graph({action:'neighbors', node_id})` for relationships, or `reindex` to refresh the index._")}],structuredContent:de}}catch(e){return ig.error(`Status failed`,I(e)),J(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const vg=F(`tools`);function yg(e){let t=G(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:R.array(R.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:R.number().min(1).max(20).default(5).describe(`Max results per query`),site:R.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:R.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},Y(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await An({query:e,limit:t,site:n,provider:r}),a=[`## Search: ${i.query} _(via ${i.provider})_`,``];if(i.results.length===0)a.push(`No results found.`);else for(let e of i.results)a.push(`### [${e.title}](${e.url})`,e.snippet,``);return a.join(`
3004
+ `)};if(i.length===1)try{return{content:[{type:`text`,text:`${await a(i[0])}\n---\n_Next: Use \`web_fetch\` to read any of these pages in full._`}]}}catch(e){return vg.error(`Web search failed`,I(e)),J(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);vg.error(`Web search failed`,{query:i[e],error:n}),s.push(`## ❌ Search failed: ${i[e]}\n\n${n}`)}}let l=`_Searched ${o.length-c}/${o.length} queries successfully._`;s.push(``,`---`,l,"_Next: Use `web_fetch` to read any of these pages in full._");let u=s.join(`
3005
+
3006
+ `);return c===o.length?J(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function bg(e){let t=G(`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:R.string().url().describe(`Request URL (http/https only)`),method:R.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:R.record(R.string(),R.string()).optional().describe(`Request headers as key-value pairs`),body:R.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:R.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},Y(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Tt({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(`
3007
+ `)}]}}catch(e){return vg.error(`HTTP request failed`,I(e)),J(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function xg(e){let t=G(`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:R.string().max(500).describe(`Regex pattern (without delimiters)`),flags:R.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:R.array(R.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:R.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:R.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},Y(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=$t({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return J(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
3008
+ `)}]}}))}function Sg(e){let t=G(`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:R.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:R.string().max(1e6).describe(`Input text`)},annotations:t.annotations},Y(`encode`,async({operation:e,input:t})=>{try{let n=ct({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 vg.error(`Encode failed`,I(e)),J(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Cg(e){let t=G(`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:xs,inputSchema:{path:R.string().describe(`File or directory path to measure`),extensions:R.array(R.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),max_tokens:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},Y(`measure`,async({path:e,extensions:t,max_tokens:n})=>{try{let r=await Ft({path:e,extensions:t}),i=[`## Code Metrics`,``,`**Files:** ${r.summary.totalFiles}`,`**Total lines:** ${r.summary.totalLines} (${r.summary.totalCodeLines} code)`,`**Functions:** ${r.summary.totalFunctions}`,`**Avg complexity:** ${r.summary.avgComplexity}`,`**Max complexity:** ${r.summary.maxComplexity.value} (${r.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of r.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);i.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}r.files.length>20&&i.push(``,`_...and ${r.files.length-20} more files_`);let a={summary:{totalFiles:r.summary.totalFiles,totalLines:r.summary.totalLines,totalCodeLines:r.summary.totalCodeLines,totalFunctions:r.summary.totalFunctions,avgComplexity:r.summary.avgComplexity,maxComplexity:{value:r.summary.maxComplexity.value,file:r.summary.maxComplexity.file}},files:r.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:n?L(i.join(`
3009
3009
  `),n):i.join(`
3010
- `)}],structuredContent:a}}catch(e){return _g.error(`Measure failed`,I(e)),J(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Cg(e){let t=G(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:R.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:R.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:R.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:R.boolean().default(!0).describe(`Highlight breaking changes`),cwd:R.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},Y(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Ve({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 _g.error(`Changelog failed`,I(e)),J(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function wg(e){let t=G(`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:R.string().max(5e5).describe(`JSON data to validate (as string)`),schema:R.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},Y(`schema_validate`,async({data:e,schema:t})=>{try{let n=un({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
3010
+ `)}],structuredContent:a}}catch(e){return vg.error(`Measure failed`,I(e)),J(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}}))}function wg(e){let t=G(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:R.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:R.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:R.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:R.boolean().default(!0).describe(`Highlight breaking changes`),cwd:R.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},Y(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Ve({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 vg.error(`Changelog failed`,I(e)),J(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Tg(e){let t=G(`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:R.string().max(5e5).describe(`JSON data to validate (as string)`),schema:R.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},Y(`schema_validate`,async({data:e,schema:t})=>{try{let n=un({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
3011
3011
 
3012
3012
  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(`
3013
- `)}]}}catch(e){return _g.error(`Schema validation failed`,I(e)),J(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Tg(e){let t=G(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:Ss,inputSchema:{include_env:R.boolean().default(!1).describe(`Include environment variables`),filter_env:R.string().optional().describe(`Filter env vars by name substring`),show_sensitive:R.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},Y(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=ut({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(`
3014
- `)}],structuredContent:a}}))}function Eg(e){let t=G(`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:Cs,inputSchema:{operation:R.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:R.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:R.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:R.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},Y(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=wn({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(`
3015
- `)}],structuredContent:o}}catch(e){return _g.error(`Time failed`,I(e)),J(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Dg(e){try{let t=N(e,`.flows`);if(!A(t))return null;let n=ue(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=N(t,e.name,`meta.json`);if(A(n)&&JSON.parse(M(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function Og(e,t,n,r,i,a,o,s,c,l){let u=new co,d=n.sources[0]?.path??process.cwd(),f={activeSlug:null};f.activeSlug=Dg(d);let p=new Oa(N(n.stateDir??``,`flow-context`),()=>f.activeSlug),m=new ya;m.register(Ei()),m.register(ga),m.register(Ii),m.register(aa),m.register(Ni),m.register(Di),m.register(Oi),m.register(pa),m.register(Ai),m.register(va),m.register(ia(()=>f.activeSlug?{active:!0,slug:f.activeSlug}:null));let h=new wa(m,t.curated,{},p),g=l??ms(n,[...Bo,...Po],W,Io(n)),_=e=>g.has(e),v=new Set([...g].filter(e=>!Yf.includes(e)&&!Ja.has(e))),y=new Qa;u.use(Sa(h),{order:5,name:`auto-knowledge`}),u.use(Eo(),{order:10,name:`replay`}),u.use(to(y,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:v}),{order:94,name:`procedural-memory`}),u.use(Wa(new Ha(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(Ho(),{order:1,name:`structured-content-guard`}),u.use(Da(Ea(n.tokenBudget)),{order:90,name:`compression`}),$o(e,u,n.toolPrefix??``);let b=[...g].filter(e=>Fo.has(e)?No.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);_(`search`)&&Ph(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a,t.stateStore,n.memory?.retention,n.memory?.consolidation);let x={store:t.store,graphStore:t.graphStore,embedder:t.embedder},S=c?e=>{c()?.prioritize(e)}:void 0;_(`lookup`)&&Rf(e,t.store,x);let C={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};_(`status`)&&gg(e,t.store,t.graphStore,t.curated,C,n,o,s,t.stateStore),_(`config`)&&ol(e,n),_(`reindex`)&&mh(e,t.indexer,n,t.curated,t.store,i,o),_(`knowledge`)&&If(e,t.curated,t.policyStore,t.evolutionCollector,i,p,t.stateStore,n.memory?.retention,n.memory?.supersession,n.memory?.consolidation,n.memory?.lessons,x),_(`analyze`)&&wc(e,t.store,t.embedder,x),_(`blast_radius`)&&Tc(e,t.store,t.embedder,t.graphStore,x),_(`produce_knowledge`)&&fh(e,n),_(`onboard`)&&tp(e,t.store,t.embedder,n,C,x),_(`graph`)&&Uu(e,t.graphStore,x),_(`audit`)&&Ac(e,t.store,t.embedder,n.tokenBudget),_(`compact`)&&_l(e,t.embedder,t.fileCache,d,n.allRoots,x,S),_(`scope_map`)&&vl(e,t.embedder,t.store,x),_(`find`)&&yl(e,t.embedder,t.store,d,x),_(`parse_output`)&&Nl(e),_(`workset`)&&rp(e),_(`check`)&&Al(e,x,n.tokenBudget),_(`symbol`)&&bl(e,t.embedder,t.store,t.graphStore,x),_(`eval`)&&jl(e),_(`test_run`)&&Ml(e,x),_(`stash`)&&ip(e,t.stateStore),_(`signal`)&&$h(e,t.stateStore),_(`git_context`)&&Hf(e),_(`diff_parse`)&&Uf(e),_(`rename`)&&Wf(e,n),_(`codemod`)&&Gf(e,n),_(`restore`)&&vh(e),_(`file_summary`)&&xl(e,t.fileCache,d,n.allRoots,x,S),_(`checkpoint`)&&ap(e,t.stateStore),_(`data_transform`)&&Kf(e),_(`trace`)&&Sl(e,t.embedder,t.store,t.graphStore,x),_(`process`)&&Gu(e),_(`watch`)&&Ku(e),_(`dead_symbols`)&&Cl(e,t.embedder,t.store,d,n.allRoots,x),_(`delegate`)&&Pl(e,a),_(`health`)&&qu(e),_(`lane`)&&op(e),_(`queue`)&&sp(e),_(`web_fetch`)&&Ju(e),_(`guide`)&&Yu(e,o),Yf.some(e=>_(e))&&Xf(e,n,b),_(`evidence_map`)&&Fu(e),_(`digest`)&&Iu(e,t.embedder),_(`forge_classify`)&&Lu(e,x),_(`stratum_card`)&&Ru(e,t.embedder,t.fileCache),_(`forge_ground`)&&zu(e,t.embedder,t.store),_(`present`)&&uh(e,r),_(`browser`)&&Yn(e,n),_(`web_search`)&&vg(e),_(`http`)&&yg(e),_(`regex_test`)&&bg(e),_(`encode`)&&xg(e),_(`measure`)&&Sg(e),_(`changelog`)&&Cg(e),_(`schema_validate`)&&wg(e),_(`env`)&&Tg(e),_(`time`)&&Eg(e),_(`flow`)&&Nu(e,n,{store:t.store?{search:async(e,n)=>(await t.store.ftsSearch(e,n)).map(e=>({content:e.record.content}))}:null,graphStore:t.graphStore,embedder:t.embedder},e=>{f.activeSlug=e}),t.bridge&&No.some(e=>_(e))&&(Pc(e,t.bridge,t.evolutionCollector),Fc(e,t.bridge),Ic(e,t.bridge)),t.policyStore&&_(`er_update_policy`)&&pp(e,t.policyStore),t.evolutionCollector&&_(`er_evolve_review`)&&Ol(e,t.evolutionCollector),Mo(e,t.store,t.curated),_(`compliance_score`)&&zc(e),_(`replay`)&&gh(e),_(`session_digest`)&&Ih(e,t.stateStore,a)}function kg(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&Al(e,void 0,t.tokenBudget),r(`eval`)&&jl(e),r(`test_run`)&&Ml(e),r(`parse_output`)&&Nl(e),r(`delegate`)&&Pl(e),r(`git_context`)&&Hf(e),r(`diff_parse`)&&Uf(e),r(`rename`)&&Wf(e,t),r(`codemod`)&&Gf(e,t),r(`data_transform`)&&Kf(e),r(`workset`)&&rp(e),r(`restore`)&&vh(e),r(`lane`)&&op(e),r(`queue`)&&sp(e),r(`session_digest`)&&Ih(e),r(`health`)&&qu(e),r(`process`)&&Gu(e),r(`watch`)&&Ku(e),r(`web_fetch`)&&Ju(e),r(`guide`)&&Yu(e),Yf.some(e=>r(e))&&Xf(e,t,[...n??new Set(Bo)]),r(`evidence_map`)&&Fu(e),r(`forge_classify`)&&Lu(e),r(`present`)&&uh(e),r(`browser`)&&Yn(e,t),r(`produce_knowledge`)&&fh(e),r(`compliance_score`)&&zc(e),r(`replay`)&&gh(e),r(`status`)&&hg(e),r(`flow`)&&Nu(e,t),r(`web_search`)&&vg(e),r(`http`)&&yg(e),r(`regex_test`)&&bg(e),r(`encode`)&&xg(e),r(`measure`)&&Sg(e),r(`changelog`)&&Cg(e),r(`schema_validate`)&&wg(e),r(`env`)&&Tg(e),r(`time`)&&Eg(e)}const Ag=F(`resource-notifier`);var jg=class{mcpServer;constructor(e){this.mcpServer=e}async notifyStatusChanged(){await this.sendUpdate(`aikit://status`)}async notifyFileTreeChanged(){await this.sendUpdate(`aikit://file-tree`)}async notifyCuratedIndexChanged(){await this.sendUpdate(`aikit://curated`)}async notifyCuratedEntryChanged(e){await this.sendUpdate(`aikit://curated/${e}`)}async notifyResourceListChanged(){try{await this.mcpServer.server.sendResourceListChanged()}catch(e){Ag.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyAfterReindex(){await Promise.allSettled([this.notifyStatusChanged(),this.notifyFileTreeChanged()])}async notifyAfterCuratedWrite(e){let t=[this.notifyStatusChanged(),this.notifyCuratedIndexChanged()];e&&t.push(this.notifyCuratedEntryChanged(e)),await Promise.allSettled(t)}async sendUpdate(e){try{await this.mcpServer.server.sendResourceUpdated({uri:e})}catch(t){Ag.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Q=F(`server`);function Mg(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function Ng(n){Q.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=Mg(process.env.AIKIT_SPLIT_STATE),o=N(i,`aikit.db`),s={splitEnabled:a,contentDbPath:o,controlDbPath:a?N(i,`aikit-control.db`):o},c=null;if(r===`sqlite-vec`){let e=s.contentDbPath;A(i)||j(i,{recursive:!0}),c=await vr(e),Q.info(`SQLite adapter ready`,{type:c.type,vectorCapable:c.vectorCapable,dbPath:e}),c.vectorCapable||Q.warn(`┌──────────────────────────────────────────────────────────────────┐
3013
+ `)}]}}catch(e){return vg.error(`Schema validation failed`,I(e)),J(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Eg(e){let t=G(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:Ss,inputSchema:{include_env:R.boolean().default(!1).describe(`Include environment variables`),filter_env:R.string().optional().describe(`Filter env vars by name substring`),show_sensitive:R.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},Y(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=ut({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(`
3014
+ `)}],structuredContent:a}}))}function Dg(e){let t=G(`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:Cs,inputSchema:{operation:R.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:R.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:R.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:R.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},Y(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=wn({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(`
3015
+ `)}],structuredContent:o}}catch(e){return vg.error(`Time failed`,I(e)),J(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Og(e){try{let t=N(e,`.flows`);if(!A(t))return null;let n=ue(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=N(t,e.name,`meta.json`);if(A(n)&&JSON.parse(M(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function kg(e,t,n,r,i,a,o,s,c,l){let u=new co,d=n.sources[0]?.path??process.cwd(),f={activeSlug:null};f.activeSlug=Og(d);let p=new Oa(N(n.stateDir??``,`flow-context`),()=>f.activeSlug),m=new ya;m.register(Ei()),m.register(ga),m.register(Ii),m.register(aa),m.register(Ni),m.register(Di),m.register(Oi),m.register(pa),m.register(Ai),m.register(va),m.register(ia(()=>f.activeSlug?{active:!0,slug:f.activeSlug}:null));let h=new wa(m,t.curated,{},p),g=l??ms(n,[...Bo,...Po],W,Io(n)),_=e=>g.has(e),v=new Set([...g].filter(e=>!Yf.includes(e)&&!Ja.has(e))),y=new Qa;u.use(Sa(h),{order:5,name:`auto-knowledge`}),u.use(Eo(),{order:10,name:`replay`}),u.use(to(y,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:v}),{order:94,name:`procedural-memory`}),u.use(Wa(new Ha(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(Ho(),{order:1,name:`structured-content-guard`}),u.use(Da(Ea(n.tokenBudget)),{order:90,name:`compression`}),$o(e,u,n.toolPrefix??``);let b=[...g].filter(e=>Fo.has(e)?No.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);_(`search`)&&Fh(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,a,t.stateStore,n.memory?.retention,n.memory?.consolidation);let x={store:t.store,graphStore:t.graphStore,embedder:t.embedder},S=c?e=>{c()?.prioritize(e)}:void 0;_(`lookup`)&&Rf(e,t.store,x);let C={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};_(`status`)&&_g(e,t.store,t.graphStore,t.curated,C,n,o,s,t.stateStore),_(`config`)&&ol(e,n),_(`reindex`)&&hh(e,t.indexer,n,t.curated,t.store,i,o),_(`knowledge`)&&If(e,t.curated,t.policyStore,t.evolutionCollector,i,p,t.stateStore,n.memory?.retention,n.memory?.supersession,n.memory?.consolidation,n.memory?.lessons,x),_(`analyze`)&&wc(e,t.store,t.embedder,x),_(`blast_radius`)&&Tc(e,t.store,t.embedder,t.graphStore,x),_(`produce_knowledge`)&&ph(e,n),_(`onboard`)&&tp(e,t.store,t.embedder,n,C,x),_(`graph`)&&Uu(e,t.graphStore,x),_(`audit`)&&Ac(e,t.store,t.embedder,n.tokenBudget),_(`compact`)&&_l(e,t.embedder,t.fileCache,d,n.allRoots,x,S),_(`scope_map`)&&vl(e,t.embedder,t.store,x),_(`find`)&&yl(e,t.embedder,t.store,d,x),_(`parse_output`)&&Nl(e),_(`workset`)&&rp(e),_(`check`)&&Al(e,x,n.tokenBudget),_(`symbol`)&&bl(e,t.embedder,t.store,t.graphStore,x),_(`eval`)&&jl(e),_(`test_run`)&&Ml(e,x),_(`stash`)&&ip(e,t.stateStore),_(`signal`)&&eg(e,t.stateStore),_(`git_context`)&&Hf(e),_(`diff_parse`)&&Uf(e),_(`rename`)&&Wf(e,n),_(`codemod`)&&Gf(e,n),_(`restore`)&&yh(e),_(`file_summary`)&&xl(e,t.fileCache,d,n.allRoots,x,S),_(`checkpoint`)&&ap(e,t.stateStore),_(`data_transform`)&&Kf(e),_(`trace`)&&Sl(e,t.embedder,t.store,t.graphStore,x),_(`process`)&&Gu(e),_(`watch`)&&Ku(e),_(`dead_symbols`)&&Cl(e,t.embedder,t.store,d,n.allRoots,x),_(`delegate`)&&Pl(e,a),_(`health`)&&qu(e),_(`lane`)&&op(e),_(`queue`)&&sp(e),_(`web_fetch`)&&Ju(e),_(`guide`)&&Yu(e,o),Yf.some(e=>_(e))&&Xf(e,n,b),_(`evidence_map`)&&Fu(e),_(`digest`)&&Iu(e,t.embedder),_(`forge_classify`)&&Lu(e,x),_(`stratum_card`)&&Ru(e,t.embedder,t.fileCache),_(`forge_ground`)&&zu(e,t.embedder,t.store),_(`present`)&&dh(e,r),_(`browser`)&&Yn(e,n),_(`web_search`)&&yg(e),_(`http`)&&bg(e),_(`regex_test`)&&xg(e),_(`encode`)&&Sg(e),_(`measure`)&&Cg(e),_(`changelog`)&&wg(e),_(`schema_validate`)&&Tg(e),_(`env`)&&Eg(e),_(`time`)&&Dg(e),_(`flow`)&&Nu(e,n,{store:t.store?{search:async(e,n)=>(await t.store.ftsSearch(e,n)).map(e=>({content:e.record.content}))}:null,graphStore:t.graphStore,embedder:t.embedder},e=>{f.activeSlug=e}),t.bridge&&No.some(e=>_(e))&&(Pc(e,t.bridge,t.evolutionCollector),Fc(e,t.bridge),Ic(e,t.bridge)),t.policyStore&&_(`er_update_policy`)&&pp(e,t.policyStore),t.evolutionCollector&&_(`er_evolve_review`)&&Ol(e,t.evolutionCollector),Mo(e,t.store,t.curated),_(`compliance_score`)&&zc(e),_(`replay`)&&_h(e),_(`session_digest`)&&Lh(e,t.stateStore,a)}function Ag(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&Al(e,void 0,t.tokenBudget),r(`eval`)&&jl(e),r(`test_run`)&&Ml(e),r(`parse_output`)&&Nl(e),r(`delegate`)&&Pl(e),r(`git_context`)&&Hf(e),r(`diff_parse`)&&Uf(e),r(`rename`)&&Wf(e,t),r(`codemod`)&&Gf(e,t),r(`data_transform`)&&Kf(e),r(`workset`)&&rp(e),r(`restore`)&&yh(e),r(`lane`)&&op(e),r(`queue`)&&sp(e),r(`session_digest`)&&Lh(e),r(`health`)&&qu(e),r(`process`)&&Gu(e),r(`watch`)&&Ku(e),r(`web_fetch`)&&Ju(e),r(`guide`)&&Yu(e),Yf.some(e=>r(e))&&Xf(e,t,[...n??new Set(Bo)]),r(`evidence_map`)&&Fu(e),r(`forge_classify`)&&Lu(e),r(`present`)&&dh(e),r(`browser`)&&Yn(e,t),r(`produce_knowledge`)&&ph(e),r(`compliance_score`)&&zc(e),r(`replay`)&&_h(e),r(`status`)&&gg(e),r(`flow`)&&Nu(e,t),r(`web_search`)&&yg(e),r(`http`)&&bg(e),r(`regex_test`)&&xg(e),r(`encode`)&&Sg(e),r(`measure`)&&Cg(e),r(`changelog`)&&wg(e),r(`schema_validate`)&&Tg(e),r(`env`)&&Eg(e),r(`time`)&&Dg(e)}const jg=F(`resource-notifier`);var Mg=class{mcpServer;constructor(e){this.mcpServer=e}async notifyStatusChanged(){await this.sendUpdate(`aikit://status`)}async notifyFileTreeChanged(){await this.sendUpdate(`aikit://file-tree`)}async notifyCuratedIndexChanged(){await this.sendUpdate(`aikit://curated`)}async notifyCuratedEntryChanged(e){await this.sendUpdate(`aikit://curated/${e}`)}async notifyResourceListChanged(){try{await this.mcpServer.server.sendResourceListChanged()}catch(e){jg.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyAfterReindex(){await Promise.allSettled([this.notifyStatusChanged(),this.notifyFileTreeChanged()])}async notifyAfterCuratedWrite(e){let t=[this.notifyStatusChanged(),this.notifyCuratedIndexChanged()];e&&t.push(this.notifyCuratedEntryChanged(e)),await Promise.allSettled(t)}async sendUpdate(e){try{await this.mcpServer.server.sendResourceUpdated({uri:e})}catch(t){jg.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Q=F(`server`);function Ng(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function Pg(n){Q.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=Ng(process.env.AIKIT_SPLIT_STATE),o=N(i,`aikit.db`),s={splitEnabled:a,contentDbPath:o,controlDbPath:a?N(i,`aikit-control.db`):o},c=null;if(r===`sqlite-vec`){let e=s.contentDbPath;A(i)||j(i,{recursive:!0}),c=await vr(e),Q.info(`SQLite adapter ready`,{type:c.type,vectorCapable:c.vectorCapable,dbPath:e}),c.vectorCapable||Q.warn(`┌──────────────────────────────────────────────────────────────────┐
3016
3016
  │ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
3017
3017
  │ Vector search is disabled. Hybrid search returns FTS only. │
3018
3018
  │ To enable: install/rebuild better-sqlite3 (native module). │
3019
- └──────────────────────────────────────────────────────────────────┘`);let t=N(i,`lance`);A(t)&&Q.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let l;if(c)if(s.splitEnabled&&s.controlDbPath!==s.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(s),l=await vr(s.controlDbPath),xr(l,_r),Q.info(`State store adapter ready`,{type:l.type,dbPath:s.controlDbPath,splitEnabled:!0})}else l=c;else{let e=N(i,`aikit-state.db`);A(i)||j(i,{recursive:!0}),l=await vr(e),xr(l,_r),Q.info(`State store adapter ready`,{type:l.type,dbPath:e})}let[u,d,f,p]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new Nr({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Q.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Q.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await br({backend:r,path:i,adapter:c??void 0,embeddingDim:n.embedding.dimensions,partition:r===`sqlite-vec`?s:void 0});return await e.initialize(),Q.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=c?new gr({adapter:c}):new gr({path:i});return await e.initialize(),Q.info(`Graph store initialized`,{shared:!!c}),e})(),(async()=>{let e=await or();if(e){let e=ir.get();Q.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=ir.get();Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),m=new Fr(u,d),h=yr(l),g=new Pr(n.store.path);g.load(),m.setHashCache(g);let _=n.curated.path,v=new e(_);await v.initialize();let y=new t(_,d,u,v);m.setGraphStore(f);let b=Nc(n.er),x=b?new ur(n.curated.path):void 0;x&&Q.info(`Policy store initialized`,{ruleCount:x.getRules().length});let S=b?new lr:void 0,C=P(n.sources[0]?.path??process.cwd(),Se.aiContext),w=A(C),T=n.onboardDir?A(n.onboardDir):!1,E=w||T,D,O=w?C:n.onboardDir;if(E&&O)try{D=pe(O).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:E,onboardTimestamp:D,aiKbExists:w,onboardDirExists:T}),{embedder:u,store:d,stateStore:h,closeStateStore:l===c?void 0:async()=>l.close(),indexer:m,curated:y,graphStore:f,fileCache:new Ie,bridge:b,policyStore:x,evolutionCollector:S,onboardComplete:E,onboardTimestamp:D}}function Pg(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
3020
- `)}const Fg=F(`background-task`);var Ig=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,Fg.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Fg.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Fg.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const Lg=F(`idle-timer`);var Rg=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){Lg.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){Lg.info(`Skipping idle cleanup — background work in progress`);return}Lg.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&Lg.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const zg=F(`memory-monitor`);var Bg=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),zg.info(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?zg.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?zg.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&zg.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const Vg=F(`tool-timeout`),Hg=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var Ug=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function Wg(e){return Hg.has(e)?6e5:12e4}function Gg(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new Ug(n,t);Vg.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const $=F(`server`),Kg=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`]);function qg(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Jg(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function Yg(e,t,n){let r=[];try{t.statePath&&lt(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${qg(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>setTimeout(()=>e(null),50))]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${qg(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function Xg(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||Kg.has(i))return o;try{r--;let e=a[0],i=await Yg(t,n,Jg(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function Zg(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`module not found`].some(e=>t.includes(e))}async function Qg(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
3021
- `),`utf8`),$.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){$.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??Te.model,n=N(Bn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=N(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=N(e.store.path,`graph.db`);try{await r(t,{force:!0}),$.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=N(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),$.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)&&$.warn(`Auto-heal: missing module detected during initialization cleanup`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}function $g(e,t){let n=ms(e,Bo,W,Io(e)),r=Pg(e,n,W),i=new Hn({name:e.serverName??`aikit`,version:ie()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${zo.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3019
+ └──────────────────────────────────────────────────────────────────┘`);let t=N(i,`lance`);A(t)&&Q.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let l;if(c)if(s.splitEnabled&&s.controlDbPath!==s.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(s),l=await vr(s.controlDbPath),xr(l,_r),Q.info(`State store adapter ready`,{type:l.type,dbPath:s.controlDbPath,splitEnabled:!0})}else l=c;else{let e=N(i,`aikit-state.db`);A(i)||j(i,{recursive:!0}),l=await vr(e),xr(l,_r),Q.info(`State store adapter ready`,{type:l.type,dbPath:e})}let[u,d,f,p]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new Nr({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads,idleTimeoutMs:n.embedding.idleTimeoutMs});return await e.initialize(),Q.info(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:n.embedding.model,dimensions:n.embedding.dimensions,interOpNumThreads:n.embedding.interOpNumThreads,intraOpNumThreads:n.embedding.intraOpNumThreads});return await t.initialize(),Q.info(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=await br({backend:r,path:i,adapter:c??void 0,embeddingDim:n.embedding.dimensions,partition:r===`sqlite-vec`?s:void 0});return await e.initialize(),Q.info(`Store initialized`,{backend:r}),e})(),(async()=>{let e=c?new gr({adapter:c}):new gr({path:i});return await e.initialize(),Q.info(`Graph store initialized`,{shared:!!c}),e})(),(async()=>{let e=await or();if(e){let e=ir.get();Q.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=ir.get();Q.warn(`WASM tree-sitter not available; analyzers will use regex fallback`,{reason:e.reason,os:e.os,arch:e.arch,healAttempted:e.healAttempted,healSuccess:e.healSuccess,healError:e.healError,pathsChecked:e.pathsChecked.map(e=>`${e.path} (${e.exists?`found`:`missing`})`)})}return e})()]),m=new Fr(u,d),h=yr(l),g=new Pr(n.store.path);g.load(),m.setHashCache(g);let _=n.curated.path,v=new e(_);await v.initialize();let y=new t(_,d,u,v);m.setGraphStore(f);let b=Nc(n.er),x=b?new ur(n.curated.path):void 0;x&&Q.info(`Policy store initialized`,{ruleCount:x.getRules().length});let S=b?new lr:void 0,C=P(n.sources[0]?.path??process.cwd(),Se.aiContext),w=A(C),T=n.onboardDir?A(n.onboardDir):!1,E=w||T,D,O=w?C:n.onboardDir;if(E&&O)try{D=pe(O).mtime.toISOString()}catch{}return Q.info(`Onboard state detected`,{onboardComplete:E,onboardTimestamp:D,aiKbExists:w,onboardDirExists:T}),{embedder:u,store:d,stateStore:h,closeStateStore:l===c?void 0:async()=>l.close(),indexer:m,curated:y,graphStore:f,fileCache:new Ie,bridge:b,policyStore:x,evolutionCollector:S,onboardComplete:E,onboardTimestamp:D}}function Fg(e,t,n){if(e.serverInstructions)return e.serverInstructions;let r=new Set;for(let e of t){let t=n[e];if(t?.category)for(let e of t.category)r.add(e)}let i=[`This server provides ${t.size} tools across ${r.size} categories: ${[...r].sort().join(`, `)}.`,`TOOL ROUTING:`,`- Understand a file -> file_summary (structure) or compact (extract section)`,`- Find code/symbols -> search (hybrid) or symbol (definition + refs)`,`- Validate changes -> check (typecheck+lint) or test_run (tests)`,`- Read file for editing -> read_file (only for exact lines before edits)`,`FORBIDDEN: DO NOT USE native equivalents when AI Kit provides same:`,`- grep/find -> search or find tool`,`- cat/read_file (for understanding) -> file_summary or compact`,`- terminal tsc/lint -> check tool`,`- terminal test -> test_run tool`];return e.readOnly&&i.push(`Server is in read-only mode. Mutating operations are disabled.`),e.features?.length&&i.push(`Active feature groups: ${e.features.join(`, `)}.`),i.join(`
3020
+ `)}const Ig=F(`background-task`);var Lg=class{queue=[];running=null;get isRunning(){return this.running!==null}get currentTask(){return this.running}get pendingCount(){return this.queue.length}schedule(e){return new Promise((t,n)=>{this.queue.push({...e,resolve:t,reject:n}),this.running||this.processQueue()})}async processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.running=e.name,Ig.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Ig.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Ig.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const Rg=F(`idle-timer`);var zg=class{timer=null;cleanupFns=[];idleMs;disposed=!1;sessionActive=!1;_busy=!1;constructor(e){this.idleMs=e?.idleMs??3e5}setBusy(e){this._busy=e,e?this.cancel():this.touch()}onIdle(e){this.cleanupFns.push(e)}markSessionActive(){this.sessionActive=!0}touch(){this.disposed||this._busy||(this.cancel(),this.timer=setTimeout(()=>{this.runCleanup()},this.idleMs),this.timer.unref&&this.timer.unref())}cancel(){this.timer&&=(clearTimeout(this.timer),null)}dispose(){this.cancel(),this.cleanupFns.length=0,this.disposed=!0}async runCleanup(){if(!this.sessionActive){Rg.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){Rg.info(`Skipping idle cleanup — background work in progress`);return}Rg.info(`Idle for ${this.idleMs/1e3}s — running cleanup`);let e=await Promise.allSettled(this.cleanupFns.map(e=>e()));for(let t of e)t.status===`rejected`&&Rg.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const Bg=F(`memory-monitor`);var Vg=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),Bg.info(`Memory monitor started`,{warningMB:Math.round(this.warningBytes/1024/1024),criticalMB:Math.round(this.criticalBytes/1024/1024),intervalSec:Math.round(this.intervalMs/1e3)}))}stop(){this.timer&&=(clearInterval(this.timer),null)}getRssBytes(){return process.memoryUsage.rss()}check(){let e=this.getRssBytes(),t=`normal`;if(e>=this.criticalBytes?t=`critical`:e>=this.warningBytes&&(t=`warning`),t!==this.lastLevel||t===`critical`){let n=Math.round(e/1024/1024);t===`critical`?Bg.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?Bg.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&Bg.info(`Memory returned to normal: ${n}MB RSS`),this.lastLevel=t}if(t!==`normal`)for(let n of this.pressureFns)try{n(t,e)}catch{}if(t===`critical`)for(let e of this.memoryPressureFns)try{let t=e();t&&typeof t.catch==`function`&&t.catch(()=>{})}catch{}return t===`critical`&&typeof globalThis.gc==`function`&&globalThis.gc(),t}};const Hg=F(`tool-timeout`),Ug=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var Wg=class extends Error{toolName;timeoutMs;constructor(e,t){super(`Tool "${e}" timed out after ${t}ms`),this.toolName=e,this.timeoutMs=t,this.name=`ToolTimeoutError`}};function Gg(e){return Ug.has(e)?6e5:12e4}function Kg(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new Wg(n,t);Hg.warn(e.message),i(e)}},t);o.unref&&o.unref(),e().then(e=>{a||(a=!0,clearTimeout(o),r(e))},e=>{a||(a=!0,clearTimeout(o),i(e))})})}const $=F(`server`),qg=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`]);function Jg(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Yg(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function Xg(e,t,n){let r=[];try{t.statePath&&lt(e.stateStore,{stateDir:t.statePath});let i=e.stateStore.stashList().map(e=>e.key);if(i.length>0){let e=n.toLowerCase().split(/\s+/).filter(e=>e.length>2);if(e.length===0)r.push(`stash: ${i.length} entries available`);else{let t=i.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0?r.push(`stash: ${t.map(e=>`"${Jg(e)}"`).join(`, `)}${i.length>t.length?` (${i.length} total)`:``}`):r.push(`stash: ${i.length} entries available`)}}}catch{}try{if(n){let t=await Promise.race([e.store.ftsSearch(n,{limit:3}),new Promise(e=>setTimeout(()=>e(null),50))]);if(Array.isArray(t)&&t.length>0){let e=t.filter(e=>e&&typeof e==`object`&&`record`in e&&(e.record.origin===`produced`||e.record.origin===`curated`));if(e.length>0){let t=e.slice(0,2).map(e=>{let t=e.record;return`"${Jg(t.headingPath||t.sourcePath||`knowledge`)}"`});r.push(`knowledge: ${t.join(`, `)}`)}}}}catch{}return r.length===0?null:`\n---\nContext available: ${r.join(` | `)}\nPull with: stash({action:'get', key:'...'}) or search({query:'...', origin:'produced'})\n---`}function Zg(e,t,n){let r=3;for(let[i,a]of Object.entries(e)){let e=a.handler;a.handler=async(...a)=>{let o=await e(...a);if(!o||typeof o!=`object`||r<=0||o.isError||qg.has(i))return o;try{r--;let e=a[0],i=await Xg(t,n,Yg(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function Qg(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`,`cannot find module`,`module not found`].some(e=>t.includes(e))}async function $g(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`transformers.node.mjs`)&&n.includes(`cannot find module`)){let e=t.match(/Cannot find module '([^']+transformers\.node\.mjs)'/);if(e){let t=e[1],n=t.replace(/\.mjs$/,`.cjs`);try{let{existsSync:e,writeFileSync:r}=await import(`node:fs`);e(n)&&!e(t)&&(r(t,[`// Auto-generated ESM shim — published package missing this file`,`import { createRequire } from 'node:module';`,`const require = createRequire(import.meta.url);`,`const mod = require('./transformers.node.cjs');`,`export default mod;`,``].join(`
3021
+ `),`utf8`),$.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){$.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??Te.model,n=N(Bn(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=N(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=N(e.store.path,`graph.db`);try{await r(t,{force:!0}),$.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=N(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),$.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}n.includes(`cannot find module`)&&!n.includes(`huggingface`)&&!n.includes(`.cache`)&&$.warn(`Auto-heal: missing module detected during initialization cleanup`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`})}function e_(e,t){let n=ms(e,Bo,W,Io(e)),r=Fg(e,n,W),i=new Hn({name:e.serverName??`aikit`,version:ie()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r}),a=`initializing`,o=``,s=!1,c=null,l=null,u=null;function d(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let f=()=>a===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**${zo.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3022
3022
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${zo.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
3023
- `);Rr(i);let p=new co;p.use(Ho(),{order:1,name:`structured-content-guard`}),$o(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of Bo){if(!n.has(e))continue;let t=G(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));zo.has(e)?r.remove():h.push(r)}kg(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:qn(R.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=JSON.parse(t(c,`utf8`)),d=Object.keys(u.dependencies??{}),f=[`@mixmark-io/domino`],p=[...d,...f.filter(e=>!d.includes(e))],m=p.filter(e=>!e.startsWith(`@aikit/`)),h=p.filter(e=>e.startsWith(`@aikit/`)),g=[];for(let e of m)try{o.resolve(e)}catch{try{o.resolve(`${e}/package.json`)}catch{g.push(e)}}g.length>0&&$.warn(`Dependencies not resolvable — server may operate in degraded mode`,{missing:g,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`});let _=[];if(h.length>0){for(let e of h)n(i(l,e.slice(7),`dist`))||_.push(e);_.length>0&&$.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:_,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit serve`})}}catch{}let n;try{n=await Ng(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(Zg(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await Qg(e,r);try{n=await Ng(e),$.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),$.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,$.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let r=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let f=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let p=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=i._registeredTools??{};for(let e of zo)m[e]?.remove();let b=new jg(i),x=zl(i);Og(i,n,e,Ir(i),b,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Yr(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let C=i._registeredTools??{};for(let[e,t]of Object.entries(C)){if(Lo.has(e))continue;let r=t.handler;t.handler=async(...i)=>{if(!n.indexer.isIndexing)return r(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${Ro/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:Jo(t.config.outputSchema)}:{}}),Ro));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=Wg(e);t.handler=async(...i)=>{try{return await Gg(()=>n(...i),r,e)}catch(n){if(n instanceof Ug)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:Jo(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(C).length;w<Bo.length&&$.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:Bo.length,registeredToolCount:w}),$.info(`MCP server configured`,{toolCount:Bo.length,resourceCount:4});let T=new Bg;T.onPressure((e,t)=>{e===`warning`&&Hr(),e===`critical`&&($.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Hr())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new Rg;l=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){$.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}$.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}Xg(C,n,{statePath:e.stateDir??``});for(let[,e]of Object.entries(C)){let t=e.config?.outputSchema;if(!t)continue;let n=e.handler;e.handler=async(...e)=>{let r=await n(...e);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=Jo(t),i.structuredContent??={},r)}}process.stdin.on(`end`,()=>($.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>($.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{$.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,I(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,I(e))}finally{l?.setBusy(!1)}},E=new Ig,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,ee=setInterval(()=>{try{process.kill(O,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(ee),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return ee.unref(),{server:i,startInit:C,ready:w,runInitialIndex:D,get aikit(){return c},scheduler:E,setSmartScheduler(e){u=e}}}const e_=F(`server`);function t_(e,t){let n=ms(t,[...Bo,...Po],W,Io(t)),r=Pg(t,n,W),i=new Hn({name:t.serverName??`aikit`,version:ie()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return Rr(i),Og(i,e,t,Ir(i),new jg(i),zl(i),void 0,null,null,n),Yr(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function n_(e){let t=await Ng(e),n=t_(t,e);e_.info(`MCP server configured`,{toolCount:Bo.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);e_.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&&e_.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&e_.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});e_.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){e_.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();e_.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){e_.error(`Curated re-index failed`,I(e))}}catch(e){e_.error(`Initial index failed; will retry on aikit_reindex`,I(e))}},i=async()=>{e_.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{e_.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{Bo as ALL_TOOL_NAMES,$g as createLazyServer,t_ as createMcpServer,n_ as createServer,Ng as initializeAikit,Og as registerMcpTools};
3023
+ `);Rr(i);let p=new co;p.use(Ho(),{order:1,name:`structured-content-guard`}),$o(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of Bo){if(!n.has(e))continue;let t=G(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));zo.has(e)?r.remove():h.push(r)}Ag(i,e,n),i.sendToolListChanged=m;let g=i.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),_=i.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:qn(R.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=JSON.parse(t(c,`utf8`)),d=Object.keys(u.dependencies??{}),f=[`@mixmark-io/domino`],p=[...d,...f.filter(e=>!d.includes(e))],m=p.filter(e=>!e.startsWith(`@aikit/`)),h=p.filter(e=>e.startsWith(`@aikit/`)),g=[];for(let e of m)try{o.resolve(e)}catch{try{o.resolve(`${e}/package.json`)}catch{g.push(e)}}g.length>0&&$.warn(`Dependencies not resolvable — server may operate in degraded mode`,{missing:g,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit serve`});let _=[];if(h.length>0){for(let e of h)n(i(l,e.slice(7),`dist`))||_.push(e);_.length>0&&$.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:_,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit serve`})}}catch{}let n;try{n=await Pg(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(Qg(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await $g(e,r);try{n=await Pg(e),$.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),$.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,$.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}let r=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let f=i.sendPromptListChanged.bind(i);i.sendPromptListChanged=()=>{};let p=i.sendResourceListChanged.bind(i);i.sendResourceListChanged=()=>{};for(let e of h)e.remove();g.remove(),_.remove();let m=i._registeredTools??{};for(let e of zo)m[e]?.remove();let b=new Mg(i),x=zl(i);kg(i,n,e,Ir(i),b,x,t,t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null),Yr(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let C=i._registeredTools??{};for(let[e,t]of Object.entries(C)){if(Lo.has(e))continue;let r=t.handler;t.handler=async(...i)=>{if(!n.indexer.isIndexing)return r(...i);let a=s?`re-indexing`:`running initial index`,o=new Promise(n=>setTimeout(()=>n({content:[{type:`text`,text:`⏳ AI Kit is ${a}. The tool "${e}" timed out waiting for index data (${Ro/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:Jo(t.config.outputSchema)}:{}}),Ro));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=Gg(e);t.handler=async(...i)=>{try{return await Kg(()=>n(...i),r,e)}catch(n){if(n instanceof Wg)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}],...t.config?.outputSchema?{structuredContent:Jo(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(C).length;w<Bo.length&&$.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:Bo.length,registeredToolCount:w}),$.info(`MCP server configured`,{toolCount:Bo.length,resourceCount:4});let T=new Vg;T.onPressure((e,t)=>{e===`warning`&&Hr(),e===`critical`&&($.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Hr())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new zg;l=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){$.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}$.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}Zg(C,n,{statePath:e.stateDir??``});for(let[,e]of Object.entries(C)){let t=e.config?.outputSchema;if(!t)continue;let n=e.handler;e.handler=async(...e)=>{let r=await n(...e);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=Jo(t),i.structuredContent??={},r)}}process.stdin.on(`end`,()=>($.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>($.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{$.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,I(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,I(e))}finally{l?.setBusy(!1)}},E=new Lg,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,ee=setInterval(()=>{try{process.kill(O,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(ee),u?.stop&&u.stop(),import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),b.then(async e=>{await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.closeStateStore?.().catch(()=>{})??Promise.resolve(),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return ee.unref(),{server:i,startInit:C,ready:w,runInitialIndex:D,get aikit(){return c},scheduler:E,setSmartScheduler(e){u=e}}}const t_=F(`server`);function n_(e,t){let n=ms(t,[...Bo,...Po],W,Io(t)),r=Fg(t,n,W),i=new Hn({name:t.serverName??`aikit`,version:ie()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return Rr(i),kg(i,e,t,Ir(i),new Mg(i),zl(i),void 0,null,null,n),Yr(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function r_(e){let t=await Pg(e),n=n_(t,e);t_.info(`MCP server configured`,{toolCount:Bo.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);t_.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&&t_.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&t_.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});t_.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){t_.warn(`FTS index creation failed`,I(e))}try{let e=await t.curated.reindexAll();t_.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){t_.error(`Curated re-index failed`,I(e))}}catch(e){t_.error(`Initial index failed; will retry on aikit_reindex`,I(e))}},i=async()=>{t_.info(`Shutting down`),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{t_.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{Bo as ALL_TOOL_NAMES,e_ as createLazyServer,n_ as createMcpServer,r_ as createServer,Pg as initializeAikit,kg as registerMcpTools};