@vpxa/aikit 0.1.207 → 0.1.209

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.
@@ -0,0 +1,2997 @@
1
+ #!/usr/bin/env node
2
+ import{n as e,t}from"./bin.js";import{_ as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,u as g,v as _,y as v}from"./supersession-BIV-v6JG.js";import{n as y,r as b}from"./resolve-sibling-ByoHo7Tp.js";import{autoUpgradeScaffold as x,getCurrentVersion as S,getUpgradeState as C}from"./version-check-gazMo-D4.js";import{createRequire as w}from"node:module";import{createHash as T,randomBytes as E,randomUUID as D,timingSafeEqual as O}from"node:crypto";import{existsSync as k,mkdirSync as A,readFileSync as j,readdirSync as M,renameSync as ee,rmSync as te,statSync as ne,writeFileSync as N}from"node:fs";import{basename as re,dirname as ie,isAbsolute as ae,join as P,relative as oe,resolve as F,sep as se}from"node:path";import{fileURLToPath as ce}from"node:url";import{AIKIT_PATHS as le,CONTENT_TYPES as ue,EMBEDDING_DEFAULTS as de,KNOWLEDGE_ORIGINS as fe,SOURCE_TYPES as pe,TOKEN_BUDGETS as me,addLogListener as he,computePartitionKey as ge,createLogger as I,getGlobalDataDir as _e,getPartitionDir as ve,isUserInstalled as ye,listWorkspaces as be,serializeError as L}from"../../core/dist/index.js";import{FileCache as xe,acquireLease as Se,addToWorkset as Ce,audit as we,bookendReorder as Te,changelog as Ee,check as De,checkpointDiff as Oe,checkpointGC as ke,checkpointHistory as Ae,checkpointLatest as je,checkpointList as Me,checkpointLoad as Ne,checkpointSave as Pe,codemod as Fe,compact as Ie,compressTerminalOutput as Le,createRestorePoint as Re,createSearchErrorResponse as ze,createSearchSuccessResponse as Be,dataTransform as Ve,delegate as He,delegateListModels as Ue,deleteWorkset as We,diffParse as Ge,digest as Ke,encode as qe,ensureLegacyStashImported as Je,envInfo as Ye,evaluate as Xe,evidenceMap as Ze,fileSummary as Qe,find as $e,findDeadSymbols as et,findExamples as tt,forgeClassify as nt,forgeGround as rt,getWorkset as it,gitContext as at,graphAugmentSearch as ot,graphQuery as st,guide as ct,health as lt,httpRequest as ut,laneCreate as dt,laneDiff as ft,laneDiscard as pt,laneList as mt,laneMerge as ht,laneStatus as gt,listActiveLeases as _t,listRestorePoints as vt,listWorksets as yt,measure as bt,onboard as xt,parseOutput as St,processList as Ct,processLogs as wt,processStart as Tt,processStatus as Et,processStop as Dt,queueClear as Ot,queueCreate as kt,queueDag as At,queueDelete as jt,queueDone as Mt,queueFail as Nt,queueGet as Pt,queueList as Ft,queueNext as It,queuePush as Lt,regexTest as Rt,releaseLease as zt,removeFromWorkset as Bt,rename as Vt,replayAppend as Ht,replayClear as Ut,replayList as Wt,replayTrim as Gt,restoreFromPoint as Kt,saveWorkset as qt,schemaValidate as Jt,scopeMap as Yt,scoreCompliance as Xt,sessionDigest as Zt,sessionDigestSampling as Qt,stashClear as $t,stashDelete as en,stashGet as tn,stashList as nn,stashSet as rn,stratumCard as an,summarizeCheckResult as on,symbol as sn,testRun as cn,timeUtils as ln,trace as un,truncateToTokenBudget as R,watchList as dn,watchStart as fn,watchStop as pn,webFetch as mn,webSearch as hn}from"../../tools/dist/index.js";import{mkdir as gn,readFile as _n,readdir as vn,rm as yn,stat as bn,unlink as xn,writeFile as Sn}from"node:fs/promises";import{homedir as Cn}from"node:os";import{McpServer as wn,ResourceTemplate as Tn}from"@modelcontextprotocol/sdk/server/mcp.js";import{buildFormSchema as En,field as Dn,normalizeResponse as On}from"../../elicitation/dist/index.js";import{completable as kn}from"@modelcontextprotocol/sdk/server/completable.js";import{z}from"zod";import{getEngine as An,registerBrowserTools as jn}from"../../browser/dist/index.js";import{BlastRadiusAnalyzer as Mn,DependencyAnalyzer as Nn,DiagramGenerator as Pn,EntryPointAnalyzer as Fn,KnowledgeProducer as In,PatternAnalyzer as Ln,StructureAnalyzer as Rn,SymbolAnalyzer as zn}from"../../analyzers/dist/index.js";import{WasmDiagnostics as Bn,WasmRuntime as Vn,initializeWasm as Hn}from"../../chunker/dist/index.js";import{ERCache as Un,ERClient as Wn,EvolutionCollector as Gn,PolicyStore as Kn,PushAdapter as qn,mergeResults as Jn}from"../../enterprise-bridge/dist/index.js";import{RESOURCE_MIME_TYPE as Yn,registerAppResource as Xn,registerAppTool as Zn}from"@modelcontextprotocol/ext-apps/server";import{SqliteGraphStore as Qn,allMigrations as $n,createSqliteAdapter as er,createStateStore as tr,createStore as nr,runMigrations as rr}from"../../store/dist/index.js";import{execFile as ir,execSync as ar}from"node:child_process";import{TemplateRegistry as or,buildShell as sr,dashboardTemplateDefinition as cr,defaultRegistry as lr,flameGraphTemplateDefinition as ur,isError as dr,isResult as fr,kanbanTemplateDefinition as pr,listSortTemplateDefinition as mr,renderSurface as hr}from"../../blocks-core/dist/index.mjs";import{createServer as gr}from"node:http";import{EmbedderProxy as _r}from"../../embeddings/dist/index.js";import{FileHashCache as vr,IncrementalIndexer as yr}from"../../indexer/dist/index.js";function br(e){function t(){return!!e.server?.getClientCapabilities?.()?.elicitation}async function n(n,r){if(t())try{let t=await e.server.elicitInput({message:n,requestedSchema:r});return On(t?{action:t.action,content:t.content}:void 0)}catch{return}}return{get available(){return t()},async ask(e){return await n(e.message,e.schema)||{action:`decline`}},async confirm(e){let t=await n(e,En({confirmed:Dn.confirm(e)}));return t?.action===`accept`&&t.content?.confirmed===!0},async selectOne(e,t){let r=await n(e,En({selection:Dn.select(`Choose one`,t)}));if(r?.action!==`accept`)return null;let i=r.content?.selection;return typeof i==`string`?i:null},async selectMany(e,t){let r=await n(e,En({selections:Dn.multi(`Choose one or more`,t)}));if(r?.action!==`accept`)return[];let i=r.content?.selections;return Array.isArray(i)?i:[]},async promptText(e,t){let r=await n(e,En({text:Dn.text(e,{description:t})}));if(r?.action!==`accept`)return null;let i=r.content?.text;return typeof i==`string`?i:null}}}const xr={debug:`debug`,info:`info`,warn:`warning`,error:`error`};function Sr(e){return he(({level:t,component:n,message:r,data:i})=>{try{Promise.resolve(e.sendLoggingMessage({level:xr[t],logger:n,data:i?{message:r,...i}:r})).catch(()=>{})}catch{}})}const Cr=3e4,wr=new Map;function Tr(e,t,n){let r=wr.get(e);if(r&&Date.now()<r.expires)return Promise.resolve(r.data);let i=n();return Promise.resolve(i).then(n=>(wr.set(e,{data:n,expires:Date.now()+t}),n))}function Er(){wr.clear()}function Dr(e,t){return Tr(`curated-paths`,Cr,async()=>(await e.list()).map(e=>e.path)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Or(e,t){return Tr(`file-paths`,Cr,()=>e.listSourcePaths()).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function kr(e,t){return Tr(`symbol-names`,Cr,async()=>(await e.findNodes({type:`symbol`,limit:500})).map(e=>e.name)).then(e=>e.filter(e=>e.toLowerCase().includes(t.toLowerCase())).slice(0,20))}function Ar(e,t){return t?nn(t).map(e=>e.key).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function jr(e){return yt().map(e=>e.name).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20)}function Mr(e,t){return t?Me(t).map(e=>e.label).filter(t=>t.toLowerCase().includes(e.toLowerCase())).slice(0,20):[]}function Nr(e,t,n){if(e.registerPrompt(`ready`,{title:`AI Kit Ready`,description:`AI Kit is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`AI Kit is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
3
+ `)}}]})),e.registerPrompt(`onboard`,{title:`Onboard Codebase`,description:`Analyze the codebase for first-time onboarding — runs all analyzers and produces a knowledge summary`,argsSchema:{path:z.string().optional().describe(`Path to analyze (default: workspace root)`)}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the full onboarding workflow for "${e??`.`}"`,``,`1. \`onboard({ path: "${e??`.`}" })\` — full codebase analysis`,`2. \`produce_knowledge({ path: "${e??`.`}" })\` — generate synthesis`,'3. `knowledge({ action: "remember", ... })` for key curated entries',"4. `status` to verify index health"].join(`
4
+ `)}}]})),e.registerPrompt(`sessionStart`,{title:`Start AI Kit Session`,description:`Initialize an AI Kit session — check status, list knowledge, and resume from last checkpoint`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session start protocol:`,``,"1. `status({})` — check AI Kit health and onboard state",'2. `knowledge({ action: "list" })` — see stored knowledge entries','3. `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — resume prior work'].join(`
5
+ `)}}]})),e.registerPrompt(`sessionEnd`,{title:`End AI Kit Session`,description:`Persist decisions and create a session checkpoint before ending`,argsSchema:{summary:z.string().describe(`Brief summary of decisions made, blockers encountered, and next steps`)}},async({summary:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session end protocol:`,``,'1. `knowledge({ action: "remember", title: "Session checkpoint: '+e.slice(0,60)+`...", content: "`+e.replace(/"/g,`\\"`)+'", category: "conventions" })` — persist findings',n===`smart`?`2. Smart indexing is active — index refreshes automatically`:"2. `reindex({})` — refresh search index if files changed",`3. Confirm session data saved`].join(`
6
+ `)}}]})),e.registerPrompt(`search`,{title:`Search AI Kit`,description:`Search AI Kit with hybrid semantic + keyword search`,argsSchema:{query:z.string().describe(`Search query`)}},async({query:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Search AI Kit for: "${e}"\n\nUse \`search({ query: "${e.replace(/"/g,`\\"`)}" })\` to find relevant code, documentation, and curated knowledge.`}}]})),e.registerPrompt(`remember`,{title:`Remember Knowledge`,description:`Store a decision, convention, or finding as curated knowledge`,argsSchema:{title:z.string().describe(`Title of the knowledge entry`),content:z.string().describe(`Content to remember`),category:z.enum([`conventions`,`decisions`,`patterns`,`blockers`,`tasks`]).optional().describe(`Category (default: conventions)`)}},async({title:e,content:t,category:n})=>({messages:[{role:`user`,content:{type:`text`,text:`Store this knowledge:\n\n\`knowledge({ action: "remember", title: "${e.replace(/"/g,`\\"`)}", content: "${t.replace(/"/g,`\\"`).slice(0,200)}...", category: "${n??`conventions`}" })\``}}]})),e.registerPrompt(`planTask`,{title:`Plan a Task`,description:`Generate a reading plan and scope map for a development task`,argsSchema:{task:z.string().describe(`Description of the task to plan`)}},async({task:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Plan implementation for: "${e}"`,``,'1. `search({ query: "'+e.replace(/"/g,`\\"`)+'" })` — find related code and prior decisions','2. `scope_map({ task: "'+e.replace(/"/g,`\\"`)+'" })` — generate a reading plan',"3. For each recommended file, use `file_summary` then `compact` for detail","4. `blast_radius` on planned changes to assess impact"].join(`
7
+ `)}}]})),e.registerPrompt(`investigate`,{title:`Investigate Bug`,description:`Bug investigation workflow — parse error, find symbols, trace data flow, assess impact`,argsSchema:{error:z.string().describe(`Error message, stack trace, or bug description`)}},async({error:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Investigate this error:`,"```",e,"```",``,`Follow the bug investigation workflow:`,"1. `parse_output({ text: <error> })` — extract structured data from the error","2. `symbol({ name: <relevant symbol> })` — find definition and references",'3. `trace({ symbol: <symbol>, direction: "backward" })` — trace data flow to find root cause',"4. `blast_radius({ changed_files: [<affected files>] })` — assess fix impact"].join(`
8
+ `)}}]})),!t)return;let{curated:r,store:i,graphStore:a}=t;e.registerPrompt(`read_knowledge`,{title:`Read Knowledge`,description:`Read a curated knowledge entry by path — with autocomplete`,argsSchema:{path:kn(z.string().describe(`Path of the curated entry (e.g. conventions/naming.md)`),async e=>Dr(r,e))}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Read the curated knowledge entry: \`knowledge({ action: "read", path: "${e}" })\``}}]})),e.registerPrompt(`update_knowledge`,{title:`Update Knowledge`,description:`Update an existing curated knowledge entry — with autocomplete`,argsSchema:{path:kn(z.string().describe(`Path of the curated entry to update`),async e=>Dr(r,e)),content:z.string().describe(`New content for the entry`)}},async({path:e,content:t})=>({messages:[{role:`user`,content:{type:`text`,text:`Update the curated entry at "${e}":\n\n\`knowledge({ action: "update", path: "${e}", content: "${t.replace(/"/g,`\\"`).slice(0,200)}..." })\``}}]})),e.registerPrompt(`forget_knowledge`,{title:`Forget Knowledge`,description:`Delete a curated knowledge entry — with autocomplete`,argsSchema:{path:kn(z.string().describe(`Path of the curated entry to delete`),async e=>Dr(r,e))}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Delete the curated entry: \`knowledge({ action: "forget", path: "${e}" })\``}}]})),e.registerPrompt(`lookup_file`,{title:`Lookup File`,description:`Look up an indexed file — with autocomplete`,argsSchema:{path:kn(z.string().describe(`Source file path`),async e=>Or(i,e))}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Look up the indexed file: \`file_summary({ path: "${e}" })\``}}]})),e.registerPrompt(`find_symbol`,{title:`Find Symbol`,description:`Find a symbol definition and references — with autocomplete`,argsSchema:{name:kn(z.string().describe(`Symbol name`),async e=>kr(a,e))}},async({name:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Find symbol: \`symbol({ name: "${e}" })\``}}]})),e.registerPrompt(`get_stash`,{title:`Get Stash`,description:`Retrieve a stashed value by key — with autocomplete`,argsSchema:{key:kn(z.string().describe(`Stash key`),e=>Ar(e,t?.stateStore))}},async({key:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Get stashed value: \`stash({ action: "get", key: "${e}" })\``}}]})),e.registerPrompt(`get_workset`,{title:`Get Workset`,description:`Load a saved workset by name — with autocomplete`,argsSchema:{name:kn(z.string().describe(`Workset name`),e=>jr(e))}},async({name:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Load workset: \`workset({ action: "load", name: "${e}" })\``}}]})),e.registerPrompt(`load_checkpoint`,{title:`Load Checkpoint`,description:`Restore a saved checkpoint by name — with autocomplete`,argsSchema:{name:kn(z.string().describe(`Checkpoint name`),e=>Mr(e,t?.stateStore))}},async({name:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Load checkpoint: \`checkpoint({ action: "load", name: "${e}" })\``}}]})),e.registerPrompt(`audit_workflow`,{title:`Audit Workflow`,description:`Run a full project quality audit: check → test_run → audit → produce recommendations`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`## Audit Workflow`,``,`Execute the following tools in sequence:`,``,"1. `check({})` — Run typecheck + lint","2. `test_run({})` — Run all tests","3. `audit({})` — Full project audit","4. Review findings and `remember` important patterns",``,`Report: pass/fail status, error counts, audit recommendations, and suggested next steps.`].join(`
9
+ `)}}]})),e.registerPrompt(`refactor_workflow`,{title:`Refactor Workflow`,description:`Safe refactoring workflow: analyze → blast_radius → implement → verify`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`## Refactor Workflow`,``,`For the target files/symbols:`,``,'1. `analyze({ aspect: "structure", path })` — Understand current structure','2. `analyze({ aspect: "dependencies", path })` — Map dependency graph',"3. `blast_radius({ changed_files })` — Assess impact scope",`4. Implement changes carefully`,"5. `check({})` + `test_run({})` — Verify nothing broke",n===`smart`?`6. Smart indexing is active — changes will be indexed automatically`:"6. `reindex({})` — Update AI Kit with changes",``,`What would you like to refactor?`].join(`
10
+ `)}}]})),e.registerPrompt(`forge_workflow`,{title:`FORGE Workflow`,description:`Full FORGE protocol: classify → ground → implement with quality gates`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`## FORGE Quality Gate Workflow`,``,"1. `forge_classify({ task })` — Determine complexity tier (floor/standard/critical)","2. `forge_ground({ task, files, root_path })` — Full grounding analysis",`3. Review typed unknowns and constraints`,`4. Implement with evidence tracking`,'5. `evidence_map({ action: "validate" })` — Verify all claims',"6. `check({})` + `test_run({})` — Final verification",``,`Describe the task to classify:`].join(`
11
+ `)}}]})),e.registerPrompt(`investigate_workflow`,{title:`Investigate Issue`,description:`Bug investigation workflow: trace → analyze → find root cause → fix`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`## Bug Investigation Workflow`,``,"1. `parse_output({ output })` — Parse error messages if available","2. `symbol({ name })` — Find the failing symbol",'3. `trace({ symbol, direction: "backward" })` — Trace data flow to root cause',"4. `blast_radius({ changed_files })` — Assess impact of fix",`5. Implement fix`,"6. `check({})` + `test_run({})` — Verify fix works",``,`Describe the issue:`].join(`
12
+ `)}}]})),e.registerPrompt(`context_workflow`,{title:`Build Context`,description:`Progressive context building: file_summary → compact → digest for deep understanding`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`## Context Building Workflow`,``,`Build understanding progressively:`,``,"1. `file_summary({ path })` — Structure overview (~50 tokens)","2. `compact({ path, query })` — Extract relevant sections (5-20x reduction)","3. `digest({ sources })` — Multi-file compressed summary","4. `stratum_card({ files })` — Reusable reference card",``,`For project-wide context:`,"- `scope_map({ task })` — Reading plan for a specific task",'- `workset({ action: "save" })` — Save working set for later',``,`What do you need to understand?`].join(`
13
+ `)}}]})),e.registerPrompt(`migrate_workflow`,{title:`Migration Workflow`,description:`Code migration workflow: analyze → plan → migrate → verify → document`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`## Migration Workflow`,``,'1. `analyze({ aspect: "structure", path })` — Current codebase state','2. `analyze({ aspect: "patterns", path })` — Identify patterns to migrate',"3. `dead_symbols({ path })` — Find unused code to remove",'4. `scope_map({ task: "migration" })` — Plan migration scope',"5. Use `codemod` for bulk transformations","6. `check({})` + `test_run({})` — Verify after each step","7. `changelog({ from })` — Document changes",``,`What are you migrating from/to?`].join(`
14
+ `)}}]}))}const Pr={enabled:!0,batchSize:10,debounceMs:5e3,maxFactsPerSession:50,minQuality:.3};function Fr(e){return(e.content??[]).filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
15
+ `)}function B(e){return T(`sha256`).update(e).digest(`hex`).slice(0,16)}function Ir(e){let t=0;return e.length>=50&&(t+=.2),e.length>=150&&(t+=.1),/[a-zA-Z]\w+\.\w+/.test(e)&&(t+=.15),/[:=]|^[-*]|\n[-*]|```/.test(e)&&(t+=.15),/\b(use|should|must|always|never|prefer|avoid|requires?|detected|confirmed|verified)\b/i.test(e)&&(t+=.2),/^(Error|TypeError|ReferenceError):/m.test(e)&&e.length<100&&(t-=.2),Math.max(0,Math.min(1,t))}const Lr={name:`build-commands`,tools:[`check`,`test_run`],extract(e){if(e.isError)return[];let t=Fr(e.result);if(!t)return[];let n=[];if(e.toolName===`check`){let r=[];if(/typecheck.*(?:pass|success|0 error)/i.test(t)&&r.push(`typecheck`),/lint.*(?:pass|success|no (?:warning|error))/i.test(t)&&r.push(`lint`),/biome.*(?:checked|no fixes)/i.test(t)&&r.push(`biome`),r.length>0){let t=[...r].sort();n.push({title:`Verified checks: ${t.join(`, `)}`,content:`The following checks passed successfully: ${t.join(`, `)}.\nRun with the \`check\` tool to verify code quality.`,category:`conventions`,tags:[`build`,`verified`,...t],hash:B(`build-checks-${t.join(`,`)}`),quality:.8,source:e.toolName})}}if(e.toolName===`test_run`){let r=t.match(/(\d+)\s*(?:tests?\s+)?pass/i),i=t.match(/(\d+)\s*(?:total|tests)/i),a=t.match(/(\d+)\s*(?:test\s+)?files?/i);if(r){let t=r[1],o=i?.[1]??t,s=a?.[1]??`unknown`;n.push({title:`Test suite summary`,content:`Test results: ${t}/${o} tests passed across ${s} test files.\nUse \`test_run\` tool to execute the test suite.`,category:`context`,tags:[`testing`,`verified`,`test-summary`],hash:B(`test-summary-${t}-${o}`),quality:.7,source:e.toolName,ttlMs:72e5})}let o=t.match(/(?:running|command|exec):\s*(.+?)$/im);if(o?.[1]){let t=o[1].trim();n.push({title:`Test command: ${t.slice(0,60)}`,content:`Verified test command: \`${t}\`\nThis command successfully ran the project's test suite.`,category:`conventions`,tags:[`testing`,`build-command`,`verified`],hash:B(`test-cmd-${t}`),quality:.9,source:e.toolName})}}return n}},Rr={name:`codebase-insights`,tools:[`analyze`,`scope_map`,`blast_radius`,`onboard`],extract(e){let t=Fr(e.result);if(!t||t.length<50||e.isError)return[];let n=[];if(e.toolName===`analyze`&&e.args.aspect===`structure`){let r=typeof e.args.path==`string`?e.args.path:`.`,i=t.slice(0,600);n.push({title:`Structure: ${r}`,content:`Project structure analysis for ${r}:\n${i}`,category:`context`,tags:[`architecture`,`structure`,`analysis`],hash:B(`structure-${r}`),quality:Math.min(.9,Ir(i)+.2),source:e.toolName})}if(e.toolName===`analyze`&&e.args.aspect===`dependencies`){let r=typeof e.args.path==`string`?e.args.path:`.`,i=t.split(/\r?\n/).filter(e=>/(?:depends on|imports?|requires?|from)\s/i.test(e)).slice(0,10);if(i.length>0){let t=`Dependency analysis for ${r}:\n${i.join(`
16
+ `)}`;n.push({title:`Dependencies: ${r}`,content:t,category:`context`,tags:[`architecture`,`dependencies`,`analysis`],hash:B(`deps-${r}`),quality:.7,source:e.toolName})}}if(e.toolName===`blast_radius`){let r=e.args.changed_files,i=Array.isArray(r)?r.map(String).join(`, `):String(r??``);if(i&&t.length>50){let r=t.slice(0,400);n.push({title:`Blast radius: ${i.slice(0,60)}`,content:`Impact analysis for changes to ${i}:\n${r}`,category:`context`,tags:[`architecture`,`blast-radius`,`impact`],hash:B(`blast-${i}`),quality:.6,source:e.toolName,ttlMs:36e5})}}if(e.toolName===`analyze`&&e.args.aspect===`entry_points`){let r=t.split(/\r?\n/).filter(e=>/(?:entry|export|main|bin)\b/i.test(e)).slice(0,10);r.length>0&&n.push({title:`Project entry points`,content:`Detected entry points:\n${r.join(`
17
+ `)}`,category:`context`,tags:[`architecture`,`entry-points`],hash:B(`entry-points`),quality:.7,source:e.toolName})}if(e.toolName===`scope_map`){let r=typeof e.args.task==`string`?e.args.task:``;r&&t.length>100&&n.push({title:`Scope map: ${r.slice(0,60)}`,content:`Scope analysis for "${r}":\n${t.slice(0,500)}`,category:`context`,tags:[`planning`,`scope-map`],hash:B(`scope-${r}`),quality:.6,source:e.toolName,ttlMs:72e5})}return e.toolName===`onboard`&&t.length>200&&n.push({title:`Onboard analysis summary`,content:`Codebase onboarding analysis:\n${t.slice(0,800)}`,category:`context`,tags:[`onboarding`,`analysis`,`structure`],hash:B(`onboard-summary`),quality:.9,source:e.toolName}),n}};function zr(e,t){let n=[],r=e.toLowerCase();r.includes(`biome`)?n.push({title:`Linter: Biome`,content:`This project uses Biome for linting and formatting.`,category:`conventions`,tags:[`tooling`,`linter`,`biome`],hash:B(`convention-linter-biome`),quality:.8,source:t}):r.includes(`eslint`)&&n.push({title:`Linter: ESLint`,content:`This project uses ESLint for linting.`,category:`conventions`,tags:[`tooling`,`linter`,`eslint`],hash:B(`convention-linter-eslint`),quality:.8,source:t}),r.includes(`prettier`)&&n.push({title:`Formatter: Prettier`,content:`This project uses Prettier for code formatting.`,category:`conventions`,tags:[`tooling`,`formatter`,`prettier`],hash:B(`convention-formatter-prettier`),quality:.8,source:t}),(/strict\s*(?:mode)?.*(?:enabled|true)/i.test(e)||/"strict"\s*:\s*true/.test(e))&&n.push({title:`TypeScript strict mode enabled`,content:`This project has TypeScript strict mode enabled. Ensure all types are explicit.`,category:`conventions`,tags:[`typescript`,`strict`,`config`],hash:B(`convention-ts-strict`),quality:.8,source:t});for(let e of[`pnpm`,`yarn`,`npm`,`bun`])if(r.includes(e)&&(r.includes(`lockfile`)||r.includes(`workspace`)||r.includes(`${e} run`))){n.push({title:`Package manager: ${e}`,content:`This project uses ${e} as its package manager.`,category:`conventions`,tags:[`tooling`,`package-manager`,e],hash:B(`convention-pm-${e}`),quality:.7,source:t});break}return(r.includes(`monorepo`)||r.includes(`workspaces`)||/packages\/\w+/.test(e))&&n.push({title:`Monorepo structure detected`,content:`This project uses a monorepo structure with multiple packages.`,category:`conventions`,tags:[`architecture`,`monorepo`],hash:B(`convention-monorepo`),quality:.7,source:t}),n}function Br(e,t){let n=[],r=e.matchAll(/(?:pattern|convention):\s*(.+?)(?:\n|$)/gi);for(let e of r){let r=e[1]?.trim();r&&r.length>20&&r.length<200&&n.push({title:`Pattern: ${r.slice(0,80)}`,content:r,category:`patterns`,tags:[`detected-pattern`],hash:B(`pattern-${r}`),quality:.6,source:t})}return n}const Vr={name:`convention-detection`,tools:[`check`,`analyze`,`onboard`],extract(e){let t=Fr(e.result);if(!t||e.isError)return[];let n=[];return n.push(...zr(t,e.toolName)),e.toolName===`analyze`&&e.args.aspect===`patterns`&&n.push(...Br(t,e.toolName)),n}};function Hr(e,t){return e.match(t)?.[1]?.trim()||null}function Ur(e,t,n,r,i,a){return{title:e,content:t,category:`context`,tags:n,hash:B(r),quality:i,source:a}}const Wr={name:`environment-facts`,tools:[`env`,`config`,`status`],extract(e){let t=Fr(e.result);if(!t)return[];let n=[],r=Hr(t,/node(?:\.js)?\s*[:=]\s*([^\r\n]+)/i);r&&n.push(Ur(`Node.js version`,`Detected Node.js version: ${r}`,[`environment`,`node`],`node-version-${r}`,.4,e.toolName));let i=Hr(t,/(?:^|\n)os\s*[:=]\s*([^\r\n]+)/i);i&&n.push(Ur(`Operating system`,`Detected OS: ${i}`,[`environment`,`os`],`os-${i}`,.4,e.toolName));let a=Hr(t,/workspace(?: path)?\s*[:=]\s*([^\r\n]+)/i);a&&n.push(Ur(`Workspace path`,`Primary workspace path: ${a}`,[`environment`,`workspace`],`workspace-${a}`,.4,e.toolName));let o=Hr(t,/store(?: backend)?\s*[:=]\s*([^\r\n]+)/i);o&&n.push(Ur(`Store backend`,`Configured store backend: ${o}`,[`environment`,`storage`],`store-${o}`,.6,e.toolName));let s=Hr(t,/embedding(?: model)?\s*[:=]\s*([^\r\n]+)/i);return s&&n.push(Ur(`Embedding model`,`Configured embedding model: ${s}`,[`environment`,`embedding`],`embedding-${s}`,.6,e.toolName)),n}},Gr={"search-result":800,"file-card":2e3,analysis:1500,"step-summary":3e3},Kr=[`search`,`file_summary`,`stratum_card`,`compact`,`blast_radius`,`scope_map`],qr={search:`search-result`,file_summary:`file-card`,stratum_card:`file-card`,compact:`analysis`,blast_radius:`analysis`,scope_map:`step-summary`},Jr={"search-result":72e5,"file-card":144e5,analysis:144e5,"step-summary":288e5};function Yr(e){return e.replace(/\s+/g,` `).trim()}function Xr(e){return Math.max(.6,Math.min(.8,Ir(e)))}function V(e,t=500){let n=Yr(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-3)).trimEnd()}...`}function Zr(e){return typeof e==`object`&&!!e}function Qr(e){try{return JSON.parse(e)}catch{return null}}function H(e){return typeof e==`string`?Yr(e):typeof e==`number`||typeof e==`boolean`?String(e):``}function $r(e,t=5){if(!Array.isArray(e))return[];let n=[];for(let r of e){if(n.length>=t)break;if(typeof r==`string`){let e=Yr(r);e&&n.push(e);continue}if(Zr(r)){let e=H(r.path)||H(r.sourcePath)||H(r.title)||H(r.name)||H(r.label);e&&n.push(e)}}return n}function U(e,...t){for(let n of t){let t=H(e[n]);if(t)return t}return``}function ei(e){let t=[e.file,e.path,e.files,e.changed_files,e.changedFiles].flatMap(e=>typeof e==`string`?[Yr(e)]:$r(e,6));return[...new Set(t.filter(Boolean))].slice(0,6)}function ti(e,t=6){let n=e.match(/(?:[A-Za-z]:[\\/]|\.\/?|\.\.[\\/]|[A-Za-z0-9_.-]+\/)[^\s,:;]+\.[A-Za-z0-9]+/g)??[];return[...new Set(n.map(e=>Yr(e)))].slice(0,t)}function ni(e,t){return e.length===0?``:`${t}: ${e.join(`, `)}`}function ri(e,t=3){return e.split(/\r?\n/).map(e=>Yr(e)).filter(e=>e.length>=12).slice(0,t)}function ii(e){if(!Zr(e))return``;let t=H(e.title)||H(e.path)||H(e.sourcePath)||H(e.file),n=H(e.snippet)||H(e.preview)||H(e.content)||H(e.summary);return Yr([t,n&&`- ${n}`].filter(Boolean).join(` `))}function ai(e,t){let n=U(e,`query`),r=Qr(t);if(Zr(r)&&Array.isArray(r.results)){let e=r.results.map(e=>ii(e)).filter(Boolean).slice(0,3);if(e.length>0)return V(`Query: ${n||`unknown`}. Top hits: ${e.join(` | `)}`,Gr[`search-result`])}let i=ri(t,3);return V(`Query: ${n||`unknown`}. Top hits: ${i.join(` | `)}`,Gr[`search-result`])}function oi(e,t){let n=U(e,`path`,`file`),r=Qr(t);if(Zr(r)){let e=H(r.path)||n||`unknown file`,t=$r(r.imports,4),i=$r(r.exports,5),a=$r(r.functions,4),o=[`File: ${e}`,ni(i,`Exports`),ni(t,`Imports`),ni(a,`Functions`)].filter(Boolean);if(o.length>1)return V(o.join(`. `),Gr[`file-card`])}let i=ri(t,4);return V(`File: ${n||`unknown file`}. Structure: ${i.join(` | `)}`,Gr[`file-card`])}function si(e,t){let n=ei(e),r=U(e,`tier`)||`T1`,i=Qr(t);if(Zr(i)){let e=(Array.isArray(i.cards)?i.cards:[]).map(e=>ii(e)).filter(Boolean).slice(0,3);if(e.length>0)return V(`Tier: ${r}. Files: ${n.join(`, `)||`unknown`}. Cards: ${e.join(` | `)}`,Gr[`file-card`])}let a=ri(t,3);return V(`Tier: ${r}. Files: ${n.join(`, `)||`unknown`}. Highlights: ${a.join(` | `)}`,Gr[`file-card`])}function ci(e,t){let n=U(e,`path`,`file`),r=U(e,`query`);return V(`Path: ${n||`unknown`}. Focus: ${r||`general`}. Summary: ${t}`,Gr.analysis)}function li(e,t){let n=ei(e),r=Qr(t),i=Zr(r)?[...$r(r.affectedFiles,8),...$r(r.tests,4),...$r(r.importers,4)]:[],a=[...new Set([...i,...ti(t,8)])].slice(0,8),o=[`Changed: ${n.join(`, `)||`unknown`}`,ni(a,`Affected`)].filter(Boolean);return o.length>1?V(o.join(`. `),Gr.analysis):V(`Changed: ${n.join(`, `)||`unknown`}. Summary: ${t}`,Gr.analysis)}function ui(e,t){let n=U(e,`task`),r=Qr(t);if(Zr(r)){let e=$r(r.files,6),t=typeof r.totalFiles==`number`?r.totalFiles:e.length;if(e.length>0)return V(`Task: ${n||`unknown`}. Reading plan (${t} files): ${e.join(`, `)}`,Gr[`step-summary`])}let i=ti(t,6);return V(`Task: ${n||`unknown`}. Reading plan: ${i.join(`, `)||ri(t,3).join(` | `)}`,Gr[`step-summary`])}function di(e,t){switch(e.toolName){case`search`:return ai(e.args,t);case`file_summary`:return oi(e.args,t);case`stratum_card`:return si(e.args,t);case`compact`:return ci(e.args,t);case`blast_radius`:return li(e.args,t);case`scope_map`:return ui(e.args,t);default:return``}}function fi(e){switch(e.toolName){case`search`:return V(`Search: ${U(e.args,`query`)||`unknown query`}`,120);case`file_summary`:return V(`File summary: ${U(e.args,`path`,`file`)||`unknown file`}`,120);case`stratum_card`:return V(`Stratum card: ${ei(e.args).join(`, `)||`unknown files`}${U(e.args,`tier`)?` (${U(e.args,`tier`)})`:``}`,120);case`compact`:return V(`Compact: ${U(e.args,`path`,`file`)||`unknown path`}${U(e.args,`query`)?` - ${U(e.args,`query`)}`:``}`,120);case`blast_radius`:return V(`Blast radius: ${ei(e.args).join(`, `)||`unknown changes`}`,120);case`scope_map`:return V(`Scope map: ${U(e.args,`task`)||`unknown task`}`,120);default:return V(`Flow context: ${e.toolName}`,120)}}function pi(e){return{name:`flow-context`,tools:[...Kr],extract(t){if(t.isError)return[];let n=e();if(!n?.active||!n.slug||!(t.toolName in qr))return[];let r=Fr(t.result).trim();if(r.length<50)return[];let i=qr[t.toolName],a=di(t,r);if(a.length<50)return[];let o=fi(t);return[{title:o,content:a,category:`flow-context`,tags:[`flow-context`,`flow:${n.slug}`,i,`tool:${t.toolName}`],hash:B(`${n.slug}|${t.toolName}|${o}|${a}`),quality:Xr(a),ttlMs:Jr[i],source:t.toolName}]}}}const mi={name:`research-results`,tools:[`web_search`,`web_fetch`,`search`],extract(e){let t=Fr(e.result);if(!t||t.length<100||e.isError)return[];let n=[];if(e.toolName===`web_search`){let r=typeof e.args.query==`string`?e.args.query:``;if(r&&t.length>200){let i=t.slice(0,800);n.push({title:`Web research: ${r.slice(0,80)}`,content:`Research query: "${r}"\n\nKey findings:\n${i}`,category:`context`,tags:[`research`,`web-search`],hash:B(`web-search-${r}`),quality:Math.min(.8,Ir(i)+.2),source:e.toolName,ttlMs:864e5})}}if(e.toolName===`web_fetch`){let r=e.args.urls,i=Array.isArray(r)?String(r[0]??``):typeof e.args.url==`string`?e.args.url:``;if(i&&t.length>200){let r=t.split(/\r?\n/).find(e=>e.trim().length>10)?.trim()??i,a=t.slice(0,600);n.push({title:`Fetched: ${r.slice(0,80)}`,content:`Source: ${i}\n\n${a}`,category:`context`,tags:[`research`,`web-fetch`],hash:B(`web-fetch-${i}`),quality:Ir(a),source:e.toolName,ttlMs:864e5})}}if(e.toolName===`search`){let r=typeof e.args.query==`string`?e.args.query:``;(typeof e.args.origin==`string`?e.args.origin:``)===`curated`&&r&&t.length>100&&n.push({title:`Curated search: ${r.slice(0,80)}`,content:`Searched curated knowledge for: "${r}"\n\nResults:\n${t.slice(0,500)}`,category:`context`,tags:[`research`,`curated-search`],hash:B(`curated-search-${r}`),quality:.5,source:e.toolName,ttlMs:36e5})}return n}};function hi(e){let t=e.toLowerCase();return t.includes(`vitest`)?`vitest`:t.includes(`jest`)?`jest`:t.includes(`mocha`)?`mocha`:t.includes(`playwright`)?`playwright`:t.includes(`cypress`)?`cypress`:null}function gi(e){let t=[/(\S+\.test\.\w+)/,/(\S+\.spec\.\w+)/,/(\S+_test\.\w+)/,/__tests__\/\S+/],n=new Set;for(let r of t){let t=e.matchAll(new RegExp(r.source,`g`));for(let e of t){let t=e[0].match(/\.(test|spec)\.\w+$/);t&&n.add(t[0])}}return n.size>0?[...n].join(`, `):null}const _i={name:`test-results`,tools:[`check`,`test_run`],extract(e){let t=Fr(e.result);if(!t)return[];let n=[],r=hi(t);r&&n.push({title:`Test framework: ${r}`,content:`This project uses ${r} for testing. Detected from ${e.toolName} output.`,category:`context`,tags:[`testing`,`environment`,r],hash:B(`test-framework-${r}`),quality:.7,source:e.toolName});let i=gi(t);return i&&n.push({title:`Test file pattern: ${i}`,content:`Test files use the naming pattern: ${i}. Follow this convention when creating new tests.`,category:`conventions`,tags:[`testing`,`naming-convention`],hash:B(`test-pattern-${i}`),quality:.7,source:e.toolName}),n}};function vi(e){let t=e.toLowerCase();return/enoent|no such file|not found/i.test(e)?{type:`missing-file`,actionable:!1}:/econnreset|econnrefused|etimedout|fetch failed/i.test(e)?{type:`network`,actionable:!1}:/permission denied|eacces/i.test(e)?{type:`permission`,actionable:!0}:/type\s*error|cannot.*property|is not a function/i.test(e)?{type:`type-error`,actionable:!0}:/syntax\s*error|unexpected token|parsing error/i.test(e)?{type:`syntax`,actionable:!0}:/out of memory|heap|allocation/i.test(e)?{type:`memory`,actionable:!0}:/timeout|timed out/i.test(e)?{type:`timeout`,actionable:t.includes(`increase`)||t.includes(`config`)}:/import|require|module not found|cannot find module/i.test(e)?{type:`module-resolution`,actionable:!0}:{type:`unknown`,actionable:e.length>100}}const yi={name:`tool-failure-patterns`,tools:[],extract(e){if(!e.isError)return[];let t=Fr(e.result);if(!t||t.length<30)return[];let{type:n,actionable:r}=vi(t);if(!r)return[];let i=t.slice(0,500),a=Ir(i);return a<.2?[]:[{title:`${n} error in ${e.toolName}`,content:`Tool \`${e.toolName}\` failed with a ${n} error.\n\nArgs: ${JSON.stringify(e.args,null,2).slice(0,200)}\n\nError:\n${i}`,category:`context`,tags:[`errors`,n,e.toolName],hash:B(`smart-error-${n}-${e.toolName}-${t.slice(0,80)}`),quality:Math.min(.7,a+.1),source:e.toolName,ttlMs:72e5}]}};var bi=class{extractors=[];register(e){this.extractors.push(e)}getExtractors(e){return this.extractors.filter(t=>t.tools.length===0||t.tools.includes(e))}extractAll(e){return this.getExtractors(e.toolName).flatMap(t=>t.extract(e))}};function xi(e){return{content:[{type:`text`,text:(e instanceof Error,String(e))}],isError:!0}}function Si(e,t){try{e.push(t)}catch{}}function Ci(e){return async(t,n)=>{let r=Date.now();try{let i=await n();return Si(e,{toolName:t.toolName,args:t.args,result:i,durationMs:Date.now()-r,isError:i.isError===!0,timestamp:new Date().toISOString()}),i}catch(n){throw Si(e,{toolName:t.toolName,args:t.args,result:xi(n),durationMs:Date.now()-r,isError:!0,timestamp:new Date().toISOString()}),n}}}const wi=I(`auto-knowledge`);var Ti=class{registry;curated;flowContextAdapter;queue=[];timer=null;seenHashes=new Map;storedCount=0;droppedCount=0;dedupedCount=0;config;existingTitles=null;constructor(e,t,n={},r){this.registry=e,this.curated=t,this.flowContextAdapter=r,this.config={...Pr,...n}}push(e){if(!(!this.config.enabled||!this.curated&&!this.flowContextAdapter)&&!(this.storedCount>=this.config.maxFactsPerSession)){if(this.queue.push(e),this.queue.length>=this.config.batchSize){this.flush().catch(e=>{wi.warn(`Auto-knowledge flush error`,{error:String(e)})});return}this.scheduleBatch()}}async flush(){this.timer&&=(clearTimeout(this.timer),null);let e=this.queue.splice(0);if(e.length===0||!this.curated&&!this.flowContextAdapter)return;this.existingTitles===null&&(this.existingTitles=await this.loadExistingTitles());let t=new Map;for(let n of e)for(let e of this.registry.extractAll(n)){if(e.quality<this.config.minQuality){this.droppedCount++;continue}if(this.isSeenRecently(e)){this.dedupedCount++;continue}if(t.has(e.hash)){this.dedupedCount++;continue}if(this.existingTitles.has(this.normalizeTitle(e.title))){this.dedupedCount++;continue}t.set(e.hash,e)}for(let e of t.values()){if(this.storedCount>=this.config.maxFactsPerSession)break;try{if(e.tags.includes(`flow-context`)&&this.flowContextAdapter){let t=`${e.tags.find(e=>!e.startsWith(`flow:`)&&!e.startsWith(`tool:`)&&e!==`flow-context`)||`analysis`}/${e.title.toLowerCase().replace(/[^a-z0-9]+/g,`-`).slice(0,60)}.md`;await this.flowContextAdapter.write(t,`# ${e.title}\n\n${e.content}`)}else if(this.curated)await this.curated.remember(e.title,e.content,e.category,e.tags);else continue;this.seenHashes.set(e.hash,Date.now()),this.existingTitles.add(this.normalizeTitle(e.title)),this.storedCount++,wi.info(`Auto-knowledge stored`,{title:e.title,category:e.category,quality:e.quality,source:e.source})}catch(t){wi.warn(`Auto-knowledge store failed`,{title:e.title,error:String(t)})}}}reset(){this.queue=[],this.seenHashes.clear(),this.storedCount=0,this.droppedCount=0,this.dedupedCount=0,this.existingTitles=null,this.timer&&=(clearTimeout(this.timer),null)}getStats(){return{queued:this.queue.length,stored:this.storedCount,seen:this.seenHashes.size,dropped:this.droppedCount,deduped:this.dedupedCount}}isSeenRecently(e){let t=this.seenHashes.get(e.hash);return t==null?!1:e.ttlMs==null?!0:Date.now()-t<e.ttlMs}normalizeTitle(e){return e.toLowerCase().trim()}async loadExistingTitles(){let e=new Set,t=this.curated;if(!t)return e;try{let n=await t.list();for(let t of n)e.add(this.normalizeTitle(t.title))}catch{wi.warn(`Failed to load existing curated titles for dedup`,{})}return e}scheduleBatch(){this.timer||=setTimeout(()=>{this.timer=null,this.flush().catch(e=>{wi.warn(`Auto-knowledge flush error`,{error:String(e)})})},this.config.debounceMs)}};const Ei=new Set([`compact`,`digest`,`file_summary`,`stratum_card`,`present`,`web_fetch`,`web_search`,`check`,`audit`]);function Di(e){switch(e){case`efficient`:return{threshold:2e3,tokenBudget:1e3};case`full`:return{threshold:1/0};default:return{threshold:4e3,tokenBudget:2e3}}}function Oi(e){let t=e?.threshold??4e3,n=e?.tokenBudget??2e3;return async(e,r)=>{if(Ei.has(e.toolName))return r();let i=await r();if(!Array.isArray(i.content))return i;let a=0;for(let e of i.content)e.type===`text`&&typeof e.text==`string`&&(a+=e.text.length);if(a<t)return i;let o=i.content.map(r=>{if(r.type!==`text`||typeof r.text!=`string`||r.text.length<t)return r;let i=Le({text:r.text,tool:e.toolName,tokenBudget:n});return{...r,text:i.text}});return{...i,content:o}}}var ki=class{baseDir;getActiveSlug;constructor(e,t){this.baseDir=e,this.getActiveSlug=t}async initialize(){await gn(this.baseDir,{recursive:!0})}async read(e){let t=this.resolveScopedPath(e);if(t==null)return null;try{return await _n(t,`utf-8`)}catch(e){if(this.isMissingError(e))return null;throw e}}async write(e,t,n){let r=this.resolveScopedPath(e);r!=null&&(await gn(ie(r),{recursive:!0}),await Sn(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`}))}async delete(e){let t=this.resolveScopedPath(e);if(t==null)return!1;try{return await xn(t),!0}catch(e){if(this.isMissingError(e))return!1;throw e}}async list(e){let t=this.getActiveSlugDir();if(t==null)return[];let n=e?this.resolveScopedPath(e):t;return n==null?[]:this.collectFiles(n,e??``)}async exists(e){let t=this.resolveScopedPath(e);if(t==null)return!1;try{return await bn(t),!0}catch(e){if(this.isMissingError(e))return!1;throw e}}async listDirectories(){let e=this.getActiveSlugDir();if(e==null)return[];try{return(await vn(e,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name).sort()}catch(e){if(this.isMissingError(e))return[];throw e}}async flushAll(){let e=this.getActiveSlugDir();if(e==null)return 0;let t=await this.countFiles(e);return t===0?0:(await yn(e,{recursive:!0,force:!0}),t)}async close(){}getActiveSlugDir(){let e=this.getActiveSlug();return e?P(this.baseDir,e):null}resolveScopedPath(e){let t=this.getActiveSlugDir();if(t==null)return null;let n=F(t),r=F(n,e),i=oe(n,r);if(i===``||i===`..`||i.startsWith(`..${se}`)||ae(i))throw Error(`Path escapes active flow context scope: ${e}`);return r}async collectFiles(e,t){let n;try{n=await vn(e,{withFileTypes:!0})}catch(e){if(this.isMissingError(e))return[];throw e}let r=[];for(let i of n){let n=t?`${t}/${i.name}`:i.name,a=P(e,i.name);if(i.isDirectory()){r.push(...await this.collectFiles(a,n));continue}if(!(!i.isFile()||!i.name.endsWith(`.md`)))try{let e=await bn(a);r.push({path:n,size:e.size})}catch(e){if(!this.isMissingError(e))throw e}}return r.sort((e,t)=>e.path.localeCompare(t.path))}async countFiles(e){let t;try{t=await vn(e,{withFileTypes:!0})}catch(e){if(this.isMissingError(e))return 0;throw e}let n=0;for(let r of t){let t=P(e,r.name);if(r.isDirectory()){n+=await this.countFiles(t);continue}r.isFile()&&(n+=1)}return n}isMissingError(e){return typeof e==`object`&&!!e&&`code`in e&&(e.code===`ENOENT`||e.code===`ENOTDIR`)}};const Ai=I(`observation-capture`),ji=[`check`,`test_run`,`search`,`trace`],Mi=[/\bAuthorization\s*:\s*Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,/\bBearer\s+[A-Za-z0-9\-._~+/]+=*/g,/\b(?:sk|ghp|gho|glpat|xoxb|xoxp)-[A-Za-z0-9\-._]{20,}\b/g,/\b(?:token|key|secret|password|auth(?:orization)?)\s*[=:]\s*['"]?[^\s'"&]{8,}/gi,/\b(?:token|key|secret|password|auth(?:orization)?)=[^\s&]+/gi,/\b[A-Z][A-Z0-9_]*(?:PASSWORD|SECRET|TOKEN|AUTH)[A-Z0-9_]*\b\s*[=:]\s*['"]?[^\s'"]+/g,/\b[A-Z][A-Z0-9_]*KEY[A-Z0-9_]*\b\s*[=:]\s*['"]?[^\s'"]{8,}/g,/-----BEGIN [\w\s]+-----[\s\S]*?-----END [\w\s]+-----/g],Ni=new Set([`env`,`auth`,`config`]),Pi=2e3,Fi={enabled:!0,rateLimit:10,captureFrom:[...ji],minContentLength:50};var Ii=class{maxPerMinute;timestamps=[];constructor(e){this.maxPerMinute=e}canCapture(e=Date.now()){return this.prune(e),this.timestamps.length<this.maxPerMinute}record(e=Date.now()){this.prune(e),this.timestamps.push(e)}setLimit(e){this.maxPerMinute=e,this.prune(Date.now())}prune(e){let t=e-6e4;this.timestamps=this.timestamps.filter(e=>e>t)}};function Li(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ri(e){return typeof e==`string`?e:Li(e)?[Array.isArray(e.content)?e.content.filter(e=>Li(e)).map(e=>typeof e.text==`string`?e.text:``).filter(e=>e.length>0).join(`
18
+ `):``,e.structuredContent==null?``:JSON.stringify(e.structuredContent,null,2)].filter(e=>e.length>0).join(`
19
+
20
+ `):JSON.stringify(e)}function zi(e,t=500){return e.length<=t?e:e.slice(0,t)}function Bi(e){let t=e.toLowerCase();return[...Ni].some(e=>t===e||t.includes(e))}function Vi(e){let t=e;for(let e of Mi)t=t.replace(e,`[REDACTED]`);return t.length>Pi&&(t=`${t.slice(0,Pi)}\n...[truncated]`),t}function Hi(e,t){let n=t?.args??{},r=[];switch(t?.workspace&&r.push(`workspace=${t.workspace}`),e){case`check`:typeof n.cwd==`string`&&r.push(`cwd=${n.cwd}`),Array.isArray(n.files)&&n.files.length>0&&r.push(`files=${n.files.join(`, `)}`);break;case`test_run`:typeof n.cwd==`string`&&r.push(`cwd=${n.cwd}`),typeof n.grep==`string`&&r.push(`grep=${n.grep}`),Array.isArray(n.files)&&n.files.length>0&&r.push(`files=${n.files.join(`, `)}`);break;case`search`:typeof n.query==`string`&&r.push(`query=${n.query}`);break;case`trace`:typeof n.start==`string`&&r.push(`start=${n.start}`),typeof n.direction==`string`&&r.push(`direction=${n.direction}`);break;default:break}return r.length>0?r.join(` | `):void 0}var Ui=class{stateStore;curatedStore;rateLimiter;config;constructor(e,t,n){this.stateStore=e,this.curatedStore=t,this.config={...Fi,...n,captureFrom:n?.captureFrom?[...n.captureFrom]:[...ji]},this.rateLimiter=new Ii(this.config.rateLimit)}getConfig(){return{...this.config,captureFrom:[...this.config.captureFrom]}}updateConfig(e){this.config={...this.config,...e,captureFrom:e.captureFrom?[...e.captureFrom]:[...this.config.captureFrom]},e.rateLimit!==void 0&&this.rateLimiter.setLimit(e.rateLimit)}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}registerTool(e){this.config.captureFrom.includes(e)||this.config.captureFrom.push(e)}unregisterTool(e){this.config.captureFrom=this.config.captureFrom.filter(t=>t!==e)}async processToolResult(e,t,n){if(!this.config.enabled||Bi(e)||!this.config.captureFrom.includes(e)||!this.rateLimiter.canCapture())return null;let r=this.extractObservation(e,t,n);if(!r)return null;let i=Vi(r.content).trim();if(i.length<this.config.minContentLength)return null;let a={...r,content:zi(i).trim()},o={...a,content:i};this.rateLimiter.record();try{await this.storeObservation(o)}catch(t){Ai.warn(`Failed to store observation`,{toolName:e,error:t instanceof Error?t.message:String(t)})}return a}extractObservation(e,t,n){let r=Ri(t);if(r.trim().length===0)return null;switch(e){case`check`:return this.extractFromCheck(t,r,n);case`test_run`:return this.extractFromTestRun(t,r,n);case`search`:return this.extractFromSearch(r,n);case`trace`:return this.extractFromTrace(r,n);default:return null}}extractFromCheck(e,t,n){return Li(e)&&e.isError===!0||/\berror\b/i.test(t)||/failed/i.test(t)?this.buildObservation(`check`,`error`,t,n):null}extractFromTestRun(e,t,n){let r=Li(e)&&Li(e.structuredContent)?e.structuredContent:void 0,i=typeof r?.failedTests==`number`?r.failedTests:void 0;return Li(e)&&e.isError===!0||typeof i==`number`&&i>0||/\bFAIL\b/.test(t)||/failed/i.test(t)?this.buildObservation(`test_run`,`test_failure`,t,n):null}extractFromSearch(e,t){if(!/\b(convention|pattern)\b/i.test(e))return null;let n=/\bconvention\b/i.test(e)?`convention`:`pattern`;return this.buildObservation(`search`,n,e,t)}extractFromTrace(e,t){return this.buildObservation(`trace`,`insight`,e,t)}buildObservation(e,t,n,r){return{id:D(),source:e,type:t,content:n,context:Hi(e,r),timestamp:new Date().toISOString()}}async storeObservation(e){let t=`Observation ${e.source} ${e.type} ${e.timestamp}`,n=[`Source: ${e.source}`,`Type: ${e.type}`,`Captured: ${e.timestamp}`,e.context?`Context: ${e.context}`:null,``,e.content].filter(e=>e!==null).join(`
21
+ `),r=await this.curatedStore.remember(t,n,`context`,[`observation`,`source-${e.source}`,`type-${e.type}`]);this.stateStore.memoryMetaCreate(r.path,`working`)}};function Wi(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 Gi(e){return async(t,n)=>{let r=await n();try{await e.processToolResult(t.toolName,r,{workspace:Wi(t.args),args:t.args})}catch(e){Ai.warn(`Observation capture failed`,{toolName:t.toolName,requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}return r}}const Ki=I(`procedural-memory`),qi=`Use when these user-facing tools are run in this order within a single session.`,Ji={minSequenceLength:3,minRepetitions:3,maxSequenceLength:10,confidenceIncrement:10,confidenceDecrement:20},Yi=new Set([`status`,`guide`,`health`,`onboard`,`reindex`,`replay`,`session_digest`,`process`,`watch`,`produce_knowledge`,`list_tools`,`describe_tool`,`search_tools`]);function Xi(e){return e.join(`→`)}function Zi(e){return{...e,steps:[...e.steps]}}function Qi(e){return e.every(e=>e.success)}var $i=class{config;history=[];sequences=new Map;procedures=new Map;pendingProcedures=new Map;constructor(e=Ji){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=>Zi(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=>Zi(e));return this.pendingProcedures.clear(),e}requeueProcedures(e){for(let t of e)this.pendingProcedures.set(Xi(t.steps),Zi(t))}extractProcedure(e,t){return{id:D(),steps:[...e],occurrences:t,confidence:Math.min(50+(t-this.config.minRepetitions)*this.config.confidenceIncrement,100),lastSeen:new Date().toISOString(),conditions:qi}}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=Xi(n),s=0;for(let e=0;e<=t.length-a;e+=1)Xi(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,Zi(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);Xi(a.map(e=>e.toolName))===n&&(r.occurrences+=1,r.lastSeen=e,this.adjustConfidence(r,Qi(a)))}}};async function ea(e,t,n){let r=await t.remember(`Procedure: ${n.steps.join(` → `)}`,ta(n),`patterns`,[`procedure`,`auto-extracted`]);return e.memoryMetaCreate(r.path,`procedural`),r.path}function ta(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??qi].join(`
22
+ `)}function na(e,t,n={}){return async(r,i)=>{if(!ra(r.toolName,n))return i();try{let n=await i();return e.record(r.toolName,n.isError!==!0),await ia(e,t,r.toolName),n}catch(n){throw e.record(r.toolName,!1),await ia(e,t,r.toolName),n}}}function ra(e,t){return t.trackedTools&&!t.trackedTools.has(e)?!1:!(t.ignoredTools??Yi).has(e)}async function ia(e,t,n){let r=e.drainNewProcedures();if(r.length===0)return;let i=[];for(let e of r)try{await ea(t.stateStore,t.curatedStore,e)}catch(t){i.push(e),Ki.warn(`Failed to store procedural memory`,{toolName:n,sequence:e.steps.join(` -> `),error:t instanceof Error?t.message:String(t)})}i.length>0&&e.requeueProcedures(i)}const aa=I(`tool-pipeline`);function oa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sa(e,t){return e.tools?(Array.isArray(e.tools)?e.tools:[e.tools]).includes(t):!0}function ca(e){return e.middleware.critical===!0}var la=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=>sa(t,e)).sort((e,t)=>e.order-t.order);return async(a,o)=>{let s={toolName:e,args:oa(a)?a:{},requestId:D(),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(ca(r))throw t;if(aa.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 ua=I(`auto-gc`);let da=`warming`,fa=null,pa=0;function ma(){let e=[...Ta()];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 ha(e){let t=ma();if(t===0){da=`warming`;return}if(t>500){da=`degraded`;let n=Date.now();if(fa&&n-fa<36e5){ua.debug(`GC cooldown active — skipping`,{lastGcAgoMs:n-fa});return}fa=n,pa++,ua.warn(`p95 latency exceeds threshold, triggering GC`,{p95:t,cycle:pa}),e&&e().catch(e=>ua.error(`GC callback failed`,{err:String(e)}))}else t<200&&(da=`healthy`)}function ga(){return{state:da,p95:ma(),lastGcAt:fa,gcCount:pa,bufferSize:Ta().length}}const _a=/key|token|secret|auth|password|bearer/i,va=new Set([`eval`,`env`]);function ya(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(ya);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]=ya(r);return t}return e}function ba(e,t){if(va.has(e))return JSON.stringify({_redacted:!0,tool:e});let n=ya(t);if(e===`http`&&n.headers&&typeof n.headers==`object`){let e={};for(let[t,r]of Object.entries(n.headers))e[t]=_a.test(t)?`[REDACTED]`:r;return n.headers=e,JSON.stringify(n).slice(0,2e3)}return JSON.stringify(n).slice(0,2e3)}const xa=new Map,Sa=[];function Ca(e,t,n,r,i){let a=xa.get(e);a||(a={callCount:0,totalDurationMs:0,totalInputChars:0,totalOutputChars:0,errorCount:0},xa.set(e,a)),a.callCount++,a.totalDurationMs+=t,a.totalInputChars+=n,a.totalOutputChars+=r,i&&a.errorCount++,Sa.push(t),Sa.length>100&&Sa.shift(),Sa.length>=10&&Sa.length%20==0&&ha()}function wa(){return Array.from(xa.entries()).map(([e,t])=>({tool:e,...t}))}function Ta(){return Sa}function Ea(){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 Ht({ts:new Date().toISOString(),source:`mcp`,tool:e.toolName,input:ba(e.toolName,e.args),durationMs:a,status:`ok`,output:o,traceId:e.requestId,outputChars:o.length}),Ca(e.toolName,a,r,o.length,!1),i}catch(t){let i=Date.now()-n;throw Ht({ts:new Date().toISOString(),source:`mcp`,tool:e.toolName,input:ba(e.toolName,e.args),durationMs:i,status:`error`,output:t instanceof Error?t.message:String(t),traceId:e.requestId,outputChars:0}),Ca(e.toolName,i,r,0,!0),t}}}function Da(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(`
23
+ `):`_No curated entries yet._`}`,mimeType:`text/markdown`}]}});let n=new Tn(`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 Oa=`aikit://schemas/channel-surface`,ka=new URL(`../../../blocks-core/schemas/channel-surface.schema.json`,import.meta.url);let Aa;function ja(){return Aa??=_n(ka,`utf8`),Aa}function Ma(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(`
24
+ `),mimeType:`text/plain`}]})),e.registerResource(`aikit-channel-surface-schema`,Oa,{description:`JSON Schema for the ChannelSurface communication contract`,mimeType:`application/schema+json`},async()=>({contents:[{uri:Oa,text:await ja(),mimeType:`application/schema+json`}]})),Da(e,n)}const Na=[`er_push`,`er_pull`,`er_sync_status`],Pa=[...Na,`er_update_policy`,`er_evolve_review`],Fa=new Set(Pa);function Ia(e){return e.toolProfiles}const La=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(`.`)),Ra=5e3,za=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(`.`)),Ba=`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(`.`),Va=I(`structured-content-guard`);function Ha(){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.isError&&n.structuredContent==null&&(n.structuredContent={},Va.warn(`Structured content guard activated`,{tool:e.toolName,action:`inject-empty-no-schema`})),n;let i=null;if(n.structuredContent==null){let t=Ua(r);n.structuredContent=t,i=`synthesize`,n.structuredContent??(n.structuredContent={},i=`synthesize-null-fallback`,Va.error(`synthesizeStructuredContent returned null/undefined — using empty fallback`,{tool:e.toolName}))}let a=Wa(r,n.structuredContent);if(a.action!=null&&(n.structuredContent=a.structuredContent,i=a.action),Ka(n.structuredContent)||(n.isError=!0,n.structuredContent={},i=`fallback-error`),Ga(r,n.structuredContent)===!1){let e=Ua(r);n.structuredContent=e??{},Ga(r,n.structuredContent)===!1?(n.structuredContent=Ka(n.structuredContent)?n.structuredContent:{},i=`final-validation-failed`):i??=`final-heal`}return Ka(n.structuredContent)||(n.isError=!0,n.structuredContent={},i=`fallback-error`),i!=null&&Va.warn(`Structured content guard activated`,{tool:e.toolName,action:i}),n});return e.critical=!0,e}function Ua(e){try{return qa(e)??{}}catch{return{}}}function Wa(e,t){if(Ga(e,t)!==!1)return{structuredContent:t,action:null};try{let n=Ua(e);if(Ka(n)&&Ka(t)){let r={...n,...t};if(Ga(e,r)!==!1)return{structuredContent:r,action:`heal`}}return{structuredContent:n,action:`fallback-zero-value`}}catch{return{structuredContent:t,action:null}}}function Ga(e,t){let n=e.safeParse;if(typeof n==`function`)try{return n(t).success}catch{return}}function Ka(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qa(e){if(!e)return{};if(e.anyOf){let t=e.anyOf.find(e=>e.type!==`null`);return t?qa(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]=qa(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]=qa(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 Ja(e){if(!e)return{};try{let t=qa(e);return Ka(t)?t:{}}catch{return{}}}const Ya={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 W(e){return Ya[e]??{title:e,annotations:{readOnlyHint:!1},category:[]}}const Xa=Symbol(`toolPipelineState`);function Za(e){return e[Xa]}function Qa(e,t){e[Xa]=t}function $a(e,t,n=``){let r=Za(e);if(r){r.pipeline=t,r.prefix=n;return}Qa(e,{originalRegisterTool:e.registerTool.bind(e),pipeline:t,prefix:n}),e.registerTool=(n,r,i)=>{let a=Za(e),o=a?.prefix?`${a.prefix}${n}`:n;if(!i)return a?.originalRegisterTool(o,r);if((a?.pipeline??t).getMiddlewareNames().length===0)return a?.originalRegisterTool(o,r,i);let s=W(n),c=(a?.pipeline??t).wrap(n,i,r,s);return a?.originalRegisterTool(o,r,c)}}const eo={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 to(e,t){return e.filter(e=>(eo[e]??0)<=t)}const no=new Set([`status`,`config`,`guide`,`health`]),ro={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 io(e,t){let n=ro[e];if(n)return n;let r=t?.[e];if(r)return r;throw Error(`Unknown tool profile: ${e}`)}function ao(e,t,n){return t.includes(`*`)?!0:(n[e]?.category??[]).some(e=>t.includes(e))}function oo(e,t,n,r){if(t.includes(`*`)){for(let t of n)e.add(t);return}for(let i of n)ao(i,t,r)&&e.add(i)}function so(e,t,n){if(t.includes(`*`)){e.clear();return}for(let r of[...e])ao(r,t,n)&&e.delete(r)}function co(e,t,n){if(!e||e.length===0||e.includes(`*`))return new Set(t);let r=new Set;return oo(r,e,t,n),r}function lo(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function uo(e,t){for(let n of[...e])t[n]?.annotations?.readOnlyHint===!1&&e.delete(n)}function fo(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=io(e,t);return lo(i.extends?fo(i.extends,t,n+1,[...r,e]):void 0,i.maxTier)}function po(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=io(e,r),c=[...o,e],l=s.extends?i(s.extends,a+1,c):co(s.includeCategories,t,n);s.extends&&s.includeCategories?.length&&oo(l,s.includeCategories,t,n),s.excludeCategories?.length&&so(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=fo(e,r);if(o!==void 0){let e=to([...a],o);a.clear();for(let t of e)a.add(t)}for(let e of no)a.add(e);return e===`safe`&&uo(a,n),a}const mo=new Set([`search`,`analysis`,`knowledge`,`compression`,`forge`,`presentation`,`execution`,`manipulation`,`session`,`git`,`process`,`system`,`meta`,`utilities`,`web`,`queue`,`flow`]);function ho(e,t,n,r){let i=process.env.AIKIT_TOOLSET||e.toolProfile||`full`,a=po(i,t,n,r);if(e.features&&e.features.length>0){let i=e.features.filter(e=>!mo.has(e));if(i.length>0)throw Error(`Unknown feature group(s): ${i.join(`, `)}. Valid categories: ${[...mo].join(`, `)}`);let o={description:`Synthetic profile from features config`,includeCategories:e.features},s=po(`_features`,t,n,{...r,_features:o});for(let e of a)!s.has(e)&&!no.has(e)&&a.delete(e)}if(e.readOnly)for(let e of[...a])n[e]?.annotations?.readOnlyHint===!1&&!no.has(e)&&a.delete(e);for(let e of no)a.add(e);return i===`safe`&&uo(a,n),a}const go=z.object({mode:z.enum([`wasm`,`regex`,`unknown`]),reason:z.string(),pathsChecked:z.array(z.object({path:z.string(),exists:z.boolean()})),os:z.string(),arch:z.string(),nodeVersion:z.string(),webTreeSitterImportable:z.boolean(),healAttempted:z.boolean(),healSuccess:z.boolean(),healError:z.string().nullable(),initError:z.string().nullable(),wasmDir:z.string().nullable(),grammarCount:z.number()}),_o=z.object({kind:z.enum([`onboard`,`reindex`,`handoff`,`proceed`]),reason:z.string()}),vo=z.object({totalRecords:z.number(),totalFiles:z.number(),lastIndexedAt:z.string().nullable(),onboarded:z.boolean(),onboardDir:z.string(),contentTypes:z.record(z.string(),z.number()),wasmAvailable:z.boolean(),wasmDiagnostics:go,graphStats:z.object({nodes:z.number(),edges:z.number()}).nullable(),curatedCount:z.number(),serverVersion:z.string(),scaffoldVersion:z.string().nullable(),workspaceScaffoldVersion:z.string().nullable(),upgradeAvailable:z.boolean(),storeBackend:z.string().optional(),storeDiagnostics:z.object({adapterType:z.string(),vectorSearchEnabled:z.boolean(),ftsEnabled:z.boolean(),degradedMode:z.boolean(),dbPath:z.string(),dbSizeBytes:z.number().nullable(),embeddingDim:z.number(),vectorDtype:z.string()}).nullable().optional(),contextPressure:z.number().min(0).max(100).describe(`0–100 score indicating AI Kit saturation`),nextAction:_o});z.object({entries:z.array(z.object({path:z.string(),title:z.string(),category:z.string(),tags:z.array(z.string()),version:z.number(),preview:z.string()})),totalCount:z.number()});const yo=z.object({ok:z.boolean(),checks:z.array(z.object({name:z.string(),ok:z.boolean(),message:z.string().optional()}))}),bo=z.object({summary:z.object({totalFiles:z.number(),totalLines:z.number(),totalCodeLines:z.number(),totalFunctions:z.number(),avgComplexity:z.number(),maxComplexity:z.object({value:z.number(),file:z.string()})}),files:z.array(z.object({path:z.string(),lines:z.number(),code:z.number(),complexity:z.number(),functions:z.number()}))}),xo=z.object({platform:z.string(),arch:z.string(),nodeVersion:z.string(),cwd:z.string(),cpus:z.number(),memoryFreeGb:z.number(),memoryTotalGb:z.number()}),So=z.object({iso:z.string(),unix:z.number(),timezone:z.string(),formatted:z.string()}),Co=z.object({passed:z.boolean(),errorCount:z.number(),warningCount:z.number(),topErrors:z.array(z.string())}),wo=z.object({passed:z.boolean(),tsc:Co,biome:Co}),To=z.object({name:z.string(),definedIn:z.object({path:z.string(),line:z.number(),kind:z.string(),signature:z.string().optional()}).nullable(),importedBy:z.array(z.object({path:z.string(),line:z.number(),importStatement:z.string()})),referencedIn:z.array(z.object({path:z.string(),line:z.number(),context:z.string(),scope:z.string().optional()})),graphContext:z.object({definingModule:z.string().optional(),importedByModules:z.array(z.string()),siblingSymbols:z.array(z.string())}).nullable()}),Eo=z.object({sourcePath:z.string(),contentType:z.string(),score:z.number(),headingPath:z.string().optional(),startLine:z.number().optional(),endLine:z.number().optional(),origin:z.string().optional(),category:z.string().optional(),tags:z.array(z.string()).optional()}),Do=z.object({results:z.array(Eo),totalResults:z.number(),searchMode:z.string(),query:z.string()}),Oo=z.object({path:z.string(),line:z.number().optional(),matchType:z.string(),preview:z.string()}),ko=z.object({matches:z.array(Oo),totalMatches:z.number(),pattern:z.string(),truncated:z.boolean()}),Ao=z.object({path:z.string(),relevance:z.number(),estimatedTokens:z.number(),focusLines:z.array(z.string()).optional()}),jo=z.object({files:z.array(Ao),totalFiles:z.number(),totalEstimatedTokens:z.number(),task:z.string()}),Mo=z.object({path:z.string(),impact:z.string(),reason:z.string()}),No=z.object({changedFiles:z.array(z.string()),affectedFiles:z.array(Mo),totalAffected:z.number(),riskLevel:z.string()}),Po=z.object({name:z.string(),passed:z.boolean(),message:z.string().optional(),severity:z.string().optional()}),Fo=z.object({passed:z.boolean(),score:z.number(),checks:z.array(Po),summary:z.string()}),Io=z.object({id:z.string(),name:z.string(),type:z.string(),sourcePath:z.string().optional()}),Lo=z.object({fromId:z.string(),toId:z.string(),type:z.string()}),Ro=z.object({nodes:z.array(Io),edges:z.array(Lo),totalNodes:z.number(),totalEdges:z.number(),query:z.string()}),zo=z.object({symbols:z.array(z.object({name:z.string(),path:z.string(),line:z.number().optional(),kind:z.string()})),totalDead:z.number()});z.object({files:z.number(),packages:z.number(),languages:z.record(z.string(),z.number()),tree:z.string()});const Bo=z.object({path:z.string(),language:z.string(),lines:z.number(),imports:z.number(),exports:z.number(),functions:z.number(),classes:z.number()}),Vo=z.object({gitRoot:z.string(),branch:z.string(),commitCount:z.number(),hasUncommitted:z.boolean(),recentCommits:z.array(z.object({hash:z.string(),message:z.string(),author:z.string(),date:z.string()}))}),Ho=z.object({originalChars:z.number(),compressedChars:z.number(),ratio:z.number(),segmentsKept:z.number(),segmentsTotal:z.number()}),Uo=z.object({passed:z.boolean(),totalTests:z.number(),passedTests:z.number(),failedTests:z.number(),skippedTests:z.number(),duration:z.number().describe(`Duration in milliseconds`),failures:z.array(z.object({name:z.string(),message:z.string(),file:z.string().optional()}))}),Wo=I(`utils:enrich`);async function G(e,t){let n={curated:[],graph:[]},r=t.limit??3,[i,a]=await Promise.allSettled([Go(e,t.query,r),Ko(e,t.filePath)]);return i.status===`fulfilled`?n.curated=i.value:Wo.debug(`Curated enrichment failed`,{error:i.reason}),a.status===`fulfilled`?n.graph=a.value:Wo.debug(`Graph enrichment failed`,{error:a.reason}),n}async function Go(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=>qo(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=>qo(e.record))}return[]}catch(e){return Wo.debug(`Curated enrichment failed`,{error:e}),[]}}async function Ko(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 Wo.debug(`Graph enrichment failed`,{error:e}),[]}}function K(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(`
25
+ `)}`}function qo(e){let t=Jo(e.metadata,`title`)||e.sourcePath||`Untitled`;return`[${Jo(e.metadata,`category`)}] ${t}: ${e.content.slice(0,200)}`}function Jo(e,t){let n=e?.[t];return typeof n==`string`?n:``}function q(e,t,n){return{content:[{type:`text`,text:`[ERROR:${e}] ${t}`}],isError:!0,...n==null?{}:{structuredContent:n}}}function J(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 Yo=I(`tools`),Xo=z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`);function Zo(e,t){return t?R(e,t):e}function Qo(){let e=[];return Vn.get()||e.push(`Tree-sitter unavailable — using regex fallback, symbol/pattern confidence reduced`),e.length===0?``:`\n\n> **⚠ Caveats:** ${e.join(`; `)}`}function $o(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 es(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(`
26
+
27
+ ### 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(`
28
+ `)}function ts(e){let t=e.replace(/\\/g,`/`);return/(^|\/)__tests__\/|\.(test|spec)\.[jt]sx?$/i.test(t)?`Tests`:/(controller|route|handler|api)/i.test(t)?`API`:/(service|store|model|schema|migration|repo|repository|db|database)/i.test(t)?`Core/Data`:/\.(ts|tsx|js|jsx)$/.test(t)?`Source`:`Config/Docs`}function ns(e){if(e.length===0)return``;let t=[`Core/Data`,`API`,`Source`,`Tests`,`Config/Docs`],n=new Map;for(let t of e){let e=ts(t),r=n.get(e)??[];r.push(t),n.set(e,r)}let r=[`
29
+
30
+ ### Layer Classification`];for(let e of t){let t=n.get(e);if(!t?.length)continue;let i=t.slice(0,5).map(e=>`\`${e}\``).join(`, `),a=t.length>5?`, ... and ${t.length-5} more`:``;r.push(`- **${e}** (${t.length}): ${i}${a}`)}return r.join(`
31
+ `)}async function rs(e,t){if(!e||t.length===0)return[];let n=new Set;for(let r of t){let i=await e.findNodes({sourcePath:r,limit:10});for(let r of i){let i=await e.getNeighbors(r.id,{direction:`incoming`,edgeType:`imports`});for(let e of i.nodes){let r=e.sourcePath??e.name;t.includes(r)||n.add(r)}}}return[...n]}async function is(e,t,n,r,i){try{let a=`produced/analysis/${n}/${T(`sha256`).update(r).digest(`hex`).slice(0,12)}.md`,o=T(`sha256`).update(i).digest(`hex`).slice(0,16),s=new Date().toISOString(),c=i.length>2e3?i.split(/(?=^## )/m).filter(e=>e.trim().length>0):[i],l=c.map((e,t)=>({id:T(`sha256`).update(`${a}::${t}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:a,contentType:`produced-knowledge`,chunkIndex:t,totalChunks:c.length,startLine:0,endLine:0,fileHash:o,indexedAt:s,origin:`produced`,tags:[`analysis`,n],category:`analysis`,version:1})),u=await t.embedBatch(l.map(e=>e.content));await e.upsert(l,u),Yo.info(`Auto-persisted analysis`,{analyzerName:n,chunkCount:l.length})}catch(e){Yo.warn(`Auto-persist analysis failed`,{analyzerName:n,...L(e)})}}const as=z.enum([`structure`,`dependencies`,`symbols`,`patterns`,`entry_points`,`diagram`]),os=z.string().describe(`Root path to analyze`),ss=z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context.`),cs=z.object({path:os,max_depth:z.number().min(1).max(10).default(6).describe(`Maximum directory depth`),format:z.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`),max_tokens:Xo,enrich:ss}),ls=z.object({path:os,format:z.enum([`json`,`markdown`,`mermaid`]).default(`markdown`).describe(`Output format`),max_tokens:Xo,enrich:ss}),us=z.object({path:os,filter:z.string().optional().describe(`Filter symbols by name substring`),format:z.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`),enrich:ss}),ds=z.object({path:os,enrich:ss}),fs=z.object({path:os,enrich:ss}),ps=z.object({path:os,diagram_type:z.enum([`architecture`,`dependencies`]).default(`architecture`).describe(`Type of diagram`),enrich:ss}),ms=z.object({aspect:as.describe(`Analysis aspect to execute`),path:os,max_depth:z.number().min(1).max(10).optional(),format:z.enum([`json`,`markdown`,`mermaid`]).optional(),max_tokens:Xo,filter:z.string().optional().describe(`Filter symbols by name substring`),diagram_type:z.enum([`architecture`,`dependencies`]).optional().describe(`Type of diagram when aspect="diagram"`),enrich:ss});async function hs(e,t,n,r){return!n||!r?e:e+K(await G(r,{query:t,filePath:t}))}async function gs(e,{store:t,embedder:n,enrichDeps:r}){let i=new Rn,{path:a,max_depth:o,format:s,max_tokens:c,enrich:l}=cs.parse(e),u=await i.analyze(a,{format:s,maxDepth:o,maxTokens:c});is(t,n,`structure`,a,u.output);let d=u.data;return{content:[{type:`text`,text:Zo(await hs(u.output+'\n\n---\n_Analysis auto-saved to AI Kit memory. Next: Use `analyze({ aspect: "dependencies", ... })` for import graphs, or `analyze({ aspect: "patterns", ... })` to detect architecture patterns._',a,l,r),c)}],structuredContent:{files:d.fileCount??u.meta.fileCount,packages:d.packageCount??0,languages:d.languages??{},tree:u.output.slice(0,2e3)}}}async function _s(e,{store:t,embedder:n,enrichDeps:r}){let i=new Nn,{path:a,format:o,max_tokens:s,enrich:c}=ls.parse(e),l=await i.analyze(a,{format:o});return is(t,n,`dependencies`,a,l.output),{content:[{type:`text`,text:Zo(await hs(l.output+'\n\n---\n_Analysis auto-saved to AI Kit memory. Next: Use `analyze({ aspect: "symbols", ... })` to explore exported symbols, or `analyze({ aspect: "diagram", ... })` for visual representation._',a,c,r),s)}]}}async function vs(e,{store:t,embedder:n,enrichDeps:r}){let i=new zn,{path:a,filter:o,format:s,enrich:c}=us.parse(e),l=await i.analyze(a,{format:s,filter:o});return is(t,n,`symbols`,a,l.output),{content:[{type:`text`,text:await hs(l.output+Qo()+'\n\n---\n_Analysis auto-saved to AI Kit memory. Next: Use `analyze({ aspect: "dependencies", ... })` to see import relationships, or `search` to find usage patterns._',a,c,r)}]}}async function ys(e,{store:t,embedder:n,enrichDeps:r}){let i=new Ln,{path:a,enrich:o}=ds.parse(e),s=await i.analyze(a);return is(t,n,`patterns`,a,s.output),{content:[{type:`text`,text:await hs(s.output+Qo()+'\n\n---\n_Analysis auto-saved to AI Kit memory. Next: Use `analyze({ aspect: "entry_points", ... })` to find Lambda handlers and main exports, or `produce_knowledge` for full analysis._',a,o,r)}]}}async function bs(e,{store:t,embedder:n,enrichDeps:r}){let i=new Fn,{path:a,enrich:o}=fs.parse(e),s=await i.analyze(a);return is(t,n,`entry-points`,a,s.output),{content:[{type:`text`,text:await hs(s.output+Qo()+'\n\n---\n_Analysis auto-saved to AI Kit memory. Next: Use `analyze({ aspect: "dependencies", ... })` to see what each entry point imports, or `produce_knowledge` for comprehensive analysis._',a,o,r)}]}}async function xs(e,{store:t,embedder:n,enrichDeps:r}){let i=new Pn,{path:a,diagram_type:o,enrich:s}=ps.parse(e),c=await i.analyze(a,{diagramType:o});return is(t,n,`diagram`,a,c.output),{content:[{type:`text`,text:await hs(c.output+'\n\n---\n_Analysis auto-saved to AI Kit memory. Next: Use `analyze({ aspect: "structure", ... })` for detailed file tree, or `produce_knowledge` for comprehensive analysis._',a,s,r)}]}}async function Ss(e,t,n){switch(e){case`structure`:return gs(t,n);case`dependencies`:return _s(t,n);case`symbols`:return vs(t,n);case`patterns`:return ys(t,n);case`entry_points`:return bs(t,n);case`diagram`:return xs(t,n)}}function Cs(e,t,n,r){let i=W(`analyze`);e.registerTool(`analyze`,{title:i.title,description:"Analyze a codebase using one of the supported aspects. Set `aspect` to structure, dependencies, symbols, patterns, entry_points, or diagram.",inputSchema:ms.shape,annotations:i.annotations},J(`analyze`,async e=>{try{let i=ms.parse(e);return await Ss(i.aspect,i,{store:t,embedder:n,enrichDeps:r})}catch(e){return Yo.error(`Analysis failed`,L(e)),q(`INTERNAL`,`Analysis failed: ${e instanceof Error?e.message:String(e)}`)}}))}function ws(e,t,n,r,i){let a=new Mn,o=W(`blast_radius`);e.registerTool(`blast_radius`,{title:o.title,description:`Given a list of changed files, trace the dependency graph to find all affected files (direct + transitive importers) and their tests. Useful for scoping code reviews and impact analysis.`,outputSchema:No,inputSchema:{path:z.string().describe(`Root path of the codebase`),files:z.array(z.string()).optional().describe(`Changed file paths (relative to root). If omitted, auto-detects from git status.`),max_depth:z.number().min(1).max(20).default(5).describe(`Maximum transitive dependency depth`),format:z.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`),max_tokens:Xo,enrich:z.boolean().default(!0).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default true for planning tools — set false to save tokens when enrichment is not needed.`)},annotations:o.annotations},J(`blast_radius`,async({path:e,files:o,max_depth:s,format:c,max_tokens:l,enrich:u})=>{try{let d=o??[];if(d.length===0)try{let t=await at({cwd:e,includeDiff:!1});if(d=Array.from(new Set([...$o(t.status?.staged),...$o(t.status?.modified),...$o(t.status?.untracked)])),d.length===0)return{content:[{type:`text`,text:"No changed files detected from git status. Provide `files` explicitly or make changes first."}]}}catch{return q(`VALIDATION`,"Could not detect changed files from git. Provide `files` explicitly.")}let f=await a.analyze(e,{files:d,maxDepth:s,format:c}),p=[],m=``;if(r)try{p=await rs(r,d),p.length>0&&(m=`\n\n### Graph-discovered importers (${p.length})\n`+p.slice(0,20).map(e=>`- \`${e}\``).join(`
32
+ `),p.length>20&&(m+=`\n- ... and ${p.length-20} more`))}catch{}let h=ns(d),g=es(d),_=f.output+m+h+g+Qo()+'\n\n---\n_Analysis auto-saved to AI Kit memory. Next: Use `analyze({ aspect: "dependencies", ... })` to see the full import graph, or `analyze({ aspect: "symbols", ... })` to inspect affected exports._';if(u&&i){let t=await G(i,{query:e,filePath:e});_+=K(t)}is(t,n,`blast-radius`,e,_);let v=p.map(e=>({path:e,impact:`transitive`,reason:`imports changed file`})),y=d.length>10?`high`:d.length>3?`medium`:`low`;return{content:[{type:`text`,text:Zo(_,l)}],structuredContent:{changedFiles:d,affectedFiles:v,totalAffected:v.length,riskLevel:y}}}catch(e){return Yo.error(`Blast radius analysis failed`,L(e)),q(`INTERNAL`,`Blast radius analysis failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Ts=I(`task-manager`);let Es=0;function Ds(e){let t=typeof e?.sendNotification==`function`;return{createTask(n,r){let i=`aikit-task-${++Es}`,a=(n,r,a)=>{t&&e.sendNotification?.({method:`notifications/progress`,params:{progressToken:i,progress:n,total:r,...a?{message:a}:{}}}).catch(e=>{Ts.debug(`Progress notification failed`,{token:i,error:String(e)})})};return t&&Ts.debug(`Task created`,{token:i,title:n,totalSteps:r}),{progress(e,t){a(e,r,t??`${n}: step ${e+1}/${r}`)},complete(e){a(r,r,e??`${n}: complete`)},fail(e){a(r,r,e??`${n}: failed`)}}}}}const Os=I(`tools`);function ks(e,t,n,r){let i=W(`audit`);e.registerTool(`audit`,{title:i.title,description:`Run a unified audit: structure, dependencies, patterns, health, dead_symbols, check, entry_points. Returns synthesized report with score, recommendations, and next steps. 6 round-trips → 1.`,outputSchema:Fo,inputSchema:{path:z.string().default(`.`).describe(`Root path to audit`),checks:z.array(z.enum([`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`])).optional().describe(`Which checks to run (default: all)`),detail:z.enum(me).optional().describe(`'efficient' for overview (~500 tokens), 'full' includes pattern table`)},annotations:i.annotations},async({path:e,checks:i,detail:a},o)=>{try{let s=await we(t,n,{path:e,checks:i,detail:a??r??`efficient`});return Ds(o).createTask(`Audit`,1).complete(`Audit complete: ${s.data?.recommendations?.length??0} recommendations`),{content:[{type:`text`,text:s.ok?`${s.summary}\n\n---\n_Audit score: ${s.data?.score}/100 | ${s.meta.durationMs}ms${s.next&&s.next.length>0?` | Next: ${s.next.map(e=>`\`${e.tool}\` (${e.reason})`).join(`, `)}`:``}_`:s.error?.message??`Audit failed`}],isError:!s.ok,...s.ok&&s.data?{structuredContent:{passed:s.ok,score:s.data.score??0,checks:(s.data.recommendations??[]).map(e=>({name:e.area,passed:e.priority!==`high`,message:e.message,severity:e.priority})),summary:s.summary??``}}:{}}}catch(e){return Os.error(`Audit failed`,L(e)),q(`INTERNAL`,`Audit failed: ${e instanceof Error?e.message:String(e)}`)}})}const As=I(`tools`);function js(e){if(!e?.enabled)return;let t=process.env.AIKIT_ER_API_KEY;if(!t){As.warn(`ER bridge enabled but AIKIT_ER_API_KEY not set; disabling`);return}return{enabled:!0,baseUrl:e.baseUrl,apiKey:t,timeoutMs:e.timeoutMs??5e3,cacheTtlMs:e.cacheTtlMs??360*60*1e3,cacheMaxEntries:e.cacheMaxEntries??100,fallbackThreshold:e.fallbackThreshold??.45}}function Ms(e){let t=js(e);if(t)try{let e=new Wn(t),n=new Un({maxEntries:t.cacheMaxEntries,defaultTtl:t.cacheTtlMs}),r=new qn(e);try{let e=new URL(t.baseUrl).hostname;As.info(`ER bridge initialized`,{host:e})}catch{As.info(`ER bridge initialized`)}return{client:e,cache:n,pushAdapter:r,config:t}}catch(e){As.warn(`ER bridge initialization failed`,L(e));return}}function Ns(e,t,n){let r=W(`er_push`);e.registerTool(`er_push`,{title:r.title,description:`Push a curated knowledge entry to Enterprise RAG. The entry is stored via ER's curated_remember tool and becomes immediately searchable in the enterprise AI Kit.`,inputSchema:{title:z.string().min(3).max(120).describe(`Title for the knowledge entry`),content:z.string().min(10).max(1e5).describe(`Markdown content to push (max 100KB)`),category:z.string().regex(/^[a-z][a-z0-9-]*$/).default(`conventions`).describe(`Category slug (e.g., "decisions", "patterns", "conventions")`),tags:z.array(z.string()).default([]).describe(`Optional tags`),rule_id:z.string().optional().describe(`ID of the classification rule that motivated this push (from remember classification signals). Improves rule effectiveness tracking.`)},annotations:r.annotations},J(`er_push`,async({title:e,content:r,category:i,tags:a,rule_id:o})=>{try{let s=`${i}/${e.toLowerCase().replace(/[^a-z0-9]+/g,`-`)}`,c=await t.pushAdapter.push(s,{title:e,content:r,category:i,tags:a});return c.pushed?(n&&n.recordPush(s,c.pushed,o),{content:[{type:`text`,text:`Pushed to ER: **${e}**\n\nRemote path: \`${c.remotePath??`unknown`}\`\nTimestamp: ${c.timestamp}\n\n---\n_Next: Use \`er_pull\` to verify the entry is searchable in ER, or \`er_sync_status\` to see push history._`}]}):(n&&n.recordPush(s,!1,o),q(`INTERNAL`,`ER push failed: ${c.error??`Unknown error`}\n\n_The local AI Kit is unaffected. You can retry or check ER health with \`er_sync_status\`._`))}catch(t){if(As.error(`ER push failed`,L(t)),n){let t=`${i}/${e.toLowerCase().replace(/[^a-z0-9]+/g,`-`)}`;n.recordPush(t,!1,o)}return q(`INTERNAL`,`ER push failed: operation unsuccessful
33
+
34
+ _The local AI Kit is unaffected. You can retry or check ER health with \`er_sync_status\`._`)}}))}function Ps(e,t){let n=W(`er_pull`);e.registerTool(`er_pull`,{title:n.title,description:`Explicitly search the Enterprise RAG AI Kit. Returns results from the enterprise system only (not local AI Kit). Uses a cache with 6-hour TTL to reduce API calls.`,inputSchema:{query:z.string().min(1).max(2e3).describe(`Search query for Enterprise RAG AI Kit (max 2000 chars)`),max_results:z.number().min(1).max(20).default(5).describe(`Maximum results to return`),bypass_cache:z.boolean().default(!0).describe(`Skip cache and fetch fresh results from ER (default: true per DR-001)`)},annotations:n.annotations},J(`er_pull`,async({query:e,max_results:n,bypass_cache:r})=>{try{if(!r){let r=t.cache.get(e);if(r)return{content:[{type:`text`,text:`${r.slice(0,n).map((e,t)=>`### Result ${t+1} (score: ${e.score.toFixed(3)}, source: ER cached)\n- **Source**: ${e.sourcePath}\n\n${e.content}`).join(`
35
+
36
+ ---
37
+
38
+ `)}\n\n---\n_Source: ER cache (${r.length} cached results) | Use \`bypass_cache: true\` for fresh results_`}]}}let i=await t.client.pull(e,n);return i.length>0&&t.cache.set(e,i),i.length===0?{content:[{type:`text`,text:`No results found in Enterprise RAG for the given query.`}]}:{content:[{type:`text`,text:`${i.map((e,t)=>`### Result ${t+1} (score: ${e.score.toFixed(3)}, source: ER)\n- **Source**: ${e.sourcePath}\n\n${e.content}`).join(`
39
+
40
+ ---
41
+
42
+ `)}\n\n---\n_Source: Enterprise RAG (${i.length} results) | Results cached for ${Math.floor(t.config.cacheTtlMs/36e5)}h_`}]}}catch(e){return As.error(`ER pull failed`,L(e)),q(`INTERNAL`,`ER pull failed: search request unsuccessful
43
+
44
+ _Enterprise RAG may be unavailable. Local AI Kit search is unaffected._`)}}))}function Fs(e,t){let n=W(`er_sync_status`);e.registerTool(`er_sync_status`,{title:n.title,description:`Show the status of the Enterprise RAG bridge: health, cache stats, and push history.`,inputSchema:{check_health:z.boolean().default(!0).describe(`Whether to ping ER health endpoint (adds latency)`)},annotations:n.annotations},J(`er_sync_status`,async({check_health:e})=>{try{let n=t.cache.stats(),r=t.pushAdapter.getStatus(),i=new URL(t.config.baseUrl),a=`${i.protocol}//${i.hostname}${i.port?`:${i.port}`:``}`,o=`_Health check skipped_`;if(e){let e=await t.client.health();o=e.healthy?`✅ Healthy (HTTP ${e.status})`:`❌ Unhealthy${e.status?` (HTTP ${e.status})`:``}`}let s=[`## ER Bridge Status
45
+ `,`**Endpoint**: \`${a}\``,`**Health**: ${o}`,`**Threshold**: ${t.config.fallbackThreshold} (vector similarity for auto-fallback)`,``,`### Cache`,`- Entries: ${n.size} / ${n.maxEntries}`,`- TTL: ${Math.floor(n.defaultTtlMs/36e5)}h`,``,`### Push History`,`- Total pushed: ${r.totalPushed}`,`- Successful: ${r.successCount}`,`- Failed: ${r.failCount}`];return r.lastPush&&s.push(`- Last push: "${r.lastPush.title}" at ${r.lastPush.pushedAt} (${r.lastPush.status})`),s.push("\n---\n_Next: Use `er_push` to send knowledge to ER, or `er_pull` to search ER._"),{content:[{type:`text`,text:s.join(`
46
+ `)}]}}catch(e){return As.error(`ER sync status failed`,L(e)),q(`INTERNAL`,`ER sync status failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Is=I(`tools`);function Ls(e){let t=[`Compliance score: ${e.score}/100`,`Calls scored: ${e.totalCalls}`,`Summary: ${e.summary}`];if(e.violations.length===0)return`${t.join(`
47
+ `)}\n\nNo violations detected.`;let n=e.violations.map(e=>`- ${e.ruleId} | ${e.tool} | ${e.timestamp}\n ${e.rule}\n Suggestion: ${e.suggestion}`);return`${t.join(`
48
+ `)}\n\nViolations:\n${n.join(`
49
+ `)}`}function Rs(e){let t=W(`compliance_score`);e.registerTool(`compliance_score`,{title:t.title,description:`Score replay log compliance against AI Kit tool-routing rules and surface violations with remediation guidance.`,inputSchema:{last_n:z.number().min(1).max(500).default(50).describe(`Maximum number of recent replay entries to score (default: 50)`)},annotations:t.annotations},J(`compliance_score`,async({last_n:e})=>{try{return{content:[{type:`text`,text:Ls(Xt(Wt({last:e}),{lastN:e}))}]}}catch(e){return Is.error(`Compliance score failed`,L(e)),q(`INTERNAL`,`Compliance score failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Y(e){return String(e??``).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}const zs=z.object({action:z.enum([`view`,`update`]).default(`view`).describe(`Action to perform: view current configuration or update it`),updates:z.record(z.string(),z.unknown()).optional().describe(`Partial configuration to merge when action is "update". Supports nested paths like { "indexing": { "chunkSize": 2000 } }`)}),Bs=I(`config-tool`),Vs=`ui://aikit/config.html`,Hs=[`serverName`,`toolPrefix`,`autoIndex`,`sources`,`indexing`,`tokenBudget`];function Us(){let e=process.env.AIKIT_CONFIG_PATH;if(e&&k(e))return e;let t=F(process.cwd(),`aikit.config.json`);return k(t)?t:``}function Ws(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gs(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(Ws(t)&&Ws(r)){n[e]=Gs(t,r);continue}n[e]=r}return n}function Ks(e){return e===void 0?`undefined`:JSON.stringify(e)}function qs(e,t,n,r=``){let i=[];for(let[a,o]of Object.entries(n)){let n=r?`${r}.${a}`:a,s=e[a],c=t[a];if(Ws(o)&&Ws(s)&&Ws(c)){i.push(...qs(s,c,o,n));continue}Ks(s)!==Ks(c)&&i.push(`- ${n}: ${Ks(s)} -> ${Ks(c)}`)}return i}function Js(e){let t=[];for(let[n,r]of Object.entries(e)){if(n===`store`||n===`embedding`||n===`er`){t.push(`Field "${n}" cannot be updated through this tool because it requires a restart.`);continue}if(n===`onboardDir`||n===`stateDir`||n===`curated`){t.push(`Field "${n}" cannot be updated through this tool because it requires a restart.`);continue}if(n===`autoIndex`){typeof r!=`boolean`&&t.push(`autoIndex must be a boolean.`);continue}if(n===`serverName`||n===`toolPrefix`){typeof r!=`string`&&t.push(`${n} must be a string.`);continue}if(n===`sources`){(!Array.isArray(r)||r.length===0)&&t.push(`sources must be a non-empty array.`);continue}if(n===`indexing`){if(!Ws(r)){t.push(`indexing must be an object.`);continue}for(let[e,n]of Object.entries(r)){if(e!==`chunkSize`&&e!==`chunkOverlap`&&e!==`minChunkSize`&&e!==`concurrency`){t.push(`indexing.${e} is not updatable through this tool.`);continue}(typeof n!=`number`||!Number.isFinite(n)||n<=0)&&t.push(`indexing.${e} must be a positive number.`)}continue}if(n===`tokenBudget`){(typeof r!=`string`||!me.includes(r))&&t.push(`tokenBudget must be one of: ${me.join(`, `)}.`);continue}t.push(`Field "${n}" is not updatable through this tool.`)}return t}function Ys(e){let t=[];if(`autoIndex`in e&&typeof e.autoIndex!=`boolean`&&t.push(`autoIndex must be a boolean.`),`serverName`in e&&e.serverName!==void 0&&typeof e.serverName!=`string`&&t.push(`serverName must be a string.`),`toolPrefix`in e&&e.toolPrefix!==void 0&&typeof e.toolPrefix!=`string`&&t.push(`toolPrefix must be a string.`),(!Array.isArray(e.sources)||e.sources.length===0)&&t.push(`sources must be a non-empty array.`),!Ws(e.indexing))return t.push(`indexing must be an object.`),t;for(let n of[`chunkSize`,`chunkOverlap`,`minChunkSize`,`concurrency`]){let r=e.indexing[n];r!==void 0&&(typeof r!=`number`||!Number.isFinite(r)||r<=0)&&t.push(`indexing.${n} must be a positive number.`)}return t}function Xs(e){let t=JSON.parse(j(e,`utf-8`));if(!Ws(t))throw Error(`Config file must contain a JSON object.`);return t}function Zs(e,t){return[`AI Kit Configuration`,`Config file: ${t}`,``,JSON.stringify(e,null,2)].join(`
50
+ `)}function Qs(e){return e===void 0?``:Ws(e)||Array.isArray(e)?JSON.stringify(e,null,2):String(e)}function $s(e){let t=e.metrics??[],n={success:`#22c55e`,warning:`#f59e0b`,error:`#ef4444`,info:`#38bdf8`},r={up:`↑`,down:`↓`,neutral:`→`};return`
51
+ <style>
52
+ .db-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px}
53
+ .db-card{padding:14px;border:1px solid var(--aikit-border,#3c3c3c);border-left-width:4px;border-radius:8px;background:var(--aikit-surface,#252526)}
54
+ .db-label{color:var(--aikit-muted,#9ca3af);font:600 11px var(--aikit-font-sans,system-ui,sans-serif);text-transform:uppercase;letter-spacing:.06em}
55
+ .db-value{color:var(--aikit-text,#e5e7eb);font:700 24px var(--aikit-font-sans,system-ui,sans-serif);margin-top:6px}
56
+ .db-trend{font:600 12px var(--aikit-font-sans,system-ui,sans-serif);margin-left:8px}
57
+ .db-trend.up{color:#22c55e}.db-trend.down{color:#ef4444}.db-trend.neutral{color:#9ca3af}
58
+ .db-progress{height:6px;background:var(--aikit-surface2,#2d2d30);border-radius:3px;margin-top:8px;overflow:hidden}
59
+ .db-progress-bar{height:100%;border-radius:3px;transition:width .3s}
60
+ .db-list{margin-top:8px;display:grid;gap:4px}
61
+ .db-list-row{display:flex;justify-content:space-between;padding:4px 0;color:var(--aikit-muted,#9ca3af);font:400 12px var(--aikit-font-sans,system-ui,sans-serif);border-bottom:1px solid var(--aikit-border,#3c3c3c)}
62
+ </style>
63
+ <div class="db-grid">${t.map(e=>{let t=n[e.status??`info`]??n.info,i=e.trend?`<span class="db-trend ${e.trend.direction}">${r[e.trend.direction]??``} ${Y(e.trend.value)}</span>`:``,a=`<div class="db-value">${Y(String(e.value))}</div>${i}`;return e.type===`progress`&&e.progress!=null&&(a+=`<div class="db-progress"><div class="db-progress-bar" style="width:${Math.min(100,Math.max(0,e.progress))}%;background:${t}"></div></div>`),e.type===`list`&&e.items?.length&&(a+=`<div class="db-list">${e.items.map(e=>`<div class="db-list-row"><span>${Y(e.label)}</span><span>${Y(e.value)}</span></div>`).join(``)}</div>`),`
64
+ <div class="db-card" style="border-left-color:${t}">
65
+ <div class="db-label">${Y(e.label)}</div>
66
+ ${a}
67
+ </div>`}).join(``)}</div>`}function ec(e){let t=e.fields??[];return`
68
+ <style>
69
+ .fm-container{display:grid;grid-template-columns:1fr 280px;gap:24px}
70
+ @media(max-width:640px){.fm-container{grid-template-columns:1fr}}
71
+ .fm-fields{display:flex;flex-direction:column;gap:16px}
72
+ .fm-group{display:flex;flex-direction:column;gap:5px}
73
+ .fm-label{font-size:11px;color:var(--aikit-muted);font-weight:600;text-transform:uppercase;letter-spacing:.5px}
74
+ .fm-input{padding:9px 14px;background:var(--aikit-surface);border:1px solid var(--aikit-border);
75
+ border-radius:8px;color:var(--aikit-text);font-size:13px;outline:none;font-family:inherit;width:100%;box-sizing:border-box}
76
+ .fm-input:focus{border-color:var(--aikit-accent)}
77
+ .fm-textarea{resize:vertical;min-height:80px}
78
+ .fm-multi{display:flex;flex-wrap:wrap;gap:10px;padding:4px 0}
79
+ .fm-check-label{display:flex;align-items:center;gap:4px;font-size:13px;color:var(--aikit-text);cursor:pointer}
80
+ .fm-check-label input{accent-color:var(--aikit-accent)}
81
+ .fm-submit{margin-top:8px;width:100%;padding:10px;background:var(--aikit-accent);color:#fff;
82
+ border:none;border-radius:8px;cursor:pointer;font-size:14px;font-weight:600}
83
+ .fm-submit:hover{filter:brightness(1.1)}
84
+ .fm-preview{background:var(--aikit-surface);border:1px solid var(--aikit-border);border-radius:10px;
85
+ padding:16px;height:fit-content;position:sticky;top:20px}
86
+ .fm-preview-title{font-size:11px;color:var(--aikit-muted);text-transform:uppercase;
87
+ letter-spacing:.5px;margin-bottom:10px}
88
+ .fm-preview-json{font-size:12px;color:var(--aikit-text);margin:0;white-space:pre-wrap;
89
+ word-break:break-all;font-family:'SF Mono',Consolas,monospace;line-height:1.5}
90
+ </style>
91
+ <div class="fm-container">
92
+ <div class="fm-fields" id="fmFields">
93
+ ${t.map(e=>{let t=e.type??`text`,n;if(t===`select`&&e.options){let t=e.options.map(t=>`<option value="${Y(t)}"${t===e.value?` selected`:``}>${Y(t)}</option>`).join(``);n=`<select class="fm-input" data-field="${Y(e.name)}">${t}</select>`}else n=t===`textarea`?`<textarea class="fm-input fm-textarea" data-field="${Y(e.name)}" rows="4">${Y(e.value??``)}</textarea>`:t===`multi-select`&&e.options?`<div class="fm-multi">${e.options.map(t=>`<label class="fm-check-label"><input type="checkbox" data-field="${Y(e.name)}" value="${Y(t)}"${e.value?.includes(t)?` checked`:``}> ${Y(t)}</label>`).join(``)}</div>`:`<input class="fm-input" type="${Y(t)}" data-field="${Y(e.name)}" value="${Y(e.value??``)}">`;return`<div class="fm-group"><label class="fm-label">${Y(e.label)}</label>${n}</div>`}).join(``)}
94
+ <button class="fm-submit" id="fmSubmit">Submit</button>
95
+ </div>
96
+ <div class="fm-preview">
97
+ <div class="fm-preview-title">Live Preview</div>
98
+ <pre class="fm-preview-json" id="fmPreview">{}</pre>
99
+ </div>
100
+ </div>
101
+ <script>
102
+ (function(){
103
+ const fields = document.getElementById('fmFields');
104
+ const preview = document.getElementById('fmPreview');
105
+ const fieldDefs = ${JSON.stringify(t.map(e=>({name:e.name,type:e.type??`text`})))};
106
+
107
+ function getValues() {
108
+ const vals = {};
109
+ fieldDefs.forEach(f => {
110
+ if(f.type === 'multi-select') {
111
+ vals[f.name] = [...fields.querySelectorAll('input[data-field="'+f.name+'"]:checked')].map(cb => cb.value).join(', ');
112
+ } else {
113
+ const el = fields.querySelector('[data-field="'+f.name+'"]');
114
+ if(el) vals[f.name] = el.value;
115
+ }
116
+ });
117
+ return vals;
118
+ }
119
+
120
+ function updatePreview() { preview.textContent = JSON.stringify(getValues(), null, 2); }
121
+ fields.addEventListener('input', updatePreview);
122
+ fields.addEventListener('change', updatePreview);
123
+ updatePreview();
124
+
125
+ document.getElementById('fmSubmit').addEventListener('click', () => {
126
+ if(window.__aikitCallback) {
127
+ fetch(window.__aikitCallback, {method:'POST',headers:{'Content-Type':'application/json'},
128
+ body:JSON.stringify({actionId:'submit',value:JSON.stringify(getValues())})}).catch(()=>{});
129
+ }
130
+ });
131
+ })();
132
+ <\/script>`}function tc(e){return $s({metrics:Object.entries(e).map(([e,t])=>({label:e,value:Ws(t)||Array.isArray(t)?JSON.stringify(t,null,2):String(t),status:`info`}))})}function nc(e){return ec({fields:Hs.map(t=>{let n=e[t];return typeof n==`boolean`?{name:t,label:t,type:`select`,options:[`true`,`false`],value:String(n)}:{name:t,label:t,type:Ws(n)||Array.isArray(n)?`textarea`:`text`,value:Qs(n)}})})}function rc(e,t){return`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${e}</title><style>:root{--aikit-bg:#1e1e1e;--aikit-surface:#252526;--aikit-surface2:#2d2d30;--aikit-border:#3c3c3c;--aikit-text:#e5e7eb;--aikit-muted:#9ca3af;--aikit-accent:#60a5fa;--aikit-success:#22c55e;font-family:system-ui,sans-serif}body{margin:0;padding:20px;background:var(--aikit-bg);color:var(--aikit-text);font-family:system-ui,sans-serif}h2{margin:0 0 16px}</style></head><body><h2>${e}</h2>${t}</body></html>`}function ic(e){let t=``,n=``,r=!1;return function(i,a){t=i,n=a,!r&&(r=!0,Xn(e,`AI Kit Config App`,Vs,{description:`View and update AI Kit configuration`},async()=>({contents:[{uri:Vs,mimeType:Yn,text:rc(t,n)}]})))}}function ac(e,t){let n=W(`config`),r=ic(e);Zn(e,`config`,{title:n.title,description:`View and update AI Kit server configuration. Use action "view" to see current settings, or "update" to modify configuration values. Changes are written to aikit.config.json and take effect on next server restart. Some settings (store, embedding) require a full restart.`,inputSchema:zs,annotations:n.annotations,_meta:{ui:{resourceUri:Vs}}},J(`config`,async e=>{let{action:n,updates:i}=e;if(t.readOnly&&n!==`view`)return q(`PERMISSION`,`Configuration updates are disabled in read-only mode`);if(n===`view`){let e=Us(),n=e||`(runtime config only; no aikit.config.json found)`;try{let i=e?Xs(e):t,a=Zs(i,n);return r(`Configuration`,tc(i)),{content:[{type:`text`,text:a}],ui:{type:`resource`,uri:Vs}}}catch(t){return Bs.error(`Failed to read config for view`,{configPath:e,error:t instanceof Error?t.message:String(t)}),{content:[{type:`text`,text:`Failed to read configuration from ${n}: ${t instanceof Error?t.message:String(t)}`}]}}}if(!i)return r(`Configuration Form`,nc(t)),{content:[{type:`text`,text:`No updates provided. Pass an updates object when action is "update".`}],ui:{type:`resource`,uri:Vs}};let a=Us();if(!a)return r(`Configuration Form`,nc(t)),{content:[{type:`text`,text:`No config file found to update.`}],ui:{type:`resource`,uri:Vs}};let o=Js(i);if(o.length>0)return r(`Configuration Form`,nc(Xs(a))),{content:[{type:`text`,text:`Configuration update rejected:\n${o.map(e=>`- ${e}`).join(`
133
+ `)}`}],ui:{type:`resource`,uri:Vs}};try{let e=Xs(a),t=Gs(e,i),n=Ys(t);if(n.length>0)return r(`Configuration Form`,nc(e)),{content:[{type:`text`,text:`Configuration update rejected:\n${n.map(e=>`- ${e}`).join(`
134
+ `)}`}],ui:{type:`resource`,uri:Vs}};N(a,JSON.stringify(t,null,2),`utf-8`);let o=qs(e,t,i),s=`Configuration updated successfully.
135
+
136
+ Config file: ${a}
137
+
138
+ Changed values:
139
+ ${o.length>0?o.join(`
140
+ `):`- No effective changes; requested values already matched the file.`}
141
+
142
+ These changes take effect on the next server restart.`;return r(`Configuration`,tc(t)),{content:[{type:`text`,text:s}],ui:{type:`resource`,uri:Vs}}}catch(e){return Bs.error(`Failed to update config`,{configPath:a,error:e instanceof Error?e.message:String(e)}),{content:[{type:`text`,text:`Failed to update configuration in ${a}: ${e instanceof Error?e.message:String(e)}`}]}}})),r(`Configuration`,tc(t))}const oc=I(`cross-workspace`);function sc(e,t){if(!ye())return[];let n=be();if(n.length===0)return[];if(e.includes(`*`))return t?n.filter(e=>e.partition!==t):n;let r=[];for(let i of e){let e=n.find(e=>e.partition===i);if(e){e.partition!==t&&r.push(e);continue}let a=n.filter(e=>e.partition!==t&&e.partition.replace(/-[a-f0-9]{8}$/,``)===i.toLowerCase());r.push(...a)}let i=new Set;return r.filter(e=>i.has(e.partition)?!1:(i.add(e.partition),!0))}async function cc(e){let t=new Map;for(let n of e)try{let e=await nr({backend:`sqlite-vec`,path:ve(n.partition)});await e.initialize(),t.set(n.partition,e)}catch(e){oc.warn(`Failed to open workspace store`,{partition:n.partition,err:e})}return{stores:t,closeAll:async()=>{for(let[,e]of t)try{await e.close()}catch{}}}}async function lc(e,t,n){let r=[...e.entries()].map(async([e,r])=>{try{return(await r.search(t,n)).map(t=>({...t,workspace:e}))}catch(t){return oc.warn(`Cross-workspace search failed for partition`,{partition:e,err:t}),[]}});return(await Promise.all(r)).flat().sort((e,t)=>t.score-e.score).slice(0,n.limit)}async function uc(e,t,n){let r=[...e.entries()].map(async([e,r])=>{try{return(await r.ftsSearch(t,n)).map(t=>({...t,workspace:e}))}catch(t){return oc.warn(`Cross-workspace FTS search failed for partition`,{partition:e,err:t}),[]}});return(await Promise.all(r)).flat().sort((e,t)=>t.score-e.score).slice(0,n.limit)}function dc(e){return e.toLowerCase().replace(/[-_]/g,``)}function fc(e){let t=ie(e),n=dc(re(e));try{let e=M(t);for(let r of e)if(dc(r)===n){let e=F(t,r);if(k(e))return e}}catch{}}function pc(e,t,n){if(ae(e))return k(e)?e:fc(e)||e;let r=F(t,e);if(k(r))return r;let i=fc(r);if(i)return i;if(n)for(let r of n){if(r===t)continue;let n=F(r,e);if(k(n))return n;let i=fc(n);if(i)return i}try{let n=M(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith(`.`)||r.name===`node_modules`)continue;let n=F(t,r.name,e);if(k(n))return n;let i=fc(n);if(i)return i}}catch{}return r}const mc=I(`tools:context`);function hc(e,t,n,r){if(!r||!e)return;let i=e.replace(/\\/g,`/`);if(![t,...n??[]].map(e=>e.replace(/\\/g,`/`)).some(e=>{let t=e.endsWith(`/`)?e.slice(0,-1):e;return i===t||i.startsWith(`${t}/`)}))try{r(e)}catch{}}function gc(e,t,n,r,i,a,o){let s=W(`compact`);e.registerTool(`compact`,{title:s.title,description:"Compress text to relevant sections using embedding similarity (no LLM). Provide either `text` or `path` (server reads the file — saves a round-trip). Segments by paragraph/sentence/line.",outputSchema:Ho,inputSchema:{text:z.string().optional().describe(`The text to compress (provide this OR path, not both)`),path:z.string().optional().describe(`File path to read server-side — avoids read_file round-trip + token doubling (provide this OR text)`),query:z.string().describe(`Focus query — what are you trying to understand?`),max_chars:z.number().min(100).max(5e4).default(3e3).describe(`Target output size in characters`),segmentation:z.enum([`paragraph`,`sentence`,`line`]).default(`paragraph`).describe(`How to split the text for scoring`),token_budget:z.number().min(50).max(12500).optional().describe(`Token budget — overrides max_chars (approx 4 chars per token). Use to fit output into a specific context window.`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context for the file/query.`)},annotations:s.annotations},J(`compact`,async({text:e,path:s,query:c,max_chars:l,segmentation:u,token_budget:d,enrich:f})=>{try{let p=s?pc(s,r,i):void 0;if(!e&&!p)return q(`VALIDATION`,`Either "text" or "path" must be provided.`);let m=await Ie(t,{text:e,path:p,query:c,maxChars:l,tokenBudget:d,segmentation:u,cache:n});hc(p,r,i,o);let h=[`Compressed ${m.originalChars} → ${m.compressedChars} chars (${(m.ratio*100).toFixed(0)}%)`,`Kept ${m.segmentsKept}/${m.segmentsTotal} segments`,``,m.text].join(`
143
+ `);if(f&&a){let e=await G(a,{query:c,filePath:p});h+=K(e)}return{content:[{type:`text`,text:h}],structuredContent:{originalChars:m.originalChars,compressedChars:m.compressedChars,ratio:m.ratio,segmentsKept:m.segmentsKept,segmentsTotal:m.segmentsTotal}}}catch(e){return mc.error(`Compact failed`,L(e)),{...q(`INTERNAL`,`Compact failed: ${e instanceof Error?e.message:String(e)}`),structuredContent:{originalChars:0,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0}}}}))}function _c(e,t,n,r){let i=W(`scope_map`);e.registerTool(`scope_map`,{title:i.title,description:`Generate a task-scoped reading plan. Given a task description, identifies which files and sections are relevant, with estimated token counts and suggested reading order.`,outputSchema:jo,inputSchema:{task:z.string().describe(`Description of the task to scope`),max_files:z.number().min(1).max(50).default(15).describe(`Maximum files to include`),content_type:z.enum(ue).optional().describe(`Filter by content type`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),enrich:z.boolean().default(!0).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default true for planning tools — set false to save tokens when enrichment is not needed.`)},annotations:i.annotations},J(`scope_map`,async({task:e,max_files:i,content_type:a,max_tokens:o,enrich:s})=>{try{let c=await Yt(t,n,{task:e,maxFiles:i,contentType:a}),l=[`## Scope Map: ${e}`,`Total estimated tokens: ~${c.totalEstimatedTokens}`,``,`### Files (by relevance)`,...c.files.map((e,t)=>`${t+1}. **${e.path}** (~${e.estimatedTokens} tokens, ${(e.relevance*100).toFixed(0)}% relevant)\n ${e.reason}\n Focus: ${e.focusRanges.map(e=>`L${e.start}-${e.end}`).join(`, `)}`),``,`### Suggested Reading Order`,...c.readingOrder.map((e,t)=>`${t+1}. ${e}`),``,`### Suggested Compact Calls`,`_Estimated compressed total: ~${Math.ceil(c.totalEstimatedTokens/5)} tokens_`,...c.compactCommands.map((e,t)=>`${t+1}. ${e}`)].join(`
144
+ `)+"\n\n---\n_Next: Use `search` to dive into specific files, or `compact` to compress file contents for context._";if(s&&r){let t=await G(r,{query:e});l+=K(t)}return{content:[{type:`text`,text:o?R(l,o):l}],structuredContent:{files:c.files.map(e=>({path:e.path,relevance:e.relevance,estimatedTokens:e.estimatedTokens,...e.focusRanges.length>0?{focusLines:e.focusRanges.map(e=>`L${e.start}-${e.end}`)}:{}})),totalFiles:c.files.length,totalEstimatedTokens:c.totalEstimatedTokens,task:e}}}catch(e){return mc.error(`Scope map failed`,L(e)),q(`INTERNAL`,`Scope map failed: ${e instanceof Error?e.message:String(e)}`)}}))}function vc(e,t,n,r,i){let a=W(`find`);e.registerTool(`find`,{title:a.title,description:`Multi-strategy search combining vector, FTS, glob, and regex. Use for precise queries needing multiple strategies. mode=examples finds real usage of a symbol. For general discovery use search instead.`,outputSchema:ko,inputSchema:{query:z.string().optional().describe(`Semantic/keyword search query (required for mode "examples")`),glob:z.string().optional().describe(`File glob pattern (search mode only)`),pattern:z.string().optional().describe(`Regex pattern to match in content (search mode only)`),limit:z.number().min(1).max(50).default(10).describe(`Max results`),content_type:z.enum(ue).optional().describe(`Filter by content type`),mode:z.enum([`search`,`examples`]).default(`search`).describe(`Mode: "search" (default) for federated search, "examples" to find usage examples of a symbol/pattern`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),workspaces:z.array(z.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all. User-level mode only.`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context for the file/query.`)},annotations:a.annotations},J(`find`,async({query:e,glob:a,pattern:o,limit:s,content_type:c,mode:l,max_tokens:u,workspaces:d,enrich:f})=>{try{if(l===`examples`){if(!e)return q(`VALIDATION`,`"query" is required for mode "examples".`);let r=await tt(t,n,{query:e,limit:s,contentType:c}),a=JSON.stringify(r);if(f&&i){let t=await G(i,{query:e});a+=K(t)}return{content:[{type:`text`,text:u?R(a,u):a}]}}let p=await $e(t,n,{query:e,glob:a,pattern:o,limit:s,contentType:c,cwd:r}),m=``;if(d&&d.length>0&&e){let n=sc(d,ge(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await cc(n);try{let i=await lc(r,await t.embedQuery(e),{limit:s,contentType:c});for(let e of i)p.results.push({path:`[${e.workspace}] ${e.record.sourcePath}`,score:e.score,source:`cross-workspace`,lineRange:e.record.startLine?{start:e.record.startLine,end:e.record.endLine}:void 0,preview:e.record.content.slice(0,200)});p.results.sort((e,t)=>t.score-e.score),p.results=p.results.slice(0,s),p.totalFound=p.results.length,m=` + ${n.length} workspace(s)`}finally{await i()}}}if(p.results.length===0){let t=`No results found.${p.failedStrategies?.length?`\nStrategies attempted: ${p.strategies.join(`, `)}\nFailed: ${p.failedStrategies.map(e=>`${e.strategy} (${e.reason})`).join(`, `)}`:p.strategies.length===0?`
145
+ No search strategies were activated. Provide at least one of: query, glob, or pattern.`:``}`;if(f&&i){let n=await G(i,{query:e});t+=K(n)}return{content:[{type:`text`,text:t}],structuredContent:{matches:[],totalMatches:0,pattern:e??a??o??``,truncated:!1}}}let h=[`Found ${p.totalFound} results via ${p.strategies.join(` + `)}${m}`,``,...p.results.map(e=>{let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``,n=e.preview?`\n ${e.preview.slice(0,100)}...`:``;return`- [${e.source}] ${e.path}${t} (${(e.score*100).toFixed(0)}%)${n}`})].join(`
146
+ `);if(f&&i){let t=await G(i,{query:e,filePath:p.results[0]?.path});h+=K(t)}return{content:[{type:`text`,text:u?R(h,u):h}],structuredContent:{matches:p.results.map(e=>({path:e.path,...e.lineRange?{line:e.lineRange.start}:{},matchType:e.source,preview:e.preview?.slice(0,200)??``})),totalMatches:p.totalFound,pattern:e??a??o??``,truncated:p.results.length<p.totalFound}}}catch(e){return mc.error(`Find failed`,L(e)),q(`INTERNAL`,`Find failed: ${e instanceof Error?e.message:String(e)}`)}}))}function yc(e,t,n,r,i){let a=W(`symbol`);e.registerTool(`symbol`,{title:a.title,description:`Find definition, imports, and references of a named symbol (function, class, type). For tracing data flow across call sites use trace instead.`,inputSchema:{name:z.string().describe(`Symbol name to look up (function, class, type, etc.)`),limit:z.number().min(1).max(50).default(20).describe(`Max results per category`),workspaces:z.array(z.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all. User-level mode only.`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),enrich:z.boolean().default(!1).optional().describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens.`)},outputSchema:To,annotations:a.annotations},J(`symbol`,async({name:e,limit:a,workspaces:o,max_tokens:s,enrich:c})=>{try{let l=await sn(t,n,{name:e,limit:a,graphStore:r});if(o&&o.length>0){let n=sc(o,ge(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await cc(n);try{for(let[n,i]of r){let r=await sn(t,i,{name:e,limit:a});r.definedIn&&!l.definedIn&&(l.definedIn={...r.definedIn,path:`[${n}] ${r.definedIn.path}`});for(let e of r.referencedIn)l.referencedIn.push({...e,path:`[${n}] ${e.path}`});if(r.importedBy){l.importedBy=l.importedBy??[];for(let e of r.importedBy)l.importedBy.push({...e,path:`[${n}] ${e.path}`})}}}finally{await i()}}}let u={name:l.name,definedIn:l.definedIn??null,importedBy:l.importedBy??[],referencedIn:l.referencedIn??[],graphContext:l.graphContext??null},d=Cc(l);if(c&&i){let t=await G(i,{query:`symbol ${e}`});d+=K(t)}return{content:[{type:`text`,text:s?R(d,s):d}],structuredContent:u}}catch(e){return mc.error(`Symbol lookup failed`,L(e)),q(`INTERNAL`,`Symbol lookup failed: ${e instanceof Error?e.message:String(e)}`)}}))}function bc(e,t,n,r,i,a){let o=new Rn,s=W(`file_summary`);e.registerTool(`file_summary`,{title:s.title,description:`Create a concise structural summary of a source file: imports, exports, functions, classes, interfaces, and types.`,outputSchema:Bo,inputSchema:{path:z.string().describe(`Absolute path to the file to summarize`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response.`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context for the file/query.`)},annotations:s.annotations},J(`file_summary`,async({path:e,max_tokens:s,enrich:c})=>{try{let l=pc(e,n,r);if((await bn(l)).isDirectory()){let t=await o.analyze(l,{format:`markdown`,maxDepth:3,maxTokens:s});hc(l,n,r,a);let u=t.data.stats?.languages??{},d=Object.entries(u).sort((e,t)=>t[1]-e[1])[0]?.[0],f=`📁 **Directory**: \`${e}\`\n\n${t.output}\n\n---\n_Path is a directory. Showing structure analysis. Use \`analyze({ aspect: "structure", ... })\` for deeper analysis with custom depth._`;if(c&&i){let t=await G(i,{query:e,filePath:l});f+=K(t)}return{content:[{type:`text`,text:s?R(f,s):f}],structuredContent:{path:l,language:d??`directory`,lines:0,imports:0,exports:0,functions:0,classes:0}}}let u=await Qe({path:l,content:(await t.get(l)).content});hc(l,n,r,a);let d=wc(u);if(c&&i){let t=await G(i,{query:e,filePath:l});d+=K(t)}return{content:[{type:`text`,text:d}],structuredContent:{path:u.path,language:u.language,lines:u.lines,imports:u.imports?.length??0,exports:u.exports?.length??0,functions:u.functions?.length??0,classes:u.classes?.length??0}}}catch(e){return mc.error(`File summary failed`,L(e)),q(`INTERNAL`,`File summary failed: ${e instanceof Error?e.message:String(e)}`)}}))}function xc(e,t,n,r,i){let a=W(`trace`);e.registerTool(`trace`,{title:a.title,description:`Follow data flow forward/backward across imports and call sites from a starting symbol or file:line. For finding a single symbol definition use symbol instead.`,inputSchema:{start:z.string().describe(`Starting point — symbol name or file:line reference`),direction:z.enum([`forward`,`backward`,`both`]).describe(`Which direction to trace relationships`),max_depth:z.number().min(1).max(10).default(3).optional().describe(`Maximum trace depth`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),enrich:z.boolean().default(!1).optional().describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens.`)},annotations:a.annotations},J(`trace`,async({start:e,direction:a,max_depth:o,max_tokens:s,enrich:c})=>{try{let l=await un(t,n,{start:e,direction:a,maxDepth:o,graphStore:r}),u=[`## Trace: ${l.start}`,`Direction: ${l.direction} | Depth: ${l.depth}`,``];if(l.graphContext&&(u.push(`### Graph Context`),l.graphContext.definingModule&&u.push(`- Module: ${l.graphContext.definingModule}`),l.graphContext.community&&u.push(`- Community: ${l.graphContext.community}`),l.graphContext.importedByModules.length>0&&u.push(`- Imported by modules: ${l.graphContext.importedByModules.join(`, `)}`),l.graphContext.siblingSymbols.length>0&&u.push(`- Sibling symbols: ${l.graphContext.siblingSymbols.join(`, `)}`),u.push(``)),l.nodes.length===0)u.push(`No connections found.`);else{let e=l.nodes.filter(e=>e.relationship===`calls`),t=l.nodes.filter(e=>e.relationship===`called-by`),n=l.nodes.filter(e=>e.relationship===`imports`),r=l.nodes.filter(e=>e.relationship===`imported-by`),i=l.nodes.filter(e=>e.relationship===`references`);if(e.length>0){u.push(`### Calls (${e.length})`);for(let t of e){let e=t.scope?` (from ${t.scope}())`:``;u.push(`- ${t.symbol}() — ${t.path}:${t.line}${e}`)}u.push(``)}if(t.length>0){u.push(`### Called by (${t.length})`);for(let e of t){let t=e.scope?` in ${e.scope}()`:``;u.push(`- ${e.symbol}()${t} — ${e.path}:${e.line}`)}u.push(``)}if(n.length>0){u.push(`### Imports (${n.length})`);for(let e of n)u.push(`- ${e.symbol} — ${e.path}:${e.line}`);u.push(``)}if(r.length>0){u.push(`### Imported by (${r.length})`);for(let e of r)u.push(`- ${e.path}:${e.line}`);u.push(``)}if(i.length>0){u.push(`### References (${i.length})`);for(let e of i)u.push(`- ${e.path}:${e.line}`);u.push(``)}}u.push(`---`,"_Next: `symbol` for definition details | `compact` to read a referenced file | `blast_radius` for impact analysis_");let d=u.join(`
147
+ `);if(c&&i){let t=await G(i,{query:`trace ${e}`});d+=K(t)}return{content:[{type:`text`,text:s?R(d,s):d}],structuredContent:{start:l.start,direction:l.direction,depth:l.depth,nodes:l.nodes,graphContext:l.graphContext??null}}}catch(e){return mc.error(`Trace failed`,L(e)),q(`INTERNAL`,`Trace failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Sc(e,t,n,r,i,a){let o=W(`dead_symbols`);e.registerTool(`dead_symbols`,{title:o.title,description:`Find exported symbols that appear to be unused because they are never imported or re-exported.`,outputSchema:zo,inputSchema:{path:z.string().optional().describe(`Root path to scope the search (default: cwd)`),limit:z.number().min(1).max(500).default(100).optional().describe(`Maximum exported symbols to scan`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context for the file/query.`)},annotations:o.annotations},J(`dead_symbols`,async({path:e,limit:o,max_tokens:s,enrich:c})=>{try{let l=e&&r?pc(e,r,i):e,u=await et(t,n,{rootPath:l,limit:o}),d=[`## Dead Symbol Analysis`,``,`**Exports scanned:** ${u.totalExports}`,`**Dead in source:** ${u.totalDeadSource} (actionable)`,`**Dead in docs:** ${u.totalDeadDocs} (informational — code samples in .md files)`,``];if(u.deadInSource.length>0){d.push(`### Dead in Source (actionable)`);for(let e of u.deadInSource)d.push(`- \`${e.name}\` (${e.kind}) — ${e.path}:${e.line}`);d.push(``)}if(u.deadInDocs.length>0){d.push(`### Dead in Docs (informational)`),d.push(`_${u.totalDeadDocs} symbol(s) found only in documentation code samples — not actionable dead code._`);for(let e of u.deadInDocs.slice(0,5))d.push(`- \`${e.name}\` — ${e.path}:${e.line}`);u.deadInDocs.length>5&&d.push(`- _... ${u.deadInDocs.length-5} more omitted_`)}u.totalDeadSource>0?d.push(``,`---`,`_Next: \`codemod\` to remove ${u.totalDeadSource} unused exports | \`symbol\` to verify usage before removing_`):d.push(``,`---`,"_Next: `check` — no dead symbols found, validate types and lint_");let f=d.join(`
148
+ `);if(c&&a){let t=await G(a,{query:`dead symbols ${e??l??``}`});f+=K(t)}return{content:[{type:`text`,text:s?R(f,s):f}],structuredContent:{symbols:[...u.deadInSource,...u.deadInDocs].map(e=>({name:e.name,path:e.path,...e.line===void 0?{}:{line:e.line},kind:e.kind})),totalDead:u.totalDeadSource+u.totalDeadDocs}}}catch(e){return mc.error(`Dead symbol scan failed`,L(e)),q(`INTERNAL`,`Dead symbol scan failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Cc(e){let t=[`Symbol: ${e.name}`];if(e.definedIn){let n=`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`;e.definedIn.signature&&(n+=`\nSignature: ${e.definedIn.signature}`),t.push(n)}else t.push(`Defined in: not found`);if(t.push(``,`Imported by:`),e.importedBy.length===0)t.push(` none`);else for(let n of e.importedBy)t.push(` - ${n.path}:${n.line} ${n.importStatement}`);if(t.push(``,`Referenced in:`),e.referencedIn.length===0)t.push(` none`);else for(let n of e.referencedIn){let e=`scope`in n&&n.scope?` in ${n.scope}()`:``;t.push(` - ${n.path}:${n.line}${e} ${n.context}`)}if(e.graphContext){let n=e.graphContext;t.push(``,`Graph context:`),n.definingModule&&t.push(` Module: ${n.definingModule}`),n.importedByModules.length>0&&t.push(` Imported by modules: ${n.importedByModules.join(`, `)}`),n.siblingSymbols.length>0&&t.push(` Sibling symbols: ${n.siblingSymbols.join(`, `)}`)}return t.join(`
149
+ `)}function wc(e){let t=[e.path,`Language: ${e.language}`,`Lines: ${e.lines}`,`Estimated tokens: ~${e.estimatedTokens}`,``,`Imports (${e.imports.length}):`,...Tc(e.imports),``,`Exports (${e.exports.length}):`,...Tc(e.exports),``,`Functions (${e.functions.length}):`,...Tc(e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}${`signature`in e&&e.signature?` — ${e.signature}`:``}`)),``,`Classes (${e.classes.length}):`,...Tc(e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}${e.signature?` — ${e.signature}`:``}`)),``,`Interfaces (${e.interfaces.length}):`,...Tc(e.interfaces.map(e=>`${e.name} @ line ${e.line}${`exported`in e&&e.exported?` [exported]`:``}`)),``,`Types (${e.types.length}):`,...Tc(e.types.map(e=>`${e.name} @ line ${e.line}${`exported`in e&&e.exported?` [exported]`:``}`))];if(`importDetails`in e&&e.importDetails&&e.importDetails.length>0){let n=e.importDetails.filter(e=>e.isExternal).length,r=e.importDetails.length-n;t.push(``,`Import breakdown: ${n} external, ${r} internal`)}if(`callEdges`in e&&e.callEdges&&e.callEdges.length>0){t.push(``,`Call edges (${e.callEdges.length} intra-file):`);for(let n of e.callEdges.slice(0,30))t.push(` - ${n.caller}() → ${n.callee}() @ line ${n.line}`);e.callEdges.length>30&&t.push(` - ... ${e.callEdges.length-30} more`)}return t.join(`
150
+ `)}function Tc(e){return e.length===0?[` none`]:e.map(e=>` - ${e}`)}const Ec=I(`tools`);function Dc(e,t){let n=W(`er_evolve_review`);e.registerTool(`er_evolve_review`,{title:n.title,description:`Review evolution metrics for the AI Kit ↔ ER bridge. Shows local miss rates, push acceptance, rule effectiveness, and top missed queries. Use this to reason about improving classification rules and knowledge flow.`,inputSchema:{include_details:z.boolean().default(!0).describe(`Include detailed breakdowns (top missed queries, rule stats)`),reset_after:z.boolean().default(!1).describe(`Reset collected metrics after review`)},annotations:n.annotations},async({include_details:e,reset_after:n})=>{try{let r=t.getMetrics(),i=[`## ER Evolution Review
151
+ `,`**Period**: ${r.period.startedAt} → ${r.period.queriedAt}`,`**Total events**: ${r.period.totalEvents}\n`,`### Search`,`- Total searches: ${r.search.totalSearches}`,`- ER fallback triggered: ${r.search.erFallbackCount} (${(r.search.erFallbackRate*100).toFixed(1)}%)`,`- ER cache hits: ${r.search.erCacheHitCount} (${(r.search.erCacheHitRate*100).toFixed(1)}% of fallbacks)`];if(e&&r.search.topMissedQueries.length>0){i.push(`
152
+ **Top missed queries** (triggered ER fallback):`);for(let e of r.search.topMissedQueries.slice(0,10)){let t=e.query.length>60?`${e.query.slice(0,57)}...`:e.query;i.push(` - "${t}" (${e.count}x)`)}}if(i.push(``,`### Push`,`- Total pushes: ${r.push.totalPushes} (${r.push.successCount} ok, ${r.push.failCount} failed)`,`- Classification match rate: ${(r.push.classificationMatchRate*100).toFixed(1)}%`,`- Push acceptance rate: ${(r.push.pushAcceptanceRate*100).toFixed(1)}%`),i.push(``,`### Rule Effectiveness`),Object.keys(r.rules.matchCounts).length>0)for(let[e,t]of Object.entries(r.rules.matchCounts)){let n=r.rules.pushCounts[e]??0,a=t>0?(n/t*100).toFixed(0):`0`;i.push(`- **${e}**: ${t} matches → ${n} pushes (${a}% conversion)`)}else i.push(`- _No rule activity recorded yet_`);if(e&&r.rules.lowConversionRules.length>0){i.push(``,`### ⚠️ Low Conversion Rules (potential false positives)`);for(let e of r.rules.lowConversionRules)i.push(`- **${e.ruleId}**: ${e.matchCount} matches, ${e.pushCount} pushes (${(e.conversionRate*100).toFixed(0)}% conversion) — consider tightening patterns`)}return i.push(``,`---`,"_Next: Use `er_update_policy` to refine rules based on these metrics, or `er_push` to share high-value knowledge._"),n&&(Ec.info(`Evolution metrics reset requested`,{requestedAt:new Date().toISOString(),clearedEvents:r.period.totalEvents}),t.reset(),i.push(`
153
+ _Metrics have been reset._`)),{content:[{type:`text`,text:i.join(`
154
+ `)}]}}catch(e){return Ec.error(`Evolution review failed`,L(e)),q(`INTERNAL`,`Evolution review failed: unable to compute metrics`)}})}const Oc=I(`tools:execution`);function kc(e,t,n){let r=W(`check`);e.registerTool(`check`,{title:r.title,description:`Run incremental typecheck (tsc) and lint (biome) on the project or specific files. Returns structured error and warning lists. Default detail level is "efficient" (~300 tokens).`,inputSchema:{files:z.array(z.string()).optional().describe(`Specific files to check (if omitted, checks all)`),cwd:z.string().optional().describe(`Working directory`),skip_types:z.boolean().default(!1).describe(`Skip TypeScript typecheck`),skip_lint:z.boolean().default(!1).describe(`Skip Biome lint`),detail:z.enum(me).optional().describe(`Output detail level: efficient (default, ~300 tokens — pass/fail + counts + top errors), normal (parsed error objects), full (includes raw terminal output)`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context.`)},outputSchema:wo,annotations:r.annotations},J(`check`,async({files:e,cwd:r,skip_types:i,skip_lint:a,detail:o,enrich:s},c)=>{try{let l=o??n??`efficient`,u=await De({files:e,cwd:r,skipTypes:i,skipLint:a,detail:l===`efficient`?`normal`:l}),d=Ds(c).createTask(`Check`,2);if(d.progress(0,`tsc: ${u.tsc.errors.length} errors`),d.progress(1,`biome: ${u.biome.errors.length} errors`),d.complete(`Check ${u.passed?`passed`:`failed`}`),l===`efficient`){let e=on(u),n=[];if(u.passed)n.push({tool:`test_run`,reason:`Types and lint clean — run tests next`});else{let t=u.tsc.errors[0]?.file??u.biome.errors[0]?.file,r=e.tsc.topErrors[0]??e.biome.topErrors[0]??`reported errors`;t&&n.push({tool:`compact`,reason:`Inspect failing code with compact({ path: ${JSON.stringify(t)}, query: ${JSON.stringify(r)} })`,suggested_args:{path:t,query:r}}),n.push({tool:`check`,reason:`Re-check after fixing errors`,suggested_args:{detail:`normal`}})}let r=[`## Check ${e.passed?`✅ PASS`:`❌ FAIL`}`,``,`**tsc**: ${e.tsc.passed?`✅`:`❌`} ${e.tsc.errorCount} errors, ${e.tsc.warningCount} warnings`];if(e.tsc.topErrors.length>0)for(let t of e.tsc.topErrors)r.push(` - ${t}`);if(r.push(`**biome**: ${e.biome.passed?`✅`:`❌`} ${e.biome.errorCount} errors, ${e.biome.warningCount} warnings`),e.biome.topErrors.length>0)for(let t of e.biome.topErrors)r.push(` - ${t}`);if(n.length>0){r.push(``,`**Next steps:**`);for(let e of n)r.push(`- \`${e.tool}\`: ${e.reason}`)}let i=r.join(`
155
+ `);if(s&&t){let e=await G(t,{query:`known issues failures`});i+=K(e)}return{content:[{type:`text`,text:i}],structuredContent:{...e}}}let f=JSON.stringify(u);if(s&&t){let e=await G(t,{query:`known issues failures`});f+=K(e)}return{content:[{type:`text`,text:f}]}}catch(e){return Oc.error(`Check failed`,L(e)),q(`INTERNAL`,`Check failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Ac(e){let t=W(`eval`);e.registerTool(`eval`,{title:t.title,description:`Execute a JavaScript or TypeScript snippet in a constrained VM sandbox with a timeout. Captures console output and returned values.`,inputSchema:{code:z.string().max(1e5).describe(`Code snippet to execute`),lang:z.enum([`js`,`ts`]).default(`js`).optional().describe(`Language mode: js executes directly, ts strips common type syntax first`),timeout:z.number().min(1).max(6e4).default(5e3).optional().describe(`Execution timeout in milliseconds`)},annotations:t.annotations},J(`eval`,async({code:e,lang:t,timeout:n})=>{try{let r=Xe({code:e,lang:t,timeout:n});return r.success?{content:[{type:`text`,text:`Eval succeeded in ${r.durationMs}ms\n\n${r.output}`}]}:q(`INTERNAL`,`Eval failed in ${r.durationMs}ms: ${r.error??`Unknown error`}`)}catch(e){return Oc.error(`Eval failed`,L(e)),q(`INTERNAL`,`Eval failed: ${e instanceof Error?e.message:String(e)}`)}}))}function jc(e,t){let n=W(`test_run`);e.registerTool(`test_run`,{title:n.title,description:`Run Vitest for the current project or a subset of files, then return a structured summary of passing and failing tests.`,inputSchema:{files:z.array(z.string()).optional().describe(`Specific test files or patterns to run`),grep:z.string().optional().describe(`Only run tests whose names match this pattern`),cwd:z.string().optional().describe(`Working directory for the test run`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context.`)},annotations:n.annotations,outputSchema:Uo},J(`test_run`,async({files:e,grep:n,cwd:r,enrich:i},a)=>{try{let o=await cn({files:e,grep:n,cwd:r}),s=Ds(a).createTask(`Test Run`,1),c=o.summary.passed+o.summary.failed+o.summary.skipped;s.complete(`Tests: ${o.passed?`passed`:`failed`} (${c} tests)`);let l=Pc(o);if(i&&t){let e=await G(t,{query:`test patterns known failures`});l+=K(e)}return{content:[{type:`text`,text:l}],structuredContent:{passed:o.passed,totalTests:c,passedTests:o.summary.passed,failedTests:o.summary.failed,skippedTests:o.summary.skipped,duration:o.summary.duration??0,failures:o.summary.tests.filter(e=>e.status===`fail`).map(e=>({name:e.name,message:e.error??``,...e.file?{file:e.file}:{}}))},isError:!o.passed}}catch(e){return Oc.error(`Test run failed`,L(e)),q(`INTERNAL`,`Test run failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Mc(e){let t=W(`parse_output`);e.registerTool(`parse_output`,{title:t.title,description:`Parse structured data from build tool output. Supports tsc, vitest, biome, and git status. Auto-detects the tool or specify explicitly.`,inputSchema:{output:z.string().max(5e5).describe(`Raw output text from a build tool`),tool:z.enum([`tsc`,`vitest`,`biome`,`git-status`]).optional().describe(`Tool to parse as (auto-detects if omitted)`)},annotations:t.annotations},async({output:e,tool:t})=>{try{let n=St(e.replace(/\\n/g,`
156
+ `).replace(/\\t/g,` `),t);return{content:[{type:`text`,text:JSON.stringify(n)}]}}catch(e){return Oc.error(`Parse failed`,L(e)),q(`INTERNAL`,`Parse failed: ${e instanceof Error?e.message:String(e)}`)}})}function Nc(e,t){let n=W(`delegate`);e.registerTool(`delegate`,{title:n.title,description:`Delegate a subtask to a local Ollama model. Use for summarization, classification, naming, or any task that can offload work from the host agent. Fails fast if Ollama is not running.`,inputSchema:{prompt:z.string().max(2e5).describe(`The task or question to send to the local model`),model:z.string().optional().describe(`Ollama model name (default: first available model)`),system:z.string().optional().describe(`System prompt for the model`),context:z.string().max(5e5).optional().describe(`Context text to include before the prompt (e.g. file contents)`),temperature:z.number().min(0).max(2).default(.3).optional().describe(`Sampling temperature (0=deterministic, default 0.3)`),timeout:z.number().min(1e3).max(6e5).default(12e4).optional().describe(`Timeout in milliseconds (default 120000)`),action:z.enum([`generate`,`list_models`]).default(`generate`).optional().describe(`Action: generate a response or list available models`)},annotations:n.annotations},async({prompt:e,model:n,system:r,context:i,temperature:a,timeout:o,action:s})=>{try{if(s===`list_models`){let e=await Ue();return{content:[{type:`text`,text:JSON.stringify({models:e,count:e.length,_Next:`Use delegate with a model name`},null,2)}]}}if(t?.available)try{let n=await t.createMessage({prompt:e,systemPrompt:r,context:i,maxTokens:4e3,modelPreferences:{intelligencePriority:.8,speedPriority:.5,costPriority:.3}});return{content:[{type:`text`,text:JSON.stringify({model:n.model??`sampling`,response:n.text,provider:`mcp-sampling`,_Next:`Use the response in your workflow. stash to save it.`},null,2)}]}}catch{Oc.debug(`Sampling failed, falling back to Ollama`)}let c=await He({prompt:e,model:n,system:r,context:i,temperature:a,timeout:o});return c.error?q(`INTERNAL`,JSON.stringify({error:c.error,model:c.model,durationMs:c.durationMs},null,2)):{content:[{type:`text`,text:JSON.stringify({model:c.model,response:c.response,durationMs:c.durationMs,tokenCount:c.tokenCount,_Next:`Use the response in your workflow. stash to save it.`},null,2)}]}}catch(e){return Oc.error(`Delegate failed`,L(e)),q(`INTERNAL`,`Delegate failed: ${e instanceof Error?e.message:String(e)}`)}})}function Pc(e){let t=[`Vitest run: ${e.passed?`passed`:`failed`}`,`Duration: ${e.durationMs}ms`,`Passed: ${e.summary.passed}`,`Failed: ${e.summary.failed}`,`Skipped: ${e.summary.skipped}`];e.summary.suites!==void 0&&t.push(`Suites: ${e.summary.suites}`);let n=e.summary.tests.filter(e=>e.status===`fail`);if(n.length>0){t.push(``,`Failed tests:`);for(let e of n)t.push(`- ${e.name}${e.file?` (${e.file})`:``}`),e.error&&t.push(` ${e.error}`)}return t.join(`
157
+ `)}const Fc=I(`sampling`);function Ic(e){if(!e.modelPreferences)return;let t={...e.modelPreferences.costPriority===void 0?{}:{costPriority:e.modelPreferences.costPriority},...e.modelPreferences.speedPriority===void 0?{}:{speedPriority:e.modelPreferences.speedPriority},...e.modelPreferences.intelligencePriority===void 0?{}:{intelligencePriority:e.modelPreferences.intelligencePriority}};return Object.keys(t).length>0?t:void 0}function Lc(e){if(Array.isArray(e))return e.map(e=>Lc(e)).filter(e=>e.length>0).join(`
158
+ `);if(e&&typeof e==`object`&&`type`in e){let t=e;if(t.type===`text`&&typeof t.text==`string`)return t.text}return JSON.stringify(e)}function Rc(e){let t=e.server,n=typeof t?.createMessage==`function`;return{get available(){return n},async createMessage(e){if(!n)throw Error(`Sampling not available: client does not support createMessage`);let r=e.context?`${e.context}\n\n---\n\n${e.prompt}`:e.prompt;try{let n=await t.createMessage({messages:[{role:`user`,content:{type:`text`,text:r}}],systemPrompt:e.systemPrompt,modelPreferences:Ic(e),maxTokens:e.maxTokens??4e3});return{text:Lc(n.content),model:n.model,stopReason:n.stopReason}}catch(e){throw Fc.warn(`Sampling createMessage failed`,{error:String(e)}),e}}}}const zc=[],Bc=[`_docs-sync`],Vc=new Map([[`_docs-sync`,`Synchronize project documentation — update docs/ folder based on changes made during the flow.`]]);function Hc(e){function t(t,n,r){let i=n?.installPath?re(n.installPath):t.replaceAll(`:`,`-`),a=F(Cn(),`.copilot`,`flows`,i).replaceAll(`\\`,`/`);if(k(a))return a;let o=F(Cn(),`.claude`,`flows`,i).replaceAll(`\\`,`/`);if(k(o))return o;let s=F(r??e(),`.github`,`flows`,i).replaceAll(`\\`,`/`);return k(s)?s:n?.installPath&&k(n.installPath)?n.installPath.replaceAll(`\\`,`/`):null}function n(e,n,r){let i=t(e.name,e,r);return i?F(i,n).replaceAll(`\\`,`/`):n}function r(t,n){let r=t.replace(/^_/,``),i=n??e(),a=[P(i,`.github`,`flows`,`_epilogue`,`steps`,r,`README.md`),P(i,`.github`,`flows`,`_epilogue`,r,`README.md`)];for(let e of a)if(k(e))return e.replaceAll(`\\`,`/`);return null}function i(e){return[...zc,...e.manifest.steps.map(e=>e.id),...Bc]}function a(e,t,r){let i=t?e.manifest.steps.find(e=>e.id===t)??null:null,a=t?Vc.get(t)??null:null;return{currentStep:i,epilogueStep:a?{id:t,description:a}:null,instructionPath:i&&t?n(e,i.instruction,r):null,description:i?.description??a}}function o(){try{let e=P(ar(`npm root -g`,{encoding:`utf-8`}).trim(),`@fission-ai`,`openspec`);if(k(e))return{path:e,sourceType:`npm-global`,isGit:!1}}catch{}return{path:`https://github.com/Fission-AI/OpenSpec.git`,sourceType:`git`,isGit:!0}}function s(e){let t=F(e);if(k(P(t,`.claude-plugin`,`plugin.json`)))return{path:t,sourceType:`claude-plugin`};let n=Cn(),r=P(n,`.claude`,`plugins`,e);if(k(P(r,`.claude-plugin`,`plugin.json`)))return{path:r,sourceType:`claude-plugin`};let i=P(n,`.claude`,`plugins`);if(!k(i))return null;for(let t of M(i,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=P(i,t.name,`.claude-plugin`,`plugin.json`);if(k(n))try{if(JSON.parse(j(n,`utf-8`)).name===e)return{path:P(i,t.name),sourceType:`claude-plugin`}}catch{}}return null}return{resolveInstallPath:t,resolveInstructionPath:n,resolveEpilogueInstructionPath:r,getStepSequence:i,resolveCurrentStepInfo:a,resolveOpenSpecSource:o,resolveClaudePluginSource:s}}function Uc(e){function t(){return e.sources?.[0]?.path??process.cwd()}function n(e){let t=[];try{let n=M(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith(`.`))continue;let n=P(e,r.name);k(P(n,`.git`))&&t.push(n)}}catch{}return t}function r(){let r=e.allRoots?.length?e.allRoots:[t()],i=new Set(r);for(let e of r)for(let t of n(e))i.add(t);return[...i]}function i(n){let i=n.replaceAll(`\\`,`/`);if(r().map(e=>e.replaceAll(`\\`,`/`)).includes(i))return!0;let a=(e.allRoots?.length?e.allRoots:[t()]).map(e=>e.replaceAll(`\\`,`/`));for(let e of a)if(i.startsWith(`${e}/`)&&k(P(n,`.git`)))return!0;return!1}function a(e){return P(e??t(),`.flows`)}async function o(){let e=r();for(let t of e){let e=a(t);if(k(e))for(let n of M(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let r=P(e,n.name,`meta.json`);if(k(r))try{let e=JSON.parse(j(r,`utf-8`));if(e.status===`active`)return e.primaryRoot?e.primaryRoot:t}catch{}}}return null}async function s(e){return e||(await o()??t())}function c(e,t,n){let r=P(a(t),e,`meta.json`),i=j(r,`utf-8`),o=JSON.parse(i);o.roots=n.map(e=>e.replaceAll(`\\`,`/`)),o.primaryRoot=t.replaceAll(`\\`,`/`);let s=`${r}.tmp`;N(s,JSON.stringify(o,null,2),`utf-8`),ee(s,r)}function l(e,t){let n=P(a(t),e,`meta.json`);if(!k(n))return;let r=j(n,`utf-8`),i=JSON.parse(r),o=i.roots;if(!o||o.length<=1)return;let s=t.replaceAll(`\\`,`/`);for(let t of o){if(t===s)continue;let n=P(t,`.flows`,e);A(n,{recursive:!0});let a=P(n,`meta.json`),o=`${a}.tmp`;N(o,r,`utf-8`),ee(o,a),A(P(n,i.artifactsDir??`.spec`),{recursive:!0})}}return{getWorkspaceRoot:t,getAllRoots:r,getFlowsDir:a,isValidFlowRoot:i,resolveFlowRoot:s,patchMetaRoots:c,syncMetaToRoots:l}}const Wc=I(`flow-tools`);function Gc(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function Kc(e){return{content:[{type:`text`,text:e}]}}function qc(e){return e instanceof Error?e.message:String(e)}const Jc={before:[],after:[{id:`_docs-sync`,description:`Synchronize project documentation — update docs/ folder based on changes made during the flow.`,position:`after`,skills:[`docs`]}]};function Yc(e,t){let n=Uc(t),r=Hc(n.getWorkspaceRoot);function i(){return P(_e(),`flows`,`registry.json`)}function a(){let t=Rc(e);return async({content:e,sourceFormat:n,stepName:r,metadata:i})=>{let a=r.charAt(0).toUpperCase()+r.slice(1),o=i?JSON.stringify(i,null,2):void 0,s=`You are converting a flow step definition from "${n}" format to aikit native flow step README.md format.
159
+
160
+ Convert the provided content into a well-structured README.md for a flow step named "${r}".
161
+
162
+ The output must:
163
+ 1. Start with a heading: # ${a}
164
+ 2. Have a "## Purpose" section explaining what this step does
165
+ 3. Have a "## Instructions" section with ALL technical instructions preserved from the source
166
+ 4. Have a "## Artifacts" section listing what this step produces
167
+ 5. Have a "## Prerequisites" section if there are dependencies on previous steps
168
+ 6. Preserve ALL tool restrictions, constraints, and requirements from the source
169
+ 7. Be formatted as clean Markdown
170
+
171
+ Output ONLY the README.md content, nothing else.`;if(t.available)try{let i=(await t.createMessage({prompt:e,systemPrompt:s,context:o?`Step name: ${r}\nSource format: ${n}\nMetadata:\n${o}`:`Step name: ${r}\nSource format: ${n}`,maxTokens:4096,modelPreferences:{intelligencePriority:.8,speedPriority:.4,costPriority:.2}})).text.trim();if(i.length>0)return i}catch(e){Wc.debug(`Flow transform sampling failed; using fallback formatting`,{error:qc(e),sourceFormat:n,stepName:r})}let c=typeof i?.description==`string`&&i.description.trim().length>0?i.description.trim():null,l=Gc(i?.produces),u=Gc(i?.requires);return[`# ${a}`,``,`## Purpose`,``,c??`${a} step.`,``,`## Instructions`,``,e.trim(),``,`## Artifacts`,``,...l.length>0?l.map(e=>`- ${e}`):[`- ${r}.md`],...u.length>0?[``,`## Prerequisites`,``,...u.map(e=>`- ${e}`)]:[],``].join(`
172
+ `).trimEnd().concat(`
173
+ `)}}async function o(e){let{FlowRegistryManager:r,FlowStateMachine:a,FlowLoader:o,GitInstaller:s}=await import(`../../flows/dist/index.js`),c=P(t.stateDir??``,`flows`,`installed`);return{registry:new r(i()),stateMachine:new a(n.getFlowsDir(e),Jc),loader:new o,installer:new s(c)}}return{server:e,config:t,log:Wc,toTextResponse:Kc,toErrorText:qc,createFlowTransform:a,getFlows:o,stateDir:t.stateDir??``,...n,...r}}async function Xc(e){let{entry:t,stepId:n,runDir:r,slug:i,primaryRoot:a,roots:o,activeRoot:s,resolveInstructionPath:c,resolveEpilogueInstructionPath:l}=e;if(!n)return null;try{let e=t.manifest.steps.find(e=>e.id===n||e.name===n),u;if(e)u=await _n(c(t,e.instruction,s),`utf-8`);else{let e=l(n,s);if(!e)return null;u=await _n(e,`utf-8`)}let d=P(r,t.manifest.artifacts_dir).replaceAll(`\\`,`/`),f=r.replaceAll(`\\`,`/`);u=u.replaceAll(`{{artifacts_path}}`,d).replaceAll(`{{run_dir}}`,f).replaceAll(`{{workspace_root}}`,(a??s).replaceAll(`\\`,`/`)).replaceAll(`{{all_roots}}`,JSON.stringify(o??[s.replaceAll(`\\`,`/`)],null,2));for(let e of[`spec-driven`])u=u.replaceAll(`${e}/${i}/`,`${d}/`);return u}catch{return null}}async function Zc(e,t){let{getFlows:n,log:r,resolveEpilogueInstructionPath:i,resolveFlowRoot:a,resolveInstructionPath:o,toErrorText:s,toTextResponse:c}=t,{step:l}=e;try{let e=await a(),{registry:t,stateMachine:r}=await n(e),s=r.getStatus();if(!s.success||!s.data)return c(`No active flow. Use flow({ action: "start", name: "<flow>" }) to begin one, or flow({ action: "list" }) to see available flows.`);let u=s.data,d=t.get(u.flow);if(!d)return c(`Flow "${u.flow}" not found in registry.`);let f=l??u.currentStep;return c(f?await Xc({entry:d,stepId:f,runDir:u.runDir,slug:u.slug,primaryRoot:u.primaryRoot,roots:u.roots,activeRoot:e,resolveInstructionPath:o,resolveEpilogueInstructionPath:i})||`Step "${f}" not found in flow "${u.flow}".`:`No current step is available for the active flow.`)}catch(e){return r.error(`flow action read failed`,L(e)),e instanceof Error&&`code`in e&&e.code===`ENOENT`?c(`Could not read instruction file: ${e.message}`):c(`Error: ${s(e)}`)}}async function Qc(e,t){let{registry:n,loader:r,installer:i}=await e.getFlows(),a=e.createFlowTransform(),o=F(t.source);if(!k(o))return e.toTextResponse(`Source path no longer exists: ${o}`);let s=`${t.installPath}.updating`,c=`${t.installPath}.backup`;k(s)&&te(s,{recursive:!0,force:!0}),k(c)&&te(c,{recursive:!0,force:!0});let l=i.copyLocal(o,re(s));if(!l.success||!l.data)return e.toTextResponse(`Failed to copy flow: ${l.error}`);let u=await r.load(s,{forceAssetSync:!0,transform:a});if(!u.success||!u.data)return i.remove(s),e.toTextResponse(`Failed to load flow manifest: ${u.error}`);let d=!1;try{ee(t.installPath,c),ee(s,t.installPath);let e=await r.load(t.installPath,{forceAssetSync:!0,transform:a});if(!e.success||!e.data)throw Error(`Failed to load flow manifest: ${e.error}`);let o=e.data.manifest,l=e.data.format,u=n.register({...t,version:o.version,format:l,installPath:t.installPath,manifest:o,updatedAt:new Date().toISOString()});if(!u.success)throw Error(`Failed to refresh flow registry entry: ${u.error}`);if(d=!0,o.install.length>0){let e=i.runInstallDeps(o.install);if(!e.success)throw Error(`Dependency install failed: ${e.error}`)}te(c,{recursive:!0,force:!0})}catch(r){return k(s)&&te(s,{recursive:!0,force:!0}),k(c)&&(k(t.installPath)&&te(t.installPath,{recursive:!0,force:!0}),ee(c,t.installPath)),d&&n.register(t),e.toTextResponse(e.toErrorText(r))}return e.toTextResponse(`Flow "${t.name}" updated from ${t.sourceType} source successfully.`)}async function $c(e,t){let{registry:n,loader:r}=await e.getFlows(),i=e.createFlowTransform();try{ar(`npm update -g @fission-ai/openspec`,{encoding:`utf-8`,stdio:`pipe`})}catch(t){return e.toTextResponse(`npm update failed: ${e.toErrorText(t)}`)}let a=e.resolveOpenSpecSource(),o=await r.load(a.path,{forceAssetSync:!0,transform:i}),s=o.success&&o.data?o.data.manifest:null,c=o.success&&o.data?o.data.format:t.format;if(s){let r=n.register({...t,version:s.version,format:c,installPath:a.path,manifest:s,updatedAt:new Date().toISOString()});if(!r.success)return e.toTextResponse(`Failed to refresh flow registry entry: ${r.error}`)}return e.toTextResponse(`Flow "${t.name}" updated via npm successfully.`)}async function el(e,t){let{registry:n,loader:r,installer:i}=await e.getFlows(),a=e.createFlowTransform(),o=i.update(t.installPath);if(!o.success)return e.toTextResponse(`Update failed: ${o.error}`);let s=await r.load(t.installPath,{forceAssetSync:!0,transform:a}),c=s.success&&s.data?s.data.manifest:null,l=s.success&&s.data?s.data.format:t.format;if(c){let r=i.getLocalCommit(t.installPath),a=n.register({...t,version:c.version,format:l,manifest:c,updatedAt:new Date().toISOString(),...r?{commitSha:r}:{}});if(!a.success)return e.toTextResponse(`Failed to refresh flow registry entry: ${a.error}`)}let u=c?.install??t.manifest.install;if(u.length>0){let t=i.runInstallDeps(u);if(!t.success)return e.toTextResponse(`Dependency install failed: ${t.error}`)}return e.toTextResponse(`Flow "${t.name}" updated successfully.`)}async function tl(e,t){let{createFlowTransform:n,getFlows:r,log:i,resolveClaudePluginSource:a,resolveOpenSpecSource:o,toErrorText:s,toTextResponse:c}=t,{source:l,name:u,token:d}=e;try{let{registry:e,loader:t,installer:i}=await r(),s=n(),f=l===`openspec`||l.startsWith(`openspec:`),p,m=l,h;if(f){let e=o();m=e.path,p=e.sourceType}let g=f?null:a(m);g&&(m=g.path,p=g.sourceType);let _=/^https?:\/\/|^git@/.test(m),v;if(_){let e=i.clone(m,d);if(!e.success||!e.data)return c(`Failed to clone flow: ${e.error}`);v=e.data}else{let e=F(m);h=e;let t=u||re(e)||`custom-flow`,n=i.copyLocal(e,t);if(!n.success||!n.data)return c(`Failed to copy flow: ${n.error}`);v=n.data}let y=await t.load(v,{forceAssetSync:!0,transform:s});if(!y.success||!y.data)return i.remove(v),c(`Failed to load flow manifest: ${y.error}`);let{manifest:b,format:x}=y.data,S=u||b.name,C=p??(_?`git`:`local`);if(e.has(S))return i.remove(v),c(`Flow "${S}" is already installed. Use flow({ action: "update", name: "${S}" }) to update it, or flow({ action: "remove", name: "${S}" }) then flow({ action: "add", source: "..." }) to replace.`);if(b.install.length>0){let e=i.runInstallDeps(b.install);if(!e.success)return i.remove(v),c(`Dependency install failed: ${e.error}`)}let w=new Date().toISOString(),T=_?i.getLocalCommit(v):void 0,E=e.register({name:S,version:b.version,source:C===`local`||C===`claude-plugin`?h??l:l,sourceType:C,installPath:v,format:x,registeredAt:w,updatedAt:w,manifest:b,...T?{commitSha:T}:{}});if(!E.success)return i.remove(v),c(`Failed to register flow: ${E.error}`);let D=b.steps.length;return c(`Flow "${S}" installed successfully (${D} steps). Use flow({ action: "start", name: "${S}" }) to begin.`)}catch(e){return i.error(`flow action add failed`,L(e)),c(`Error: ${s(e)}`)}}async function nl(e,t){let{getFlows:n,log:r,toErrorText:i,toTextResponse:a}=t,{name:o}=e;try{let{registry:e,installer:t}=await n();if(!e.has(o))return a(`Flow "${o}" is not installed.`);let r=e.get(o);if(!r)return a(`Flow "${o}" is not installed.`);if(r.sourceType===`builtin`)return a(`Cannot remove builtin flow "${o}".`);let i=t.remove(r.installPath);if(!i.success)return a(`Failed to remove flow files: ${i.error}`);let s=e.unregister(o);return s.success?a(`Flow "${o}" removed successfully.`):a(`Failed to unregister flow: ${s.error}`)}catch(e){return r.error(`flow action remove failed`,L(e)),a(`Error: ${i(e)}`)}}async function rl(e,t){let{getFlows:n,log:r,toErrorText:i,toTextResponse:a}=t,{name:o}=e,s={createFlowTransform:t.createFlowTransform,getFlows:t.getFlows,resolveOpenSpecSource:t.resolveOpenSpecSource,toErrorText:t.toErrorText,toTextResponse:t.toTextResponse};try{let{registry:e}=await n();if(!e.has(o))return a(`Flow "${o}" is not installed.`);let t=e.get(o);return!t||t.sourceType!==`git`&&t.sourceType!==`npm-global`&&t.sourceType!==`local`&&t.sourceType!==`claude-plugin`?a(`Flow "${o}" was not installed from git, npm, or a local source — cannot update. Remove and re-add instead.`):t.sourceType===`local`||t.sourceType===`claude-plugin`?Qc(s,t):t.sourceType===`npm-global`?$c(s,t):el(s,t)}catch(e){return r.error(`flow action update failed`,L(e)),a(`Error: ${i(e)}`)}}async function il(e,t){let{getAllRoots:n,getFlows:r,getStepSequence:i,getWorkspaceRoot:a,isValidFlowRoot:o,log:s,patchMetaRoots:c,resolveCurrentStepInfo:l,stateDir:u,toErrorText:d,toTextResponse:f}=t,{flow:p,topic:m,roots:h}=e;try{if(h&&h.length>0){let e=h.filter(e=>!o(e));if(e.length>0)return f(`Invalid roots — not part of the workspace or a recognized sub-repository: ${e.join(`, `)}. Available roots: ${n().map(e=>e.replaceAll(`\\`,`/`)).join(`, `)}`)}let e=n(),s=e.length>1,d=!h&&s,g=h?.[0]??a(),{registry:_,stateMachine:v}=await r(g),y=_.get(p);if(!y)return f(`Flow "${p}" not found. Use flow({ action: "list" }) to see available flows.`);let b=v.start(y.name,y.manifest,m);if(!b.success||!b.data)return f(`Cannot start: ${b.error}`);let x=b.data;if(h&&h.length>1)try{c(x.slug,g,h),t.syncMetaToRoots(x.slug,g)}catch(e){return v.reset(),f(`Flow created but failed to sync to secondary roots — rolled back. Error: ${e instanceof Error?e.message:String(e)}`)}try{await gn(P(u,`flow-context`,x.slug),{recursive:!0})}catch{}let{instructionPath:S,description:C}=l(y,x.currentStep,g),w=i(y),T=await Xc({entry:y,stepId:x.currentStep,runDir:x.runDir,slug:x.slug,primaryRoot:null,roots:h??null,activeRoot:g,resolveInstructionPath:t.resolveInstructionPath,resolveEpilogueInstructionPath:t.resolveEpilogueInstructionPath}),E={started:!0,flow:x.flow,slug:x.slug,topic:x.topic,runDir:x.runDir,artifactsPath:P(x.runDir,y.manifest.artifacts_dir).replaceAll(`\\`,`/`),currentStep:x.currentStep,currentStepInstruction:S,currentStepDescription:C,currentStepContent:T,phase:x.phase,isEpilogue:x.isEpilogue,totalSteps:w.length,stepSequence:w,artifactsDir:y.manifest.artifacts_dir,roots:h??[g.replaceAll(`\\`,`/`)],_hint:`IMPORTANT: Follow the instructions in currentStepContent to execute this flow step. Do NOT proceed without reading them.`,...d?{multiRootWarning:`No roots specified in multi-root workspace. Flow created at workspace root. Pass roots parameter with target repo for precise placement.`,availableRoots:e.map(e=>e.replaceAll(`\\`,`/`))}:{}};return f(JSON.stringify(E,null,2))}catch(e){return s.error(`flow action start failed`,L(e)),f(`Error: ${d(e)}`)}}async function al(e){let{config:t,getAllRoots:n,getFlows:r,getStepSequence:i,getWorkspaceRoot:a,log:o,resolveCurrentStepInfo:s,resolveFlowRoot:c,toErrorText:l,toTextResponse:u}=e;try{let o=await c(),{registry:l,stateMachine:d}=await r(o),f=d.getStatus();if(!f.success||!f.data)return u(`No active flow. Use flow({ action: "start", name: "<flow>" }) to begin one, or flow({ action: "list" }) to see available flows.`);let p=f.data,m=l.get(p.flow),h=m?s(m,p.currentStep,o):null,g=m?i(m):[],_=h?.instructionPath??null,v=m?await Xc({entry:m,stepId:p.currentStep,runDir:p.runDir,slug:p.slug,primaryRoot:p.primaryRoot,roots:p.roots,activeRoot:o,resolveInstructionPath:e.resolveInstructionPath,resolveEpilogueInstructionPath:e.resolveEpilogueInstructionPath}):null,y={flow:p.flow,status:p.status,slug:p.slug,topic:p.topic,runDir:p.runDir,artifactsPath:m?P(p.runDir,m.manifest.artifacts_dir).replaceAll(`\\`,`/`):null,currentStep:p.currentStep,currentStepInstruction:_,instructionPath:_,currentStepDescription:h?.description??null,currentStepContent:v,_hint:p.currentStep?`IMPORTANT: Follow the instructions in currentStepContent to execute this flow step. Do NOT proceed without reading them.`:void 0,phase:p.phase,isEpilogue:p.isEpilogue,completedSteps:p.completedSteps,skippedSteps:p.skippedSteps,artifacts:p.artifacts,startedAt:p.startedAt,updatedAt:p.updatedAt,totalSteps:g.length,progress:m?`${p.completedSteps.length+p.skippedSteps.length}/${g.length}`:`unknown`,workspaceRoot:o.replaceAll(`\\`,`/`),primaryRoot:(p.primaryRoot??o).replaceAll(`\\`,`/`),roots:p.roots??[o.replaceAll(`\\`,`/`)],allRoots:n().map(e=>e.replaceAll(`\\`,`/`)),discoveredRepos:(()=>{let e=(t.allRoots?.length?t.allRoots:[a()]).map(e=>e.replaceAll(`\\`,`/`)),r=n().map(e=>e.replaceAll(`\\`,`/`)).filter(t=>!e.includes(t));return r.length>0?r:void 0})()};return u(JSON.stringify(y,null,2))}catch(e){return o.error(`flow action status failed`,L(e)),u(`Error: ${l(e)}`)}}async function ol(e){let{getFlows:t,log:n,resolveFlowRoot:r,stateDir:i,syncMetaToRoots:a,toErrorText:o,toTextResponse:s}=e;try{let e=await r(),{stateMachine:n}=await t(e),o=n.getStatus(),c=n.reset();if(!c.success)return s(`Reset failed: ${c.error}`);if(o.success&&o.data&&a(o.data.slug,e),o.success&&o.data?.slug)try{await yn(P(i,`flow-context`,o.data.slug),{recursive:!0,force:!0})}catch{}return s(`Flow abandoned. Use flow({ action: "start", name: "<flow>" }) to begin a new flow.`)}catch(e){return n.error(`flow action reset failed`,L(e)),s(`Error: ${o(e)}`)}}async function sl(e,t){let{getFlows:n,getStepSequence:r,log:i,resolveCurrentStepInfo:a,resolveFlowRoot:o,syncMetaToRoots:s,toErrorText:c,toTextResponse:l}=t,{action:u}=e;try{let e=await o(),{registry:i,stateMachine:c}=await n(e),d=c.getStatus();if(!d.success||!d.data)return l(`No active flow. Use flow({ action: "start", name: "<flow>" }) first.`);let f=i.get(d.data.flow);if(!f)return l(`Flow "${d.data.flow}" not found in registry.`);let p=c.step(u,f.manifest);if(!p.success||!p.data)return l(`Cannot ${u}: ${p.error}`);s(p.data.slug,e);let m=p.data,{instructionPath:h,description:g}=a(f,m.currentStep,e),_=r(f),v=await Xc({entry:f,stepId:m.currentStep,runDir:m.runDir,slug:m.slug,primaryRoot:m.primaryRoot,roots:m.roots,activeRoot:e,resolveInstructionPath:t.resolveInstructionPath,resolveEpilogueInstructionPath:t.resolveEpilogueInstructionPath}),y={flow:m.flow,status:m.status,action:u,slug:m.slug,topic:m.topic,runDir:m.runDir,artifactsPath:P(m.runDir,f.manifest.artifacts_dir).replaceAll(`\\`,`/`),currentStep:m.currentStep,currentStepInstruction:h,currentStepDescription:g,currentStepContent:v,_hint:m.currentStep?`IMPORTANT: Follow the instructions in currentStepContent to execute this flow step. Do NOT proceed without reading them.`:void 0,phase:m.phase,isEpilogue:m.isEpilogue,completedSteps:m.completedSteps,skippedSteps:m.skippedSteps,totalSteps:_.length,remaining:_.filter(e=>!m.completedSteps.includes(e)&&!m.skippedSteps.includes(e)&&e!==m.currentStep)};return l(JSON.stringify(y,null,2))}catch(e){return i.error(`flow action step failed`,L(e)),l(`Error: ${c(e)}`)}}async function cl(e){let{config:t,getAllRoots:n,getFlows:r,getWorkspaceRoot:i,log:a,resolveFlowRoot:o,toErrorText:s,toTextResponse:c}=e;try{let{registry:e,stateMachine:a,installer:s}=await r(await o()),l=e.list(),u=a.getStatus(),d={flows:l.map(e=>{let t={name:e.name,version:e.version,source:e.source,sourceType:e.sourceType,format:e.format,steps:e.manifest.steps.map(e=>e.id)};if(e.sourceType===`git`&&e.commitSha){let n=s.hasUpdates(e.installPath);return{...t,commitSha:e.commitSha,updateAvailable:n.success&&n.data?n.data.hasUpdates:void 0}}return t}),activeFlow:u.success&&u.data?{flow:u.data.flow,status:u.data.status,currentStep:u.data.currentStep,slug:u.data.slug,topic:u.data.topic,runDir:u.data.runDir}:null,allRoots:n().map(e=>e.replaceAll(`\\`,`/`)),discoveredRepos:(()=>{let e=(t.allRoots?.length?t.allRoots:[i()]).map(e=>e.replaceAll(`\\`,`/`)),r=n().map(e=>e.replaceAll(`\\`,`/`)).filter(t=>!e.includes(t));return r.length>0?r:void 0})()};return c(JSON.stringify(d,null,2))}catch(e){return a.error(`flow action list failed`,L(e)),c(`Error: ${s(e)}`)}}async function ll(e,t){let{getFlows:n,log:r,resolveInstallPath:i,resolveInstructionPath:a,toErrorText:o,toTextResponse:s}=t,{name:c}=e;try{let{registry:e,installer:t}=await n(),r=e.get(c);if(!r)return s(`Flow "${c}" not found. Use flow({ action: "list" }) to see available flows.`);let o=r.commitSha??null,l;if(r.sourceType===`git`&&r.installPath){let e=t.hasUpdates(r.installPath);l=e.success&&e.data?e.data.hasUpdates:void 0}let u={name:r.name,version:r.version,description:r.manifest.description,source:r.source,sourceType:r.sourceType,format:r.format,commitSha:o,updateAvailable:l,installPath:i(r.name,r),registeredAt:r.registeredAt,updatedAt:r.updatedAt,steps:r.manifest.steps.map(e=>({id:e.id,name:e.name,instruction:a(r,e.instruction),produces:e.produces,requires:e.requires,description:e.description})),agents:r.manifest.agents,artifactsDir:r.manifest.artifacts_dir,install:r.manifest.install};return s(JSON.stringify(u,null,2))}catch(e){return r.error(`flow action info failed`,L(e)),s(`Error: ${o(e)}`)}}async function ul(e,t){let{getAllRoots:n,getFlows:r,log:i,toErrorText:a,toTextResponse:o}=t,{flow:s,status:c}=e;try{let e=n(),t=[];for(let n of e){let{stateMachine:e}=await r(n),i=e.listRuns({flow:s,status:c});for(let e of i)t.push({...JSON.parse(JSON.stringify(e)),root:n.replaceAll(`\\`,`/`)})}let i=new Set,a=t.filter(e=>{let t=e.id;return i.has(t)?!1:(i.add(t),!0)});return a.length===0?o(`No flow runs found.`):o(JSON.stringify(a,null,2))}catch(e){return i.error(`flow action runs failed`,L(e)),o(`Error: ${a(e)}`)}}function dl(e){let t=e.content?.find(e=>e.type===`text`)?.text??``;if(!t)return null;try{let e=JSON.parse(t);if(typeof e.slug==`string`&&e.slug.length>0)return e.slug}catch{}return t.match(/[Ss]lug[:\s]*`?([^`\s,]+)`?/)?.[1]??null}function fl(e,t,n){let r=Yc(e,t),i=W(`flow`);e.registerTool(`flow`,{title:i.title,description:`Manage development flows — list available flows, start/stop runs, navigate steps, read instructions, and install/remove/update flows. Use action parameter to select operation.`,annotations:i.annotations,inputSchema:{action:z.enum([`list`,`info`,`start`,`step`,`status`,`reset`,`read`,`runs`,`add`,`remove`,`update`]).describe(`The flow operation to perform.`),name:z.string().optional().describe(`Flow name — required for info, start, remove, update. Optional override for add.`),topic:z.string().optional().describe(`Human-readable topic for the run (used by start).`),roots:z.array(z.string()).optional().describe(`Workspace roots participating in this flow (used by start).`),advance:z.enum([`next`,`skip`,`redo`]).optional().describe(`Step navigation action — required for step.`),step:z.string().optional().describe(`Step id or name to read (used by read). Defaults to current step.`),source:z.string().optional().describe(`Git URL, local path, or "openspec" shorthand — required for add.`),token:z.string().optional().describe(`Auth token for private repos (used by add).`),filter_flow:z.string().optional().describe(`Filter runs by flow name (used by runs).`),filter_status:z.string().optional().describe(`Filter runs by status: active, completed, abandoned (used by runs).`)}},J(`flow`,async e=>{switch(e.action){case`list`:return cl(r);case`info`:return e.name?ll({name:e.name},r):r.toTextResponse(`Missing required parameter: name`);case`start`:{if(!e.name)return r.toTextResponse(`Missing required parameter: name (flow to start)`);let t=await il({flow:e.name,topic:e.topic,roots:e.roots},r),i=dl(t);return i&&n&&n(i),t}case`step`:return e.advance?sl({action:e.advance},r):r.toTextResponse(`Missing required parameter: advance (next/skip/redo)`);case`status`:{let e=await al(r);return n&&n(dl(e)),e}case`reset`:{let e=await ol(r);return n&&n(null),e}case`read`:return Zc({step:e.step},r);case`runs`:return ul({flow:e.filter_flow,status:e.filter_status},r);case`add`:return e.source?tl({source:e.source,name:e.name,token:e.token},r):r.toTextResponse(`Missing required parameter: source`);case`remove`:return e.name?nl({name:e.name},r):r.toTextResponse(`Missing required parameter: name`);case`update`:return e.name?rl({name:e.name},r):r.toTextResponse(`Missing required parameter: name`);default:return r.toTextResponse(`Unknown action: ${e.action}`)}}))}const pl=I(`tools`);function ml(e){let t=W(`evidence_map`);e.registerTool(`evidence_map`,{title:t.title,description:`Track verified/assumed/unresolved claims for complex tasks. Gate readiness: YIELD (proceed), HOLD (unknowns), HARD_BLOCK (critical gaps). Persists across calls.`,inputSchema:{action:z.enum([`create`,`add`,`update`,`get`,`gate`,`list`,`delete`]).describe(`Operation to perform`),task_id:z.string().optional().describe(`Task identifier (required for all except list)`),tier:z.enum([`floor`,`standard`,`critical`]).optional().describe(`FORGE tier (required for create)`),claim:z.string().optional().describe(`Critical-path claim text (for add)`),status:z.enum([`V`,`A`,`U`]).optional().describe(`Evidence status: V=Verified, A=Assumed, U=Unresolved`),receipt:z.string().optional().describe(`Evidence receipt: tool→ref for V, reasoning for A, attempts for U`),id:z.number().optional().describe(`Entry ID (for update)`),critical_path:z.boolean().default(!0).describe(`Whether this claim is on the critical path`),unknown_type:z.enum([`contract`,`convention`,`freshness`,`runtime`,`data-flow`,`impact`]).optional().describe(`Typed unknown classification`),safety_gate:z.enum([`provenance`,`commitment`,`coverage`]).optional().describe(`Safety gate tag: provenance (claim→evidence), commitment (user-approved), coverage (nothing dropped)`),retry_count:z.number().default(0).describe(`Retry count for gate evaluation (0 = first attempt)`),max_retries:z.number().int().min(0).optional().describe(`Maximum retries before escalating. Default: 3`),timeout_action:z.enum([`iterate`,`retry`,`manual`,`terminate`]).optional().describe(`Action to take when gate retries are exhausted. Default: manual`),cwd:z.string().optional().describe(`Working directory for evidence map storage (default: server cwd). Use root_path from forge_ground to match.`)},annotations:t.annotations},J(`evidence_map`,async({action:e,task_id:t,tier:n,claim:r,status:i,receipt:a,id:o,critical_path:s,unknown_type:c,safety_gate:l,retry_count:u,max_retries:d,timeout_action:f,cwd:p})=>{try{switch(e){case`create`:if(!t)throw Error(`task_id required for create`);if(!n)throw Error(`tier required for create`);return Ze({action:`create`,taskId:t,tier:n},p),{content:[{type:`text`,text:`Created evidence map "${t}" (tier: ${n}).\n\n---\n_Next: Use \`evidence_map\` with action "add" to record critical-path claims._`}]};case`add`:{if(!t)throw Error(`task_id required for add`);if(!r)throw Error(`claim required for add`);if(!i)throw Error(`status required for add`);let e=Ze({action:`add`,taskId:t,claim:r,status:i,receipt:a??``,criticalPath:s,unknownType:c,safetyGate:l},p),n=e.autoCreated?[`⚠️ Evidence map "${t}" was auto-created with tier "standard". Use \`create\` action to set a specific tier.`,``,`Added entry #${e.entry?.id} to "${t}": [${i}] ${r}`]:[`Added entry #${e.entry?.id} to "${t}": [${i}] ${r}`];return e.formattedMap&&n.push(``,e.formattedMap),{content:[{type:`text`,text:n.join(`
174
+ `)}]}}case`update`:{if(!t)throw Error(`task_id required for update`);if(o===void 0)throw Error(`id required for update`);if(!i)throw Error(`status required for update`);let e=Ze({action:`update`,taskId:t,id:o,status:i,receipt:a??``},p),n=[`Updated entry #${o} in "${t}" → ${i}`];return e.formattedMap&&n.push(``,e.formattedMap),{content:[{type:`text`,text:n.join(`
175
+ `)}]}}case`get`:{if(!t)throw Error(`task_id required for get`);let e=Ze({action:`get`,taskId:t},p);return e.state?{content:[{type:`text`,text:[`## Evidence Map: ${t} (${e.state.tier})`,``,e.formattedMap??`No entries.`,``,`_${e.state.entries.length} entries — created ${e.state.createdAt}_`].join(`
176
+ `)}]}:{content:[{type:`text`,text:`Evidence map "${t}" not found.`}]}}case`gate`:{if(!t)throw Error(`task_id required for gate`);let e=Ze({action:`gate`,taskId:t,retryCount:u,maxRetries:d,timeoutAction:f},p);if(!e.gate)return{content:[{type:`text`,text:`Evidence map "${t}" not found.`}]};let n=e.gate,r=[`## FORGE Gate: **${n.verdict}**`,``,`**Reason:** ${n.reason}`,``,`**Stats:** ${n.stats.verified}V / ${n.stats.assumed}A / ${n.stats.unresolved}U (${n.stats.total} total)`];return n.action&&r.push(``,`**Recommended action:** ${n.action}`),n.retriesRemaining!==void 0&&r.push(`**Retries remaining:** ${n.retriesRemaining}`),n.summary&&r.push(``,`**Summary:** ${n.summary}`),n.warnings.length>0&&r.push(``,`**Warnings:**`,...n.warnings.map(e=>`- ⚠️ ${e}`)),n.unresolvedCritical.length>0&&r.push(``,`**Blocking entries:**`,...n.unresolvedCritical.map(e=>`- #${e.id}: ${e.claim} [${e.unknownType??`untyped`}]`)),n.safetyGates&&(r.push(``,`**Safety Gates:**`,`- Provenance: ${n.safetyGates.provenance}`,`- Commitment: ${n.safetyGates.commitment}`,`- Coverage: ${n.safetyGates.coverage}`),n.safetyGates.failures.length>0&&r.push(``,`**Safety failures:**`,...n.safetyGates.failures.map(e=>`- \u{1F6D1} ${e}`))),n.annotation&&r.push(``,`**Annotation:**`,n.annotation),e.formattedMap&&r.push(``,`---`,``,e.formattedMap),r.push(``,`---`,`_Next: ${n.verdict===`YIELD`?`Proceed to implementation.`:n.action===`iterate`?`Re-run the build loop, then evaluate the gate again.`:n.action===`retry`?`Re-evaluate the gate after refreshing evidence.`:n.action===`manual`?`Ask for human review before proceeding.`:`Abort the current path and terminate the task.`}_`),{content:[{type:`text`,text:r.join(`
177
+ `)}]}}case`list`:{let e=Ze({action:`list`},p);return!e.states||e.states.length===0?{content:[{type:`text`,text:`No evidence maps found.`}]}:{content:[{type:`text`,text:e.states.map(e=>`- **${e.taskId}** (${e.tier}) — ${e.entries.length} entries — ${e.updatedAt}`).join(`
178
+ `)}]}}case`delete`:if(!t)throw Error(`task_id required for delete`);return{content:[{type:`text`,text:Ze({action:`delete`,taskId:t},p).deleted?`Deleted evidence map "${t}".`:`Evidence map "${t}" not found.`}]}}}catch(e){return pl.error(`Evidence map error`,L(e)),q(`INTERNAL`,`Evidence map error: ${e instanceof Error?e.message:String(e)}`)}}))}function hl(e,t){let n=W(`digest`);e.registerTool(`digest`,{title:n.title,description:`Compress multiple text sources (handoffs, debates, phase summaries) into a token-budgeted digest. Jointly ranks across all sources, pins structured fields (status, files, decisions, blockers), and allocates budget by priority weight.`,inputSchema:{sources:z.array(z.object({id:z.string().describe(`Source identifier (e.g., "phase-2-handoff")`),text:z.string().max(5e5).describe(`Source text to compress`),weight:z.number().min(0).default(1).describe(`Priority weight (higher = more budget)`)})).min(1).max(20).describe(`Text sources to compress`),query:z.string().describe(`Focus query — what matters for the next step?`),max_chars:z.number().min(100).max(5e4).default(4e3).describe(`Target budget in characters`),pin_fields:z.array(z.string()).optional().describe(`Key fields to always extract (default: status, files, decisions, blockers, next)`),segmentation:z.enum([`paragraph`,`sentence`,`line`]).default(`paragraph`).describe(`How to split text for scoring`),token_budget:z.number().min(50).max(12500).optional().describe(`Token budget — overrides max_chars (approx 4 chars per token). Use to fit output into a specific context window.`)},annotations:n.annotations},async({sources:e,query:n,max_chars:r,pin_fields:i,segmentation:a,token_budget:o})=>{try{let s=await Ke(t,{sources:e,query:n,maxChars:o?o*4:r,pinFields:i,segmentation:a}),c=[`## Digest (${s.totalOriginalChars} → ${s.totalCompressedChars} chars, ${(s.ratio*100).toFixed(0)}%)`,``],l=Object.keys(s.fields);if(l.length>0){c.push(`### Extracted Fields`);for(let e of l){let t=s.fields[e];c.push(`**${e}:**`);for(let e of t)c.push(` - [${e.sourceId}] ${e.value}`)}c.push(``)}c.push(`### Compressed Content`,``,s.text),c.push(``,`### Source Stats`);for(let e of s.sourceStats)c.push(`- **${e.id}**: ${e.originalChars} → ${e.keptChars} chars (${e.segmentsKept}/${e.segmentsTotal} segments)`);return c.push(``,`---`,"_Next: Use the digest as compressed context for the next phase. Use `stash` to persist it if needed._"),{content:[{type:`text`,text:c.join(`
179
+ `)}]}}catch(e){return pl.error(`Digest failed`,L(e)),q(`INTERNAL`,`Digest failed: ${e instanceof Error?e.message:String(e)}`)}})}function gl(e,t){let n=W(`forge_classify`);e.registerTool(`forge_classify`,{title:n.title,description:`Classify FORGE tier (Floor/Standard/Critical) from target files and task description. Checks blast radius, cross-package boundaries, schema/contract patterns, and security signals. Returns tier, triggers, typed unknown seeds, and ceremony guidance.`,inputSchema:{files:z.array(z.string()).min(1).max(100).describe(`Files being modified (paths)`),task:z.string().describe(`Task description`),root_path:z.string().describe(`Root path of the codebase`),enrich:z.boolean().default(!1).optional().describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens.`)},annotations:n.annotations},J(`forge_classify`,async({files:e,task:n,root_path:r,enrich:i})=>{try{let a=await nt({files:e,task:n,rootPath:r}),o=[`## FORGE Classification: **${a.tier.toUpperCase()}**`,``];if(a.triggers.length>0){o.push(`### Triggers`);for(let e of a.triggers)o.push(`- **${e.rule}** (${e.source}): ${e.detail}`);o.push(``)}if(a.packagesCrossed.length>0&&o.push(`**Packages crossed:** ${a.packagesCrossed.join(`, `)}`),a.typedUnknownSeeds.length>0){o.push(``,`### Typed Unknown Seeds`);for(let e of a.typedUnknownSeeds)o.push(`- [${e.type}] ${e.description} → use \`${e.suggestedTool}\``)}o.push(``,`### Ceremony`);let s=a.ceremony;o.push(`- **Ground:** ${s.ground}`,`- **Build:** ${s.build}`,`- **Break:** ${s.break}`,`- **Evidence Map:** ${s.evidenceMap}`,`- **Gate:** ${s.gate}`),o.push(``,`---`,`_Next: ${a.tier===`floor`?`Proceed directly to implementation.`:"Run `forge_ground` to execute the full Ground phase."}_`);let c=o.join(`
180
+ `);if(i&&t){let e=await G(t,{query:`forge classify ${n}`});c+=K(e)}return{content:[{type:`text`,text:c}]}}catch(e){return pl.error(`FORGE classify failed`,L(e)),q(`INTERNAL`,`FORGE classify failed: ${e instanceof Error?e.message:String(e)}`)}}))}function _l(e,t,n){let r=W(`stratum_card`);e.registerTool(`stratum_card`,{title:r.title,description:`Generate context cards from files — a compressed alternative to reading full files (10-100x token reduction). Tier 1 (T1): structure only (~100 tokens/file — imports, exports, functions). Tier 2 (T2): structure + query-relevant content (~300 tokens/file).`,inputSchema:{files:z.array(z.string()).min(1).max(50).describe(`Absolute file paths to generate cards for`),query:z.string().describe(`Current task query — guides relevance scoring`),tier:z.enum([`T1`,`T2`]).default(`T1`).describe(`Card tier: T1 = structural only, T2 = T1 + compressed content`),max_content_chars:z.number().min(100).max(5e3).default(800).describe(`For T2: max chars for compressed content section`)},annotations:r.annotations},async({files:e,query:r,tier:i,max_content_chars:a})=>{try{let o=await an(t,{files:e,query:r,tier:i,maxContentChars:a,cache:n}),s=[`## STRATUM Cards (${i}) — ${o.cards.length} files`,`Total: ~${o.totalTokenEstimate} tokens (was ~${o.totalOriginalTokenEstimate}, ${(o.compressionRatio*100).toFixed(0)}% of original)`,``];for(let e of o.cards)s.push(e.card,``);return s.push(`---`,"_Next: Use these cards as context instead of reading full files. Use `compact` for deeper content extraction on specific files._"),{content:[{type:`text`,text:s.join(`
181
+ `)}]}}catch(e){return pl.error(`STRATUM cards failed`,L(e)),q(`INTERNAL`,`STRATUM cards failed: ${e instanceof Error?e.message:String(e)}`)}})}function vl(e,t,n){let r=W(`forge_ground`);e.registerTool(`forge_ground`,{title:r.title,description:`Execute the complete FORGE Ground phase in a single call. Chains: tier classification → scope map → typed unknown seeds → constraint loading → file summaries → evidence map creation. Replaces 5-15 manual tool calls.`,inputSchema:{task:z.string().describe(`Task description`),files:z.array(z.string()).min(1).max(100).describe(`Target files being modified (absolute paths)`),root_path:z.string().describe(`Root path of the codebase`),max_constraints:z.number().min(0).max(10).default(3).describe(`Max constraint entries to load from AI Kit memory`),force_tier:z.enum([`floor`,`standard`,`critical`]).optional().describe(`Force a specific tier (skips auto-classification)`),task_id:z.string().optional().describe(`Custom task ID for evidence map (auto-generated if omitted)`)},annotations:r.annotations},J(`forge_ground`,async({task:e,files:r,root_path:i,max_constraints:a,force_tier:o,task_id:s},c)=>{try{let l=await rt(t,n,{task:e,files:r,rootPath:i,maxConstraints:a,forceTier:o,taskId:s}),u=Ds(c).createTask(`FORGE Ground`,3);u.progress(0,`Classification: ${l.tier}`),u.progress(1,`Files analyzed: ${l.fileSummaries.length}`),u.progress(2,`Unknowns: ${l.typedUnknownSeeds.length}`),u.complete(`FORGE Ground complete: tier=${l.tier}`);let d=[`## FORGE Ground: **${l.tier.toUpperCase()}**`,`Estimated output: ~${l.estimatedTokens} tokens`,``];if(l.classifyTriggers.length>0){d.push(`### Classification Triggers`);for(let e of l.classifyTriggers)d.push(`- **${e.rule}** (${e.source}): ${e.detail}`);d.push(``)}if(l.fileSummaries.length>0){d.push(`### Target Files`);for(let e of l.fileSummaries)d.push(`- **${e.path}** (${e.lines} lines) — exports: ${e.exports.join(`, `)||`none`} — functions: ${e.functions.join(`, `)||`none`}`);d.push(``)}if(l.typedUnknownSeeds.length>0){d.push(`### Typed Unknown Seeds`);for(let e of l.typedUnknownSeeds)d.push(`- [${e.type}] ${e.description} → \`${e.suggestedTool}\``);d.push(``)}if(l.constraints.length>0){d.push(`### Constraint Seed`);for(let e of l.constraints)d.push(`- **${e.source}** (${(e.relevance*100).toFixed(0)}%): ${e.snippet}`);d.push(``)}if(l.scopeMap){d.push(`### Scope Map: ${l.scopeMap.files.length} files (~${l.scopeMap.totalEstimatedTokens} tokens)`);for(let e of l.scopeMap.files.slice(0,5))d.push(`- ${e.path} (${(e.relevance*100).toFixed(0)}%) — ${e.reason}`);l.scopeMap.files.length>5&&d.push(`- _...and ${l.scopeMap.files.length-5} more_`),d.push(``)}l.evidenceMapTaskId&&(d.push(`**Evidence Map:** \`${l.evidenceMapTaskId}\` (initialized)`),d.push(``)),d.push(`### Ceremony Guidance`);let f=l.ceremony;return d.push(`- **Ground:** ${f.ground}`,`- **Build:** ${f.build}`,`- **Break:** ${f.break}`,`- **Evidence Map:** ${f.evidenceMap}`,`- **Gate:** ${f.gate}`),d.push(``,`---`,`_Next: ${l.tier===`floor`?`Proceed to Build phase.`:"Use `evidence_map` to track claims during Build, then `evidence_map` gate after Break."}_`),{content:[{type:`text`,text:d.join(`
182
+ `)}]}}catch(e){return pl.error(`FORGE Ground failed`,L(e)),q(`INTERNAL`,`FORGE Ground failed: ${e instanceof Error?e.message:String(e)}`)}}))}const yl=I(`tools`),bl=z.object({id:z.string().optional().describe(`Node ID (auto-generated if omitted)`),type:z.string().describe(`Node type (entity, service, api, concept, decision)`),name:z.string().describe(`Display name`),properties:z.record(z.string(),z.unknown()).optional().describe(`Arbitrary properties`),sourceRecordId:z.string().optional().describe(`Back-link to knowledge record ID`),sourcePath:z.string().optional().describe(`Source file path`)}),xl=z.object({id:z.string().optional().describe(`Edge ID (auto-generated if omitted)`),fromId:z.string().describe(`Source node ID`),toId:z.string().describe(`Target node ID`),type:z.string().describe(`Relationship type (depends-on, implements, calls, affects)`),weight:z.number().min(0).max(1).optional().describe(`Relationship weight`),properties:z.record(z.string(),z.unknown()).optional().describe(`Arbitrary properties`)});function Sl(e,t,n){let r=W(`graph`);e.registerTool(`graph`,{title:r.title,description:`Query the auto-populated code knowledge graph (modules, symbols, imports) to answer
183
+ structural questions vector search cannot.
184
+
185
+ Common flow (when you don't have a node_id yet — TWO STEPS):
186
+ 1) Discover: graph({action:'find_nodes', name_pattern:'<module-or-symbol>'})
187
+ 2) Explore: graph({action:'neighbors', node_id, direction:'incoming'|'outgoing'})
188
+
189
+ Single-step read actions:
190
+ • symbol360 — full context (definition + references + imports) for a named symbol
191
+ • traverse — walk N hops from a node
192
+ • depth_traverse — bounded-depth traversal
193
+ • find_edges — list edges matching criteria
194
+ • cohesion — module cohesion score
195
+ • stats — graph size/health
196
+ • validate — integrity check
197
+
198
+ Mutating actions (use deliberately): add, delete, clear, set_community,
199
+ detect_communities, trace_process, delete_process.
200
+
201
+ Complements: \`symbol\` (single lookup), \`trace\` (call-chain AST), \`blast_radius\` (change impact).`,outputSchema:Ro,inputSchema:{action:z.enum([`find_nodes`,`find_edges`,`neighbors`,`traverse`,`stats`,`validate`,`add`,`delete`,`clear`,`detect_communities`,`set_community`,`trace_process`,`list_processes`,`delete_process`,`depth_traverse`,`cohesion`,`symbol360`]).describe(`Action: find_nodes (search nodes), find_edges (search edges), neighbors (direct connections), traverse (multi-hop), stats (graph overview), validate (check graph integrity), add (insert nodes/edges), delete (remove nodes), clear (remove all), detect_communities (find clusters), set_community (label a node), trace_process (persist execution flow), list_processes (list traced flows), delete_process (remove a flow), depth_traverse (bucket traversal by depth), cohesion (score a community), symbol360 (full node context)`),node_type:z.string().optional().describe(`Node type filter (for find_nodes)`),name_pattern:z.string().optional().describe(`Name substring match (for find_nodes)`),source_path:z.string().optional().describe(`Source path filter`),node_id:z.string().optional().describe(`Node ID (for neighbors, traverse, delete)`),edge_type:z.string().optional().describe(`Edge type filter`),from_id:z.string().optional().describe(`Source node ID (for find_edges)`),to_id:z.string().optional().describe(`Target node ID (for find_edges)`),direction:z.enum([`outgoing`,`incoming`,`both`]).default(`both`).describe(`Traversal direction`),max_depth:z.number().min(1).max(5).default(2).describe(`Max traversal depth`),limit:z.number().min(1).max(100).default(50).describe(`Max results`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),nodes:z.array(bl).max(500).optional().describe(`Nodes to add (for action=add)`),edges:z.array(xl).max(500).optional().describe(`Edges to add (for action=add)`),community:z.string().optional().describe(`Community label (for set_community, cohesion)`),process_id:z.string().optional().describe(`Process ID (for delete_process)`),label:z.string().optional().describe(`Label for process tracing (for trace_process)`),enrich:z.boolean().default(!1).optional().describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens.`)},annotations:r.annotations},J(`graph`,async e=>{try{let r=await st(t,{action:e.action,nodeType:e.node_type,namePattern:e.name_pattern,sourcePath:e.source_path,nodeId:e.node_id,edgeType:e.edge_type,fromId:e.from_id,toId:e.to_id,direction:e.direction,maxDepth:e.max_depth,limit:e.limit,nodes:e.nodes,edges:e.edges,community:e.community,processId:e.process_id,label:e.label}),i=[r.summary];if(r.nodes&&r.nodes.length>0){i.push(`
202
+ ### Nodes`);for(let e of r.nodes){let t=Object.keys(e.properties).length>0?` — ${JSON.stringify(e.properties)}`:``;i.push(`- **${e.name}** (${e.type}, id: \`${e.id}\`)${t}`)}}if(r.edges&&r.edges.length>0){i.push(`
203
+ ### Edges`);for(let e of r.edges)i.push(`- \`${e.fromId}\` —[${e.type}]→ \`${e.toId}\`${e.weight===1?``:` (weight: ${e.weight})`}`)}if(r.stats&&(i.push(`\nNode types: ${JSON.stringify(r.stats.nodeTypes)}`),i.push(`Edge types: ${JSON.stringify(r.stats.edgeTypes)}`)),r.validation){if(i.push(`
204
+ ### Validation`),i.push(`- **Valid**: ${r.validation.valid?`yes`:`no`}`),r.validation.danglingEdges.length>0){i.push(`- **Dangling edges**:`);for(let e of r.validation.danglingEdges)i.push(` - \`${e.edgeId}\` references missing node \`${e.missingNodeId}\``)}r.validation.orphanNodes.length>0&&i.push(`- **Orphan nodes**: ${r.validation.orphanNodes.map(e=>`\`${e}\``).join(`, `)}`)}if(r.communities){i.push(`
205
+ ### Communities`);for(let[e,t]of Object.entries(r.communities)){let n=t;i.push(`- **${e}**: ${n.length} node(s) — ${n.slice(0,5).map(e=>`\`${e}\``).join(`, `)}${n.length>5?`…`:``}`)}}if(r.process&&(i.push(`
206
+ ### Process`),i.push(`- **${r.process.label}** (id: \`${r.process.id}\`)`),i.push(`- Entry: \`${r.process.entryNodeId}\``),i.push(`- Steps: ${r.process.steps.map(e=>`\`${e}\``).join(` → `)}`)),r.processes&&r.processes.length>0){i.push(`
207
+ ### Processes`);for(let e of r.processes)i.push(`- **${e.label}** (id: \`${e.id}\`) — ${e.steps.length} step(s)`)}if(r.depthGroups){i.push(`
208
+ ### Depth Groups`);for(let[e,t]of Object.entries(r.depthGroups))i.push(`- **Depth ${e}**: ${t.map(e=>`${e.name} (${e.type})`).join(`, `)}`)}if(r.cohesionScore!==void 0&&i.push(`\n**Cohesion Score**: ${(r.cohesionScore*100).toFixed(1)}%`),r.symbol360){let e=r.symbol360;i.push(`
209
+ ### 360° Symbol View`),i.push(`- **Node**: ${e.node.name} (${e.node.type})`),i.push(`- **Community**: ${e.community??`none`}`),i.push(`- **Incoming**: ${e.incoming.length} edge(s)`),i.push(`- **Outgoing**: ${e.outgoing.length} edge(s)`),i.push(`- **Processes**: ${e.processes.length}`)}i.push("\n---\n_Next: Use `graph(traverse)` to explore connections, `graph(add)` to insert entities, `graph(symbol360)` for full node context, or `graph(detect_communities)` to find clusters._");let a=i.join(`
210
+ `);if(e.enrich&&n){let t=await G(n,{query:`graph ${e.action} ${e.name_pattern??e.node_id??e.community??``}`.trim(),filePath:e.source_path});a+=K(t)}return{content:[{type:`text`,text:e.max_tokens?R(a,e.max_tokens):a}],structuredContent:{nodes:(r.nodes??[]).map(e=>({id:e.id,name:e.name,type:e.type,...e.sourcePath?{sourcePath:e.sourcePath}:{}})),edges:(r.edges??[]).map(e=>({fromId:e.fromId,toId:e.toId,type:e.type})),totalNodes:r.stats?.nodeCount??r.nodes?.length??0,totalEdges:r.stats?.edgeCount??r.edges?.length??0,query:e.action}}}catch(e){return yl.error(`Graph query failed`,L(e)),q(`INTERNAL`,`Graph query failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Cl=I(`tools:infra`);function wl(e){let t=W(`process`);e.registerTool(`process`,{title:t.title,description:`Start, stop, inspect, list, and tail logs for in-memory managed child processes.`,inputSchema:{action:z.enum([`start`,`stop`,`status`,`list`,`logs`]).describe(`Process action to perform`),id:z.string().optional().describe(`Managed process ID`),command:z.string().optional().describe(`Executable to start`),args:z.array(z.string()).optional().describe(`Arguments for start actions`),tail:z.number().min(1).max(500).optional().describe(`Log lines to return for logs actions`)},annotations:t.annotations},J(`process`,async({action:e,id:t,command:n,args:r,tail:i})=>{try{switch(e){case`start`:if(!t||!n)throw Error(`id and command are required for start`);return{content:[{type:`text`,text:JSON.stringify(Tt(t,n,r??[]))}]};case`stop`:if(!t)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify(Dt(t)??null)}]};case`status`:if(!t)throw Error(`id is required for status`);return{content:[{type:`text`,text:JSON.stringify(Et(t)??null)}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(Ct())}]};case`logs`:if(!t)throw Error(`id is required for logs`);return{content:[{type:`text`,text:JSON.stringify(wt(t,i))}]}}}catch(e){return Cl.error(`Process action failed`,L(e)),q(`INTERNAL`,`Process action failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Tl(e){let t=W(`watch`);e.registerTool(`watch`,{title:t.title,description:`Watch a directory for file changes (create/modify/delete). Actions: start (begin watching), stop (by ID), list (show active watchers). Events are emitted as structured JSON with path, event type, and timestamp.`,inputSchema:{action:z.enum([`start`,`stop`,`list`]).describe(`Watch action to perform`),path:z.string().optional().describe(`Directory path to watch for start actions`),id:z.string().optional().describe(`Watcher ID for stop actions`)},annotations:t.annotations},J(`watch`,async({action:e,path:t,id:n})=>{try{switch(e){case`start`:if(!t)throw Error(`path is required for start`);return{content:[{type:`text`,text:JSON.stringify(fn({path:t}))}]};case`stop`:if(!n)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify({stopped:pn(n)})}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(dn())}]}}}catch(e){return Cl.error(`Watch action failed`,L(e)),q(`INTERNAL`,`Watch action failed: ${e instanceof Error?e.message:String(e)}`)}}))}function El(e){let t=W(`health`);e.registerTool(`health`,{title:t.title,description:`Run project health checks — verifies package.json, tsconfig, scripts, lockfile, README, LICENSE, .gitignore.`,outputSchema:yo,inputSchema:{path:z.string().optional().describe(`Root directory to check (defaults to cwd)`)},annotations:t.annotations},J(`health`,async({path:e})=>{try{let t=lt(e),n={ok:t.checks.every(e=>e.status!==`fail`),checks:t.checks.map(e=>({name:e.name,ok:e.status===`pass`,message:e.message}))};return{content:[{type:`text`,text:JSON.stringify(t)}],structuredContent:n}}catch(e){return Cl.error(`Health check failed`,L(e)),q(`INTERNAL`,`Health check failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Dl(e){let t=W(`web_fetch`);e.registerTool(`web_fetch`,{title:t.title,description:`PREFERRED web fetcher — fetch one or many URLs and convert to LLM-optimized markdown. Pass one URL or multiple for parallel fetching. Supports CSS selectors, 4 output modes (markdown/raw/links/outline), smart paragraph-boundary truncation. Strips scripts/styles/nav automatically.`,inputSchema:{urls:z.array(z.string().url()).min(1).max(10).describe('URLs to fetch (1–10). Single URL: `["https://..."]`. Multiple fetched in parallel.'),mode:z.enum([`markdown`,`raw`,`links`,`outline`]).default(`markdown`).describe(`Output mode: markdown (clean content), raw (HTML), links (extracted URLs), outline (heading hierarchy)`),selector:z.string().optional().describe(`CSS selector to extract a specific element instead of auto-detecting main content`),max_length:z.number().min(500).max(1e5).default(15e3).describe(`Max characters in output — truncates at paragraph boundaries`),include_metadata:z.boolean().default(!0).describe(`Include page title, description, and URL as a header`),include_links:z.boolean().default(!1).describe(`Append extracted links list at the end`),include_images:z.boolean().default(!1).describe(`Include image alt texts inline`),timeout:z.number().min(1e3).max(12e4).default(3e4).describe(`Request timeout in milliseconds`)},annotations:t.annotations},J(`web_fetch`,async({urls:e,mode:t,selector:n,max_length:r,include_metadata:i,include_links:a,include_images:o,timeout:s})=>{let c=e,l=async(e,c)=>{let l=await mn({url:e,mode:t,selector:n,maxLength:r,includeMetadata:i,includeLinks:a,includeImages:o,timeout:s}),u=[c?`## ${c} ${l.title||`Web Page`}\n> Source: ${e}`:`## ${l.title||`Web Page`}`,``,l.content];return l.truncated&&u.push(``,`_Original length: ${l.originalLength.toLocaleString()} chars_`),u.join(`
211
+ `)};if(c.length===1)try{return{content:[{type:`text`,text:await l(c[0])+"\n\n---\n_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"}]}}catch(e){let t=e instanceof Error?e.message:String(e);return/HTTP [45]\d{2}/.test(t)?Cl.warn(`Web fetch failed`,{error:t}):Cl.error(`Web fetch failed`,L(e)),{...q(`INTERNAL`,`Web fetch failed: ${t}`)}}let u=c.length,d=await Promise.allSettled(c.map((e,t)=>l(e,`[${t+1}/${u}]`))),f=[],p=0;for(let e=0;e<d.length;e++){let t=d[e];if(t.status===`fulfilled`)f.push(t.value);else{p++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);/HTTP [45]\d{2}/.test(n)?Cl.warn(`Web fetch failed`,{url:c[e],error:n}):Cl.error(`Web fetch failed`,{url:c[e],...L(t.reason)}),f.push(`## ❌ Failed: ${c[e]}\n\n${n}`)}}let m=`_Fetched ${d.length-p}/${d.length} URLs successfully._`;f.push(``,`---`,m,"_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._");let h=f.join(`
212
+
213
+ `);return p===d.length?q(`INTERNAL`,h):{content:[{type:`text`,text:h}]}}))}function Ol(e,t){let n=W(`guide`);e.registerTool(`guide`,{title:n.title,description:`Tool discovery — given a goal description, recommends which AI Kit tools to use and in what order. Matches against 10 predefined workflows: onboard, audit, bugfix, implement, refactor, search, context, memory, validate, analyze.`,inputSchema:{goal:z.string().describe(`What you want to accomplish (e.g., "audit this monorepo", "fix a failing test")`),max_recommendations:z.number().min(1).max(10).default(5).describe(`Maximum number of tool recommendations`)},annotations:n.annotations},J(`guide`,async({goal:e,max_recommendations:n})=>{try{let r=ct(e,n,t),i=[`## Recommended Workflow: **${r.workflow}**`,r.description,``,`### Tools`,...r.tools.map(e=>{let t=e,n=t.suggestedArgs?` — \`${JSON.stringify(t.suggestedArgs)}\``:``,r=t.tokenTip?`\n 💡 ${t.tokenTip}`:``;return`${t.order}. **${t.tool}** — ${t.reason}${n}${r}`})];return r.alternativeWorkflows.length>0&&i.push(``,`_Alternative workflows: ${r.alternativeWorkflows.join(`, `)}_`),i.push(``,`---`,"_Next: Run the first recommended tool, or use `guide` again with a more specific goal._"),{content:[{type:`text`,text:i.join(`
214
+ `)}]}}catch(e){return Cl.error(`Guide failed`,L(e)),q(`INTERNAL`,`Guide failed: ${e instanceof Error?e.message:String(e)}`)}}))}const kl={decision:6,pattern:5,"file-card":4,analysis:3,"search-result":2,"step-summary":1},Al={implementer:{name:`implementer`,contextTypes:[`file-card`,`decision`,`pattern`],priority:{...kl}},documenter:{name:`documenter`,contextTypes:[`decision`,`pattern`,`step-summary`],priority:{...kl}},reviewer:{name:`reviewer`,contextTypes:[`file-card`,`search-result`,`decision`,`pattern`,`step-summary`,`analysis`],priority:{...kl}},researcher:{name:`researcher`,contextTypes:[`search-result`,`decision`,`analysis`],priority:{...kl}},debugger:{name:`debugger`,contextTypes:[`file-card`,`search-result`,`pattern`,`analysis`],priority:{...kl}}};function jl(e){return Al[e]}function Ml(e,t,n){if(n<=0)return[];let r=new Set(t.contextTypes),i=e.filter(e=>r.has(e.type)).map((e,t)=>({entry:e,index:t})).sort((e,n)=>{let r=t.priority[n.entry.type]-t.priority[e.entry.type];return r===0?e.index-n.index:r}),a=[],o=0;for(let{entry:e}of i){let t=e.content.length;o+t>n||(a.push(e),o+=t)}return a}function Nl(e,t,n){if(!(!e||typeof e!=`string`)&&!(e.includes(`..`)||e.startsWith(`/`)||e.startsWith(`[`)))return{type:`resource_link`,uri:`aikit://curated/${e}`,name:t??e,mimeType:`text/markdown`,...n?{description:n}:{}}}function Pl(e){let t=new Set,n=[];for(let r of e){let e=Nl(r.path,r.title,r.category?`[${r.category}]`:void 0);e&&!t.has(e.uri)&&(t.add(e.uri),n.push(e))}return n}function Fl(e){if(e.startsWith(`.ai/curated/`))return e.slice(12)}const Il=I(`tools`),Ll=z.enum([`remember`,`read`,`update`,`forget`,`list`,`history`,`diff`,`recover`,`orphaned`,`withdraw`,`flush`,`flagged`,`lesson`]),Rl=z.string().min(3).max(120).describe(`Short descriptive title for the knowledge entry`),zl=z.string().min(10).max(1e5),Bl=z.string().regex(/^[a-z][a-z0-9-]*$/).describe(`Category slug (e.g., "decisions", "patterns", "conventions", "api-contracts")`),Vl=z.array(z.string()).default([]).describe(`Optional tags for filtering`),Hl=z.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/use-lancedb.md")`),Ul=z.string().min(3),Wl=z.object({title:Rl,content:zl.describe(`The markdown content to store`),category:Bl,tags:Vl,force:z.boolean().optional().describe(`When true, supersede flagged similar entries without waiting for confirmation`)}),Gl=z.object({path:Hl}),Kl=z.object({path:Hl,content:zl.describe(`New markdown content to replace existing content`),reason:Ul.max(1e3).describe(`Why this update is being made (recorded in changelog)`)}),ql=z.object({path:z.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/deprecated-approach.md")`),reason:Ul.describe(`Why this entry is being removed`)}),Jl=z.object({category:z.string().optional().describe(`Filter by category (e.g., "decisions", "patterns")`),tag:z.string().optional().describe(`Filter by tag`)}),Yl=z.enum([`create`,`confirm`,`contradict`,`list-lessons`]),Xl=z.enum([`confidence`,`recent`]),Zl=z.number().int().min(0).max(100).describe(`Lesson confidence from 0-100`),Ql=z.object({action:Ll.describe(`Knowledge operation to perform`),title:Rl.optional(),content:zl.optional(),category:Bl.optional(),tags:z.array(z.string()).optional().describe(`Optional tags for remember`),path:Hl.optional(),reason:Ul.max(1e3).optional(),scope:z.enum([`curated`,`flow`]).optional().describe(`Storage scope: curated (default) or flow-scoped ephemeral context`),profile:z.string().optional().describe(`Role profile for withdraw filtering (e.g., "implementer", "reviewer", "debugger")`),budget:z.number().int().min(100).max(5e4).optional().describe(`Maximum character budget for withdraw results (default: 6000)`),tag:z.string().optional().describe(`Filter by tag when action="list"`),id:Hl.optional().describe(`Alias for path when action="lesson"`),subAction:Yl.optional().describe(`Lesson sub-action when action="lesson"`),context:zl.optional().describe(`What happened (the situation) for lesson creation`),insight:zl.optional().describe(`What was learned (the lesson) for lesson creation`),evidence:zl.optional().describe(`Proof or justification for lesson creation`),confidence:Zl.optional(),minConfidence:Zl.optional().describe(`Minimum confidence when listing lessons`),topic:z.string().optional().describe(`Topic filter when listing lessons`),sortBy:Xl.optional().describe(`Sort lessons by confidence or recency`),includeArchived:z.boolean().optional().describe(`Include auto-archived lessons in list-lessons`),limit:z.number().int().min(1).max(100).optional().describe(`Maximum history entries to return (for action="history", default: 20)`),force:z.boolean().optional().describe(`When true, supersede flagged similar entries without waiting for confirmation`),from_sha:z.string().optional().describe(`Start SHA for diff (older version). If omitted with to_sha, shows full content.`),to_sha:z.string().optional().describe(`End SHA for diff (newer version). If omitted, uses the latest two versions.`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),enrich:z.boolean().default(!1).optional().describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens.`)});function $l(e,t){return[`knowledge`,e,t.path,t.id,t.title,t.topic,t.category,t.tag,t.profile].filter(e=>typeof e==`string`&&e.length>0).join(` `)}async function eu(e,t,n){let r=e.content.find(e=>e.type===`text`);if(!r)return e;let i=r.text;if(t.enrich&&n){let e=await G(n,{query:$l(t.action,t)});i+=K(e)}return t.max_tokens&&(i=R(i,t.max_tokens)),{...e,content:e.content.map(e=>e.type===`text`?{...e,text:i}:e)}}const tu=z.object({title:Rl,context:zl.describe(`What happened (the situation)`),insight:zl.describe(`What was learned (the lesson)`),evidence:zl.describe(`Proof or justification`),confidence:Zl.default(50),tags:Vl.optional().default([])}),nu=z.object({path:Hl.optional(),id:Hl.optional(),reason:Ul.max(1e3).optional()}).refine(e=>!!(e.path??e.id),{message:`path or id is required`,path:[`path`]}),ru=z.object({topic:z.string().optional(),minConfidence:Zl.optional(),tag:z.string().optional(),tags:z.array(z.string()).optional(),sortBy:Xl.default(`confidence`),includeArchived:z.boolean().default(!1)});function iu(e,t,i,a){r(e,t,i);let o=e.memoryMetaGet(t);if(!o)return;let s=_(o,{...n,...a});return s?(v(e,t,s),h(e,t,i)??e.memoryMetaGet(t)):o}function au(e,t){return`\n\n### ${e}\n${t.map(e=>`- **${e.title}** (${e.id}) — similarity ${e.similarity.toFixed(3)}`).join(`
215
+ `)}`}async function ou(e,t,n,r){if(typeof e.list!=`function`||typeof e.read!=`function`)return[];let i=c(r),a=await e.list({category:n});return a.length===0?[]:d(t,await Promise.all(a.slice(0,i.maxCompare).map(async t=>{let n=await e.read(t.path);return{id:t.path,title:n.title,content:n.content,path:t.path}})),i)}function su(e,t,n){return{superseded:e.filter(e=>n||e.similarity>=t).map(e=>({id:e.entryId,title:e.title,similarity:e.similarity})),supersessionCandidates:n?[]:e.filter(e=>e.similarity<t).map(e=>({id:e.entryId,title:e.title,similarity:e.similarity}))}}const cu={decisions:`decision`,patterns:`pattern`,conventions:`pattern`,context:`analysis`,session:`step-summary`},lu=new Set([`decision`,`pattern`,`file-card`,`analysis`,`search-result`,`step-summary`]);function uu(e){if(!e)return`analysis`;let t=cu[e]??e;return lu.has(t)?t:`analysis`}function du(e){let t=[...new Set(e.issues.filter(e=>e.code===`invalid_type`&&/received undefined$/i.test(e.message)).map(e=>e.path.join(`.`)).filter(e=>e.length>0))];if(t.length>0)return`Missing required fields: ${t.join(`, `)}`;let n=e.issues.map(e=>`${e.path.length>0?`${e.path.join(`.`)}: `:``}${e.message}`).join(`; `);return n.length>0?`Invalid parameters: ${n}`:`Invalid parameters.`}function fu(e,t){return e??t??``}function pu(e){return[...new Set([...e??[],`lesson`])]}function mu(e,t,n){if(e)return e.memoryMetaCreate(t,`working`),e.memoryMetaUpdateConfidence(t,n),e.memoryMetaGet(t)}async function hu(e,t,n){let r=await e.read(n),i=p(r.content),a=t?.memoryMetaGet(n)?.confidence??i.confidence??50;return{entry:r,confidence:a,meta:mu(t,n,a)??t?.memoryMetaGet(n)}}async function gu(e,{curated:t,stateStore:n,resourceNotifier:r}){let{title:i,context:o,insight:s,evidence:c,confidence:l,tags:u}=tu.parse(e),d=a({title:i,context:o,insight:s,evidence:c,confidence:l,tags:u}),f=await t.remember(i,d,`lessons`,pu(u));return mu(n,f.path,l),r&&r.notifyAfterCuratedWrite(f.path).catch(()=>{}),{content:[{type:`text`,text:`Recorded lesson: **${i}**\n\nStored at \`.ai/curated/${f.path}\` with confidence ${l}/100.`}],structuredContent:{path:f.path,confidence:l,category:`lessons`,tags:pu(u)}}}async function _u(e,t,n){let{curated:r,stateStore:a,resourceNotifier:o,retentionConfig:c,consolidationConfig:d,lessonConfig:f}=n,p=nu.parse(e);if(t===`contradict`&&!p.reason)throw new z.ZodError([{code:`custom`,path:[`reason`],message:`reason is required`}]);let m=fu(p.path,p.id),h=u(f??l);a&&iu(a,m,c,d);let{entry:g,confidence:_}=await hu(r,a,m),v=i(_,t,h),y=s(g.content,v),b=t===`confirm`?p.reason??`Confirmed lesson confidence`:`Contradicted lesson confidence: ${p.reason}`,x=await r.update(m,y,b);return a&&a.memoryMetaUpdateConfidence(m,v),o&&o.notifyAfterCuratedWrite(m).catch(()=>{}),{content:[{type:`text`,text:`${t===`confirm`?`Confirmed`:`Contradicted`} lesson: \`${m}\`\n\nConfidence ${_}/100 → ${v}/100.`}],structuredContent:{path:x.path,confidence:v,previousConfidence:_,version:x.version}}}async function vu(e,{curated:t,stateStore:n,lessonConfig:r}){let{topic:i,minConfidence:a,tag:s,tags:c,sortBy:d,includeArchived:f}=ru.parse(e),p=pu([...c??[],...s?[s]:[]]),m=u(r??l),h=await t.list({category:`lessons`,...s?{tag:s}:{}}),_=await Promise.all(h.filter(e=>e.tags.includes(`lesson`)).map(async e=>{let t=n?.memoryMetaGet(e.path),r=t?.confidence??50,i=mu(n,e.path,r)??t;i&&i.supersededBy===null&&o(i,m)&&n?.memoryMetaSetSuperseded(e.path,g);let a=n?.memoryMetaGet(e.path)??i,s=a?.lastAccessedAt??a?.createdAt??null;return{path:e.path,title:e.title,category:e.category,tags:e.tags,version:e.version,preview:e.contentPreview,confidence:a?.confidence??r,createdAt:a?.createdAt??null,lastAccessedAt:a?.lastAccessedAt??null,recency:s,archived:a?.supersededBy===g,supersededBy:a?.supersededBy??null}})),v=_.filter(e=>e.archived).length,y=_.filter(e=>f?!0:e.supersededBy===null).filter(e=>a===void 0?!0:e.confidence>=a).filter(e=>p.length===0?!0:p.every(t=>e.tags.includes(t))).filter(e=>i?`${e.title}\n${e.preview}\n${e.tags.join(` `)}`.toLowerCase().includes(i.toLowerCase()):!0).sort((e,t)=>d===`recent`?Date.parse(t.recency??``)-Date.parse(e.recency??``)||t.confidence-e.confidence:t.confidence-e.confidence||Date.parse(t.recency??``)-Date.parse(e.recency??``));if(y.length===0)return{content:[{type:`text`,text:`No lessons matched the requested filters.`}],structuredContent:{entries:[],totalCount:0,archivedCount:v}};let b=y.map(e=>{let t=e.recency?` | recent ${e.recency}`:``;return`- **${e.title}** (${e.confidence}/100)${t}\n \`${e.path}\` — ${e.preview.slice(0,80)}…`}).join(`
216
+ `);return{content:[{type:`text`,text:`## Lessons (${y.length})\n\n${b}`}],structuredContent:{entries:y,totalCount:y.length,archivedCount:v}}}async function yu(e,t){switch(e.subAction??`create`){case`create`:return gu(e,t);case`confirm`:return _u(e,`confirm`,t);case`contradict`:return _u(e,`contradict`,t);case`list-lessons`:return vu(e,t)}}async function bu(e,t){if(e.scope===`flow`){let{flowContextAdapter:n,stateStore:r}=t;if(!n)return{content:[{type:`text`,text:`Flow context not available.`}]};let{title:i,content:a,category:o}=Wl.parse(e),s=`${uu(o)}/${i.toLowerCase().replace(/[^a-z0-9]+/g,`-`).slice(0,60)}.md`;return await n.write(s,`# ${i}\n\n${a}`),r?.memoryMetaCreate(s,`working`),{content:[{type:`text`,text:`Deposited flow context: **${i}** at \`${s}\``}]}}let{curated:n,policyStore:r,evolutionCollector:i,resourceNotifier:a,stateStore:o,supersessionConfig:s}=t,{title:l,content:u,category:d,tags:f,force:p=!1}=Wl.parse(e),h=c(s),g=await ou(n,u,d,h),_=await n.remember(l,u,d,f);o?.memoryMetaCreate(_.path,`working`);let v=su(g,h.autoThreshold,p);if(o)for(let e of v.superseded)m(o,e.id,_.path);let y=``;if(r){let e=r.classify(l,u,f);i&&i.recordClassification(l,e.matchingRules.map(e=>e.ruleId),e.pushRecommended),e.matchingRules.length>0&&(y=`\n\n### Classification Signals\n${e.matchingRules.map(e=>` - **${e.ruleId}** (${e.category}, weight: ${e.pushWeight}) — matched: ${e.matchedPatterns.join(`, `)}`).join(`
217
+ `)}\n- **Push recommended**: ${e.pushRecommended?`yes`:`no`} (max weight: ${e.maxPushWeight})`,e.pushRecommended&&(y+=`
218
+
219
+ > 💡 This entry matches push rules. Consider \`er_push\` to share with Enterprise RAG.`))}a&&a.notifyAfterCuratedWrite(_.path).catch(()=>{});let b=Nl(_.path,l,`[${d}]`),x=v.superseded.length>0?au(`Superseded Entries`,v.superseded):``,S=v.supersessionCandidates.length>0?au(`Supersession Suggestions`,v.supersessionCandidates):``;return{content:[{type:`text`,text:`Remembered: **${l}**\n\nStored at \`.ai/curated/${_.path}\` and indexed for semantic search.${y}${x}${S}\n\n---\n_Next: Use \`search\` to verify the entry is findable, or \`knowledge({ action: "list" })\` to see all curated entries._`},...b?[b]:[]],structuredContent:{path:_.path,superseded:v.superseded,supersessionCandidates:v.supersessionCandidates}}}async function xu(e,{curated:t,stateStore:n,retentionConfig:r,consolidationConfig:i}){let{path:a}=Gl.parse(e),o=await t.read(a),s=n?iu(n,a,r,i):void 0,c=[`## ${o.title}`,`- **Path**: .ai/curated/${a}`,`- **Category**: ${o.category}`,o.tags.length?`- **Tags**: ${o.tags.join(`, `)}`:null,`- **Version**: ${o.version}`,`- **Created**: ${o.created}`,o.updated===o.created?null:`- **Updated**: ${o.updated}`,s?`- **Tier**: ${s.tier}`:null,s?`- **Retention**: ${s.retentionScore.toFixed(3)}`:null,``].filter(e=>e!==null).join(`
220
+ `),l=Nl(a,o.title,`[${o.category}]`);return{content:[{type:`text`,text:`${c}\n${o.content}\n\n---\n_Next: Use \`knowledge({ action: "update", ... })\` to modify this entry, or \`search\` to find related entries._`},...l?[l]:[]]}}async function Su(e,{curated:t,resourceNotifier:n}){let{path:r,content:i,reason:a}=Kl.parse(e),o=await t.update(r,i,a);return n&&n.notifyAfterCuratedWrite(r).catch(()=>{}),{content:[{type:`text`,text:`Updated: \`.ai/curated/${o.path}\` → version ${o.version}\n\nReason: ${a}\n\n---\n_Next: Use \`knowledge({ action: "read", path: "${o.path}" })\` to verify the updated content, or \`search\` to test searchability._`}]}}async function Cu(e,{curated:t,resourceNotifier:n}){let{path:r,reason:i}=ql.parse(e),a=F(t.curatedDir,r);if(k(a))try{Re(`forget`,[{path:a,content:j(a,`utf-8`)}],`forget: ${r}`)}catch{}let o=await t.forget(r,i);return Il.info(`Forgot entry`,{path:o.path,reason:i}),n&&(n.notifyAfterCuratedWrite().catch(()=>{}),n.notifyResourceListChanged().catch(()=>{})),{content:[{type:`text`,text:`Forgotten: \`.ai/curated/${o.path}\`\n\nRemoved from disk and vector store.\nReason: ${i}\n\n---\n_Next: Use \`knowledge({ action: "list" })\` to verify removal, or \`search\` to confirm the entry is no longer returned._`}]}}async function wu(e,{curated:t,flowContextAdapter:n,stateStore:r,retentionConfig:i}){if(e.scope===`flow`){if(!n)return{content:[{type:`text`,text:`Flow context not available.`}]};let e=await n.list();if(e.length===0)return{content:[{type:`text`,text:`No flow context entries.`}]};let t=e.map(e=>({entry:e,retentionMeta:r?h(r,e.path,i):void 0})),a=t.map(({entry:e,retentionMeta:t})=>{let n=t?`, tier ${t.tier}, retention ${t.retentionScore.toFixed(3)}`:``;return`- \`${e.path}\` (${e.size} bytes${n})`}).join(`
221
+ `);return{content:[{type:`text`,text:`## Flow Context (${e.length} entries)\n\n${a}`}],structuredContent:{entries:t.map(({entry:e,retentionMeta:t})=>({path:e.path,size:e.size,...t?{retentionScore:t.retentionScore,tier:t.tier}:{}})),totalCount:e.length}}}let{category:a,tag:o}=Jl.parse(e),s=await t.list({category:a,tag:o}),c=s.map(e=>({entry:e,retentionMeta:r?h(r,e.path,i):void 0})),l={entries:c.map(({entry:e,retentionMeta:t})=>({path:e.path,title:e.title,category:e.category,tags:e.tags,version:e.version,preview:e.contentPreview?.slice(0,120)??``,...t?{retentionScore:t.retentionScore,tier:t.tier}:{}})),totalCount:s.length};if(s.length===0)return{content:[{type:`text`,text:`No curated knowledge entries found.`+(a?` (category: ${a})`:``)+(o?` (tag: ${o})`:``)}],structuredContent:l};let u=c.map(({entry:e,retentionMeta:t})=>{let n=e.tags.length>0?` [${e.tags.join(`, `)}]`:``,r=t?` | tier ${t.tier} | retention ${t.retentionScore.toFixed(3)}`:``;return`- **${e.title}** (v${e.version})${n}${r}\n \`${e.path}\` — ${e.contentPreview.slice(0,80)}…`}).join(`
222
+ `),d=Pl(s);return{content:[{type:`text`,text:`## Curated Knowledge (${s.length} entries)\n\n${u}\n\n---\n_Next: Use \`knowledge({ action: "read", path: "..." })\` to view full content of any entry, or \`knowledge({ action: "remember", ... })\` to store new knowledge._`},...d],structuredContent:l}}async function Tu(e,{curated:t}){let{path:n}=Gl.parse(e),r=e.limit??20,i=await t.history(n,r);if(i.length===0)return{content:[{type:`text`,text:`No git history available for this entry. Git-backing may not be available or the entry predates git-backing.`}]};let a=i.map((e,t)=>`${t+1}. **${e.date}** \`${e.sha.slice(0,8)}\` — ${e.message}`).join(`
223
+ `);return{content:[{type:`text`,text:`## History for \`${n}\` (${i.length} entries)\n\n${a}\n\n_Use \`knowledge({ action: "diff", path: "${n}", from_sha: "...", to_sha: "..." })\` to compare versions._`}]}}async function Eu(e,{curated:t}){let{path:n}=Gl.parse(e),{from_sha:r,to_sha:i}=e,a=await t.diff(n,r,i);return a?{content:[{type:`text`,text:`## Diff for \`${n}\`\n\n\`\`\`diff\n${a}\n\`\`\``}]}:{content:[{type:`text`,text:`No diff available. Git-backing may not be available or the entry has no history.`}]}}async function Du(e,{curated:t}){let{path:n}=Gl.parse(e),r=await t.recover(n);return r?{content:[{type:`text`,text:`✅ Recovered \`${r.path}\` (version ${r.version}) from git history. The entry has been restored to the filesystem and re-indexed.`}]}:{content:[{type:`text`,text:`No git history found for \`${n}\`. Cannot recover — the entry either never existed or was never git-backed.`}]}}async function Ou(e,{curated:t}){let n=await t.listOrphaned();if(n.length===0)return{content:[{type:`text`,text:`No orphaned entries found. All git-backed entries have corresponding filesystem files.`}]};let r=n.map((e,t)=>`${t+1}. \`${e.path}\` — last: ${e.lastMessage}`).join(`
224
+ `);return{content:[{type:`text`,text:`## Orphaned Knowledge Entries (${n.length})\n\nThese entries exist in git but are missing from the filesystem:\n\n${r}\n\n_Use \`knowledge({ action: "recover", path: "..." })\` to restore any of these entries._`}]}}async function ku(e,{flowContextAdapter:t,stateStore:n,retentionConfig:r,consolidationConfig:i}){let a=z.object({profile:z.string(),budget:z.number().int().min(100).max(5e4).default(6e3)}).parse(e);if(!t)return{content:[{type:`text`,text:`Flow context not available — no active flow or adapter not configured.`}]};let o=jl(a.profile);if(!o)return{content:[{type:`text`,text:`Unknown profile: "${a.profile}". Available: implementer, documenter, reviewer, researcher, debugger`}]};let s=await t.list();if(s.length===0)return{content:[{type:`text`,text:`No flow context available yet. Context is deposited automatically as agents use search, file_summary, and other analysis tools.`}]};let c=(await Promise.all(s.map(async e=>{let a=e.path.split(`/`),o=a[0];if(a.length<2||!lu.has(o))return null;let s=await t.read(e.path);return s?(n&&iu(n,e.path,r,i),{type:o,content:s}):null}))).filter(e=>e!==null),l=Ml(c,o,a.budget);if(l.length===0)return{content:[{type:`text`,text:`No relevant context for profile "${a.profile}". ${c.length} entries available but none match your role's context types.`}]};let u=l.map(e=>`### [${e.type}]\n${e.content}`).join(`
225
+
226
+ `),d=l.reduce((e,t)=>e+t.content.length,0);return{content:[{type:`text`,text:`## Flow Context (${l.length}/${c.length} entries, ${d} chars, profile: ${a.profile})\n\n${u}`}]}}async function Au(e,{flowContextAdapter:t}){return t?{content:[{type:`text`,text:`Flushed ${await t.flushAll()} flow context entries.`}]}:{content:[{type:`text`,text:`Flow context not available — no active flow or adapter not configured.`}]}}async function ju(e,{stateStore:t,retentionConfig:n}){if(!t)return{content:[{type:`text`,text:`Retention state store not available.`}],structuredContent:{entries:[],totalCount:0}};let r=f(t,n);if(r.length===0)return{content:[{type:`text`,text:`No flagged knowledge entries found below the current retention threshold.`}],structuredContent:{entries:[],totalCount:0}};let i=r.map(e=>`- \`${e.entryId}\` — score ${e.retentionScore.toFixed(3)}, tier ${e.tier}, accesses ${e.accessCount}`).join(`
227
+ `);return{content:[{type:`text`,text:`## Flagged Knowledge Entries (${r.length})\n\n${i}`}],structuredContent:{entries:r,totalCount:r.length}}}async function Mu(e,t,n){switch(e){case`remember`:return bu(t,n);case`read`:return xu(t,n);case`update`:return Su(t,n);case`forget`:return Cu(t,n);case`list`:return wu(t,n);case`history`:return Tu(t,n);case`diff`:return Eu(t,n);case`recover`:return Du(t,n);case`orphaned`:return Ou(t,n);case`withdraw`:return ku(t,n);case`flush`:return Au(t,n);case`flagged`:return ju(t,n);case`lesson`:return yu(t,n)}}function Nu(e,t,n,r,i,a,o,s,c,l,u,d){let f=W(`knowledge`),p={curated:t,policyStore:n,evolutionCollector:r,resourceNotifier:i,flowContextAdapter:a,stateStore:o,retentionConfig:s,consolidationConfig:l,supersessionConfig:c,lessonConfig:u};e.registerTool(`knowledge`,{title:f.title,description:"Operate on curated knowledge entries with a single tool. Use `action` to remember, read, update, forget, list, history, diff, recover, orphaned, withdraw, flush, flagged, or lesson entries.",inputSchema:Ql.shape,annotations:f.annotations},J(`knowledge`,async({action:e,...t})=>{try{let n=Ql.parse({action:e,...t});return await eu(await Mu(n.action,n,p),n,d)}catch(e){return e instanceof z.ZodError?q(`VALIDATION`,du(e)):(Il.error(`Knowledge operation failed`,L(e)),q(`INTERNAL`,`Knowledge operation failed: ${e instanceof Error?e.message:String(e)}`))}}))}const Pu=I(`tools`);function Fu(e,t,n){let r=W(`lookup`);e.registerTool(`lookup`,{title:r.title,description:`Get all indexed content for a known file path, sorted by position. Use when you know the exact file. For discovery across files use search.`,inputSchema:{path:z.string().describe(`Relative file path to look up (e.g., "src/index.ts")`),enrich:z.boolean().default(!1).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default false — set true when you need stored decisions, conventions, or relationship context.`)},annotations:r.annotations},J(`lookup`,async({path:e,enrich:r})=>{try{let i=await t.getBySourcePath(e);if(i.length===0)return{content:[{type:`text`,text:`No indexed content found for: ${e}`}]};i.sort((e,t)=>e.chunkIndex-t.chunkIndex);let a=`## ${e}\n**Chunks**: ${i.length} | **Type**: ${i[0].contentType}\n`,o=i.map(e=>{let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;return`### Chunk ${e.chunkIndex+1}/${e.totalChunks}${t}\n${e.content}`}).join(`
228
+
229
+ `),s=Fl(e),c=s?Nl(s):void 0,l=`${a}\n${o}\n\n---\n_Next: Use \`search\` to find related content, or \`analyze({ aspect: "dependencies", path: "${e}" })\` to see what this file imports._`;if(r&&n){let t=await G(n,{query:e});l+=K(t)}return{content:[{type:`text`,text:l},...c?[c]:[]]}}catch(e){return Pu.error(`Lookup failed`,L(e)),q(`INTERNAL`,`Lookup failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Iu=I(`tools:manipulation`);function Lu(e){return e.sources[0]?.path??process.cwd()}function Ru(e,t){let n=F(t,e),r=oe(t,n);if(r.startsWith(`..`)||ae(r))throw Error(`Path "${e}" escapes workspace root: ${t}`);return n}function zu(e){let t=W(`git_context`);e.registerTool(`git_context`,{title:t.title,description:`Summarize the current Git branch, working tree state, recent commits, and optional diff statistics for the repository.`,inputSchema:{cwd:z.string().optional().describe(`Repository root or working directory`),commit_count:z.number().min(1).max(50).default(5).optional().describe(`How many recent commits to include`),include_diff:z.boolean().default(!1).optional().describe(`Include diff stat for working tree changes`)},annotations:t.annotations,outputSchema:Vo},async({cwd:e,commit_count:t,include_diff:n})=>{try{let r=await at({cwd:e,commitCount:t,includeDiff:n});return{content:[{type:`text`,text:Wu(r)}],structuredContent:{gitRoot:r.gitRoot,branch:r.branch,commitCount:r.recentCommits.length,hasUncommitted:r.status.staged.length>0||r.status.modified.length>0||r.status.untracked.length>0,recentCommits:r.recentCommits.map(e=>({hash:e.hash,message:e.message,author:e.author,date:e.date}))}}}catch(e){return Iu.error(`Git context failed`,L(e)),q(`INTERNAL`,`Git context failed: ${e instanceof Error?e.message:String(e)}`)}})}function Bu(e){let t=W(`diff_parse`);e.registerTool(`diff_parse`,{title:t.title,description:`Parse raw unified diff text into file-level and hunk-level structural changes.`,inputSchema:{diff:z.string().max(1e6).describe(`Raw unified diff text`)},annotations:t.annotations},async({diff:e})=>{try{return{content:[{type:`text`,text:Gu(Ge({diff:e.replace(/\\n/g,`
230
+ `).replace(/\\t/g,` `)}))}]}}catch(e){return Iu.error(`Diff parse failed`,L(e)),q(`INTERNAL`,`Diff parse failed: ${e instanceof Error?e.message:String(e)}`)}})}function Vu(e,t){let n=W(`rename`),r=Lu(t);e.registerTool(`rename`,{title:n.title,description:`Rename a symbol across files using whole-word regex matching for exports, imports, and general usage references.`,inputSchema:{old_name:z.string().describe(`Existing symbol name to replace`),new_name:z.string().describe(`New symbol name to use`),root_path:z.string().describe(`Root directory to search within`),extensions:z.array(z.string()).optional().describe(`Optional file extensions to include, such as .ts,.tsx,.js,.jsx`),dry_run:z.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:n.annotations},J(`rename`,async({old_name:e,new_name:t,root_path:n,extensions:i,dry_run:a},o)=>{let s;try{s=Ds(o).createTask(`Rename Symbol`,2),s.progress(0,`Scanning for references`);let c=Ru(n,r);s.progress(1,`Applying renames`);let l=await Vt({oldName:e,newName:t,rootPath:c,extensions:i,dryRun:a});return s.complete(`Rename complete`),{content:[{type:`text`,text:JSON.stringify(l)}]}}catch(e){return s?.fail?.(`Rename failed`),Iu.error(`Rename failed`,L(e)),q(`INTERNAL`,`Rename failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Hu(e,t){let n=W(`codemod`),r=Lu(t);e.registerTool(`codemod`,{title:n.title,description:`Apply regex-based codemod rules across files and return structured before/after changes for each affected line.`,inputSchema:{root_path:z.string().describe(`Root directory to transform within`),rules:z.array(z.object({description:z.string().describe(`What the codemod rule does`),pattern:z.string().describe(`Regex pattern in string form`),replacement:z.string().describe(`Replacement string with optional capture groups`)})).min(1).describe(`Codemod rules to apply`),dry_run:z.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:n.annotations},J(`codemod`,async({root_path:e,rules:t,dry_run:n},i)=>{let a;try{a=Ds(i).createTask(`Codemod`,2),a.progress(0,`Scanning files`);let o=Ru(e,r);a.progress(1,`Applying transforms`);let s=await Fe({rootPath:o,rules:t,dryRun:n});return a.complete(`Codemod complete`),{content:[{type:`text`,text:JSON.stringify(s)}]}}catch(e){return a?.fail?.(`Codemod failed`),Iu.error(`Codemod failed`,L(e)),q(`INTERNAL`,`Codemod failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Uu(e){let t=W(`data_transform`);e.registerTool(`data_transform`,{title:t.title,description:`Apply small jq-like transforms to JSON input for filtering, projection, grouping, and path extraction.`,inputSchema:{input:z.string().max(5e5).describe(`Input JSON string`),expression:z.string().max(1e4).describe(`Transform expression to apply`)},annotations:t.annotations},async({input:e,expression:t})=>{try{return{content:[{type:`text`,text:Ve({input:e,expression:t}).outputString}]}}catch(e){return Iu.error(`Data transform failed`,L(e)),q(`INTERNAL`,`Data transform failed: ${e instanceof Error?e.message:String(e)}`)}})}function Wu(e){let t=[`Git root: ${e.gitRoot}`,`Branch: ${e.branch}`,`Staged: ${e.status.staged.length}`,...e.status.staged.map(e=>` - ${e}`),`Modified: ${e.status.modified.length}`,...e.status.modified.map(e=>` - ${e}`),`Untracked: ${e.status.untracked.length}`,...e.status.untracked.map(e=>` - ${e}`),``,`Recent commits:`];if(e.recentCommits.length===0)t.push(` none`);else for(let n of e.recentCommits)t.push(` - ${n.hash} ${n.message}`),t.push(` ${n.author} @ ${n.date}`);return e.diff&&t.push(``,`Diff stat:`,e.diff),t.join(`
231
+ `)}function Gu(e){if(e.length===0)return`No diff files found.`;let t=[];for(let n of e){let e=n.oldPath?` (from ${n.oldPath})`:``;t.push(`${n.path}${e} [${n.status}] +${n.additions} -${n.deletions} (${n.hunks.length} hunks)`);for(let e of n.hunks){let n=e.header?` ${e.header}`:``;t.push(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${n}`)}}return t.join(`
232
+ `)}const Ku=[`list_tools`,`describe_tool`,`search_tools`];function qu(e,t,n){let r=[...new Set(n)].sort();e.registerTool(`list_tools`,{title:W(`list_tools`).title,description:`List the available AI Kit tools with names, titles, and categories. Use this before describe_tool when you need to discover the active toolset.`,inputSchema:{category:z.string().optional().describe(`Optional category filter`)},annotations:W(`list_tools`).annotations},J(`list_tools`,async({category:e})=>{let t=e?.trim().toLowerCase();return{content:[{type:`text`,text:r.filter(e=>t?(Ya[e]?.category??[]).some(e=>e.toLowerCase()===t):!0).map(e=>{let t=Ya[e]??{title:e,category:[]},n=t.category?.join(`, `)||`uncategorized`;return`${e}: ${t.title} [${n}]`}).join(`
233
+ `)||`No tools matched the filter.`}]}})),e.registerTool(`describe_tool`,{title:W(`describe_tool`).title,description:`Describe a specific active AI Kit tool using centralized metadata. Use this after list_tools when you need a tool title, categories, and annotations before calling it directly.`,inputSchema:{tool_name:z.string().describe(`The active tool name to describe`)},annotations:W(`describe_tool`).annotations},J(`describe_tool`,async({tool_name:e})=>{if(!r.includes(e))return q(`VALIDATION`,`Unknown or inactive tool: ${e}`);let t=Ya[e],n={name:e,title:t?.title??e,categories:t?.category??[],annotations:t?.annotations??{},note:`Call the tool directly after discovery. AI Kit does not expose an execute_tool proxy.`};return{content:[{type:`text`,text:JSON.stringify(n,null,2)}]}})),e.registerTool(`search_tools`,{title:W(`search_tools`).title,description:`Search active AI Kit tools by keyword across tool names, titles, and categories.`,inputSchema:{query:z.string().min(1).describe(`Keyword query to match against active tools`)},annotations:W(`search_tools`).annotations},J(`search_tools`,async({query:e})=>{let t=e.trim().toLowerCase(),n=r.filter(e=>{let n=Ya[e];return e.toLowerCase().includes(t)||n?.title.toLowerCase().includes(t)||(n?.category??[]).some(e=>e.toLowerCase().includes(t))}).map(e=>{let t=Ya[e]??{title:e,category:[]},n=t.category?.join(`, `)||`uncategorized`;return`${e}: ${t.title} [${n}]`});return{content:[{type:`text`,text:n.length>0?n.join(`
234
+ `):`No tools found matching "${e}"`}]}}))}const Ju=I(`tools`);let Yu=!1;async function Xu(e,t,n){for(let r of n.steps)if(!(r.status!==`success`||!r.output))try{let i=T(`sha256`).update(n.path).digest(`hex`).slice(0,12),a=`produced/onboard/${r.name}/${i}.md`,o=T(`sha256`).update(r.output).digest(`hex`).slice(0,16),s=new Date().toISOString(),c=r.output.length>2e3?r.output.split(/(?=^## )/m).filter(e=>e.trim().length>0):[r.output],l=c.map((e,t)=>({id:T(`sha256`).update(`${a}::${t}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:a,contentType:`produced-knowledge`,chunkIndex:t,totalChunks:c.length,startLine:0,endLine:0,fileHash:o,indexedAt:s,origin:`produced`,tags:[`onboard`,r.name],category:`analysis`,version:1})),u=await t.embedBatch(l.map(e=>e.content));await e.upsert(l,u)}catch(e){Ju.warn(`Auto-persist onboard step failed`,{stepName:r.name,...L(e)})}}async function Zu(e,t,n){if(n.autoRemember?.length)for(let r of n.autoRemember)try{let n=T(`sha256`).update(`onboard-remember::${r.title}`).digest(`hex`).slice(0,16),i=new Date().toISOString(),a={id:n,content:`# ${r.title}\n\n${r.content}`,sourcePath:`curated/onboard/${r.category}/${n}.md`,contentType:`curated`,chunkIndex:0,totalChunks:1,startLine:0,endLine:0,fileHash:T(`sha256`).update(r.content).digest(`hex`).slice(0,16),indexedAt:i,origin:`curated`,tags:r.tags,category:r.category,version:1},[o]=await t.embedBatch([a.content]);await e.upsert([a],[o])}catch(e){Ju.warn(`Auto-persist remember entry failed`,{title:r.title,...L(e)})}}function Qu(e,t,n,r,i,a){let o=W(`onboard`);e.registerTool(`onboard`,{title:o.title,description:`First-time codebase onboarding: runs all analysis tools (structure, dependencies, entry-points, symbols, patterns, diagram) in one command. Results are auto-persisted to AI Kit memory. Use mode=generate to also write structured output to .ai/context/ directory.`,inputSchema:{path:z.string().describe(`Root path of the codebase to onboard`),mode:z.enum([`memory`,`generate`]).default(`generate`).describe(`Output mode: generate (default) = persist to AI Kit + write .ai/context/ files; memory = AI Kit vector store only`),out_dir:z.string().optional().describe(`Custom output directory for generate mode (default: <path>/.ai/context)`),enrich:z.boolean().default(!0).describe(`Append curated knowledge and graph context to output. Adds ~150-250 tokens. Default true for planning tools — set false to save tokens when enrichment is not needed.`)},annotations:o.annotations},J(`onboard`,async({path:e,mode:o,out_dir:s,enrich:c},l)=>{try{if(Yu)return{content:[{type:`text`,text:`Onboard is already running. Please wait for it to complete before starting another.`}]};Yu=!0,Ju.info(`Starting onboard`,{path:e,mode:o});let u=await xt({path:e,mode:o,outDir:s??r?.onboardDir}),d=Ds(l).createTask(`Onboard`,u.steps.length);for(let e=0;e<u.steps.length;e++){let t=u.steps[e];d.progress(e,`${t.name}: ${t.status}`)}d.complete(`Onboard complete: ${u.steps.filter(e=>e.status===`success`).length}/${u.steps.length} steps succeeded`),Xu(t,n,u),u.autoRemember?.length&&Zu(t,n,u).catch(e=>{Ju.warn(`Auto-persist autoRemember failed`,L(e))}),i&&(i.onboardComplete=!0,i.onboardTimestamp=new Date().toISOString());let f=[`## Onboard Complete`,``,`**Path:** \`${u.path}\``,`**Mode:** ${u.mode}`,`**Duration:** ${u.totalDurationMs}ms`,``];u.outDir&&(f.push(`**Output directory:** \`${u.outDir}\``),f.push(``)),f.push(`### Analysis Results`,``);let p=[],m=[];for(let e of u.steps)e.status===`success`?p.push(`- ✓ **${e.name}** (${e.durationMs}ms) — ${e.output.length} chars`):m.push(`- ✗ **${e.name}** — ${e.error}`);f.push(...p),m.length>0&&f.push(``,`### Failed`,``,...m),f.push(``,`---`,``);for(let e of u.steps)e.status===`success`&&f.push(`### ${e.name}`,``,e.output,``,`---`,``);f.push(`_All results auto-saved to AI Kit memory._`,u.mode===`generate`?` Files written to \`${u.outDir}\`.`:``,' Next: Use `search` to query the knowledge, or `knowledge({ action: "remember", ... })` to add custom insights.');let h=f.join(`
235
+ `);if(c&&a){let e=await G(a,{query:`onboard codebase conventions`});h+=K(e)}return{content:[{type:`text`,text:h}]}}catch(e){return Ju.error(`Onboard failed`,L(e)),q(`INTERNAL`,`Onboard failed: ${e instanceof Error?e.message:String(e)}`)}finally{Yu=!1}}))}const $u=I(`tools:persistence`);function ed(e){let t=W(`workset`);e.registerTool(`workset`,{title:t.title,description:`Manage named file sets (worksets). Save, load, list, add/remove files. Worksets persist across sessions in .aikit-state/worksets.json.`,inputSchema:{action:z.enum([`save`,`get`,`list`,`delete`,`add`,`remove`]).describe(`Operation to perform`),name:z.string().optional().describe(`Workset name (required for all except list)`),files:z.array(z.string()).optional().describe(`File paths (required for save, add, remove)`),description:z.string().optional().describe(`Description (for save)`)},annotations:t.annotations},J(`workset`,async({action:e,name:t,files:n,description:r})=>{try{switch(e){case`save`:{if(!t||!n)throw Error(`name and files required for save`);let e=qt(t,n,{description:r});return{content:[{type:`text`,text:`Saved workset "${e.name}" with ${e.files.length} files.`}]}}case`get`:{if(!t)throw Error(`name required for get`);let e=it(t);return e?{content:[{type:`text`,text:JSON.stringify(e)}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}case`list`:{let e=yt();return e.length===0?{content:[{type:`text`,text:`No worksets.`}]}:{content:[{type:`text`,text:e.map(e=>`- **${e.name}** (${e.files.length} files) — ${e.description??`no description`}`).join(`
236
+ `)}]}}case`delete`:if(!t)throw Error(`name required for delete`);return{content:[{type:`text`,text:We(t)?`Deleted workset "${t}".`:`Workset "${t}" not found.`}]};case`add`:{if(!t||!n)throw Error(`name and files required for add`);let e=Ce(t,n);return{content:[{type:`text`,text:`Added to workset "${e.name}": now ${e.files.length} files.`}]}}case`remove`:{if(!t||!n)throw Error(`name and files required for remove`);let e=Bt(t,n);return e?{content:[{type:`text`,text:`Removed from workset "${e.name}": now ${e.files.length} files.`}]}:{content:[{type:`text`,text:`Workset "${t}" not found.`}]}}}}catch(e){return $u.error(`Workset operation failed`,L(e)),q(`INTERNAL`,`Workset operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function td(e,t){let n=W(`stash`);e.registerTool(`stash`,{title:n.title,description:`Persist and retrieve named values in the SQLite-backed state store for intermediate results between tool calls.`,inputSchema:{action:z.enum([`set`,`get`,`list`,`delete`,`clear`]).describe(`Operation to perform on the stash`),key:z.string().optional().describe(`Entry key for set/get/delete operations`),value:z.string().optional().describe(`String or JSON value for set operations`)},annotations:n.annotations},J(`stash`,async({action:e,key:n,value:r})=>{try{switch(e){case`set`:{if(!n)throw Error(`key required for set`);let e=rn(t,n,od(r??``));return{content:[{type:`text`,text:`Stored stash entry "${e.key}" (${e.type}) at ${e.storedAt}.`}]}}case`get`:{if(!n)throw Error(`key required for get`);let e=tn(t,n);return{content:[{type:`text`,text:e?JSON.stringify(e):`Stash entry "${n}" not found.`}]}}case`list`:{let e=nn(t);return{content:[{type:`text`,text:e.length===0?`Stash is empty.`:e.map(e=>`- ${e.key} (${e.type}) — ${e.storedAt}`).join(`
237
+ `)}]}}case`delete`:if(!n)throw Error(`key required for delete`);return{content:[{type:`text`,text:en(t,n)?`Deleted stash entry "${n}".`:`Stash entry "${n}" not found.`}]};case`clear`:{let e=$t(t);return{content:[{type:`text`,text:`Cleared ${e} stash entr${e===1?`y`:`ies`}.`}]}}}}catch(e){return $u.error(`Stash operation failed`,L(e)),q(`INTERNAL`,`Stash operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function nd(e,t){let n=W(`checkpoint`);e.registerTool(`checkpoint`,{title:n.title,description:`Save and restore lightweight session checkpoints in the SQLite-backed state store for cross-session continuity. Legacy .aikit-state/checkpoints directories are imported automatically on first access.`,inputSchema:{action:z.enum([`save`,`load`,`list`,`latest`,`diff`,`history`,`gc`]).describe(`Checkpoint action to perform`),label:z.string().optional().describe(`Checkpoint label for save, or checkpoint id for load`),data:z.string().max(5e5).optional().describe(`JSON object string for save actions`),notes:z.string().max(1e4).optional().describe(`Optional notes for save actions`),from_id:z.string().optional().describe(`Checkpoint ID to diff FROM (for diff action)`),to_id:z.string().optional().describe(`Checkpoint ID to diff TO (for diff action)`),limit:z.number().min(1).max(50).optional().describe(`Max history entries to return`),keep_last:z.number().min(1).max(100).optional().describe(`Keep N most recent checkpoints per label (default: 10, for gc action)`),max_age_days:z.number().min(1).optional().describe(`Delete checkpoints older than N days (for gc action)`),dry_run:z.boolean().optional().describe(`Preview changes without deleting (default: true, for gc action)`)},annotations:n.annotations},J(`checkpoint`,async({action:e,label:n,data:r,notes:i,from_id:a,to_id:o,limit:s,keep_last:c,max_age_days:l,dry_run:u})=>{try{switch(e){case`save`:if(!n)throw Error(`label required for save`);return{content:[{type:`text`,text:ad(Pe(t,n,sd(r),{notes:i}))}]};case`load`:{if(!n)throw Error(`label required for load`);let e=Ne(t,n);return{content:[{type:`text`,text:e?ad(e):`Checkpoint "${n}" not found.`}]}}case`list`:{let e=Me(t,{label:n,limit:s});return{content:[{type:`text`,text:e.length===0?`No checkpoints saved.`:e.map(e=>`- ${e.id} — ${e.label} (${e.createdAt})`).join(`
238
+ `)}]}}case`latest`:{let e=je(t,{label:n});return{content:[{type:`text`,text:e?ad(e):`No checkpoints saved.`}]}}case`diff`:{if(!a||!o)throw Error(`from_id and to_id required for diff`);let e=Oe(t,a,o);return e?{content:[{type:`text`,text:[`## Checkpoint Diff: ${a} → ${o}`,e.added.length?`**Added:** ${e.added.join(`, `)}`:``,e.removed.length?`**Removed:** ${e.removed.join(`, `)}`:``,e.modified.length?`**Modified:** ${e.modified.join(`, `)}`:``,!e.added.length&&!e.removed.length&&!e.modified.length?`No differences found.`:``].filter(Boolean).join(`
239
+ `)}]}:{content:[{type:`text`,text:`One or both checkpoints not found.`}]}}case`history`:{if(!n)throw Error(`label required for history`);let e=Ae(t,n,{limit:s??20});return e.length===0?{content:[{type:`text`,text:`No history found for "${n}".`}]}:{content:[{type:`text`,text:`## History: ${n}\n${e.map(e=>`- ${e.sha?e.sha.slice(0,8):e.id} — ${e.createdAt}${e.label?` (${e.label})`:``}`).join(`
240
+ `)}`}]}}case`gc`:{let e=ke(t,{label:n,keepLast:c,maxAgeDays:l,dryRun:u});return{content:[{type:`text`,text:[`## Checkpoint GC${e.labels.length?`: ${e.labels.join(`, `)}`:``}`,`Deleted: ${e.deleted}`,`Kept: ${e.kept}`,`Mode: ${u??!0?`dry-run`:`delete`}`,e.deletedIds.length?`Deleted IDs: ${e.deletedIds.join(`, `)}`:`Deleted IDs: none`].join(`
241
+ `)}]}}}}catch(e){return $u.error(`Checkpoint failed`,L(e)),q(`INTERNAL`,`Checkpoint failed: ${e instanceof Error?e.message:String(e)}`)}}))}function rd(e){let t=W(`lane`);e.registerTool(`lane`,{title:t.title,description:`Manage verified lanes — isolated file copies for parallel exploration. Also provides advisory write-intent leases for multi-agent coordination.`,inputSchema:{action:z.enum([`create`,`list`,`status`,`diff`,`merge`,`discard`,`lease`,`unlease`,`leases`]).describe(`Lane action to perform`),name:z.string().optional().describe(`Lane name (required for create/status/diff/merge/discard)`),files:z.array(z.string()).optional().describe(`File paths to copy into the lane (required for create)`),agent:z.string().optional().describe(`Agent identifier (required for lease)`),intent:z.string().optional().describe(`What the agent plans to do (required for lease)`),id:z.string().optional().describe(`Lease ID (required for unlease)`),symbols:z.array(z.string()).optional().describe(`Symbol names within files (optional for lease)`),ttl_minutes:z.number().optional().describe(`Lease TTL in minutes (default 10, optional for lease)`)},annotations:t.annotations},J(`lane`,async({action:e,name:t,files:n,agent:r,intent:i,id:a,symbols:o,ttl_minutes:s})=>{try{switch(e){case`create`:{if(!t)throw Error(`name is required for create`);if(!n||n.length===0)throw Error(`files are required for create`);let e=dt(t,n);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`list`:return{content:[{type:`text`,text:JSON.stringify(mt())}]};case`status`:if(!t)throw Error(`name is required for status`);return{content:[{type:`text`,text:JSON.stringify(gt(t))}]};case`diff`:if(!t)throw Error(`name is required for diff`);return{content:[{type:`text`,text:JSON.stringify(ft(t))}]};case`merge`:if(!t)throw Error(`name is required for merge`);return{content:[{type:`text`,text:JSON.stringify(ht(t))}]};case`discard`:if(!t)throw Error(`name is required for discard`);return{content:[{type:`text`,text:JSON.stringify({discarded:pt(t)})}]};case`lease`:{if(!r)throw Error(`agent is required for lease`);if(!n||n.length===0)throw Error(`files are required for lease`);if(!i)throw Error(`intent is required for lease`);let e=Se({agent:r,files:n,intent:i,symbols:o,ttl_minutes:s});return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`unlease`:{if(!a)throw Error(`id is required for unlease`);let e=zt({id:a});return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`leases`:{let e=_t({agent:r});return{content:[{type:`text`,text:JSON.stringify(e)}]}}}}catch(e){return $u.error(`Lane action failed`,L(e)),q(`INTERNAL`,`Lane action failed: ${e instanceof Error?e.message:String(e)}`)}}))}function id(e){let t=W(`queue`);e.registerTool(`queue`,{title:t.title,description:`Manage task queues with optional DAG dependencies. Push items with dependsOn for wave-based execution. Take next, mark done/failed, list queues.`,inputSchema:{action:z.enum([`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`,`dag`]).describe(`Queue action`),name:z.string().optional().describe(`Queue name (required for most actions)`),title:z.string().optional().describe(`Item title (required for push)`),id:z.string().optional().describe(`Item ID (required for done/fail)`),data:z.unknown().optional().describe(`Arbitrary data to attach to a queue item`),error:z.string().optional().describe(`Error message (required for fail)`),dependsOn:z.array(z.string()).optional().describe(`Item IDs this task depends on. Dependent items start as blocked until deps complete.`)},annotations:t.annotations},J(`queue`,async({action:e,name:t,title:n,id:r,data:i,error:a,dependsOn:o})=>{try{switch(e){case`create`:if(!t)throw Error(`name is required for create`);return{content:[{type:`text`,text:JSON.stringify(kt(t))}]};case`push`:if(!t)throw Error(`name is required for push`);if(!n)throw Error(`title is required for push`);return{content:[{type:`text`,text:JSON.stringify(Lt(t,n,i,void 0,o))}]};case`next`:{if(!t)throw Error(`name is required for next`);let e=It(t);return{content:[{type:`text`,text:JSON.stringify(e)}]}}case`done`:if(!t)throw Error(`name is required for done`);if(!r)throw Error(`id is required for done`);return{content:[{type:`text`,text:JSON.stringify(Mt(t,r))}]};case`fail`:if(!t)throw Error(`name is required for fail`);if(!r)throw Error(`id is required for fail`);if(!a)throw Error(`error is required for fail`);return{content:[{type:`text`,text:JSON.stringify(Nt(t,r,a))}]};case`get`:if(!t)throw Error(`name is required for get`);return{content:[{type:`text`,text:JSON.stringify(Pt(t))}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(Ft())}]};case`clear`:if(!t)throw Error(`name is required for clear`);return{content:[{type:`text`,text:JSON.stringify({cleared:Ot(t)})}]};case`delete`:if(!t)throw Error(`name is required for delete`);return{content:[{type:`text`,text:JSON.stringify({deleted:jt(t)})}]};case`dag`:if(!t)throw Error(`name is required for dag`);return{content:[{type:`text`,text:JSON.stringify(At(t))}]}}}catch(e){return $u.error(`Queue action failed`,L(e)),q(`INTERNAL`,`Queue action failed: ${e instanceof Error?e.message:String(e)}`)}}))}function ad(e){let t=[e.id,`Label: ${e.label}`,`Created: ${e.createdAt}`];return e.notes&&t.push(`Notes: ${e.notes}`),t.push(``,`Data:`,JSON.stringify(e.data)),t.join(`
242
+ `)}function od(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function sd(e){let t=e?.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{throw Error(`data must be a valid JSON object string`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`data must be a JSON object string`);return n}const cd=I(`tools`);function ld(e){let t=[`## Rule: ${e.id}`,``,`- **Status**: ${e.enabled?`enabled`:`disabled`}`,`- **Description**: ${e.description??`—`}`,`- **Category**: ${e.category??`—`}`,`- **Push weight**: ${e.pushWeight??`—`}`];return e.patterns?.length&&t.push(`- **Patterns**: ${e.patterns.join(`, `)}`),e.examples?.length&&t.push(`- **Examples**: ${e.examples.join(`, `)}`),t.join(`
243
+ `)}function ud(e,t){let n=W(`er_update_policy`);e.registerTool(`er_update_policy`,{title:n.title,description:`Manage ER push classification rules. Supports listing, updating, creating, and deleting rules that determine when knowledge should be pushed to Enterprise RAG.`,inputSchema:{action:z.enum([`list`,`get`,`update`,`create`,`delete`]).describe(`Action to perform on classification rules`),rule_id:z.string().optional().describe(`Rule ID (required for get, update, delete)`),changes:z.object({patterns:z.array(z.string()).optional(),category:z.string().optional(),pushWeight:z.number().min(0).max(1).optional(),description:z.string().optional(),examples:z.array(z.string()).optional(),enabled:z.boolean().optional()}).optional().describe(`Changes to apply (for update action)`),new_rule:z.object({id:z.string().regex(/^[a-z][a-z0-9-]*$/),patterns:z.array(z.string()).min(1),category:z.string(),pushWeight:z.number().min(0).max(1),description:z.string(),examples:z.array(z.string()).default([]),enabled:z.boolean().default(!0)}).optional().describe(`New rule definition (for create action)`)},annotations:n.annotations},J(`er_update_policy`,async({action:e,rule_id:n,changes:r,new_rule:i})=>{try{if(e===`list`){let e=t.getRules();return{content:[{type:`text`,text:`## Classification Rules\n\n${e.map(e=>`- **${e.id}** (${e.enabled?`enabled`:`disabled`}) — ${e.description}\n Category: ${e.category} | Weight: ${e.pushWeight} | Patterns: ${e.patterns.join(`, `)}`).join(`
244
+ `)}\n\n---\n_${e.length} rules total. Use \`action: "update"\` to modify a rule._`}]}}if(e===`get`){if(!n)return q(`VALIDATION`,'`rule_id` is required for "get" action.');let e=t.getRule(n);return e?{content:[{type:`text`,text:ld(e)}]}:q(`NOT_FOUND`,`Rule "${n}" not found.`)}if(e===`update`){if(!n||!r)return q(`VALIDATION`,'`rule_id` and `changes` are required for "update" action.');let e=t.updateRule(n,r);return e?{content:[{type:`text`,text:`${ld(e)}\n\n---\n_Updated. Next: Use \`action: "list"\` to verify._`}]}:q(`NOT_FOUND`,`Rule "${n}" not found.`)}return e===`create`?i?{content:[{type:`text`,text:`${ld(t.addRule(i))}\n\n---\n_Created. Next: Test classification with \`remember\`._`}]}:q(`VALIDATION`,'`new_rule` is required for "create" action.'):e===`delete`?n?t.deleteRule(n)?{content:[{type:`text`,text:`Deleted rule **${n}**.\n\n---\n_Next: Use \`action: "list"\` to verify._`}]}:q(`NOT_FOUND`,`Rule "${n}" not found.`):q(`VALIDATION`,'`rule_id` is required for "delete" action.'):q(`VALIDATION`,`Unknown action: ${e}`)}catch(e){return cd.error(`Policy update failed`,L(e)),q(`INTERNAL`,`Policy update failed: ${e instanceof Error?e.message:String(e)}`)}}))}const dd=new Map([{type:`markdown`,category:`content`,description:`Markdown content rendered with the marked parser.`,valueShape:`string`,relevantSkills:[`present`,`docs`]},{type:`code`,category:`content`,description:`Formatted code block rendered inside pre/code tags.`,valueShape:`string`,relevantSkills:[`present`,`docs`]},{type:`mermaid`,category:`visualization`,description:`Mermaid diagram source rendered in a mermaid pre block.`,valueShape:`string`,vendorScripts:[`mermaid`],relevantSkills:[`present`,`c4-architecture`,`docs`]},{type:`table`,category:`data`,description:`Tabular data rendered from records or explicit headers and rows.`,valueShape:`Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }`,relevantSkills:[`present`,`docs`]},{type:`metrics`,category:`data`,description:`Metric cards showing label/value pairs with optional trend and status.`,valueShape:`Array<{ label: string; value: string | number; trend?: string | number; status?: string }>`,relevantSkills:[`present`]},{type:`cards`,category:`visualization`,description:`Card grid for titled items with optional body, badge, and status.`,valueShape:`Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>`,relevantSkills:[`present`,`docs`]},{type:`tree`,category:`visualization`,description:`Hierarchical object or name/children tree rendered recursively.`,valueShape:`{ name: string; children?: unknown[] } | Record<string, unknown>`,relevantSkills:[`present`]},{type:`graph`,category:`visualization`,description:`Node and edge graph rendered as a Mermaid flow graph in HTML mode.`,valueShape:`{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }`,vendorScripts:[`mermaid`],relevantSkills:[`present`,`c4-architecture`]},{type:`chart`,category:`data`,description:`Structured chart definition rendered as SVG.`,valueShape:`{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }`,relevantSkills:[`present`]},{type:`timeline`,category:`interactive`,description:`Timeline entries rendered as a vertical sequence of events.`,valueShape:`Array<{ title: string; description?: string; timestamp?: string; status?: string }>`,relevantSkills:[`present`]},{type:`checklist`,category:`interactive`,description:`Checklist items with boolean checked state.`,valueShape:`Array<{label, checked}> | {items: Array<{label, checked}>}`,relevantSkills:[`present`]},{type:`comparison`,category:`interactive`,description:`Side-by-side comparison columns with titled item lists.`,valueShape:`Array<{title, items}> | {columns: Array<{title, items}>}`,relevantSkills:[`present`]},{type:`status-board`,category:`interactive`,description:`Status categories containing labeled status items.`,valueShape:`Array<{category, items}> | {items: Array<{category, items}>}`,relevantSkills:[`present`]},{type:`prompt`,category:`interactive`,description:`Prompt payload rendered through the prompt display helper.`,valueShape:`unknown`,relevantSkills:[`present`]},{type:`progress`,category:`interactive`,description:`Progress bar with current value and optional maximum.`,valueShape:`{label, value, max?} | {items: Array<{label, value, max?, color?}>}`,relevantSkills:[`present`]},{type:`docs-browser`,category:`interactive`,description:`Documentation file list with inline content previews for chat-safe rendering.`,valueShape:`{ files: Array<{ path: string; title?: string; content?: string; status?: "current" | "stale" | "missing" }>; title?: string }`,relevantSkills:[`present`,`docs`],usageExample:`{
245
+ type: 'docs-browser',
246
+ value: {
247
+ title: 'Project Docs',
248
+ files: [
249
+ { path: 'docs/README.md', title: 'Overview', status: 'current' },
250
+ { path: 'docs/api.md', title: 'API Reference', status: 'stale' },
251
+ ],
252
+ },
253
+ }`},{type:`text`,category:`content`,description:`Plain text content rendered through the markdown parser.`,valueShape:`string`},{type:`heading`,category:`content`,description:`Single heading with configurable level from h1 to h6.`,valueShape:`string`},{type:`paragraph`,category:`content`,description:`Single paragraph rendered inside a p tag.`,valueShape:`string`},{type:`separator`,category:`layout`,description:`Horizontal rule used to separate adjacent blocks.`,valueShape:`undefined`},{type:`actions`,category:`layout`,description:`Action bar containing button and select action definitions.`,valueShape:`Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>`}].map(e=>[e.type,{...e}]));function fd(){let e={};for(let[t,n]of dd)n.vendorScripts?.length&&(e[t]=n.vendorScripts);return e}const pd=1024,md=new Set([`user-closed`,`host-dismissed`,`replaced`]);function hd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e,t,n){let r={code:e,message:t};return n!==void 0&&(r.details=n),{kind:`error`,error:r}}function gd(e,t,n,r){e.writeHead(t,{"Content-Type":`application/json`,"Access-Control-Allow-Origin":r??`null`}),e.end(JSON.stringify(n))}async function _d(e){return await new Promise((t,n)=>{let r=[],i=0;e.on(`data`,t=>{if(i+=t.length,i>65536){n(Error(`Callback payload exceeds 64KB limit`)),e.destroy();return}r.push(t)}),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf8`))),e.on(`error`,n)})}function vd(e,t){if(typeof e!=`string`||e.length!==t.length)return!1;let n=Buffer.from(e,`utf8`),r=Buffer.from(t,`utf8`);return n.length===r.length?O(n,r):!1}function yd(e,t){let n=e.headers.origin;if(n!=null)return n===t;let r=e.headers.referer;return r==null?!1:r.startsWith(t)}function bd(e){return(e.headers[`content-type`]??``).startsWith(`application/json`)}function xd(e){for(let[t,n]of Object.entries(e)){let e=typeof n==`string`?n:JSON.stringify(n);if(Buffer.byteLength(e,`utf8`)>8192)return`Form field "${t}" exceeds 8KB limit`}return null}function Sd(e){return Array.isArray(e)&&e.length>pd?`Selection exceeds ${pd} items (got ${e.length})`:null}function Cd(e,t,n){let r=typeof e.actionId==`string`?e.actionId:``,i=n.find(e=>e.id===r);if(!i)return X(`INVALID_ACTION`,`Unknown actionId: ${r||`(missing)`}`);let a=typeof e.selection==`string`||Array.isArray(e.selection)?e.selection:void 0,o=hd(e.formData)?e.formData:void 0,s={surfaceId:t,actionId:i.id,actionType:i.type,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString(),sourceTransport:`browser`};return e.value!==void 0&&(s.value=e.value),a!==void 0&&(s.selection=a),o!==void 0&&(s.formData=o),typeof e.label==`string`?s.label=e.label:i.label&&(s.label=i.label),{kind:`result`,result:s}}function wd(e,t){let n=E(16).toString(`hex`),r=!1,i=!1,a,o,s=new Promise(e=>{o=e}),c=e=>r?a??e:(r=!0,a=e,o?.(e),e);return{nonce:n,promise:s,settleTimeout(e){return c({kind:`timeout`,waitedMs:e})},settleCancelled(e){return c({kind:`cancelled`,reason:e})},settleError(e,t,n){return c(X(e,t,n))},async handle(r,a,o){if(!bd(r)){let e=c(X(`INVALID_CONTENT_TYPE`,`Content-Type must be application/json`));return gd(a,415,{ok:!1,error:`unsupported-media-type`},o),e}if(!yd(r,o)){let e=c(X(`INVALID_ORIGIN`,`Unexpected callback origin: ${r.headers.origin??r.headers.referer??`(missing)`}`));return gd(a,403,{ok:!1,error:`invalid-origin`},o),e}let s=``;try{s=await _d(r)}catch(e){let t=c(X(`INVALID_PAYLOAD`,e instanceof Error?e.message:`Unable to read callback payload`));return gd(a,413,{ok:!1,error:`payload-too-large`},o),t}let l;try{let e=JSON.parse(s);if(!hd(e))throw Error(`Callback payload must be an object`);l=e}catch(e){let t=c(X(`INVALID_PAYLOAD`,e instanceof Error?e.message:`Malformed callback payload`));return gd(a,400,{ok:!1,error:`invalid-json`},o),t}if(i){let e=X(`NONCE_CONSUMED`,`Nonce has already been used`);return gd(a,403,{ok:!1,error:`nonce-consumed`},o),e}if(!vd(typeof l.nonce==`string`?l.nonce:``,n)){let e=c(X(`INVALID_NONCE`,`Callback nonce did not match`));return gd(a,403,{ok:!1,error:`invalid-nonce`},o),e}i=!0;let u=Sd(l.selection);if(u){let e=c(X(`SELECTION_TOO_LARGE`,u));return gd(a,413,{ok:!1,error:`selection-too-large`},o),e}if(hd(l.formData)){let e=xd(l.formData);if(e){let t=c(X(`PAYLOAD_FIELD_TOO_LARGE`,e));return gd(a,413,{ok:!1,error:`field-too-large`},o),t}}if(l.kind===`cancelled`){let e=typeof l.reason==`string`?l.reason:``;if(!md.has(e)){let t=c(X(`INVALID_CANCEL_REASON`,`Unsupported cancel reason: ${e||`(missing)`}`));return gd(a,400,{ok:!1,error:`invalid-cancel-reason`},o),t}let t=c({kind:`cancelled`,reason:e});return gd(a,200,{ok:!0,kind:`cancelled`},o),t}let d=c(Cd(l,e,t));return gd(a,d.kind===`error`?400:200,{ok:d.kind!==`error`,kind:d.kind},o),d}}}const Td=new Map;function Ed(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`)}function Dd(e){let t=`(?=[^>]*\\bid=['"]${Ed(e)}['"])`;return RegExp(`(<script\\b(?=[^>]*\\btype=['"]application\\/json['"])${t}[^>]*>)[\\s\\S]*?(<\/script>)`,`i`)}function Od(e){Td.has(e.id)&&console.warn(`[viewer-registry] Overwriting viewer template "${e.id}"`),Td.set(e.id,e)}function kd(e){return Td.get(e)}function Ad(e){return typeof e==`string`&&Td.has(e)}function jd(){return[...Td.values()]}function Md(e,t,n,r){let i=Dd(n);if(!i.test(e))throw Error(`No <script type="application/json" id="${n}"> found in template`);let a=r?r(t):t,o=JSON.stringify(a??null).replace(/<\/script/gi,`<\\/script`).replace(/<script/gi,`\\u003Cscript`).replace(/-->/g,`--\\u003E`).replace(/<!--/g,`\\u003C!--`);return e.replace(i,`$1\n${o}\n$2`)}const Nd=import.meta.dirname??ie(ce(import.meta.url)),Pd={type:`object`,properties:{title:{type:`string`},description:{type:`string`},layout:{type:`object`,properties:{direction:{type:`string`},spacing:{type:`number`},layerSpacing:{type:`number`}}},nodes:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},type:{type:`string`,enum:[`person`,`system`,`container`,`component`,`database`,`queue`,`external`,`boundary`]},label:{type:`string`},technology:{type:`string`},icon:{type:`string`},description:{type:`string`}},required:[`id`,`type`,`label`]}},edges:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`},label:{type:`string`},style:{type:`string`,enum:[`sync`,`async`,`dashed`,`dotted`,`solid`]}},required:[`source`,`target`]},default:[]}},required:[`nodes`]},Fd={type:`object`,properties:{nodes:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},label:{type:`string`},type:{type:`string`,enum:[`start-end`,`manual`,`automated`,`integration`,`decision`,`prerequisite`]},description:{type:`string`}},required:[`id`,`label`]}},edges:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`},label:{type:`string`},type:{type:`string`,enum:[`standard`,`loop-back`,`exception`]}},required:[`source`,`target`]}}},required:[`nodes`]},Id={type:`object`,properties:{title:{type:`string`},description:{type:`string`},phases:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},label:{type:`string`},outcome:{type:`string`},batches:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},order:{type:`number`},parallel:{type:`boolean`},label:{type:`string`},tasks:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},title:{type:`string`},agent:{type:`string`},files:{type:`array`,items:{type:`string`},default:[]},status:{type:`string`,enum:[`pending`,`in-progress`,`done`,`blocked`]},dependsOn:{type:`array`,items:{type:`string`},default:[]}},required:[`id`,`title`]},default:[]}},required:[`id`,`tasks`]},default:[]}},required:[`id`,`label`,`batches`]}}},required:[`phases`]};function Ld(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rd(e,t){return Ld(t)?{...t,kind:e}:{kind:e}}function zd(e){let t=e===`canvas.html`?[P(Nd,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`canvas`,`index.html`),P(Nd,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`canvas`,`index.html`)]:[],n=y(`server`,[P(`viewers`,`dist`,e),P(`viewers`,e)]),r=[...t,...n?[n]:[],P(Nd,`..`,`..`,`..`,`viewers`,e),P(Nd,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`src`,`static`,e),P(Nd,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,`dist`,e),P(Nd,`..`,`..`,`..`,`..`,`..`,`scaffold`,`general`,`viewers`,e),P(Nd,`..`,`..`,`scaffold`,`general`,`viewers`,`dist`,e),P(Nd,`..`,`..`,`scaffold`,`general`,`viewers`,e),P(Nd,`..`,`viewers`,`dist`,e),P(Nd,`..`,`viewers`,e)];for(let e of r)try{return j(e,`utf8`)}catch{}throw Error(`Viewer HTML not found: ${e}. Searched: ${r.join(`, `)}`)}let Bd,Vd,Hd,Ud,Wd,Gd;function Kd(){return Bd??=zd(`c4-viewer.html`),Bd}function qd(){return Vd??=zd(`tour-viewer.html`),Vd}function Jd(){return Hd??=zd(`canvas.html`),Hd}function Yd(){return Ud??=zd(`architecture-static.html`),Ud}function Xd(){return Wd??=zd(`process-flow-static.html`),Wd}function Zd(){return Gd??=zd(`task-plan-static.html`),Gd}function Qd(){Od({id:`c4@1`,label:`C4 Architecture Diagram`,description:`Interactive C4 architecture diagram with zoom, pan, and ELK auto-layout`,inputSchema:Pd,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:Kd}),Od({id:`c4-static@1`,label:`C4 Architecture Diagram (Static)`,description:`Static SVG architecture diagram for inline rendering`,inputSchema:Pd,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Yd}),Od({id:`tour@1`,label:`Code Tour Viewer`,description:`Interactive code tour with step navigation and dependency graph`,inputSchema:{type:`object`,properties:{title:{type:`string`},description:{type:`string`},estimatedTime:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{stepNumber:{type:`number`},id:{type:`string`},title:{type:`string`},file:{type:`string`},explanation:{type:`string`},description:{type:`string`},learnsConcept:{type:`string`},duration:{type:`string`},line:{type:`number`},code:{type:`string`}},required:[`id`,`title`]}},dependencies:{type:`array`,items:{type:`object`,properties:{source:{type:`string`},target:{type:`string`}},required:[`source`,`target`]},default:[]}},required:[`steps`]},injectId:`tour-data`,supportedTransports:[`browser`],resolveHtml:qd}),Od({id:`process-flow-static@1`,label:`Process Flow Diagram (Static)`,description:`Static SVG process flow diagram for inline rendering`,inputSchema:Fd,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Xd}),Od({id:`task-plan-static@1`,label:`Task Execution Plan (Static)`,description:`Static SVG task execution plan for inline rendering`,inputSchema:Id,injectId:`diagram-data`,supportedTransports:[`mcp-app`],resolveHtml:Zd}),Od({id:`task-plan@1`,label:`Task Execution Plan (Interactive)`,description:`Interactive task execution plan with ReactFlow, phase grouping, and dependency edges`,inputSchema:Id,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:Jd,transformData:e=>Rd(`task-plan`,e)}),Od({id:`process-flow@1`,label:`Process Flow Diagram (Interactive)`,description:`Interactive process flow diagram with ReactFlow`,inputSchema:Fd,injectId:`diagram-data`,supportedTransports:[`browser`],resolveHtml:Jd,transformData:e=>Rd(`process-flow`,e)})}function $d(){let e=new or;for(let t of lr.list())e.register(t);return e.register(cr),e.register(pr),e.register(mr),e.register(ur),e}function ef(e,t){return e?.supportedTransports.includes(t)??!1}const tf=$d();function nf(e){if(e.template)return tf.get(e.template)}function rf(e){if((e.actions?.length??0)>0)return!0;if(e.template&&Ad(e.template)){let t=kd(e.template);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)}let t=nf(e);return ef(t,`browser`)&&!ef(t,`mcp-app`)}Qd();const af=String.raw`(function(){
254
+ 'use strict';
255
+
256
+ var SVG_NS = 'http://www.w3.org/2000/svg';
257
+ var DEFAULT_DIRECTION = 'TD';
258
+ var HORIZONTAL_GAP = 60;
259
+ var VERTICAL_GAP = 80;
260
+ var OUTER_PADDING = 32;
261
+ var GROUP_PADDING = 18;
262
+ var FONT_SIZE = 14;
263
+ var LINE_HEIGHT = 18;
264
+ var CHAR_WIDTH = 8;
265
+ var MAX_RENDER_PASSES = 1;
266
+
267
+ function createSvg(tag) {
268
+ return document.createElementNS(SVG_NS, tag);
269
+ }
270
+
271
+ function setAttrs(node, attrs) {
272
+ var keys = Object.keys(attrs);
273
+ for (var i = 0; i < keys.length; i += 1) {
274
+ var key = keys[i];
275
+ var value = attrs[key];
276
+ if (value !== undefined && value !== null) {
277
+ node.setAttribute(key, String(value));
278
+ }
279
+ }
280
+ return node;
281
+ }
282
+
283
+ function pushUnique(list, value) {
284
+ if (list.indexOf(value) === -1) {
285
+ list.push(value);
286
+ }
287
+ }
288
+
289
+ function stripQuotes(value) {
290
+ var text = String(value || '').trim();
291
+ if (text.length >= 2) {
292
+ var first = text.charAt(0);
293
+ var last = text.charAt(text.length - 1);
294
+ if ((first === '"' && last === '"') || (first === '\'' && last === '\'')) {
295
+ return text.slice(1, -1);
296
+ }
297
+ }
298
+ return text;
299
+ }
300
+
301
+ function normalizeLabel(value) {
302
+ var text = stripQuotes(value);
303
+ return text.replace(/<br\s*\/?>/gi, '\n').replace(/\\n/g, '\n').trim();
304
+ }
305
+
306
+ function isTopLevel(depths, quote) {
307
+ return !quote && depths.square === 0 && depths.round === 0 && depths.curly === 0;
308
+ }
309
+
310
+ function splitTopLevel(text, delimiter) {
311
+ var items = [];
312
+ var current = '';
313
+ var quote = '';
314
+ var depths = { square: 0, round: 0, curly: 0 };
315
+
316
+ for (var i = 0; i < text.length; i += 1) {
317
+ var ch = text.charAt(i);
318
+ var prev = i > 0 ? text.charAt(i - 1) : '';
319
+
320
+ if (quote) {
321
+ current += ch;
322
+ if (ch === quote && prev !== '\\') {
323
+ quote = '';
324
+ }
325
+ continue;
326
+ }
327
+
328
+ if (ch === '"' || ch === '\'') {
329
+ quote = ch;
330
+ current += ch;
331
+ continue;
332
+ }
333
+
334
+ if (ch === '[') depths.square += 1;
335
+ else if (ch === ']') depths.square = Math.max(0, depths.square - 1);
336
+ else if (ch === '(') depths.round += 1;
337
+ else if (ch === ')') depths.round = Math.max(0, depths.round - 1);
338
+ else if (ch === '{') depths.curly += 1;
339
+ else if (ch === '}') depths.curly = Math.max(0, depths.curly - 1);
340
+
341
+ if (ch === delimiter && isTopLevel(depths, quote)) {
342
+ if (current.trim()) {
343
+ items.push(current.trim());
344
+ }
345
+ current = '';
346
+ continue;
347
+ }
348
+
349
+ current += ch;
350
+ }
351
+
352
+ if (current.trim()) {
353
+ items.push(current.trim());
354
+ }
355
+
356
+ return items;
357
+ }
358
+
359
+ function stripComment(line) {
360
+ var quote = '';
361
+ var depths = { square: 0, round: 0, curly: 0 };
362
+
363
+ for (var i = 0; i < line.length; i += 1) {
364
+ var ch = line.charAt(i);
365
+ var next = i + 1 < line.length ? line.charAt(i + 1) : '';
366
+ var prev = i > 0 ? line.charAt(i - 1) : '';
367
+
368
+ if (quote) {
369
+ if (ch === quote && prev !== '\\') {
370
+ quote = '';
371
+ }
372
+ continue;
373
+ }
374
+
375
+ if (ch === '"' || ch === '\'') {
376
+ quote = ch;
377
+ continue;
378
+ }
379
+
380
+ if (ch === '[') depths.square += 1;
381
+ else if (ch === ']') depths.square = Math.max(0, depths.square - 1);
382
+ else if (ch === '(') depths.round += 1;
383
+ else if (ch === ')') depths.round = Math.max(0, depths.round - 1);
384
+ else if (ch === '{') depths.curly += 1;
385
+ else if (ch === '}') depths.curly = Math.max(0, depths.curly - 1);
386
+
387
+ if (ch === '%' && next === '%' && isTopLevel(depths, quote)) {
388
+ return line.slice(0, i);
389
+ }
390
+ }
391
+
392
+ return line;
393
+ }
394
+
395
+ function extractStatements(source) {
396
+ var lines = String(source || '').split(/\r?\n/);
397
+ var statements = [];
398
+
399
+ for (var i = 0; i < lines.length; i += 1) {
400
+ var line = stripComment(lines[i]).trim();
401
+ if (!line) {
402
+ continue;
403
+ }
404
+
405
+ var parts = splitTopLevel(line, ';');
406
+ for (var j = 0; j < parts.length; j += 1) {
407
+ if (parts[j]) {
408
+ statements.push(parts[j]);
409
+ }
410
+ }
411
+ }
412
+
413
+ return statements;
414
+ }
415
+
416
+ function readBalanced(text, index, open, close) {
417
+ var depth = 0;
418
+ var quote = '';
419
+
420
+ for (var i = index; i < text.length; i += 1) {
421
+ var ch = text.charAt(i);
422
+ var prev = i > 0 ? text.charAt(i - 1) : '';
423
+
424
+ if (quote) {
425
+ if (ch === quote && prev !== '\\') {
426
+ quote = '';
427
+ }
428
+ continue;
429
+ }
430
+
431
+ if (ch === '"' || ch === '\'') {
432
+ quote = ch;
433
+ continue;
434
+ }
435
+
436
+ if (text.slice(i, i + open.length) === open) {
437
+ depth += 1;
438
+ i += open.length - 1;
439
+ continue;
440
+ }
441
+
442
+ if (text.slice(i, i + close.length) === close) {
443
+ depth -= 1;
444
+ i += close.length - 1;
445
+ if (depth === 0) {
446
+ return {
447
+ value: text.slice(index + open.length, i - close.length + 1),
448
+ index: i + 1,
449
+ };
450
+ }
451
+ }
452
+ }
453
+
454
+ throw new Error('Unterminated node shape');
455
+ }
456
+
457
+ function skipWhitespace(text, index) {
458
+ var cursor = index;
459
+ while (cursor < text.length && /\s/.test(text.charAt(cursor))) {
460
+ cursor += 1;
461
+ }
462
+ return cursor;
463
+ }
464
+
465
+ function readIdentifier(text, index) {
466
+ var cursor = skipWhitespace(text, index);
467
+ var start = cursor;
468
+
469
+ while (cursor < text.length) {
470
+ var ch = text.charAt(cursor);
471
+ if (/\s/.test(ch) || ch === '[' || ch === '(' || ch === '{' || ch === '-' || ch === '=' || ch === '.' || ch === '|' || ch === ';') {
472
+ break;
473
+ }
474
+ cursor += 1;
475
+ }
476
+
477
+ if (cursor === start) {
478
+ return null;
479
+ }
480
+
481
+ return {
482
+ value: text.slice(start, cursor),
483
+ index: cursor,
484
+ };
485
+ }
486
+
487
+ function readNodeRef(text, index) {
488
+ var idToken = readIdentifier(text, index);
489
+ if (!idToken) {
490
+ return null;
491
+ }
492
+
493
+ var id = idToken.value.trim();
494
+ var cursor = skipWhitespace(text, idToken.index);
495
+ var shape = 'rect';
496
+ var label = id;
497
+
498
+ if (text.slice(cursor, cursor + 2) === '((') {
499
+ var circle = readBalanced(text, cursor, '((', '))');
500
+ shape = 'circle';
501
+ label = normalizeLabel(circle.value);
502
+ cursor = circle.index;
503
+ } else if (text.slice(cursor, cursor + 2) === '([') {
504
+ var stadium = readBalanced(text, cursor, '([', '])');
505
+ shape = 'stadium';
506
+ label = normalizeLabel(stadium.value);
507
+ cursor = stadium.index;
508
+ } else if (text.slice(cursor, cursor + 2) === '{{') {
509
+ var hexagon = readBalanced(text, cursor, '{{', '}}');
510
+ shape = 'hexagon';
511
+ label = normalizeLabel(hexagon.value);
512
+ cursor = hexagon.index;
513
+ } else if (text.charAt(cursor) === '[') {
514
+ var rect = readBalanced(text, cursor, '[', ']');
515
+ shape = 'rect';
516
+ label = normalizeLabel(rect.value);
517
+ cursor = rect.index;
518
+ } else if (text.charAt(cursor) === '(') {
519
+ var rounded = readBalanced(text, cursor, '(', ')');
520
+ shape = 'rounded';
521
+ label = normalizeLabel(rounded.value);
522
+ cursor = rounded.index;
523
+ } else if (text.charAt(cursor) === '{') {
524
+ var diamond = readBalanced(text, cursor, '{', '}');
525
+ shape = 'diamond';
526
+ label = normalizeLabel(diamond.value);
527
+ cursor = diamond.index;
528
+ }
529
+
530
+ return {
531
+ node: {
532
+ id: id,
533
+ label: label || id,
534
+ shape: shape,
535
+ },
536
+ index: cursor,
537
+ };
538
+ }
539
+
540
+ function edgePattern(match, style, arrow) {
541
+ return {
542
+ match: match,
543
+ style: style,
544
+ arrow: arrow,
545
+ };
546
+ }
547
+
548
+ var EDGE_PATTERNS = [
549
+ edgePattern(/^\s*-\.->\|([^|]+)\|\s*/, 'dotted', true),
550
+ edgePattern(/^\s*==>\|([^|]+)\|\s*/, 'thick', true),
551
+ edgePattern(/^\s*-->\|([^|]+)\|\s*/, 'solid', true),
552
+ edgePattern(/^\s*---\|([^|]+)\|\s*/, 'solid', false),
553
+ edgePattern(/^\s*--\s+(.+?)\s+-->\s*/, 'solid', true),
554
+ edgePattern(/^\s*-\.->\s*/, 'dotted', true),
555
+ edgePattern(/^\s*==>\s*/, 'thick', true),
556
+ edgePattern(/^\s*-->\s*/, 'solid', true),
557
+ edgePattern(/^\s*---\s*/, 'solid', false),
558
+ ];
559
+
560
+ function readEdge(text, index) {
561
+ var remainder = text.slice(index);
562
+
563
+ for (var i = 0; i < EDGE_PATTERNS.length; i += 1) {
564
+ var pattern = EDGE_PATTERNS[i];
565
+ var match = remainder.match(pattern.match);
566
+ if (!match) {
567
+ continue;
568
+ }
569
+
570
+ return {
571
+ index: index + match[0].length,
572
+ style: pattern.style,
573
+ arrow: pattern.arrow,
574
+ label: match[1] ? normalizeLabel(match[1]) : '',
575
+ };
576
+ }
577
+
578
+ return null;
579
+ }
580
+
581
+ function newGraph(direction) {
582
+ return {
583
+ direction: direction,
584
+ nodesById: Object.create(null),
585
+ nodeOrder: [],
586
+ edges: [],
587
+ subgraphs: [],
588
+ };
589
+ }
590
+
591
+ function addNode(graph, ref, activeGroups) {
592
+ var node = graph.nodesById[ref.id];
593
+
594
+ if (!node) {
595
+ node = {
596
+ id: ref.id,
597
+ label: ref.label || ref.id,
598
+ shape: ref.shape || 'rect',
599
+ groups: [],
600
+ rank: 0,
601
+ width: 0,
602
+ height: 0,
603
+ lines: [],
604
+ x: 0,
605
+ y: 0,
606
+ order: graph.nodeOrder.length,
607
+ };
608
+ graph.nodesById[ref.id] = node;
609
+ graph.nodeOrder.push(ref.id);
610
+ }
611
+
612
+ if (ref.label && ref.label !== ref.id) {
613
+ node.label = ref.label;
614
+ }
615
+ if (ref.shape && ref.shape !== 'rect') {
616
+ node.shape = ref.shape;
617
+ }
618
+
619
+ for (var i = 0; i < activeGroups.length; i += 1) {
620
+ var groupId = activeGroups[i];
621
+ pushUnique(node.groups, groupId);
622
+ for (var j = 0; j < graph.subgraphs.length; j += 1) {
623
+ if (graph.subgraphs[j].id === groupId) {
624
+ pushUnique(graph.subgraphs[j].members, node.id);
625
+ }
626
+ }
627
+ }
628
+
629
+ return node;
630
+ }
631
+
632
+ function addEdge(graph, fromNode, edgeDef, toNode) {
633
+ graph.edges.push({
634
+ from: fromNode.id,
635
+ to: toNode.id,
636
+ label: edgeDef.label || '',
637
+ style: edgeDef.style,
638
+ arrow: edgeDef.arrow,
639
+ });
640
+ }
641
+
642
+ function parseDirection(statement) {
643
+ var match = statement.match(/^(graph|flowchart)\s+(TD|TB|BT|LR|RL)\b/i);
644
+ if (!match) {
645
+ return null;
646
+ }
647
+ var direction = match[2].toUpperCase();
648
+ return direction === 'TB' ? 'TD' : direction;
649
+ }
650
+
651
+ function parseMermaid(source) {
652
+ var statements = extractStatements(source);
653
+ var direction = DEFAULT_DIRECTION;
654
+
655
+ if (statements.length > 0) {
656
+ var explicitDirection = parseDirection(statements[0]);
657
+ if (explicitDirection) {
658
+ direction = explicitDirection;
659
+ statements.shift();
660
+ }
661
+ }
662
+
663
+ var graph = newGraph(direction);
664
+ var activeGroups = [];
665
+ var groupCount = 0;
666
+
667
+ for (var i = 0; i < statements.length; i += 1) {
668
+ var statement = statements[i];
669
+ if (!statement) {
670
+ continue;
671
+ }
672
+
673
+ if (/^subgraph\b/i.test(statement)) {
674
+ groupCount += 1;
675
+ var title = normalizeLabel(statement.replace(/^subgraph\s+/i, '')) || ('Subgraph ' + groupCount);
676
+ var group = {
677
+ id: 'subgraph_' + groupCount,
678
+ title: title,
679
+ members: [],
680
+ };
681
+ graph.subgraphs.push(group);
682
+ activeGroups.push(group.id);
683
+ continue;
684
+ }
685
+
686
+ if (/^end$/i.test(statement)) {
687
+ activeGroups.pop();
688
+ continue;
689
+ }
690
+
691
+ var first = readNodeRef(statement, 0);
692
+ if (!first) {
693
+ throw new Error('Unable to parse node: ' + statement);
694
+ }
695
+
696
+ var fromNode = addNode(graph, first.node, activeGroups.slice());
697
+ var cursor = first.index;
698
+ var consumedEdge = false;
699
+
700
+ while (true) {
701
+ var edge = readEdge(statement, cursor);
702
+ if (!edge) {
703
+ break;
704
+ }
705
+
706
+ cursor = edge.index;
707
+ var next = readNodeRef(statement, cursor);
708
+ if (!next) {
709
+ throw new Error('Edge is missing a target node: ' + statement);
710
+ }
711
+
712
+ var toNode = addNode(graph, next.node, activeGroups.slice());
713
+ addEdge(graph, fromNode, edge, toNode);
714
+ fromNode = toNode;
715
+ cursor = next.index;
716
+ consumedEdge = true;
717
+ }
718
+
719
+ if (!consumedEdge) {
720
+ var tail = statement.slice(cursor).trim();
721
+ if (tail) {
722
+ throw new Error('Unexpected trailing content: ' + tail);
723
+ }
724
+ }
725
+ }
726
+
727
+ return graph;
728
+ }
729
+
730
+ function createMeasurer() {
731
+ var svg = null;
732
+ var text = null;
733
+
734
+ return function measureLine(line) {
735
+ var sample = String(line || '');
736
+
737
+ try {
738
+ if (!svg) {
739
+ svg = createSvg('svg');
740
+ setAttrs(svg, {
741
+ width: 0,
742
+ height: 0,
743
+ style: 'position:absolute;left:-9999px;top:-9999px;overflow:hidden;pointer-events:none',
744
+ 'aria-hidden': 'true',
745
+ });
746
+ text = createSvg('text');
747
+ setAttrs(text, {
748
+ 'font-size': FONT_SIZE,
749
+ 'font-family': 'var(--dt-font-sans, ui-sans-serif, system-ui, sans-serif)',
750
+ });
751
+ svg.appendChild(text);
752
+ if (document.body) {
753
+ document.body.appendChild(svg);
754
+ }
755
+ }
756
+
757
+ if (text && typeof text.getBBox === 'function') {
758
+ text.textContent = sample || ' ';
759
+ var box = text.getBBox();
760
+ if (box && box.width) {
761
+ return box.width;
762
+ }
763
+ }
764
+ } catch (_error) {
765
+ return sample.length * CHAR_WIDTH;
766
+ }
767
+
768
+ return Math.max(16, sample.length * CHAR_WIDTH);
769
+ };
770
+ }
771
+
772
+ var measureLine = createMeasurer();
773
+
774
+ function splitLabelLines(label) {
775
+ var lines = String(label || '').split(/\n+/).map(function(line) {
776
+ return line.trim();
777
+ }).filter(Boolean);
778
+ return lines.length ? lines : [''];
779
+ }
780
+
781
+ function sizeNode(node) {
782
+ if (node.stateKind === 'start') {
783
+ node.lines = [];
784
+ node.width = 18;
785
+ node.height = 18;
786
+ return;
787
+ }
788
+
789
+ if (node.stateKind === 'end') {
790
+ node.lines = [];
791
+ node.width = 24;
792
+ node.height = 24;
793
+ return;
794
+ }
795
+
796
+ var lines = splitLabelLines(node.label || node.id);
797
+ var maxWidth = 0;
798
+
799
+ for (var i = 0; i < lines.length; i += 1) {
800
+ maxWidth = Math.max(maxWidth, measureLine(lines[i]));
801
+ }
802
+
803
+ var width = Math.max(72, Math.ceil(maxWidth + 28));
804
+ var height = Math.max(44, lines.length * LINE_HEIGHT + 18);
805
+
806
+ if (node.shape === 'circle') {
807
+ var diameter = Math.max(width, height);
808
+ width = diameter;
809
+ height = diameter;
810
+ } else if (node.shape === 'diamond') {
811
+ width = Math.max(width + 16, 88);
812
+ height = Math.max(height + 12, 56);
813
+ } else if (node.shape === 'hexagon') {
814
+ width = Math.max(width + 18, 92);
815
+ } else if (node.shape === 'stadium') {
816
+ width = Math.max(width + 12, 88);
817
+ }
818
+
819
+ node.lines = lines;
820
+ node.width = width;
821
+ node.height = height;
822
+ }
823
+
824
+ function buildAdjacency(graph) {
825
+ var incoming = Object.create(null);
826
+ var outgoing = Object.create(null);
827
+ var indegree = Object.create(null);
828
+
829
+ for (var i = 0; i < graph.nodeOrder.length; i += 1) {
830
+ var id = graph.nodeOrder[i];
831
+ incoming[id] = [];
832
+ outgoing[id] = [];
833
+ indegree[id] = 0;
834
+ }
835
+
836
+ for (var j = 0; j < graph.edges.length; j += 1) {
837
+ var edge = graph.edges[j];
838
+ outgoing[edge.from].push(edge);
839
+ incoming[edge.to].push(edge);
840
+ if (edge.from !== edge.to) {
841
+ indegree[edge.to] += 1;
842
+ }
843
+ }
844
+
845
+ return {
846
+ incoming: incoming,
847
+ outgoing: outgoing,
848
+ indegree: indegree,
849
+ };
850
+ }
851
+
852
+ function topologicalOrder(graph, adjacency) {
853
+ var queue = [];
854
+ var order = [];
855
+ var seen = Object.create(null);
856
+
857
+ for (var i = 0; i < graph.nodeOrder.length; i += 1) {
858
+ var id = graph.nodeOrder[i];
859
+ if (adjacency.indegree[id] === 0) {
860
+ queue.push(id);
861
+ }
862
+ }
863
+
864
+ while (queue.length) {
865
+ var current = queue.shift();
866
+ if (seen[current]) {
867
+ continue;
868
+ }
869
+ seen[current] = true;
870
+ order.push(current);
871
+
872
+ var outgoing = adjacency.outgoing[current];
873
+ for (var j = 0; j < outgoing.length; j += 1) {
874
+ var edge = outgoing[j];
875
+ if (edge.from === edge.to) {
876
+ continue;
877
+ }
878
+ adjacency.indegree[edge.to] -= 1;
879
+ if (adjacency.indegree[edge.to] === 0) {
880
+ queue.push(edge.to);
881
+ }
882
+ }
883
+ }
884
+
885
+ for (var k = 0; k < graph.nodeOrder.length; k += 1) {
886
+ var fallbackId = graph.nodeOrder[k];
887
+ if (!seen[fallbackId]) {
888
+ order.push(fallbackId);
889
+ }
890
+ }
891
+
892
+ return order;
893
+ }
894
+
895
+ function assignRanks(graph, adjacency, order) {
896
+ var ranks = Object.create(null);
897
+
898
+ for (var i = 0; i < graph.nodeOrder.length; i += 1) {
899
+ ranks[graph.nodeOrder[i]] = 0;
900
+ }
901
+
902
+ for (var j = 0; j < order.length; j += 1) {
903
+ var id = order[j];
904
+ var edges = adjacency.outgoing[id];
905
+ for (var k = 0; k < edges.length; k += 1) {
906
+ var edge = edges[k];
907
+ if (edge.from === edge.to) {
908
+ continue;
909
+ }
910
+ ranks[edge.to] = Math.max(ranks[edge.to], ranks[edge.from] + 1);
911
+ }
912
+ }
913
+
914
+ var layers = [];
915
+ for (var m = 0; m < graph.nodeOrder.length; m += 1) {
916
+ var node = graph.nodesById[graph.nodeOrder[m]];
917
+ node.rank = ranks[node.id] || 0;
918
+ if (!layers[node.rank]) {
919
+ layers[node.rank] = [];
920
+ }
921
+ layers[node.rank].push(node.id);
922
+ }
923
+
924
+ return layers;
925
+ }
926
+
927
+ function barycenterSort(layers, graph, adjacency) {
928
+ function positions(layer) {
929
+ var map = Object.create(null);
930
+ for (var i = 0; i < layer.length; i += 1) {
931
+ map[layer[i]] = i;
932
+ }
933
+ return map;
934
+ }
935
+
936
+ for (var pass = 0; pass < 2; pass += 1) {
937
+ for (var rank = 1; rank < layers.length; rank += 1) {
938
+ if (!layers[rank] || layers[rank].length < 2) {
939
+ continue;
940
+ }
941
+
942
+ var previous = layers[rank - 1] || [];
943
+ var prevPos = positions(previous);
944
+ layers[rank].sort(function(a, b) {
945
+ var aIncoming = adjacency.incoming[a];
946
+ var bIncoming = adjacency.incoming[b];
947
+ var aSum = 0;
948
+ var bSum = 0;
949
+ var aCount = 0;
950
+ var bCount = 0;
951
+
952
+ for (var i = 0; i < aIncoming.length; i += 1) {
953
+ if (prevPos[aIncoming[i].from] !== undefined) {
954
+ aSum += prevPos[aIncoming[i].from];
955
+ aCount += 1;
956
+ }
957
+ }
958
+ for (var j = 0; j < bIncoming.length; j += 1) {
959
+ if (prevPos[bIncoming[j].from] !== undefined) {
960
+ bSum += prevPos[bIncoming[j].from];
961
+ bCount += 1;
962
+ }
963
+ }
964
+
965
+ var aValue = aCount ? aSum / aCount : graph.nodesById[a].order;
966
+ var bValue = bCount ? bSum / bCount : graph.nodesById[b].order;
967
+ if (aValue === bValue) {
968
+ return graph.nodesById[a].order - graph.nodesById[b].order;
969
+ }
970
+ return aValue - bValue;
971
+ });
972
+ }
973
+
974
+ for (var reverseRank = layers.length - 2; reverseRank >= 0; reverseRank -= 1) {
975
+ if (!layers[reverseRank] || layers[reverseRank].length < 2) {
976
+ continue;
977
+ }
978
+
979
+ var next = layers[reverseRank + 1] || [];
980
+ var nextPos = positions(next);
981
+ layers[reverseRank].sort(function(a, b) {
982
+ var aOutgoing = adjacency.outgoing[a];
983
+ var bOutgoing = adjacency.outgoing[b];
984
+ var aSum = 0;
985
+ var bSum = 0;
986
+ var aCount = 0;
987
+ var bCount = 0;
988
+
989
+ for (var i = 0; i < aOutgoing.length; i += 1) {
990
+ if (nextPos[aOutgoing[i].to] !== undefined) {
991
+ aSum += nextPos[aOutgoing[i].to];
992
+ aCount += 1;
993
+ }
994
+ }
995
+ for (var j = 0; j < bOutgoing.length; j += 1) {
996
+ if (nextPos[bOutgoing[j].to] !== undefined) {
997
+ bSum += nextPos[bOutgoing[j].to];
998
+ bCount += 1;
999
+ }
1000
+ }
1001
+
1002
+ var aValue = aCount ? aSum / aCount : graph.nodesById[a].order;
1003
+ var bValue = bCount ? bSum / bCount : graph.nodesById[b].order;
1004
+ if (aValue === bValue) {
1005
+ return graph.nodesById[a].order - graph.nodesById[b].order;
1006
+ }
1007
+ return aValue - bValue;
1008
+ });
1009
+ }
1010
+ }
1011
+ }
1012
+
1013
+ function directionOrder(length, direction) {
1014
+ var items = [];
1015
+ if (direction === 'BT' || direction === 'RL') {
1016
+ for (var i = length - 1; i >= 0; i -= 1) {
1017
+ items.push(i);
1018
+ }
1019
+ return items;
1020
+ }
1021
+ for (var j = 0; j < length; j += 1) {
1022
+ items.push(j);
1023
+ }
1024
+ return items;
1025
+ }
1026
+
1027
+ function layoutGraph(graph) {
1028
+ for (var i = 0; i < graph.nodeOrder.length; i += 1) {
1029
+ sizeNode(graph.nodesById[graph.nodeOrder[i]]);
1030
+ }
1031
+
1032
+ var adjacency = buildAdjacency(graph);
1033
+ var order = topologicalOrder(graph, adjacency);
1034
+ var layers = assignRanks(graph, buildAdjacency(graph), order);
1035
+ barycenterSort(layers, graph, buildAdjacency(graph));
1036
+
1037
+ var direction = graph.direction;
1038
+ var mainAxis = direction === 'LR' || direction === 'RL' ? 'x' : 'y';
1039
+ var crossAxis = mainAxis === 'x' ? 'y' : 'x';
1040
+ var rankOrder = directionOrder(layers.length, direction);
1041
+ var layerSpans = [];
1042
+ var layerCross = [];
1043
+ var totalMain = OUTER_PADDING;
1044
+ var maxCross = 0;
1045
+
1046
+ for (var layerIndex = 0; layerIndex < rankOrder.length; layerIndex += 1) {
1047
+ var rank = rankOrder[layerIndex];
1048
+ var layer = layers[rank] || [];
1049
+ var mainSize = 0;
1050
+ var crossSize = 0;
1051
+
1052
+ for (var nodeIndex = 0; nodeIndex < layer.length; nodeIndex += 1) {
1053
+ var node = graph.nodesById[layer[nodeIndex]];
1054
+ mainSize = Math.max(mainSize, mainAxis === 'x' ? node.width : node.height);
1055
+ crossSize += (crossAxis === 'x' ? node.width : node.height);
1056
+ }
1057
+
1058
+ if (layer.length > 1) {
1059
+ crossSize += (layer.length - 1) * (crossAxis === 'x' ? HORIZONTAL_GAP : VERTICAL_GAP);
1060
+ }
1061
+
1062
+ layerSpans[rank] = mainSize;
1063
+ layerCross[rank] = crossSize;
1064
+ totalMain += mainSize;
1065
+ if (layerIndex < rankOrder.length - 1) {
1066
+ totalMain += mainAxis === 'x' ? HORIZONTAL_GAP : VERTICAL_GAP;
1067
+ }
1068
+ maxCross = Math.max(maxCross, crossSize);
1069
+ }
1070
+
1071
+ totalMain += OUTER_PADDING;
1072
+ maxCross += OUTER_PADDING * 2;
1073
+
1074
+ var currentMain = OUTER_PADDING;
1075
+ for (var ranked = 0; ranked < rankOrder.length; ranked += 1) {
1076
+ var currentRank = rankOrder[ranked];
1077
+ var currentLayer = layers[currentRank] || [];
1078
+ var layerMainSize = layerSpans[currentRank] || 0;
1079
+ var crossStart = OUTER_PADDING + (maxCross - OUTER_PADDING * 2 - (layerCross[currentRank] || 0)) / 2;
1080
+
1081
+ for (var entry = 0; entry < currentLayer.length; entry += 1) {
1082
+ var currentNode = graph.nodesById[currentLayer[entry]];
1083
+ var nodeMainSize = mainAxis === 'x' ? currentNode.width : currentNode.height;
1084
+ var nodeCrossSize = crossAxis === 'x' ? currentNode.width : currentNode.height;
1085
+ var centerMain = currentMain + layerMainSize / 2;
1086
+ var centerCross = crossStart + nodeCrossSize / 2;
1087
+
1088
+ if (mainAxis === 'x') {
1089
+ currentNode.x = centerMain;
1090
+ currentNode.y = centerCross;
1091
+ } else {
1092
+ currentNode.x = centerCross;
1093
+ currentNode.y = centerMain;
1094
+ }
1095
+
1096
+ crossStart += nodeCrossSize + (crossAxis === 'x' ? HORIZONTAL_GAP : VERTICAL_GAP);
1097
+ }
1098
+
1099
+ currentMain += layerMainSize + (mainAxis === 'x' ? HORIZONTAL_GAP : VERTICAL_GAP);
1100
+ }
1101
+
1102
+ graph.bounds = {
1103
+ width: mainAxis === 'x' ? totalMain : maxCross,
1104
+ height: mainAxis === 'x' ? maxCross : totalMain,
1105
+ };
1106
+ }
1107
+
1108
+ function nodeBounds(node) {
1109
+ return {
1110
+ left: node.x - node.width / 2,
1111
+ right: node.x + node.width / 2,
1112
+ top: node.y - node.height / 2,
1113
+ bottom: node.y + node.height / 2,
1114
+ };
1115
+ }
1116
+
1117
+ function computeGroupBounds(graph) {
1118
+ for (var i = 0; i < graph.subgraphs.length; i += 1) {
1119
+ var group = graph.subgraphs[i];
1120
+ if (!group.members.length) {
1121
+ group.bounds = null;
1122
+ continue;
1123
+ }
1124
+
1125
+ var minX = Infinity;
1126
+ var minY = Infinity;
1127
+ var maxX = -Infinity;
1128
+ var maxY = -Infinity;
1129
+
1130
+ for (var j = 0; j < group.members.length; j += 1) {
1131
+ var node = graph.nodesById[group.members[j]];
1132
+ if (!node) {
1133
+ continue;
1134
+ }
1135
+ var bounds = nodeBounds(node);
1136
+ minX = Math.min(minX, bounds.left);
1137
+ minY = Math.min(minY, bounds.top);
1138
+ maxX = Math.max(maxX, bounds.right);
1139
+ maxY = Math.max(maxY, bounds.bottom);
1140
+ }
1141
+
1142
+ group.bounds = {
1143
+ x: minX - GROUP_PADDING,
1144
+ y: minY - GROUP_PADDING - 12,
1145
+ width: Math.max(80, maxX - minX + GROUP_PADDING * 2),
1146
+ height: Math.max(50, maxY - minY + GROUP_PADDING * 2 + 12),
1147
+ };
1148
+ }
1149
+ }
1150
+
1151
+ function attachText(parent, x, y, lines, className) {
1152
+ var text = createSvg('text');
1153
+ setAttrs(text, {
1154
+ x: x,
1155
+ y: y,
1156
+ fill: 'var(--dt-text-primary)',
1157
+ 'font-size': FONT_SIZE,
1158
+ 'font-family': 'var(--dt-font-sans, ui-sans-serif, system-ui, sans-serif)',
1159
+ 'text-anchor': 'middle',
1160
+ 'dominant-baseline': 'middle',
1161
+ class: className || '',
1162
+ });
1163
+
1164
+ var offset = -((lines.length - 1) * LINE_HEIGHT) / 2;
1165
+ for (var i = 0; i < lines.length; i += 1) {
1166
+ var tspan = createSvg('tspan');
1167
+ setAttrs(tspan, {
1168
+ x: x,
1169
+ y: y + offset + i * LINE_HEIGHT,
1170
+ });
1171
+ tspan.textContent = lines[i];
1172
+ text.appendChild(tspan);
1173
+ }
1174
+
1175
+ parent.appendChild(text);
1176
+ return text;
1177
+ }
1178
+
1179
+ function drawNode(parent, node) {
1180
+ var group = createSvg('g');
1181
+ setAttrs(group, { class: 'mini-mermaid-node' });
1182
+ var fill = 'var(--dt-bg-secondary)';
1183
+ var stroke = 'var(--dt-border-default)';
1184
+ var bounds = nodeBounds(node);
1185
+
1186
+ if (node.stateKind === 'start') {
1187
+ var startCircle = createSvg('circle');
1188
+ setAttrs(startCircle, {
1189
+ cx: node.x,
1190
+ cy: node.y,
1191
+ r: node.width / 2,
1192
+ fill: 'var(--dt-text-primary)',
1193
+ stroke: 'var(--dt-text-primary)',
1194
+ 'stroke-width': 1,
1195
+ });
1196
+ group.appendChild(startCircle);
1197
+ parent.appendChild(group);
1198
+ return;
1199
+ }
1200
+
1201
+ if (node.stateKind === 'end') {
1202
+ var endOuter = createSvg('circle');
1203
+ setAttrs(endOuter, {
1204
+ cx: node.x,
1205
+ cy: node.y,
1206
+ r: node.width / 2,
1207
+ fill: 'var(--dt-bg-canvas)',
1208
+ stroke: 'var(--dt-text-primary)',
1209
+ 'stroke-width': 1.5,
1210
+ });
1211
+ group.appendChild(endOuter);
1212
+
1213
+ var endInner = createSvg('circle');
1214
+ setAttrs(endInner, {
1215
+ cx: node.x,
1216
+ cy: node.y,
1217
+ r: Math.max(4, node.width / 2 - 5),
1218
+ fill: 'var(--dt-text-primary)',
1219
+ stroke: 'none',
1220
+ });
1221
+ group.appendChild(endInner);
1222
+ parent.appendChild(group);
1223
+ return;
1224
+ }
1225
+
1226
+ if (node.shape === 'diamond') {
1227
+ var diamond = createSvg('polygon');
1228
+ var diamondPoints = [
1229
+ node.x + ',' + bounds.top,
1230
+ bounds.right + ',' + node.y,
1231
+ node.x + ',' + bounds.bottom,
1232
+ bounds.left + ',' + node.y,
1233
+ ].join(' ');
1234
+ setAttrs(diamond, { points: diamondPoints, fill: fill, stroke: stroke, 'stroke-width': 1.5 });
1235
+ group.appendChild(diamond);
1236
+ } else if (node.shape === 'circle') {
1237
+ var circle = createSvg('ellipse');
1238
+ setAttrs(circle, {
1239
+ cx: node.x,
1240
+ cy: node.y,
1241
+ rx: node.width / 2,
1242
+ ry: node.height / 2,
1243
+ fill: fill,
1244
+ stroke: stroke,
1245
+ 'stroke-width': 1.5,
1246
+ });
1247
+ group.appendChild(circle);
1248
+ } else if (node.shape === 'hexagon') {
1249
+ var inset = Math.max(14, node.width * 0.16);
1250
+ var hexagon = createSvg('polygon');
1251
+ var hexPoints = [
1252
+ (bounds.left + inset) + ',' + bounds.top,
1253
+ (bounds.right - inset) + ',' + bounds.top,
1254
+ bounds.right + ',' + node.y,
1255
+ (bounds.right - inset) + ',' + bounds.bottom,
1256
+ (bounds.left + inset) + ',' + bounds.bottom,
1257
+ bounds.left + ',' + node.y,
1258
+ ].join(' ');
1259
+ setAttrs(hexagon, { points: hexPoints, fill: fill, stroke: stroke, 'stroke-width': 1.5 });
1260
+ group.appendChild(hexagon);
1261
+ } else {
1262
+ var rect = createSvg('rect');
1263
+ var radius = 8;
1264
+ if (node.shape === 'stadium') {
1265
+ radius = node.height / 2;
1266
+ } else if (node.shape !== 'rounded') {
1267
+ radius = 4;
1268
+ }
1269
+ setAttrs(rect, {
1270
+ x: bounds.left,
1271
+ y: bounds.top,
1272
+ width: node.width,
1273
+ height: node.height,
1274
+ rx: radius,
1275
+ ry: radius,
1276
+ fill: fill,
1277
+ stroke: stroke,
1278
+ 'stroke-width': 1.5,
1279
+ });
1280
+ group.appendChild(rect);
1281
+ }
1282
+
1283
+ attachText(group, node.x, node.y, node.lines, 'mini-mermaid-node-label');
1284
+ parent.appendChild(group);
1285
+ }
1286
+
1287
+ function edgeAnchors(source, target, direction) {
1288
+ if (source.id === target.id) {
1289
+ return {
1290
+ start: { x: source.x + source.width * 0.22, y: source.y - source.height / 2 },
1291
+ end: { x: source.x + source.width / 2, y: source.y - source.height * 0.18 },
1292
+ };
1293
+ }
1294
+
1295
+ var vertical = direction === 'TD' || direction === 'BT';
1296
+
1297
+ if (vertical) {
1298
+ if (Math.abs(target.y - source.y) >= Math.abs(target.x - source.x)) {
1299
+ return target.y >= source.y ? {
1300
+ start: { x: source.x, y: source.y + source.height / 2 },
1301
+ end: { x: target.x, y: target.y - target.height / 2 },
1302
+ } : {
1303
+ start: { x: source.x, y: source.y - source.height / 2 },
1304
+ end: { x: target.x, y: target.y + target.height / 2 },
1305
+ };
1306
+ }
1307
+
1308
+ return target.x >= source.x ? {
1309
+ start: { x: source.x + source.width / 2, y: source.y },
1310
+ end: { x: target.x - target.width / 2, y: target.y },
1311
+ } : {
1312
+ start: { x: source.x - source.width / 2, y: source.y },
1313
+ end: { x: target.x + target.width / 2, y: target.y },
1314
+ };
1315
+ }
1316
+
1317
+ if (Math.abs(target.x - source.x) >= Math.abs(target.y - source.y)) {
1318
+ return target.x >= source.x ? {
1319
+ start: { x: source.x + source.width / 2, y: source.y },
1320
+ end: { x: target.x - target.width / 2, y: target.y },
1321
+ } : {
1322
+ start: { x: source.x - source.width / 2, y: source.y },
1323
+ end: { x: target.x + target.width / 2, y: target.y },
1324
+ };
1325
+ }
1326
+
1327
+ return target.y >= source.y ? {
1328
+ start: { x: source.x, y: source.y + source.height / 2 },
1329
+ end: { x: target.x, y: target.y - target.height / 2 },
1330
+ } : {
1331
+ start: { x: source.x, y: source.y - source.height / 2 },
1332
+ end: { x: target.x, y: target.y + target.height / 2 },
1333
+ };
1334
+ }
1335
+
1336
+ function buildEdgePath(edge, source, target, direction) {
1337
+ var anchors = edgeAnchors(source, target, direction);
1338
+ var start = anchors.start;
1339
+ var end = anchors.end;
1340
+
1341
+ if (edge.from === edge.to) {
1342
+ return [
1343
+ 'M', start.x, start.y,
1344
+ 'C', start.x + 34, start.y - 36, end.x + 22, end.y - 34, end.x, end.y,
1345
+ ].join(' ');
1346
+ }
1347
+
1348
+ var dx = end.x - start.x;
1349
+ var dy = end.y - start.y;
1350
+ var vertical = direction === 'TD' || direction === 'BT';
1351
+ var radius = 16;
1352
+
1353
+ if (vertical) {
1354
+ var midY = start.y + dy / 2;
1355
+ if (Math.abs(dx) < 8) {
1356
+ return ['M', start.x, start.y, 'L', end.x, end.y].join(' ');
1357
+ }
1358
+ return [
1359
+ 'M', start.x, start.y,
1360
+ 'L', start.x, midY - radius,
1361
+ 'Q', start.x, midY, start.x + (dx > 0 ? radius : -radius), midY,
1362
+ 'L', end.x - (dx > 0 ? radius : -radius), midY,
1363
+ 'Q', end.x, midY, end.x, midY + radius,
1364
+ 'L', end.x, end.y,
1365
+ ].join(' ');
1366
+ }
1367
+
1368
+ var midX = start.x + dx / 2;
1369
+ if (Math.abs(dy) < 8) {
1370
+ return ['M', start.x, start.y, 'L', end.x, end.y].join(' ');
1371
+ }
1372
+ return [
1373
+ 'M', start.x, start.y,
1374
+ 'L', midX - radius, start.y,
1375
+ 'Q', midX, start.y, midX, start.y + (dy > 0 ? radius : -radius),
1376
+ 'L', midX, end.y - (dy > 0 ? radius : -radius),
1377
+ 'Q', midX, end.y, midX + radius, end.y,
1378
+ 'L', end.x, end.y,
1379
+ ].join(' ');
1380
+ }
1381
+
1382
+ function edgeMidpoint(edge, source, target) {
1383
+ if (edge.from === edge.to) {
1384
+ return {
1385
+ x: source.x + source.width * 0.4,
1386
+ y: source.y - source.height * 0.9,
1387
+ };
1388
+ }
1389
+ return {
1390
+ x: (source.x + target.x) / 2,
1391
+ y: (source.y + target.y) / 2,
1392
+ };
1393
+ }
1394
+
1395
+ function drawLabel(parent, x, y, textValue) {
1396
+ var label = String(textValue || '').trim();
1397
+ if (!label) {
1398
+ return;
1399
+ }
1400
+
1401
+ var width = Math.max(24, measureLine(label) + 12);
1402
+ var group = createSvg('g');
1403
+ var rect = createSvg('rect');
1404
+ setAttrs(rect, {
1405
+ x: x - width / 2,
1406
+ y: y - 10,
1407
+ width: width,
1408
+ height: 20,
1409
+ rx: 6,
1410
+ ry: 6,
1411
+ fill: 'var(--dt-bg-canvas)',
1412
+ stroke: 'var(--dt-border-default)',
1413
+ 'stroke-width': 0.75,
1414
+ });
1415
+ group.appendChild(rect);
1416
+
1417
+ var text = createSvg('text');
1418
+ setAttrs(text, {
1419
+ x: x,
1420
+ y: y + 1,
1421
+ fill: 'var(--dt-text-primary)',
1422
+ 'font-size': 12,
1423
+ 'font-family': 'var(--dt-font-sans, ui-sans-serif, system-ui, sans-serif)',
1424
+ 'text-anchor': 'middle',
1425
+ 'dominant-baseline': 'middle',
1426
+ });
1427
+ text.textContent = label;
1428
+ group.appendChild(text);
1429
+ parent.appendChild(group);
1430
+ }
1431
+
1432
+ function drawEdges(parent, graph) {
1433
+ for (var i = 0; i < graph.edges.length; i += 1) {
1434
+ var edge = graph.edges[i];
1435
+ var source = graph.nodesById[edge.from];
1436
+ var target = graph.nodesById[edge.to];
1437
+ if (!source || !target) {
1438
+ continue;
1439
+ }
1440
+
1441
+ var path = createSvg('path');
1442
+ setAttrs(path, {
1443
+ d: buildEdgePath(edge, source, target, graph.direction),
1444
+ fill: 'none',
1445
+ stroke: 'var(--dt-text-primary)',
1446
+ 'stroke-width': edge.style === 'thick' ? 2.5 : 1.6,
1447
+ 'stroke-dasharray': edge.style === 'dotted' ? '4 5' : '',
1448
+ 'stroke-linecap': 'round',
1449
+ 'stroke-linejoin': 'round',
1450
+ 'marker-end': edge.arrow ? 'url(#mini-mermaid-arrow)' : '',
1451
+ });
1452
+ parent.appendChild(path);
1453
+
1454
+ if (edge.label) {
1455
+ var midpoint = edgeMidpoint(edge, source, target);
1456
+ drawLabel(parent, midpoint.x, midpoint.y, edge.label);
1457
+ }
1458
+ }
1459
+ }
1460
+
1461
+ function drawSubgraphs(parent, graph) {
1462
+ for (var i = 0; i < graph.subgraphs.length; i += 1) {
1463
+ var group = graph.subgraphs[i];
1464
+ if (!group.bounds) {
1465
+ continue;
1466
+ }
1467
+
1468
+ var rect = createSvg('rect');
1469
+ setAttrs(rect, {
1470
+ x: group.bounds.x,
1471
+ y: group.bounds.y,
1472
+ width: group.bounds.width,
1473
+ height: group.bounds.height,
1474
+ rx: 12,
1475
+ ry: 12,
1476
+ fill: 'rgba(127, 127, 127, 0.06)',
1477
+ stroke: 'var(--dt-border-default)',
1478
+ 'stroke-width': 1,
1479
+ 'stroke-dasharray': '6 5',
1480
+ });
1481
+ parent.appendChild(rect);
1482
+
1483
+ var label = createSvg('text');
1484
+ setAttrs(label, {
1485
+ x: group.bounds.x + 14,
1486
+ y: group.bounds.y + 18,
1487
+ fill: 'var(--dt-text-primary)',
1488
+ 'font-size': 12,
1489
+ 'font-family': 'var(--dt-font-sans, ui-sans-serif, system-ui, sans-serif)',
1490
+ 'font-weight': '600',
1491
+ });
1492
+ label.textContent = group.title;
1493
+ parent.appendChild(label);
1494
+ }
1495
+ }
1496
+
1497
+ function ensureMarkers(defs) {
1498
+ var marker = createSvg('marker');
1499
+ setAttrs(marker, {
1500
+ id: 'mini-mermaid-arrow',
1501
+ viewBox: '0 0 10 10',
1502
+ refX: 9,
1503
+ refY: 5,
1504
+ markerWidth: 8,
1505
+ markerHeight: 8,
1506
+ orient: 'auto-start-reverse',
1507
+ markerUnits: 'strokeWidth',
1508
+ });
1509
+ var polygon = createSvg('polygon');
1510
+ setAttrs(polygon, {
1511
+ points: '0,0 10,5 0,10 2.5,5',
1512
+ fill: 'var(--dt-text-primary)',
1513
+ });
1514
+ marker.appendChild(polygon);
1515
+ defs.appendChild(marker);
1516
+
1517
+ var openArrow = createSvg('marker');
1518
+ setAttrs(openArrow, {
1519
+ id: 'mini-mermaid-open-arrow',
1520
+ viewBox: '0 0 10 10',
1521
+ refX: 9,
1522
+ refY: 5,
1523
+ markerWidth: 8,
1524
+ markerHeight: 8,
1525
+ orient: 'auto-start-reverse',
1526
+ markerUnits: 'strokeWidth',
1527
+ });
1528
+ var openPath = createSvg('path');
1529
+ setAttrs(openPath, {
1530
+ d: 'M 1 1 L 9 5 L 1 9',
1531
+ fill: 'none',
1532
+ stroke: 'var(--dt-text-primary)',
1533
+ 'stroke-width': 1.4,
1534
+ 'stroke-linecap': 'round',
1535
+ 'stroke-linejoin': 'round',
1536
+ });
1537
+ openArrow.appendChild(openPath);
1538
+ defs.appendChild(openArrow);
1539
+
1540
+ var triangleArrow = createSvg('marker');
1541
+ setAttrs(triangleArrow, {
1542
+ id: 'mini-mermaid-triangle-arrow',
1543
+ viewBox: '0 0 10 10',
1544
+ refX: 9,
1545
+ refY: 5,
1546
+ markerWidth: 9,
1547
+ markerHeight: 9,
1548
+ orient: 'auto-start-reverse',
1549
+ markerUnits: 'strokeWidth',
1550
+ });
1551
+ var triangle = createSvg('polygon');
1552
+ setAttrs(triangle, {
1553
+ points: '0,0 10,5 0,10',
1554
+ fill: 'var(--dt-bg-canvas)',
1555
+ stroke: 'var(--dt-text-primary)',
1556
+ 'stroke-width': 1.1,
1557
+ 'stroke-linejoin': 'round',
1558
+ });
1559
+ triangleArrow.appendChild(triangle);
1560
+ defs.appendChild(triangleArrow);
1561
+
1562
+ var filledDiamond = createSvg('marker');
1563
+ setAttrs(filledDiamond, {
1564
+ id: 'mini-mermaid-diamond-arrow',
1565
+ viewBox: '0 0 12 10',
1566
+ refX: 10,
1567
+ refY: 5,
1568
+ markerWidth: 11,
1569
+ markerHeight: 9,
1570
+ orient: 'auto-start-reverse',
1571
+ markerUnits: 'strokeWidth',
1572
+ });
1573
+ var filledDiamondShape = createSvg('polygon');
1574
+ setAttrs(filledDiamondShape, {
1575
+ points: '0,5 5,0 10,5 5,10',
1576
+ fill: 'var(--dt-text-primary)',
1577
+ stroke: 'var(--dt-text-primary)',
1578
+ 'stroke-width': 1,
1579
+ 'stroke-linejoin': 'round',
1580
+ });
1581
+ filledDiamond.appendChild(filledDiamondShape);
1582
+ defs.appendChild(filledDiamond);
1583
+
1584
+ var openDiamond = createSvg('marker');
1585
+ setAttrs(openDiamond, {
1586
+ id: 'mini-mermaid-open-diamond-arrow',
1587
+ viewBox: '0 0 12 10',
1588
+ refX: 10,
1589
+ refY: 5,
1590
+ markerWidth: 11,
1591
+ markerHeight: 9,
1592
+ orient: 'auto-start-reverse',
1593
+ markerUnits: 'strokeWidth',
1594
+ });
1595
+ var openDiamondShape = createSvg('polygon');
1596
+ setAttrs(openDiamondShape, {
1597
+ points: '0,5 5,0 10,5 5,10',
1598
+ fill: 'var(--dt-bg-canvas)',
1599
+ stroke: 'var(--dt-text-primary)',
1600
+ 'stroke-width': 1,
1601
+ 'stroke-linejoin': 'round',
1602
+ });
1603
+ openDiamond.appendChild(openDiamondShape);
1604
+ defs.appendChild(openDiamond);
1605
+ }
1606
+
1607
+ function createRootSvg(width, height, label) {
1608
+ var svg = createSvg('svg');
1609
+ setAttrs(svg, {
1610
+ width: '100%',
1611
+ viewBox: '0 0 ' + Math.max(120, Math.ceil(width)) + ' ' + Math.max(80, Math.ceil(height)),
1612
+ role: 'img',
1613
+ 'aria-label': label,
1614
+ style: 'display:block;overflow:visible;background:var(--dt-bg-canvas)',
1615
+ preserveAspectRatio: 'xMidYMid meet',
1616
+ });
1617
+
1618
+ var defs = createSvg('defs');
1619
+ ensureMarkers(defs);
1620
+ svg.appendChild(defs);
1621
+ return svg;
1622
+ }
1623
+
1624
+ function renderSvg(graph) {
1625
+ layoutGraph(graph);
1626
+ computeGroupBounds(graph);
1627
+
1628
+ var svg = createRootSvg(graph.bounds.width, graph.bounds.height, 'Mermaid flowchart diagram');
1629
+
1630
+ if (!graph.nodeOrder.length) {
1631
+ var empty = createSvg('text');
1632
+ setAttrs(empty, {
1633
+ x: 24,
1634
+ y: 32,
1635
+ fill: 'var(--dt-text-secondary, var(--dt-text-primary))',
1636
+ 'font-size': FONT_SIZE,
1637
+ 'font-family': 'var(--dt-font-sans, ui-sans-serif, system-ui, sans-serif)',
1638
+ });
1639
+ empty.textContent = 'Empty diagram';
1640
+ svg.appendChild(empty);
1641
+ return svg;
1642
+ }
1643
+
1644
+ var groupLayer = createSvg('g');
1645
+ drawSubgraphs(groupLayer, graph);
1646
+ svg.appendChild(groupLayer);
1647
+
1648
+ var edgeLayer = createSvg('g');
1649
+ setAttrs(edgeLayer, { class: 'mini-mermaid-edges' });
1650
+ drawEdges(edgeLayer, graph);
1651
+ svg.appendChild(edgeLayer);
1652
+
1653
+ var nodeLayer = createSvg('g');
1654
+ setAttrs(nodeLayer, { class: 'mini-mermaid-nodes' });
1655
+ for (var i = 0; i < graph.nodeOrder.length; i += 1) {
1656
+ drawNode(nodeLayer, graph.nodesById[graph.nodeOrder[i]]);
1657
+ }
1658
+ svg.appendChild(nodeLayer);
1659
+ return svg;
1660
+ }
1661
+
1662
+ function appendText(parent, x, y, textValue, options) {
1663
+ var text = createSvg('text');
1664
+ setAttrs(text, {
1665
+ x: x,
1666
+ y: y,
1667
+ fill: options && options.fill ? options.fill : 'var(--dt-text-primary)',
1668
+ 'font-size': options && options.size ? options.size : FONT_SIZE,
1669
+ 'font-family': 'var(--dt-font-sans, ui-sans-serif, system-ui, sans-serif)',
1670
+ 'font-weight': options && options.weight ? options.weight : '400',
1671
+ 'text-anchor': options && options.anchor ? options.anchor : 'start',
1672
+ 'dominant-baseline': options && options.baseline ? options.baseline : 'middle',
1673
+ class: options && options.className ? options.className : '',
1674
+ });
1675
+ text.textContent = textValue;
1676
+ parent.appendChild(text);
1677
+ return text;
1678
+ }
1679
+
1680
+ function appendLeftText(parent, x, y, lines, options) {
1681
+ for (var i = 0; i < lines.length; i += 1) {
1682
+ appendText(parent, x, y + i * LINE_HEIGHT, lines[i], {
1683
+ anchor: 'start',
1684
+ baseline: 'hanging',
1685
+ weight: options && options.weight ? options.weight : '400',
1686
+ size: options && options.size ? options.size : FONT_SIZE,
1687
+ fill: options && options.fill ? options.fill : 'var(--dt-text-primary)',
1688
+ className: options && options.className ? options.className : '',
1689
+ });
1690
+ }
1691
+ }
1692
+
1693
+ function cleanedLines(source) {
1694
+ var raw = String(source || '').split(/\r?\n/);
1695
+ var lines = [];
1696
+
1697
+ for (var i = 0; i < raw.length; i += 1) {
1698
+ var line = stripComment(raw[i]).trim();
1699
+ if (line) {
1700
+ lines.push(line);
1701
+ }
1702
+ }
1703
+
1704
+ return lines;
1705
+ }
1706
+
1707
+ function boxAnchor(source, target) {
1708
+ var dx = target.x - source.x;
1709
+ var dy = target.y - source.y;
1710
+
1711
+ if (Math.abs(dx) >= Math.abs(dy)) {
1712
+ return dx >= 0 ? { x: source.x + source.width / 2, y: source.y } : { x: source.x - source.width / 2, y: source.y };
1713
+ }
1714
+
1715
+ return dy >= 0 ? { x: source.x, y: source.y + source.height / 2 } : { x: source.x, y: source.y - source.height / 2 };
1716
+ }
1717
+
1718
+ function drawStraightLine(parent, x1, y1, x2, y2, options) {
1719
+ var line = createSvg('line');
1720
+ setAttrs(line, {
1721
+ x1: x1,
1722
+ y1: y1,
1723
+ x2: x2,
1724
+ y2: y2,
1725
+ fill: 'none',
1726
+ stroke: options && options.stroke ? options.stroke : 'var(--dt-text-primary)',
1727
+ 'stroke-width': options && options.strokeWidth ? options.strokeWidth : 1.6,
1728
+ 'stroke-dasharray': options && options.dash ? options.dash : '',
1729
+ 'stroke-linecap': 'round',
1730
+ 'stroke-linejoin': 'round',
1731
+ 'marker-start': options && options.markerStart ? options.markerStart : '',
1732
+ 'marker-end': options && options.markerEnd ? options.markerEnd : '',
1733
+ });
1734
+ parent.appendChild(line);
1735
+ return line;
1736
+ }
1737
+
1738
+ function ensureSequenceParticipant(participants, participantsById, id, label) {
1739
+ if (!participantsById[id]) {
1740
+ participantsById[id] = { id: id, label: label || id, width: 0, x: 0 };
1741
+ participants.push(participantsById[id]);
1742
+ }
1743
+ if (label && (!participantsById[id].label || participantsById[id].label === id || label !== id)) {
1744
+ participantsById[id].label = label;
1745
+ }
1746
+ return participantsById[id];
1747
+ }
1748
+
1749
+ function renderSequenceDiagram(source) {
1750
+ var lines = cleanedLines(source);
1751
+ var participants = [];
1752
+ var participantsById = Object.create(null);
1753
+ var entries = [];
1754
+
1755
+ for (var i = 0; i < lines.length; i += 1) {
1756
+ var line = lines[i];
1757
+ if (i === 0 && /^sequenceDiagram\b/i.test(line)) {
1758
+ continue;
1759
+ }
1760
+
1761
+ var participantMatch = line.match(/^participant\s+([A-Za-z0-9_.-]+)(?:\s+as\s+(.+))?$/i);
1762
+ if (participantMatch) {
1763
+ ensureSequenceParticipant(participants, participantsById, participantMatch[1], normalizeLabel(participantMatch[2] || participantMatch[1]));
1764
+ continue;
1765
+ }
1766
+
1767
+ var noteMatch = line.match(/^Note\s+over\s+([^:]+):\s*(.+)$/i);
1768
+ if (noteMatch) {
1769
+ var refs = noteMatch[1].split(',');
1770
+ var noteRefs = [];
1771
+ for (var refIndex = 0; refIndex < refs.length; refIndex += 1) {
1772
+ var refId = refs[refIndex].trim();
1773
+ if (!refId) {
1774
+ continue;
1775
+ }
1776
+ ensureSequenceParticipant(participants, participantsById, refId, refId);
1777
+ noteRefs.push(refId);
1778
+ }
1779
+ if (noteRefs.length) {
1780
+ entries.push({ type: 'note', refs: noteRefs, text: normalizeLabel(noteMatch[2]) });
1781
+ }
1782
+ continue;
1783
+ }
1784
+
1785
+ var messageMatch = line.match(/^([A-Za-z0-9_.-]+)\s*(-->>|->>|-->|->)\s*([A-Za-z0-9_.-]+)(?:\s*:\s*(.+))?$/);
1786
+ if (messageMatch) {
1787
+ ensureSequenceParticipant(participants, participantsById, messageMatch[1], messageMatch[1]);
1788
+ ensureSequenceParticipant(participants, participantsById, messageMatch[3], messageMatch[3]);
1789
+ entries.push({
1790
+ type: 'message',
1791
+ from: messageMatch[1],
1792
+ to: messageMatch[3],
1793
+ arrow: messageMatch[2],
1794
+ text: normalizeLabel(messageMatch[4] || ''),
1795
+ });
1796
+ }
1797
+ }
1798
+
1799
+ if (!participants.length) {
1800
+ throw new Error('Sequence diagram is missing participants');
1801
+ }
1802
+
1803
+ var totalParticipantWidth = 0;
1804
+ for (var participantIndex = 0; participantIndex < participants.length; participantIndex += 1) {
1805
+ var participant = participants[participantIndex];
1806
+ participant.width = Math.max(96, Math.ceil(measureLine(participant.label) + 28));
1807
+ totalParticipantWidth += participant.width;
1808
+ }
1809
+
1810
+ var gap = Math.max(HORIZONTAL_GAP, 48);
1811
+ var width = OUTER_PADDING * 2 + totalParticipantWidth + gap * Math.max(0, participants.length - 1);
1812
+ var boxHeight = 34;
1813
+ var topY = OUTER_PADDING + 18;
1814
+ var cursorX = OUTER_PADDING;
1815
+
1816
+ for (var position = 0; position < participants.length; position += 1) {
1817
+ participants[position].x = cursorX + participants[position].width / 2;
1818
+ cursorX += participants[position].width + gap;
1819
+ }
1820
+
1821
+ var contentY = topY + boxHeight + 26;
1822
+ for (var entryIndex = 0; entryIndex < entries.length; entryIndex += 1) {
1823
+ var entry = entries[entryIndex];
1824
+ entry.y = contentY;
1825
+ if (entry.type === 'note') {
1826
+ entry.lines = splitLabelLines(entry.text);
1827
+ entry.height = Math.max(42, entry.lines.length * LINE_HEIGHT + 18);
1828
+ contentY += entry.height + 14;
1829
+ } else {
1830
+ contentY += 42;
1831
+ }
1832
+ }
1833
+
1834
+ var height = contentY + OUTER_PADDING;
1835
+ var svg = createRootSvg(width, height, 'Mermaid sequence diagram');
1836
+
1837
+ for (var drawParticipantIndex = 0; drawParticipantIndex < participants.length; drawParticipantIndex += 1) {
1838
+ var drawParticipant = participants[drawParticipantIndex];
1839
+ var left = drawParticipant.x - drawParticipant.width / 2;
1840
+
1841
+ var participantRect = createSvg('rect');
1842
+ setAttrs(participantRect, {
1843
+ x: left,
1844
+ y: topY,
1845
+ width: drawParticipant.width,
1846
+ height: boxHeight,
1847
+ rx: 8,
1848
+ ry: 8,
1849
+ fill: 'var(--dt-bg-secondary)',
1850
+ stroke: 'var(--dt-border-default)',
1851
+ 'stroke-width': 1.5,
1852
+ });
1853
+ svg.appendChild(participantRect);
1854
+ attachText(svg, drawParticipant.x, topY + boxHeight / 2 + 1, [drawParticipant.label], '');
1855
+
1856
+ var lifeline = createSvg('line');
1857
+ setAttrs(lifeline, {
1858
+ x1: drawParticipant.x,
1859
+ y1: topY + boxHeight,
1860
+ x2: drawParticipant.x,
1861
+ y2: height - OUTER_PADDING / 2,
1862
+ stroke: 'var(--dt-text-secondary, var(--dt-text-primary))',
1863
+ 'stroke-width': 1.2,
1864
+ 'stroke-dasharray': '6 6',
1865
+ });
1866
+ svg.appendChild(lifeline);
1867
+ }
1868
+
1869
+ for (var drawEntryIndex = 0; drawEntryIndex < entries.length; drawEntryIndex += 1) {
1870
+ var drawEntry = entries[drawEntryIndex];
1871
+
1872
+ if (drawEntry.type === 'note') {
1873
+ var leftParticipant = participantsById[drawEntry.refs[0]];
1874
+ var rightParticipant = participantsById[drawEntry.refs[drawEntry.refs.length - 1]];
1875
+ var noteWidth = Math.max(measureLine(drawEntry.text) + 26, Math.abs(rightParticipant.x - leftParticipant.x) + 40);
1876
+ var noteX = (leftParticipant.x + rightParticipant.x) / 2;
1877
+ var noteRect = createSvg('rect');
1878
+ setAttrs(noteRect, {
1879
+ x: noteX - noteWidth / 2,
1880
+ y: drawEntry.y - 12,
1881
+ width: noteWidth,
1882
+ height: drawEntry.height,
1883
+ rx: 10,
1884
+ ry: 10,
1885
+ fill: 'var(--dt-bg-secondary)',
1886
+ stroke: 'var(--dt-border-default)',
1887
+ 'stroke-width': 1.2,
1888
+ });
1889
+ svg.appendChild(noteRect);
1890
+ attachText(svg, noteX, drawEntry.y - 12 + drawEntry.height / 2, drawEntry.lines, '');
1891
+ continue;
1892
+ }
1893
+
1894
+ var fromParticipant = participantsById[drawEntry.from];
1895
+ var toParticipant = participantsById[drawEntry.to];
1896
+ var messageY = drawEntry.y;
1897
+ var dashed = drawEntry.arrow === '-->>' || drawEntry.arrow === '-->';
1898
+ var closedArrow = drawEntry.arrow === '->>' || drawEntry.arrow === '-->>';
1899
+
1900
+ if (fromParticipant.id === toParticipant.id) {
1901
+ var loopPath = createSvg('path');
1902
+ var loopX = fromParticipant.x + 34;
1903
+ setAttrs(loopPath, {
1904
+ d: ['M', fromParticipant.x, messageY, 'L', loopX, messageY, 'L', loopX, messageY + 20, 'L', fromParticipant.x + 8, messageY + 20].join(' '),
1905
+ fill: 'none',
1906
+ stroke: 'var(--dt-text-primary)',
1907
+ 'stroke-width': 1.6,
1908
+ 'stroke-dasharray': dashed ? '6 5' : '',
1909
+ 'marker-end': closedArrow ? 'url(#mini-mermaid-arrow)' : 'url(#mini-mermaid-open-arrow)',
1910
+ 'stroke-linecap': 'round',
1911
+ 'stroke-linejoin': 'round',
1912
+ });
1913
+ svg.appendChild(loopPath);
1914
+ if (drawEntry.text) {
1915
+ appendText(svg, loopX + 6, messageY + 10, drawEntry.text, { anchor: 'start', baseline: 'middle', size: 12 });
1916
+ }
1917
+ continue;
1918
+ }
1919
+
1920
+ drawStraightLine(svg, fromParticipant.x, messageY, toParticipant.x, messageY, {
1921
+ dash: dashed ? '6 5' : '',
1922
+ markerEnd: closedArrow ? 'url(#mini-mermaid-arrow)' : 'url(#mini-mermaid-open-arrow)',
1923
+ });
1924
+
1925
+ if (drawEntry.text) {
1926
+ appendText(svg, (fromParticipant.x + toParticipant.x) / 2, messageY - 11, drawEntry.text, { anchor: 'middle', baseline: 'middle', size: 12 });
1927
+ }
1928
+ }
1929
+
1930
+ return svg;
1931
+ }
1932
+
1933
+ function parseClassDiagram(source) {
1934
+ var lines = cleanedLines(source);
1935
+ var classes = [];
1936
+ var classesById = Object.create(null);
1937
+ var relations = [];
1938
+ var currentClass = null;
1939
+
1940
+ function ensureClass(id) {
1941
+ if (!classesById[id]) {
1942
+ classesById[id] = { id: id, name: id, attributes: [], methods: [], width: 0, height: 0, x: 0, y: 0 };
1943
+ classes.push(classesById[id]);
1944
+ }
1945
+ return classesById[id];
1946
+ }
1947
+
1948
+ for (var i = 0; i < lines.length; i += 1) {
1949
+ var line = lines[i];
1950
+ if (i === 0 && /^classDiagram\b/i.test(line)) {
1951
+ continue;
1952
+ }
1953
+ if (currentClass) {
1954
+ if (line === '}') {
1955
+ currentClass = null;
1956
+ continue;
1957
+ }
1958
+ if (/\([^)]*\)/.test(line)) {
1959
+ currentClass.methods.push(line);
1960
+ } else {
1961
+ currentClass.attributes.push(line);
1962
+ }
1963
+ continue;
1964
+ }
1965
+
1966
+ var classBlockMatch = line.match(/^class\s+([A-Za-z0-9_.-]+)\s*\{$/i);
1967
+ if (classBlockMatch) {
1968
+ currentClass = ensureClass(classBlockMatch[1]);
1969
+ continue;
1970
+ }
1971
+
1972
+ var classMatch = line.match(/^class\s+([A-Za-z0-9_.-]+)$/i);
1973
+ if (classMatch) {
1974
+ ensureClass(classMatch[1]);
1975
+ continue;
1976
+ }
1977
+
1978
+ var relationMatch = line.match(/^([A-Za-z0-9_.-]+)\s+(<\|--|\*--|o--|-->|--|\.\.>)\s+([A-Za-z0-9_.-]+)(?:\s*:\s*(.+))?$/);
1979
+ if (relationMatch) {
1980
+ ensureClass(relationMatch[1]);
1981
+ ensureClass(relationMatch[3]);
1982
+ relations.push({ left: relationMatch[1], right: relationMatch[3], type: relationMatch[2], label: normalizeLabel(relationMatch[4] || '') });
1983
+ }
1984
+ }
1985
+
1986
+ return { classes: classes, classesById: classesById, relations: relations };
1987
+ }
1988
+
1989
+ function renderClassDiagram(source) {
1990
+ var diagram = parseClassDiagram(source);
1991
+ if (!diagram.classes.length) {
1992
+ throw new Error('Class diagram is empty');
1993
+ }
1994
+
1995
+ var maxWidth = 0;
1996
+ var maxHeight = 0;
1997
+ for (var i = 0; i < diagram.classes.length; i += 1) {
1998
+ var classDef = diagram.classes[i];
1999
+ var classWidth = Math.max(120, measureLine(classDef.name) + 28);
2000
+ var maxMemberWidth = classWidth;
2001
+ var lineIndex;
2002
+
2003
+ for (lineIndex = 0; lineIndex < classDef.attributes.length; lineIndex += 1) {
2004
+ maxMemberWidth = Math.max(maxMemberWidth, measureLine(classDef.attributes[lineIndex]) + 24);
2005
+ }
2006
+ for (lineIndex = 0; lineIndex < classDef.methods.length; lineIndex += 1) {
2007
+ maxMemberWidth = Math.max(maxMemberWidth, measureLine(classDef.methods[lineIndex]) + 24);
2008
+ }
2009
+
2010
+ var attrHeight = classDef.attributes.length ? classDef.attributes.length * LINE_HEIGHT + 12 : 0;
2011
+ var methodHeight = classDef.methods.length ? classDef.methods.length * LINE_HEIGHT + 12 : 0;
2012
+ classDef.width = Math.ceil(maxMemberWidth);
2013
+ classDef.height = 34 + attrHeight + methodHeight + (classDef.attributes.length && classDef.methods.length ? 6 : 0) + 12;
2014
+ maxWidth = Math.max(maxWidth, classDef.width);
2015
+ maxHeight = Math.max(maxHeight, classDef.height);
2016
+ }
2017
+
2018
+ var columns = Math.min(4, Math.max(1, Math.ceil(Math.sqrt(diagram.classes.length))));
2019
+ var rows = Math.ceil(diagram.classes.length / columns);
2020
+ var width = OUTER_PADDING * 2 + columns * maxWidth + Math.max(0, columns - 1) * HORIZONTAL_GAP;
2021
+ var height = OUTER_PADDING * 2 + rows * maxHeight + Math.max(0, rows - 1) * VERTICAL_GAP;
2022
+ var svg = createRootSvg(width, height, 'Mermaid class diagram');
2023
+
2024
+ for (var classIndex = 0; classIndex < diagram.classes.length; classIndex += 1) {
2025
+ var current = diagram.classes[classIndex];
2026
+ var column = classIndex % columns;
2027
+ var row = Math.floor(classIndex / columns);
2028
+ current.x = OUTER_PADDING + column * (maxWidth + HORIZONTAL_GAP) + maxWidth / 2;
2029
+ current.y = OUTER_PADDING + row * (maxHeight + VERTICAL_GAP) + maxHeight / 2;
2030
+ }
2031
+
2032
+ for (var relationIndex = 0; relationIndex < diagram.relations.length; relationIndex += 1) {
2033
+ var relation = diagram.relations[relationIndex];
2034
+ var fromClass = diagram.classesById[relation.left];
2035
+ var toClass = diagram.classesById[relation.right];
2036
+ var relationFrom = fromClass;
2037
+ var relationTo = toClass;
2038
+ var markerEnd = '';
2039
+ var dash = '';
2040
+
2041
+ if (relation.type === '<|--' || relation.type === '*--' || relation.type === 'o--') {
2042
+ relationFrom = toClass;
2043
+ relationTo = fromClass;
2044
+ }
2045
+
2046
+ if (relation.type === '<|--') {
2047
+ markerEnd = 'url(#mini-mermaid-triangle-arrow)';
2048
+ } else if (relation.type === '*--') {
2049
+ markerEnd = 'url(#mini-mermaid-diamond-arrow)';
2050
+ } else if (relation.type === 'o--') {
2051
+ markerEnd = 'url(#mini-mermaid-open-diamond-arrow)';
2052
+ } else if (relation.type === '-->') {
2053
+ markerEnd = 'url(#mini-mermaid-open-arrow)';
2054
+ } else if (relation.type === '..>') {
2055
+ markerEnd = 'url(#mini-mermaid-open-arrow)';
2056
+ dash = '6 5';
2057
+ }
2058
+
2059
+ var relationStart = boxAnchor(relationFrom, relationTo);
2060
+ var relationEnd = boxAnchor(relationTo, relationFrom);
2061
+ drawStraightLine(svg, relationStart.x, relationStart.y, relationEnd.x, relationEnd.y, { dash: dash, markerEnd: markerEnd });
2062
+ if (relation.label) {
2063
+ drawLabel(svg, (relationStart.x + relationEnd.x) / 2, (relationStart.y + relationEnd.y) / 2 - 10, relation.label);
2064
+ }
2065
+ }
2066
+
2067
+ for (var drawClassIndex = 0; drawClassIndex < diagram.classes.length; drawClassIndex += 1) {
2068
+ var drawClass = diagram.classes[drawClassIndex];
2069
+ var bounds = { left: drawClass.x - drawClass.width / 2, top: drawClass.y - drawClass.height / 2 };
2070
+
2071
+ var outer = createSvg('rect');
2072
+ setAttrs(outer, {
2073
+ x: bounds.left,
2074
+ y: bounds.top,
2075
+ width: drawClass.width,
2076
+ height: drawClass.height,
2077
+ rx: 8,
2078
+ ry: 8,
2079
+ fill: 'var(--dt-bg-secondary)',
2080
+ stroke: 'var(--dt-border-default)',
2081
+ 'stroke-width': 1.5,
2082
+ });
2083
+ svg.appendChild(outer);
2084
+
2085
+ var headerHeight = 34;
2086
+ drawStraightLine(svg, bounds.left, bounds.top + headerHeight, bounds.left + drawClass.width, bounds.top + headerHeight, {
2087
+ stroke: 'var(--dt-border-default)',
2088
+ strokeWidth: 1,
2089
+ });
2090
+ attachText(svg, drawClass.x, bounds.top + headerHeight / 2 + 1, [drawClass.name], '');
2091
+
2092
+ var contentY = bounds.top + headerHeight + 10;
2093
+ if (drawClass.attributes.length) {
2094
+ appendLeftText(svg, bounds.left + 10, contentY, drawClass.attributes, { size: 13 });
2095
+ contentY += drawClass.attributes.length * LINE_HEIGHT + 8;
2096
+ }
2097
+ if (drawClass.methods.length) {
2098
+ drawStraightLine(svg, bounds.left, contentY - 4, bounds.left + drawClass.width, contentY - 4, {
2099
+ stroke: 'var(--dt-border-default)',
2100
+ strokeWidth: 1,
2101
+ });
2102
+ appendLeftText(svg, bounds.left + 10, contentY + 4, drawClass.methods, { size: 13 });
2103
+ }
2104
+ }
2105
+
2106
+ return svg;
2107
+ }
2108
+
2109
+ function ensureStateNode(graph, id, label, shape, stateKind) {
2110
+ var node = graph.nodesById[id];
2111
+ if (!node) {
2112
+ node = {
2113
+ id: id,
2114
+ label: label,
2115
+ shape: shape,
2116
+ groups: [],
2117
+ rank: 0,
2118
+ width: 0,
2119
+ height: 0,
2120
+ lines: [],
2121
+ x: 0,
2122
+ y: 0,
2123
+ order: graph.nodeOrder.length,
2124
+ stateKind: stateKind || '',
2125
+ };
2126
+ graph.nodesById[id] = node;
2127
+ graph.nodeOrder.push(id);
2128
+ }
2129
+ node.label = label;
2130
+ node.shape = shape;
2131
+ node.stateKind = stateKind || node.stateKind || '';
2132
+ return node;
2133
+ }
2134
+
2135
+ function parseStateDiagram(source) {
2136
+ var lines = cleanedLines(source);
2137
+ var graph = newGraph('TD');
2138
+
2139
+ for (var i = 0; i < lines.length; i += 1) {
2140
+ var line = lines[i];
2141
+ if (i === 0 && /^stateDiagram(?:-v2)?\b/i.test(line)) {
2142
+ continue;
2143
+ }
2144
+
2145
+ var match = line.match(/^(.+?)\s*-->\s*(.+?)(?:\s*:\s*(.+))?$/);
2146
+ if (!match) {
2147
+ continue;
2148
+ }
2149
+
2150
+ var fromToken = match[1].trim();
2151
+ var toToken = match[2].trim();
2152
+ var fromNode = fromToken === '[*]' ? ensureStateNode(graph, '__state_start__', '', 'circle', 'start') : ensureStateNode(graph, fromToken, normalizeLabel(fromToken), 'rounded', '');
2153
+ var toNode = toToken === '[*]' ? ensureStateNode(graph, '__state_end__', '', 'circle', 'end') : ensureStateNode(graph, toToken, normalizeLabel(toToken), 'rounded', '');
2154
+
2155
+ addEdge(graph, fromNode, { label: normalizeLabel(match[3] || ''), style: 'solid', arrow: true }, toNode);
2156
+ }
2157
+
2158
+ return graph;
2159
+ }
2160
+
2161
+ function renderStateDiagram(source) {
2162
+ var svg = renderSvg(parseStateDiagram(source));
2163
+ svg.setAttribute('aria-label', 'Mermaid state diagram');
2164
+ return svg;
2165
+ }
2166
+
2167
+ function parseGanttChart(source) {
2168
+ var lines = cleanedLines(source);
2169
+ var title = '';
2170
+ var sections = [];
2171
+ var sectionsByName = Object.create(null);
2172
+ var tasks = [];
2173
+ var tasksById = Object.create(null);
2174
+ var currentSection = null;
2175
+ var nextDateSlot = 0;
2176
+ var dateSlots = Object.create(null);
2177
+
2178
+ function ensureSection(name) {
2179
+ if (!sectionsByName[name]) {
2180
+ sectionsByName[name] = { name: name, tasks: [], index: sections.length };
2181
+ sections.push(sectionsByName[name]);
2182
+ }
2183
+ return sectionsByName[name];
2184
+ }
2185
+
2186
+ for (var i = 0; i < lines.length; i += 1) {
2187
+ var line = lines[i];
2188
+ if (i === 0 && /^gantt\b/i.test(line)) {
2189
+ continue;
2190
+ }
2191
+ var titleMatch = line.match(/^title\s+(.+)$/i);
2192
+ if (titleMatch) {
2193
+ title = normalizeLabel(titleMatch[1]);
2194
+ continue;
2195
+ }
2196
+ if (/^dateFormat\b/i.test(line)) {
2197
+ continue;
2198
+ }
2199
+ var sectionMatch = line.match(/^section\s+(.+)$/i);
2200
+ if (sectionMatch) {
2201
+ currentSection = ensureSection(normalizeLabel(sectionMatch[1]));
2202
+ continue;
2203
+ }
2204
+
2205
+ var separator = line.indexOf(':');
2206
+ if (separator === -1) {
2207
+ continue;
2208
+ }
2209
+ if (!currentSection) {
2210
+ currentSection = ensureSection('Tasks');
2211
+ }
2212
+
2213
+ var taskName = normalizeLabel(line.slice(0, separator));
2214
+ var fields = line.slice(separator + 1).split(',');
2215
+ var taskId = stripQuotes((fields[0] || '').trim()) || ('task_' + (tasks.length + 1));
2216
+ var startExpr = (fields[1] || '').trim();
2217
+ var durationField = (fields[2] || fields[fields.length - 1] || '').trim();
2218
+ var durationMatch = durationField.match(/(\d+)\s*d/i);
2219
+ var task = {
2220
+ id: taskId,
2221
+ name: taskName,
2222
+ startExpr: startExpr,
2223
+ duration: durationMatch ? Math.max(1, Number(durationMatch[1])) : 1,
2224
+ section: currentSection,
2225
+ start: null,
2226
+ end: null,
2227
+ };
2228
+ tasks.push(task);
2229
+ tasksById[task.id] = task;
2230
+ currentSection.tasks.push(task);
2231
+ }
2232
+
2233
+ var autoCursor = 0;
2234
+ for (var pass = 0; pass < tasks.length + 1; pass += 1) {
2235
+ for (var taskIndex = 0; taskIndex < tasks.length; taskIndex += 1) {
2236
+ var task = tasks[taskIndex];
2237
+ if (task.start !== null) {
2238
+ continue;
2239
+ }
2240
+ var afterMatch = task.startExpr.match(/^after\s+(.+)$/i);
2241
+ if (afterMatch) {
2242
+ var dependency = tasksById[afterMatch[1].trim()];
2243
+ if (!dependency || dependency.end === null) {
2244
+ continue;
2245
+ }
2246
+ task.start = dependency.end + 1;
2247
+ } else if (task.startExpr) {
2248
+ if (dateSlots[task.startExpr] === undefined) {
2249
+ dateSlots[task.startExpr] = nextDateSlot;
2250
+ nextDateSlot += task.duration + 1;
2251
+ }
2252
+ task.start = dateSlots[task.startExpr];
2253
+ } else {
2254
+ task.start = autoCursor;
2255
+ }
2256
+
2257
+ task.end = task.start + task.duration;
2258
+ autoCursor = Math.max(autoCursor, task.end + 1);
2259
+ }
2260
+ }
2261
+
2262
+ for (var fallbackIndex = 0; fallbackIndex < tasks.length; fallbackIndex += 1) {
2263
+ if (tasks[fallbackIndex].start === null) {
2264
+ tasks[fallbackIndex].start = autoCursor;
2265
+ tasks[fallbackIndex].end = autoCursor + tasks[fallbackIndex].duration;
2266
+ autoCursor = tasks[fallbackIndex].end + 1;
2267
+ }
2268
+ }
2269
+
2270
+ return { title: title, sections: sections, tasks: tasks };
2271
+ }
2272
+
2273
+ function renderGanttChart(source) {
2274
+ var gantt = parseGanttChart(source);
2275
+ if (!gantt.tasks.length) {
2276
+ throw new Error('Gantt chart is empty');
2277
+ }
2278
+
2279
+ var labelWidth = 0;
2280
+ var maxEnd = 0;
2281
+ for (var i = 0; i < gantt.tasks.length; i += 1) {
2282
+ labelWidth = Math.max(labelWidth, measureLine(gantt.tasks[i].name) + 18);
2283
+ maxEnd = Math.max(maxEnd, gantt.tasks[i].end || 0);
2284
+ }
2285
+ for (var sectionIndex = 0; sectionIndex < gantt.sections.length; sectionIndex += 1) {
2286
+ labelWidth = Math.max(labelWidth, measureLine(gantt.sections[sectionIndex].name) + 18);
2287
+ }
2288
+
2289
+ labelWidth = Math.max(120, labelWidth);
2290
+ var scaleX = 28;
2291
+ var titleHeight = gantt.title ? 30 : 0;
2292
+ var rows = gantt.tasks.length + gantt.sections.length;
2293
+ var width = OUTER_PADDING * 2 + labelWidth + 24 + Math.max(4, maxEnd + 1) * scaleX;
2294
+ var height = OUTER_PADDING * 2 + titleHeight + 28 + rows * 28 + 20;
2295
+ var svg = createRootSvg(width, height, 'Mermaid gantt chart');
2296
+ var chartLeft = OUTER_PADDING + labelWidth + 20;
2297
+ var currentY = OUTER_PADDING;
2298
+
2299
+ if (gantt.title) {
2300
+ appendText(svg, width / 2, currentY + 10, gantt.title, { anchor: 'middle', baseline: 'middle', weight: '600' });
2301
+ currentY += titleHeight;
2302
+ }
2303
+
2304
+ var axisY = currentY + 14;
2305
+ drawStraightLine(svg, chartLeft, axisY + 10, width - OUTER_PADDING, axisY + 10, { stroke: 'var(--dt-border-default)', strokeWidth: 1 });
2306
+ for (var tick = 0; tick <= maxEnd + 1; tick += 1) {
2307
+ var tickX = chartLeft + tick * scaleX;
2308
+ drawStraightLine(svg, tickX, axisY + 10, tickX, height - OUTER_PADDING, { stroke: 'var(--dt-border-default)', strokeWidth: 0.8 });
2309
+ appendText(svg, tickX + scaleX / 2, axisY, String(tick + 1), {
2310
+ anchor: 'middle',
2311
+ baseline: 'middle',
2312
+ size: 11,
2313
+ fill: 'var(--dt-text-secondary, var(--dt-text-primary))',
2314
+ });
2315
+ }
2316
+
2317
+ currentY = axisY + 28;
2318
+ for (var drawSectionIndex = 0; drawSectionIndex < gantt.sections.length; drawSectionIndex += 1) {
2319
+ var section = gantt.sections[drawSectionIndex];
2320
+ appendText(svg, OUTER_PADDING, currentY, section.name, { anchor: 'start', baseline: 'middle', weight: '600', size: 13 });
2321
+ drawStraightLine(svg, OUTER_PADDING, currentY + 10, width - OUTER_PADDING, currentY + 10, {
2322
+ stroke: 'var(--dt-border-default)',
2323
+ strokeWidth: 1,
2324
+ });
2325
+ currentY += 18;
2326
+
2327
+ for (var taskIndex = 0; taskIndex < section.tasks.length; taskIndex += 1) {
2328
+ var task = section.tasks[taskIndex];
2329
+ var barX = chartLeft + task.start * scaleX + 2;
2330
+ var barWidth = Math.max(18, task.duration * scaleX - 4);
2331
+ appendText(svg, OUTER_PADDING + 4, currentY + 8, task.name, { anchor: 'start', baseline: 'middle', size: 13 });
2332
+
2333
+ var bar = createSvg('rect');
2334
+ setAttrs(bar, {
2335
+ x: barX,
2336
+ y: currentY - 2,
2337
+ width: barWidth,
2338
+ height: 18,
2339
+ rx: 6,
2340
+ ry: 6,
2341
+ fill: 'var(--dt-bg-secondary)',
2342
+ 'fill-opacity': String(Math.max(0.45, 0.95 - drawSectionIndex * 0.12)),
2343
+ stroke: 'var(--dt-text-primary)',
2344
+ 'stroke-width': 1,
2345
+ });
2346
+ svg.appendChild(bar);
2347
+
2348
+ if (barWidth > measureLine(task.name) + 12) {
2349
+ appendText(svg, barX + barWidth / 2, currentY + 7, task.name, { anchor: 'middle', baseline: 'middle', size: 11 });
2350
+ }
2351
+ currentY += 28;
2352
+ }
2353
+ }
2354
+
2355
+ return svg;
2356
+ }
2357
+
2358
+ function parseErDiagram(source) {
2359
+ var lines = cleanedLines(source);
2360
+ var entities = [];
2361
+ var entitiesById = Object.create(null);
2362
+ var relationships = [];
2363
+ var currentEntity = null;
2364
+
2365
+ function ensureEntity(id) {
2366
+ if (!entitiesById[id]) {
2367
+ entitiesById[id] = { id: id, name: id, attributes: [], width: 0, height: 0, x: 0, y: 0 };
2368
+ entities.push(entitiesById[id]);
2369
+ }
2370
+ return entitiesById[id];
2371
+ }
2372
+
2373
+ for (var i = 0; i < lines.length; i += 1) {
2374
+ var line = lines[i];
2375
+ if (i === 0 && /^erDiagram\b/i.test(line)) {
2376
+ continue;
2377
+ }
2378
+ if (currentEntity) {
2379
+ if (line === '}') {
2380
+ currentEntity = null;
2381
+ continue;
2382
+ }
2383
+ var attrMatch = line.match(/^([A-Za-z0-9_.-]+)\s+([A-Za-z0-9_.-]+)(?:\s+(PK|FK))?$/i);
2384
+ if (attrMatch) {
2385
+ currentEntity.attributes.push({ type: attrMatch[1], name: attrMatch[2], key: attrMatch[3] || '' });
2386
+ }
2387
+ continue;
2388
+ }
2389
+
2390
+ var entityMatch = line.match(/^([A-Za-z0-9_.-]+)\s*\{$/);
2391
+ if (entityMatch) {
2392
+ currentEntity = ensureEntity(entityMatch[1]);
2393
+ continue;
2394
+ }
2395
+
2396
+ var relationMatch = line.match(/^([A-Za-z0-9_.-]+)\s+(\|\||o\{|\|\{|o\|)\-\-(\|\||o\{|\|\{|o\|)\s+([A-Za-z0-9_.-]+)(?:\s*:\s*(.+))?$/);
2397
+ if (relationMatch) {
2398
+ ensureEntity(relationMatch[1]);
2399
+ ensureEntity(relationMatch[4]);
2400
+ relationships.push({
2401
+ from: relationMatch[1],
2402
+ to: relationMatch[4],
2403
+ fromCardinality: relationMatch[2],
2404
+ toCardinality: relationMatch[3],
2405
+ label: normalizeLabel(relationMatch[5] || ''),
2406
+ });
2407
+ }
2408
+ }
2409
+
2410
+ return { entities: entities, entitiesById: entitiesById, relationships: relationships };
2411
+ }
2412
+
2413
+ function drawErToken(parent, token, x, y, angle) {
2414
+ var dx = Math.cos(angle);
2415
+ var dy = Math.sin(angle);
2416
+ var nx = -dy;
2417
+ var ny = dx;
2418
+
2419
+ function drawPart(kind, offset) {
2420
+ var cx = x + dx * offset;
2421
+ var cy = y + dy * offset;
2422
+
2423
+ if (kind === 'o') {
2424
+ var circle = createSvg('circle');
2425
+ setAttrs(circle, {
2426
+ cx: cx,
2427
+ cy: cy,
2428
+ r: 4,
2429
+ fill: 'var(--dt-bg-canvas)',
2430
+ stroke: 'var(--dt-text-primary)',
2431
+ 'stroke-width': 1.2,
2432
+ });
2433
+ parent.appendChild(circle);
2434
+ return;
2435
+ }
2436
+
2437
+ if (kind === '|') {
2438
+ drawStraightLine(parent, cx - nx * 7, cy - ny * 7, cx + nx * 7, cy + ny * 7, { stroke: 'var(--dt-text-primary)', strokeWidth: 1.6 });
2439
+ return;
2440
+ }
2441
+
2442
+ if (kind === '{') {
2443
+ var baseX = cx - dx * 5;
2444
+ var baseY = cy - dy * 5;
2445
+ drawStraightLine(parent, baseX, baseY, cx + nx * 7, cy + ny * 7, { stroke: 'var(--dt-text-primary)', strokeWidth: 1.3 });
2446
+ drawStraightLine(parent, baseX, baseY, cx, cy, { stroke: 'var(--dt-text-primary)', strokeWidth: 1.3 });
2447
+ drawStraightLine(parent, baseX, baseY, cx - nx * 7, cy - ny * 7, { stroke: 'var(--dt-text-primary)', strokeWidth: 1.3 });
2448
+ }
2449
+ }
2450
+
2451
+ drawPart(token.charAt(0), 6);
2452
+ drawPart(token.charAt(1), 15);
2453
+ }
2454
+
2455
+ function renderErDiagram(source) {
2456
+ var diagram = parseErDiagram(source);
2457
+ if (!diagram.entities.length) {
2458
+ throw new Error('ER diagram is empty');
2459
+ }
2460
+
2461
+ var maxWidth = 0;
2462
+ var maxHeight = 0;
2463
+ for (var i = 0; i < diagram.entities.length; i += 1) {
2464
+ var entity = diagram.entities[i];
2465
+ var entityWidth = Math.max(140, measureLine(entity.name) + 28);
2466
+ for (var attributeIndex = 0; attributeIndex < entity.attributes.length; attributeIndex += 1) {
2467
+ var attribute = entity.attributes[attributeIndex];
2468
+ var attributeLabel = attribute.type + ' ' + attribute.name + (attribute.key ? ' ' + attribute.key : '');
2469
+ entityWidth = Math.max(entityWidth, measureLine(attributeLabel) + 24);
2470
+ }
2471
+ entity.width = Math.ceil(entityWidth);
2472
+ entity.height = 36 + Math.max(1, entity.attributes.length) * LINE_HEIGHT + 18;
2473
+ maxWidth = Math.max(maxWidth, entity.width);
2474
+ maxHeight = Math.max(maxHeight, entity.height);
2475
+ }
2476
+
2477
+ var columns = Math.min(3, Math.max(1, Math.ceil(Math.sqrt(diagram.entities.length))));
2478
+ var rows = Math.ceil(diagram.entities.length / columns);
2479
+ var width = OUTER_PADDING * 2 + columns * maxWidth + Math.max(0, columns - 1) * HORIZONTAL_GAP;
2480
+ var height = OUTER_PADDING * 2 + rows * maxHeight + Math.max(0, rows - 1) * VERTICAL_GAP;
2481
+ var svg = createRootSvg(width, height, 'Mermaid ER diagram');
2482
+
2483
+ for (var entityIndex = 0; entityIndex < diagram.entities.length; entityIndex += 1) {
2484
+ var currentEntity = diagram.entities[entityIndex];
2485
+ var column = entityIndex % columns;
2486
+ var row = Math.floor(entityIndex / columns);
2487
+ currentEntity.x = OUTER_PADDING + column * (maxWidth + HORIZONTAL_GAP) + maxWidth / 2;
2488
+ currentEntity.y = OUTER_PADDING + row * (maxHeight + VERTICAL_GAP) + maxHeight / 2;
2489
+ }
2490
+
2491
+ for (var relationIndex = 0; relationIndex < diagram.relationships.length; relationIndex += 1) {
2492
+ var relation = diagram.relationships[relationIndex];
2493
+ var fromEntity = diagram.entitiesById[relation.from];
2494
+ var toEntity = diagram.entitiesById[relation.to];
2495
+ var start = boxAnchor(fromEntity, toEntity);
2496
+ var end = boxAnchor(toEntity, fromEntity);
2497
+
2498
+ drawStraightLine(svg, start.x, start.y, end.x, end.y, { stroke: 'var(--dt-text-primary)', strokeWidth: 1.4 });
2499
+
2500
+ var forwardAngle = Math.atan2(end.y - start.y, end.x - start.x);
2501
+ drawErToken(svg, relation.fromCardinality, start.x, start.y, forwardAngle);
2502
+ drawErToken(svg, relation.toCardinality, end.x, end.y, forwardAngle + Math.PI);
2503
+ if (relation.label) {
2504
+ drawLabel(svg, (start.x + end.x) / 2, (start.y + end.y) / 2 - 10, relation.label);
2505
+ }
2506
+ }
2507
+
2508
+ for (var drawEntityIndex = 0; drawEntityIndex < diagram.entities.length; drawEntityIndex += 1) {
2509
+ var drawEntity = diagram.entities[drawEntityIndex];
2510
+ var bounds = { left: drawEntity.x - drawEntity.width / 2, top: drawEntity.y - drawEntity.height / 2 };
2511
+
2512
+ var outer = createSvg('rect');
2513
+ setAttrs(outer, {
2514
+ x: bounds.left,
2515
+ y: bounds.top,
2516
+ width: drawEntity.width,
2517
+ height: drawEntity.height,
2518
+ rx: 8,
2519
+ ry: 8,
2520
+ fill: 'var(--dt-bg-canvas)',
2521
+ stroke: 'var(--dt-border-default)',
2522
+ 'stroke-width': 1.5,
2523
+ });
2524
+ svg.appendChild(outer);
2525
+
2526
+ var header = createSvg('rect');
2527
+ setAttrs(header, {
2528
+ x: bounds.left,
2529
+ y: bounds.top,
2530
+ width: drawEntity.width,
2531
+ height: 34,
2532
+ rx: 8,
2533
+ ry: 8,
2534
+ fill: 'var(--dt-bg-secondary)',
2535
+ stroke: 'var(--dt-border-default)',
2536
+ 'stroke-width': 1.2,
2537
+ });
2538
+ svg.appendChild(header);
2539
+
2540
+ drawStraightLine(svg, bounds.left, bounds.top + 34, bounds.left + drawEntity.width, bounds.top + 34, {
2541
+ stroke: 'var(--dt-border-default)',
2542
+ strokeWidth: 1,
2543
+ });
2544
+ attachText(svg, drawEntity.x, bounds.top + 18, [drawEntity.name], '');
2545
+
2546
+ var attrLines = [];
2547
+ for (var attrIndex = 0; attrIndex < drawEntity.attributes.length; attrIndex += 1) {
2548
+ var entityAttr = drawEntity.attributes[attrIndex];
2549
+ attrLines.push(entityAttr.type + ' ' + entityAttr.name + (entityAttr.key ? ' ' + entityAttr.key : ''));
2550
+ }
2551
+ appendLeftText(svg, bounds.left + 10, bounds.top + 42, attrLines.length ? attrLines : ['(no attributes)'], { size: 13 });
2552
+ }
2553
+
2554
+ return svg;
2555
+ }
2556
+
2557
+ function renderBlock(pre) {
2558
+ var source = pre.textContent || '';
2559
+ if (!source.trim()) {
2560
+ return;
2561
+ }
2562
+
2563
+ var firstLine = source.trim().split('\n')[0].trim();
2564
+ var svg;
2565
+
2566
+ if (/^sequenceDiagram/i.test(firstLine)) {
2567
+ svg = renderSequenceDiagram(source);
2568
+ } else if (/^classDiagram/i.test(firstLine)) {
2569
+ svg = renderClassDiagram(source);
2570
+ } else if (/^stateDiagram/i.test(firstLine)) {
2571
+ svg = renderStateDiagram(source);
2572
+ } else if (/^gantt/i.test(firstLine)) {
2573
+ svg = renderGanttChart(source);
2574
+ } else if (/^erDiagram/i.test(firstLine)) {
2575
+ svg = renderErDiagram(source);
2576
+ } else {
2577
+ svg = renderSvg(parseMermaid(source));
2578
+ }
2579
+
2580
+ pre.innerHTML = '';
2581
+ pre.style.whiteSpace = 'normal';
2582
+ pre.style.overflowX = 'auto';
2583
+ pre.setAttribute('data-mini-mermaid-rendered', 'true');
2584
+ pre.appendChild(svg);
2585
+ }
2586
+
2587
+ function renderAll() {
2588
+ if (!document || typeof document.querySelectorAll !== 'function') {
2589
+ return;
2590
+ }
2591
+
2592
+ var blocks = document.querySelectorAll('pre.mermaid');
2593
+ for (var i = 0; i < blocks.length; i += 1) {
2594
+ var block = blocks[i];
2595
+ if (!block || block.getAttribute('data-mini-mermaid-rendered') === 'true') {
2596
+ continue;
2597
+ }
2598
+
2599
+ try {
2600
+ renderBlock(block);
2601
+ } catch (_error) { console.error("[mini-mermaid] renderBlock error:", _error, "source:", block.textContent && block.textContent.substring(0, 80)); block.removeAttribute('data-mini-mermaid-rendered');
2602
+ }
2603
+ }
2604
+ }
2605
+
2606
+ function init() {
2607
+ if (document.readyState === 'loading') {
2608
+ document.addEventListener('DOMContentLoaded', function onReady() {
2609
+ document.removeEventListener('DOMContentLoaded', onReady);
2610
+ renderAll();
2611
+ });
2612
+ return;
2613
+ }
2614
+ renderAll();
2615
+ }
2616
+
2617
+ window.__aikit_initMermaid = function() {
2618
+ for (var i = 0; i < MAX_RENDER_PASSES; i += 1) {
2619
+ init();
2620
+ }
2621
+ };
2622
+
2623
+ window.__aikitMiniMermaid = {
2624
+ renderAll: renderAll,
2625
+ parse: parseMermaid,
2626
+ };
2627
+
2628
+ init();
2629
+ })();`;function of(){let e;return()=>{if(e!==void 0)return e;try{e=j(w(import.meta.url).resolve(`mermaid/dist/mermaid.min.js`),`utf-8`)}catch{e=``}return e}}const sf={id:`mermaid`,cdn:`https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js`,inlineSource:af,initScript:`window.__aikit_initMermaid = function() {
2630
+ if (typeof mermaid === 'undefined') return;
2631
+ if (document.readyState === 'loading') {
2632
+ document.addEventListener('DOMContentLoaded', window.__aikit_initMermaid);
2633
+ return;
2634
+ }
2635
+
2636
+ var theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default';
2637
+ if (!document.documentElement.getAttribute('data-theme')) {
2638
+ theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default';
2639
+ }
2640
+ mermaid.initialize({ startOnLoad: false, theme: theme });
2641
+ mermaid.run();
2642
+ };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:of()}},cf=new Map([[`mermaid`,sf]]);function lf(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=cf.get(r);if(e){if(t===`browser`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}if(t===`mcp-app`){n.push({inlineSource:e.inlineSource,onload:e.onload});continue}n.push({src:e.cdn,initScript:e.initScript,onload:e.onload})}}return n.length>0?n:void 0}function uf(){let e=[];for(let t of cf.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const df=300*1e3,ff=15*1e3;let Z=null,pf;process.on(`exit`,()=>{let e=Z;if(e){try{e.close()}catch{}Z=null}});function mf(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${Y(e.description)}</p>`:``;return[`<h1 class="present-surface-title">${Y(e.title)}</h1>`,t].filter(Boolean).join(`
2643
+ `)}function hf(e,t){return e.length===0?``:`
2644
+ <section class="present-surface-actions">
2645
+ <div class="present-action-bar">${e.map(e=>{let t=Y(e.id),n=Y(e.label);if(e.type===`select`||e.type===`multi-select`)return`<label class="present-action-field"><span>${n}</span><select data-action-id="${t}"${e.type===`multi-select`?` multiple`:``}>${(e.options??[]).map(e=>`<option value="${Y(e.value)}">${Y(e.label)}</option>`).join(``)}</select></label>`;if(e.type===`text-submit`)return`<label class="present-action-field"><span>${n}</span><div class="present-text-submit"><input type="text" class="present-text-input" data-action-id="${t}" data-action-label="${n}" placeholder="${n}" /><button type="button" class="present-action-btn present-action-primary present-submit-btn" data-submit-for="${t}">Send</button></div></label>`;if(e.type===`form-submit`){let r=e.schema;if(r)return`<form class="present-form" data-action-id="${t}" data-action-label="${n}">${Object.entries(r).map(([e,t])=>{let n=Y(t.description??e);return`<label class="present-action-field"><span>${n}</span><input type="${t.type===`number`?`number`:t.type===`boolean`?`checkbox`:`text`}" class="present-text-input" name="${Y(e)}" placeholder="${n}" /></label>`}).join(``)}<button type="submit" class="present-action-btn present-action-primary">${n}</button></form>`}return`<button type="button" class="present-action-btn present-action-${Y(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}).join(``)}</div>
2646
+ <p id="present-action-status" class="present-action-status" aria-live="polite"></p>
2647
+ </section>
2648
+ <style>
2649
+ .present-surface-title { margin: 0 0 0.75rem; font-size: 1.875rem; }
2650
+ .present-surface-description { margin: 0; color: var(--muted-foreground, #6b7280); }
2651
+ .present-surface-actions { display: grid; gap: 0.75rem; margin-top: 1.5rem; }
2652
+ .present-action-bar { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: flex-end; }
2653
+ .present-action-btn,
2654
+ .present-action-field select {
2655
+ font: inherit;
2656
+ font-size: 0.9375rem;
2657
+ line-height: 1.2;
2658
+ border-radius: 0.75rem;
2659
+ border: 1px solid var(--border, #d0d5dd);
2660
+ min-height: 2.5rem;
2661
+ }
2662
+ .present-action-btn {
2663
+ display: inline-flex;
2664
+ align-items: center;
2665
+ justify-content: center;
2666
+ padding: 0.5rem 1rem;
2667
+ background: var(--card, #ffffff);
2668
+ color: var(--card-foreground, #101828);
2669
+ cursor: pointer;
2670
+ text-align: center;
2671
+ transition:
2672
+ background 120ms ease,
2673
+ color 120ms ease,
2674
+ border-color 120ms ease;
2675
+ }
2676
+ .present-action-field {
2677
+ display: grid;
2678
+ gap: 0.35rem;
2679
+ min-width: 14rem;
2680
+ }
2681
+ .present-action-field span {
2682
+ color: var(--muted-foreground, #6b7280);
2683
+ font-size: 0.8125rem;
2684
+ font-weight: 500;
2685
+ }
2686
+ .present-action-field select {
2687
+ padding: 0.5rem 1rem;
2688
+ background: var(--card, #ffffff);
2689
+ color: var(--foreground, #101828);
2690
+ cursor: pointer;
2691
+ }
2692
+ .present-action-btn:hover,
2693
+ .present-action-btn:focus-visible,
2694
+ .present-action-field select:hover,
2695
+ .present-action-field select:focus-visible {
2696
+ background: var(--accent, #f3f4f6);
2697
+ color: var(--accent-foreground, #101828);
2698
+ outline: none;
2699
+ }
2700
+ .present-action-status { margin: 0; min-height: 1.25rem; color: var(--muted-foreground, #6b7280); }
2701
+ .present-text-submit {
2702
+ display: flex;
2703
+ gap: 0.5rem;
2704
+ align-items: stretch;
2705
+ }
2706
+ .present-text-input {
2707
+ font: inherit;
2708
+ font-size: 0.9375rem;
2709
+ line-height: 1.2;
2710
+ border-radius: 0.75rem;
2711
+ border: 1px solid var(--border, #d0d5dd);
2712
+ min-height: 2.5rem;
2713
+ padding: 0.5rem 1rem;
2714
+ background: var(--card, #ffffff);
2715
+ color: var(--foreground, #101828);
2716
+ flex: 1;
2717
+ min-width: 200px;
2718
+ }
2719
+ .present-text-input:focus {
2720
+ outline: 2px solid var(--ring, #2563eb);
2721
+ outline-offset: -1px;
2722
+ }
2723
+ .present-form {
2724
+ display: flex;
2725
+ flex-direction: column;
2726
+ gap: 0.75rem;
2727
+ }
2728
+ .present-action-primary {
2729
+ background: var(--primary, #2563eb) !important;
2730
+ color: var(--primary-foreground, #ffffff) !important;
2731
+ border-color: var(--primary, #2563eb) !important;
2732
+ }
2733
+ </style>
2734
+ <script>
2735
+ (() => {
2736
+ const nonce = ${JSON.stringify(t)};
2737
+ let settled = false;
2738
+ const statusNode = document.getElementById('present-action-status');
2739
+ const controls = Array.from(document.querySelectorAll('[data-action-id]'));
2740
+
2741
+ function setStatus(message) {
2742
+ if (statusNode) statusNode.textContent = message;
2743
+ }
2744
+
2745
+ function disableControls() {
2746
+ for (const control of controls) {
2747
+ control.disabled = true;
2748
+ }
2749
+ }
2750
+
2751
+ async function sendPayload(payload) {
2752
+ settled = true;
2753
+ disableControls();
2754
+ setStatus('Sending response...');
2755
+ try {
2756
+ await fetch('/callback', {
2757
+ method: 'POST',
2758
+ headers: { 'Content-Type': 'application/json' },
2759
+ body: JSON.stringify({ nonce, ...payload }),
2760
+ });
2761
+ setStatus('Response sent.');
2762
+ } catch {
2763
+ setStatus('Unable to send response.');
2764
+ }
2765
+ }
2766
+
2767
+ for (const control of controls) {
2768
+ if (control.tagName === 'SELECT' || control.tagName === 'INPUT' || control.tagName === 'FORM') {
2769
+ continue;
2770
+ }
2771
+
2772
+ control.addEventListener('click', () => {
2773
+ // Submit button for text-submit: read sibling input value
2774
+ const submitFor = control.dataset.submitFor;
2775
+ if (submitFor) {
2776
+ const input = document.querySelector('input[data-action-id="' + submitFor + '"]');
2777
+ const value = input ? input.value : '';
2778
+ void sendPayload({
2779
+ actionId: submitFor,
2780
+ value: value,
2781
+ label: input ? input.dataset.actionLabel : '',
2782
+ timestamp: new Date().toISOString(),
2783
+ });
2784
+ return;
2785
+ }
2786
+
2787
+ void sendPayload({
2788
+ actionId: control.dataset.actionId,
2789
+ value: 'clicked',
2790
+ label: control.dataset.actionLabel,
2791
+ timestamp: new Date().toISOString(),
2792
+ });
2793
+ });
2794
+ }
2795
+
2796
+ // Handle text-submit on Enter key
2797
+ for (const input of document.querySelectorAll('input.present-text-input[data-action-id]')) {
2798
+ input.addEventListener('keydown', (e) => {
2799
+ if (e.key === 'Enter') {
2800
+ e.preventDefault();
2801
+ void sendPayload({
2802
+ actionId: input.dataset.actionId,
2803
+ value: input.value,
2804
+ label: input.dataset.actionLabel,
2805
+ timestamp: new Date().toISOString(),
2806
+ });
2807
+ }
2808
+ });
2809
+ }
2810
+
2811
+ // Handle form-submit
2812
+ for (const form of document.querySelectorAll('form.present-form[data-action-id]')) {
2813
+ form.addEventListener('submit', (e) => {
2814
+ e.preventDefault();
2815
+ const formData = {};
2816
+ for (const input of form.querySelectorAll('input[name]')) {
2817
+ formData[input.name] = input.type === 'checkbox' ? input.checked : input.value;
2818
+ }
2819
+ void sendPayload({
2820
+ actionId: form.dataset.actionId,
2821
+ value: formData,
2822
+ label: form.dataset.actionLabel,
2823
+ timestamp: new Date().toISOString(),
2824
+ });
2825
+ });
2826
+ }
2827
+
2828
+ for (const control of document.querySelectorAll('select[data-action-id]')) {
2829
+ control.addEventListener('change', () => {
2830
+ const selected = Array.from(control.selectedOptions).map((option) => option.value);
2831
+ if (selected.length === 0) return;
2832
+
2833
+ void sendPayload({
2834
+ actionId: control.dataset.actionId,
2835
+ selection: control.multiple ? selected : selected[0],
2836
+ value: control.multiple ? selected : selected[0],
2837
+ timestamp: new Date().toISOString(),
2838
+ });
2839
+ });
2840
+ }
2841
+
2842
+ window.addEventListener('beforeunload', () => {
2843
+ if (settled || !navigator.sendBeacon) return;
2844
+ const body = JSON.stringify({ nonce, kind: 'cancelled', reason: 'user-closed' });
2845
+ navigator.sendBeacon('/callback', new Blob([body], { type: 'application/json' }));
2846
+ });
2847
+ })();
2848
+ <\/script>`}function gf(e){try{if(process.platform===`win32`){ir(`cmd`,[`/c`,`start`,``,e],{windowsHide:!0});return}if(process.platform===`darwin`){ir(`open`,[e]);return}ir(`xdg-open`,[e])}catch{}}async function _f(e){try{let t=An();return await t.launch(`ui`),t.resetIdleTimer(),await(await t.getContext().newPage()).goto(e,{waitUntil:`domcontentloaded`}),!0}catch{return gf(e),!1}}function vf(e,t,n){let r=[e.title];return e.description&&r.push(e.description),r.push(``,`Opened in browser at ${t}`,n),r.join(`
2849
+ `)}function yf(e){return e.some(e=>e.id!==`__dismiss`)}function bf(){return pf===void 0&&(pf=b(`blocks-interactive`)),pf}function xf(e){let t=e?.split(`?`)[0];if(!t?.startsWith(`/@aikit/blocks-interactive/dist/`))return;let n=bf();if(n)return P(n,`dist`,t.slice(32))}function Sf(e){return e.replace(`</head>`,`<style>
2850
+ .toolbar, .badge, body > header, body > footer { display: none !important; }
2851
+ body { padding-top: 0 !important; margin-top: 0 !important; }
2852
+ </style>
2853
+ </head>`).replace(`</body>`,`<script>
2854
+ window.addEventListener('message', function(e) {
2855
+ if (e.data && e.data.type === 'aikit-theme-change') {
2856
+ document.documentElement.setAttribute('data-theme', e.data.theme);
2857
+ }
2858
+ });
2859
+ <\/script>
2860
+ </body>`)}function Cf(){let e=Z;e&&(Z=null,setTimeout(()=>{try{e.close()}catch{}},2e3))}function wf(e){if(!e.headersSent)try{e.writeHead(500,{"Content-Type":`text/plain`}),e.end(`Internal Server Error`)}catch{try{e.end()}catch{}}}async function Tf(e,t){if(Af(`<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=Jt({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(`
2861
+ `);return{content:[{type:`text`,text:`[ERROR:VALIDATION] Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}],structuredContent:{kind:`error`,error:{code:`VIEWER_DATA_INVALID`,message:`Template "${t.id}" data validation failed:\n${e}\n\nExpected schema: ${JSON.stringify(t.inputSchema,null,2)}`}},isError:!0}}}let n=Sf(Md(t.resolveHtml(),e.data??null,t.injectId,t.transformData)),r=sr({title:e.title,html:[mf(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" src="/viewer" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2862
+ (function() {
2863
+ const iframe = document.querySelector('.present-viewer-iframe');
2864
+ if (!iframe) return;
2865
+ const sendTheme = function() {
2866
+ const theme = document.documentElement.getAttribute('data-theme');
2867
+ if (iframe.contentWindow) {
2868
+ iframe.contentWindow.postMessage({ type: 'aikit-theme-change', theme: theme }, '*');
2869
+ }
2870
+ };
2871
+ const observer = new MutationObserver(sendTheme);
2872
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
2873
+ iframe.addEventListener('load', sendTheme);
2874
+ })();
2875
+ <\/script>`,`</div>`].join(`
2876
+ `),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(`
2877
+ `)],islands:[],payload:void 0,nonce:``,generatedAt:new Date().toISOString(),colorScheme:e.colorScheme,lang:e.lang,dir:e.dir,transport:`browser`,exportPolicy:`local-interactive`}),i=``;try{Cf(),i=await new Promise((e,t)=>{let i=gr((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{wf(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 _f(i);let a=Z;return a&&setTimeout(()=>{Z===a&&(a.close(),Z=null)},df),{content:[{type:`text`,text:vf(e,i,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}async function Ef(e){Af(`<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=hr(e,{transport:`browser`,registry:tf,blockVendorScripts:fd()}),n=wd(t.surfaceId,t.actions),r=lf(t.vendorScripts,`browser`),i=uf(),a=sr({title:e.title,html:[mf(e),t.html,hf(t.actions,n.nonce)].filter(Boolean).join(`
2878
+ `),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=gr((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(()=>{wf(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=xf(e.url);if(o)try{let e=j(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{wf(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 _f(o);if(!yf(t.actions)){let t=Z;return t&&(n.promise.finally(()=>{Z===t&&(t.close(),Z=null)}),setTimeout(()=>{Z===t&&(t.close(),Z=null)},df)),{content:[{type:`text`,text:vf(e,o,`Rendered.`)}],structuredContent:{kind:`rendered`,reason:`no-response-required`}}}let u=await Promise.race([n.promise,new Promise(e=>{setTimeout(()=>{c||(Cf(),e(n.settleError(`BROWSER_CONNECT_TIMEOUT`,l?`No browser client connected within ${ff}ms.`:`Fell back to system browser, but no browser client connected within ${ff}ms.`)))},ff)}),new Promise(e=>{setTimeout(()=>e(n.settleTimeout(df)),df)})]),d=Z;d&&setTimeout(()=>{Z===d&&(d.close(),Z=null)},df);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:vf(e,o,f)}],structuredContent:u,isError:u.kind===`error`}}const Df=`ui://aikit/present.html`;let Of=``;function kf(){return Of}function Af(e){Of=e}function jf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Mf=/\\u[0-9a-fA-F]{4}/,Nf=/^\s*\|(?:[^|\r\n]+\|){2,}\s*$/,Pf=/^\s*\|?(?:\s*:?-{3,}:?\s*\|){2,}\s*$/,Ff=/\b(cli|terminal|tty|console|command(?:-|\s)?line)\b/i;function If(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 Lf(e){let t=e.split(/\r?\n/);for(let e=0;e<t.length-1;e+=1)if(Nf.test(t[e])&&Pf.test(t[e+1]))return!0;return!1}function Rf(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 zf(e,t){if(t<2)return!1;let n=e.trim();return n.startsWith(`|`)?Rf(n).length===t:!1}function Bf(e){let t=e.split(/\r?\n/),n=[],r=[],i=()=>{r.length!==0&&(n.push({type:`text`,content:r.join(`
2879
+ `)}),r.length=0)},a=0;for(;a<t.length;){let e=t[a],o=t[a+1];if(o!==void 0&&Nf.test(e)&&Pf.test(o)){let r=Rf(e),o=[];i();let s=a+2;for(;s<t.length&&zf(t[s],r.length);)o.push(Rf(t[s])),s+=1;n.push({type:`table`,headers:r,rows:o}),a=s;continue}r.push(e),a+=1}return i(),n}function Vf(e){let t=If(e);return!t||!Lf(t)?[e]:Bf(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 Hf(e){if(typeof e==`string`)return Ff.test(e);if(Array.isArray(e))return e.some(e=>Hf(e));if(!jf(e))return!1;let t=[`client`,`clientInfo`,`host`,`source`,`mode`,`name`,`title`,`channel`];return Object.entries(e).some(([e,n])=>t.includes(e)?Hf(n):!1)}function Uf(e,t){return{preferBrowser:[t,e._meta,jf(e.metadata)?e.metadata.source:void 0].some(e=>Hf(e))}}function Wf(e){if(!e.template)return!0;let t=kd(e.template);return t?t.supportedTransports.includes(`browser`):nf(e)?.supportedTransports.includes(`browser`)??!1}function Gf(e){let t=typeof e.description==`string`&&e.description.trim().length>0?`<p class="present-surface-description">${Y(e.description)}</p>`:``;return[`<section class="present-surface-header">`,` <h1>${Y(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(`
2880
+ `)}function Kf(e,t){let n=[e.title];return e.description&&n.push(e.description),fr(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(`
2881
+ `)}const qf={id:`__dismiss`,type:`button`,label:`Done`,variant:`default`};function Jf(e){if((e.actions?.length??0)>0||!e.template)return e;let t=nf(e);return t?.supportedTransports.includes(`browser`)===!0&&!t.supportedTransports.includes(`mcp-app`)?{...e,actions:[qf]}:e}function Yf(e){return e.replace(`</head>`,`<style>
2882
+ .toolbar, .badge, body > header, body > footer { display: none !important; }
2883
+ body { padding-top: 0 !important; margin-top: 0 !important; }
2884
+ </style>
2885
+ </head>`).replace(`</body>`,`<script>
2886
+ (function() {
2887
+ function report() {
2888
+ var h = document.documentElement.scrollHeight;
2889
+ window.parent.postMessage({ type: 'aikit-viewer-height', height: h }, '*');
2890
+ }
2891
+ var ro = new ResizeObserver(report);
2892
+ ro.observe(document.documentElement);
2893
+ report();
2894
+ })();
2895
+ <\/script>
2896
+ <script>
2897
+ window.addEventListener('message', function(e) {
2898
+ if (e.data && e.data.type === 'aikit-theme-change') {
2899
+ document.documentElement.setAttribute('data-theme', e.data.theme);
2900
+ }
2901
+ });
2902
+ <\/script>
2903
+ </body>`)}function Xf(e){let t=`<script>
2904
+ (function(){
2905
+ var last=0;
2906
+ function notify(){
2907
+ var h=Math.ceil(document.documentElement.scrollHeight);
2908
+ if(h!==last){last=h;window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/size-changed",params:{height:h}},"*")}
2909
+ }
2910
+ notify();
2911
+ if(typeof ResizeObserver!=="undefined"){new ResizeObserver(notify).observe(document.documentElement)}
2912
+ else{setInterval(notify,500)}
2913
+ })();
2914
+ <\/script>`;return e.includes(`</body>`)?e.replace(`</body>`,`${t}</body>`):`${e}${t}`}function Zf(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 — ${Y(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">${Y(e)}</h1>`,` <p class="error-message">${Y(t)}</p>`,`</div>`,`</body></html>`].join(`
2915
+ `)}function Qf(e,t,n,r){return Af(Zf(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function $f(e,t){if(!jf(e)||!(`schemaVersion`in e))return{ok:!1,response:Qf(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:Qf(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&Mf.test(e.title))return{ok:!1,response:Qf(`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(!jf(e)||e.type!==`markdown`)return[e];let t=If(e);return!t||!Lf(t)?[e]:Vf(e)})}:e;return{ok:!0,surface:n,options:Uf(n,t)}}async function ep(e,t={}){let n=Jf(e);if(e.template){let r=kd(e.template);if(r)return await tp(n,r,t)}return rf(n)||t.preferBrowser&&Wf(n)?await Ef(n):np(n)}async function tp(e,t,n={}){if(e.data!=null&&t.inputSchema){let n=Jt({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(`
2916
+ `);return Qf(`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 Tf(e,t);if(!i)return Qf(`VIEWER_TRANSPORT_UNSUPPORTED`,`Viewer template "${t.id}" does not support an available transport`,void 0,e.title);try{let n=Yf(Md(t.resolveHtml(),e.data??null,t.injectId,t.transformData)).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`);return Af(Xf(sr({title:e.title,html:[Gf(e),`<div class="present-viewer-container">`,` <iframe class="present-viewer-iframe" srcdoc="${n}" sandbox="allow-scripts allow-same-origin"></iframe>`,` <script>
2917
+ (function() {
2918
+ const iframe = document.querySelector('.present-viewer-iframe');
2919
+ if (!iframe) return;
2920
+ const sendTheme = function() {
2921
+ const theme = document.documentElement.getAttribute('data-theme');
2922
+ if (iframe.contentWindow) {
2923
+ iframe.contentWindow.postMessage({ type: 'aikit-theme-change', theme: theme }, '*');
2924
+ }
2925
+ };
2926
+ const observer = new MutationObserver(sendTheme);
2927
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
2928
+ iframe.addEventListener('load', sendTheme);
2929
+ })();
2930
+ <\/script>`,` <script>
2931
+ window.addEventListener('message', function(e) {
2932
+ if (e.data && e.data.type === 'aikit-viewer-height') {
2933
+ var container = document.querySelector('.present-viewer-container');
2934
+ if (container) { container.style.height = e.data.height + 'px'; }
2935
+ }
2936
+ });
2937
+ <\/script>`,`</div>`].join(`
2938
+ `),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(`
2939
+ `)],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:[Kf(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
2940
+
2941
+ `)}],ui:{type:`resource`,uri:Df}}}catch(t){return Qf(`VIEWER_RENDER_FAILED`,t instanceof Error?t.message:`Failed to render viewer template`,void 0,e.title)}}function np(e){try{let t=hr(e,{transport:`mcp-app`,registry:tf,blockVendorScripts:fd()}),n=lf(t.vendorScripts,`mcp-app`);return Of=Xf(sr({title:e.title,html:[Gf(e),t.html].filter(Boolean).join(`
2942
+ `),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:[Kf(e,{kind:`rendered`,reason:`no-response-required`}),`If this content doesn't render inline, retry with format: 'browser'.`].join(`
2943
+
2944
+ `)}],ui:{type:`resource`,uri:Df}}}catch(t){return Qf(`RENDER_FAILED`,t instanceof Error?t.message:`Failed to render ChannelSurface`,void 0,e.title)}}const rp=z.object({label:z.string(),value:z.string(),description:z.string().optional()}),ip=z.object({id:z.string().describe(`Unique action identifier`),type:z.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:z.string().describe(`Visible action label`),variant:z.enum([`primary`,`danger`,`default`]).optional(),options:z.array(rp).optional(),schema:z.record(z.string(),z.unknown()).optional()}),ap=z.object({type:z.string(),title:z.string().optional(),value:z.unknown().optional(),language:z.string().optional()}).catchall(z.unknown()),op={schemaVersion:z.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:z.string().describe(`Surface title shown to the user.`),description:z.string().optional().describe(`Optional supporting copy for the surface.`),template:z.string().optional().describe(`Optional template id such as report@1.`),layout:z.object({maxWidth:z.string().optional(),padding:z.string().optional(),columns:z.number().optional()}).optional(),blocks:z.array(ap).optional().describe(`Typed block content for the surface.`),data:z.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:z.array(ip).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:z.object({timeout:z.number().optional(),required:z.boolean().optional()}).optional(),metadata:z.object({surfaceId:z.string().optional(),createdAt:z.string().optional(),source:z.string().optional()}).optional(),colorScheme:z.enum([`light`,`dark`,`auto`]).optional(),lang:z.string().optional(),dir:z.enum([`ltr`,`rtl`,`auto`]).optional()};z.object({surfaceId:z.string(),actionId:z.string(),actionType:z.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:z.unknown().optional(),formData:z.record(z.string(),z.unknown()).optional(),selection:z.union([z.string(),z.array(z.string())]).optional(),label:z.string().optional(),timestamp:z.string(),sourceTransport:z.enum([`mcp-app`,`browser`,`export`])});function sp(e,t){let n=W(`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(`
2945
+ `);Zn(e,`present`,{title:n.title,description:r,inputSchema:op,annotations:n.annotations,_meta:{ui:{resourceUri:Df}}},J(`present`,async(e,t)=>{let n=$f(e,t);return n.ok?await ep(n.surface,n.options):n.response}));try{Xn(e,`Present View`,Df,{description:`AI Kit present tool viewer`},async()=>({contents:[{uri:Df,mimeType:Yn,text:kf()||`<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=jd().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 cp=I(`tools`);function lp(e,t){let n=new In({structure:new Rn,dependencies:new Nn,symbols:new zn,patterns:new Ln,entryPoints:new Fn,diagrams:new Pn}),r=W(`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:z.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:z.array(z.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},J(`produce_knowledge`,async({scope:e,aspects:r},i)=>{let a;try{a=Ds(i).createTask(`Produce Knowledge`,3),a.progress(0,`Running analyzers`);let o=e??`.`;cp.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=t?.onboardDir??``;if(!e)throw cp.warn(`onboardDir not configured — skipping artifact persistence.`),Error(`skip`);A(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`&&N(P(e,`${t}.md`),n+r,`utf-8`);cp.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){cp.warn(`Failed to persist knowledge to .ai/context/`,{error:L(e)})}a.progress(1,`Synthesizing results`);let c=n.buildSynthesisInstructions(s,r);return a.complete(`Knowledge production complete`),{content:[{type:`text`,text:c+`
2946
+
2947
+ ---
2948
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),cp.error(`Knowledge production failed`,L(e)),q(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const up=I(`tools`);function dp(e,t,n,r,i,a,o){let s=W(`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:z.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:z.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},J(`reindex`,async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
2949
+
2950
+ 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
2951
+
2952
+ Smart indexing (trickle mode) is enabled — files are automatically indexed as they are accessed by tools. Manual reindex is not needed.
2953
+
2954
+ **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
2955
+
2956
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=Ds(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),up.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&up.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(up.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(),up.info(`FTS index rebuilt after reindex`)}catch(e){up.warn(`FTS index rebuild failed`,L(e))}try{let e=await r.reindexAll();up.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){up.warn(`Curated re-index failed`,L(e))}if(a)try{await a.notifyAfterReindex()}catch(e){up.warn(`Post-reindex resource notification failed`,L(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),up.error(`Background reindex failed`,L(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 up.error(`Reindex failed`,L(e)),q(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const fp=I(`tools`);function pp(e){let t=W(`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:z.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:z.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:z.string().optional().describe(`Filter by tool name (list only)`),source:z.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:z.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},J(`replay`,async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return Ut(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Wt({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 Gt().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
2957
+
2958
+ `)}`}]}}catch(e){return fp.error(`Replay failed`,L(e)),q(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const mp=I(`tools`);function hp(e){let t=W(`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:z.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:z.string().optional().describe(`Restore point ID (required for action=restore)`),limit:z.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=vt().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(`
2959
+ `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await Kt(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
2960
+ `)}`}]}}catch(e){return mp.error(`Restore failed`,L(e)),q(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const gp=/<\/?curated-context>/gi;function _p(e){return e.replace(gp,``)}function vp(e){return`<curated-context>\n${_p(e)}\n</curated-context>`}const yp=I(`tools`);function bp(e,t,i,a){r(e,t,i);let o=e.memoryMetaGet(t);if(!o)return;let s=_(o,{...n,...a});s&&(v(e,t,s),h(e,t,i))}function xp(e,t){let n=[],r=re(process.cwd());r&&n.push(`[project: ${r}]`);let i=t?tn(t,`__context_boost`):void 0;return i&&n.push(`[focus: ${i.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function Sp(e,t,n){return n?e:t===`curated`?e*1.2:e}function Cp(e,t){return t?e:e.map(e=>({record:e.record,score:Sp(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}async function wp(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:Jn(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 yp.warn(`ER fallback failed`,L(e)),{results:n,triggered:!0,cacheHit:a}}}function Tp(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 Ep(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 Dp(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 Op(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&&!kp.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 kp=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 Ap(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 bn(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 jp(e,t,n,r,i,a,o,s,c,l){let u=W(`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:Do,inputSchema:{query:z.string().max(5e3).describe(`Natural language search query`),limit:z.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:z.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:z.enum(ue).optional().describe(`Filter by content type`),source_type:z.enum(pe).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:z.enum(fe).optional().describe(`Filter by knowledge origin`),category:z.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:z.array(z.string()).optional().describe(`Filter by tags (returns results matching ANY of the specified tags)`),min_score:z.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:z.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:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),dedup:z.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:z.array(z.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`,k=xp(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(k);w=await n.search(r,C);let a=await wp(i,w[0]?.score??0,w,e,u);w=a.results,T=a.triggered,E=a.cacheHit}catch(t){O=!1,yp.warn(`Embedder unavailable in semantic mode, falling back to FTS`,L(t)),w=await n.ftsSearch(e,{...C,limit:u}),D=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
2961
+
2962
+ `}else{let r=[],a=[];try{let i=await t.embedQuery(k),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,yp.warn(`Embedder unavailable, falling back to FTS-only`,L(t)),a=await n.ftsSearch(e,{...C,limit:u*2}),D=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
2963
+
2964
+ `}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):Tp(r,a).slice(0,u):w=a.slice(0,u),O){let t=await wp(i,r[0]?.score??0,w,e,u);w=t.results,T=t.triggered,E=t.cacheHit}}w=Cp(w,m).slice(0,u),a&&a.recordSearch(e,T,E),w.length>1&&(w=Ep(w,e)),w=Dp(w);let A=``;if(x&&x.length>0){let n=sc(x,ge(process.cwd()));if(n.length>0){let{stores:r,closeAll:i}=await cc(n);try{let i;i=d===`keyword`||!O?await uc(r,e,{...C,limit:u}):await lc(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),A=` + ${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(`
2965
+ `)[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`,yp.info(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){yp.debug(`Smart search fallback failed`,{error:String(e)})}if(w.length===0){let t=Be({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,...t.data?{structuredContent:t.data}:{}}}}let j,M;if(v>0&&!r&&(M="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),v>0&&r)try{let e=await ot(r,w.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:v,maxPerHit:5});j=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(`
2966
+ `),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(`
2967
+ `),i=[`- **Graph Context** (${v} hop${v>1?`s`:``}):`];e&&i.push(` Entities:\n${e}`),r&&i.push(` Relationships:\n${r}`),j.set(t.recordId,i.join(`
2968
+ `))}}catch(e){yp.warn(`Graph augmentation failed`,L(e)),M=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let ee=Date.now();for(let e of w)if(e.record.origin===`curated`&&e.record.indexedAt){let t=ee-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=Te(w),s)for(let e of w){if(e.record.origin!==`curated`)continue;let t=Fl(e.record.sourcePath);t&&bp(s,t,c,l)}let te=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,j?.get(n.id)??null].filter(Boolean).join(`
2969
+ `)}\n\n${n.origin===`curated`?vp(n.content):n.content}`}).join(`
2970
+
2971
+ ---
2972
+
2973
+ `),ne=(d===`hybrid`?`hybrid (vector + keyword RRF)`:d===`keyword`?`keyword (FTS)`:`semantic (vector)`)+A,N=Op(w,e),re=N.length>0?`\n_Distinctive terms: ${N.map(e=>`\`${e}\``).join(`, `)}_`:``,ie=await Ap(n,w),ae=[];if(w.length===0)ae.push("`reindex` — no results found, index may be stale"),ae.push("`find` — try federated search with glob/regex");else{let e=w[0]?.record.sourcePath;e&&ae.push(`\`lookup\` — see all chunks from \`${e}\``),ae.push("`symbol` — resolve a specific symbol from the results"),ae.push("`compact` — compress a result file for focused reading")}let P=[M?`${M}\n\n`:``,ie?`${ie}\n\n`:``,te,`\n\n---\n_Search mode: ${ne} | ${w.length} results_${re}`,`\n_Next: ${ae.join(` | `)}_`],oe=D+P.join(``),F=!1;if(y){let e=R(oe,y);F=e!==oe,oe=e}let se=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}:{}})),ce=[M,ie].filter(e=>!!e),le=Be({text:oe,query:e,searchMode:d,limit:u,results:se,durationMs:Date.now()-S,truncated:F,caveats:ce}),ue=new Set,de=[];for(let e of w){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Fl(e.record.sourcePath);if(!t)continue;let n=Nl(t,e.record.headingPath??t);n&&!ue.has(n.uri)&&(ue.add(n.uri),de.push(n))}return{content:[{type:`text`,text:le.summary},...de],isError:!le.ok,...le.data?{structuredContent:le.data}:{}}}catch(t){yp.error(`Search failed`,L(t));let n=ze(`Search failed: ${t instanceof Error?t.message:String(t)}`,Date.now()-S);return q(`INTERNAL`,n.error?.message??n.summary,{results:[],totalResults:0,searchMode:d??`hybrid`,query:e??``})}})}const Mp=I(`tools`);function Np(e,t,n){let r=W(`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:z.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:z.string().optional().describe(`ISO timestamp — only include activity after this time`),last:z.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:z.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:z.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:z.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:z.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},J(`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 Qt(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):Zt(l,u)).digest}]}}catch(e){return Mp.error(`Session digest failed`,L(e)),q(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Pp=1e4,Fp={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function Ip(e){return e??Fp}function Lp(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function Rp(e,t,n){let r=Lp(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function zp(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function Bp(e,t=!1,n){Lp(e,`workspace`);let r=Ip(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function Vp(e,t,n){let r=Ip(n),i=Bp(t.workspace,t.global??!1,r),a=Rp(t.key,`key`,500),o=Rp(t.value,`value`,Pp),s=t.agent?Rp(t.agent,`agent`,500):void 0,c=zp(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Hp(e,t,n){let r=Lp(t,`workspace`),i=Rp(n,`key`,500);return e.signalGet(r,i)}function Up(e,t){let n=Lp(t,`workspace`);return e.signalList(n)}function Wp(e,t,n){let r=Lp(t,`workspace`),i=n===void 0?void 0:Rp(n,`key`,500);return e.signalClear(r,i)}function Gp(e,t,n){let r=Ip(n),i=Rp(t.resource,`resource`,500),a=Rp(t.holder,`holder`,500),o=Lp(t.workspace,`workspace`),s=t.intent?Rp(t.intent,`intent`,Pp):void 0,c=zp(t.ttlMinutes??r.defaultLeaseTtlMinutes,`ttlMinutes`);if(c>60)throw Error(`ttlMinutes exceeds max of 60`);let l=e.leaseAcquire(i,a,o,s,c),u=e.leaseGet(i,o);return u?{acquired:l,holder:u.holder,expiresAt:u.expiresAt}:{acquired:l}}function Kp(e,t,n,r){let i=Lp(t,`workspace`),a=Rp(n,`resource`,500),o=Rp(r,`holder`,500);return e.leaseRelease(a,o,i)}function qp(e,t){let n=Lp(t,`workspace`);return e.leaseList(n)}const Jp=I(`tools:signal`);function Yp(e){return JSON.stringify(e,null,2)}function Xp(e,t,n){let r=W(`signal`),i={...Fp,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:z.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:z.string().describe(`Workspace identifier (required)`),key:z.string().optional().describe(`Signal key (for post/get/clear)`),value:z.string().optional().describe(`Signal value (for post)`),agent:z.string().optional().describe(`Agent identifier`),resource:z.string().optional().describe(`Resource path (for lease/unlease)`),holder:z.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:z.string().optional().describe(`What the holder plans to do`),ttl:z.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:z.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},J(`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=Vp(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:Yp({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Hp(t,Bp(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:Yp(e)}],structuredContent:{signals:e}}}case`list`:{let e=Up(t,Bp(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:Yp(e)}],structuredContent:{signals:e}}}case`clear`:{let e=Wp(t,Bp(n,d??!1,i),r);return{content:[{type:`text`,text:Yp({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=Gp(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:Yp(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=Kp(t,n,s,c);return{content:[{type:`text`,text:Yp({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=qp(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:Yp(e)}],structuredContent:{leases:e}}}}}catch(e){return Jp.error(`Signal operation failed`,L(e)),q(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Zp=I(`tools`);function Qp(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{Zp.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),Zp.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function $p(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 em(){let e=Vn.get(),t=Bn.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(`
2974
+ `):` 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(`
2975
+ `)}const tm=5*6e4;let nm=null,rm=null;function im(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 am(){let e=Date.now();if(nm&&e-nm.ts<tm)return nm.value;try{let t=F(Cn(),`.copilot`,`.aikit-scaffold.json`);if(!k(t))return nm={value:null,ts:e},null;let n=JSON.parse(j(t,`utf-8`)).version??null;return nm={value:n,ts:e},n}catch{return nm={value:null,ts:e},null}}function om(){let e=Date.now();if(rm&&e-rm.ts<tm)return rm.value;try{let t=F(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!k(t))return rm={value:null,ts:e},null;let n=JSON.parse(j(t,`utf-8`)).version??null;return rm={value:n,ts:e},n}catch{return rm={value:null,ts:e},null}}function sm(e){let t=W(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:vo,annotations:t.annotations},J(`status`,async()=>{let e=S(),t=am(),n=om(),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)**: ${Vn.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=C(),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`?(x(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(x(),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:!!Vn.get(),wasmDiagnostics:Bn.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:$p({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
2976
+ `)}],structuredContent:o}}))}function cm(e,t,n,r,i,a,o,s){let c=W(`status`);e.registerTool(`status`,{title:c.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:vo,annotations:c.annotations},J(`status`,async()=>{let e=[];try{let[c,l]=await Promise.all([Qp(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),Qp(t.listSourcePaths(),[],`store.listSourcePaths`)]),u=c.value;c.timedOut&&e.push(`⚠ Index stats timed out — values may be incomplete`);let d=l.value;l.timedOut&&e.push(`⚠ File listing timed out`);let f=null,p=0,m=[`## AI Kit Status`,``,`- **Total Records**: ${u.totalRecords}`,`- **Total Files**: ${u.totalFiles}`,`- **Last Indexed**: ${u.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(u.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...d.slice(0,50).map(e=>`- ${e}`),d.length>50?`\n... and ${d.length-50} more files`:``];if(n)try{let t=await Qp(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(t.timedOut)e.push(`⚠ Graph stats timed out`),m.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let e=t.value;f={nodes:e.nodeCount,edges:e.edgeCount},m.push(``,`### Knowledge Graph`,`- **Nodes**: ${e.nodeCount}`,`- **Edges**: ${e.edgeCount}`,...Object.entries(e.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await Qp(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||m.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&m.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{m.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let h=a?.onboardDir??``,g=k(h),_=i?.onboardComplete||g;if(m.push(``,`### Onboard Status`,_?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${h}\``),r)try{let t=await Qp(r.list(),[],`curated.list`);if(t.timedOut)e.push(`⚠ Curated knowledge listing timed out`),m.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let e=t.value;p=e.length,m.push(``,`### Curated Knowledge`,e.length>0?`- ${e.length} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions')}}catch{m.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let v=im(u.totalRecords,f?.nodes??0,f?.edges??0,p),y=u.lastIndexedAt?new Date(u.lastIndexedAt).getTime():0,b=y>0?Date.now()-y:1/0,w=$p({onboarded:_,indexStale:_&&b>1440*60*1e3,contextPressure:v});m.push(``),m.push(`## 📊 Context Pressure: ${v}/100`),v>=80?m.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):v>=50?m.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):m.push(`✅ Low pressure — plenty of headroom for more content.`);let T=0;if(u.lastIndexedAt){T=new Date(u.lastIndexedAt).getTime();let e=(Date.now()-T)/(1e3*60*60);m.push(``,`### Index Freshness`,e>24?o===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}m.push(``,`### Next Action`,`- **${w.kind}**: ${w.reason}`);let E=null,D=t;if(typeof D.getDiagnostics==`function`)try{E=D.getDiagnostics(),m.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${E.adapterType}`,`- **Vector search**: ${E.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,E.dbPath?`- **DB**: ${E.dbPath}`:``,E.dbSizeBytes==null?``:`- **DB size**: ${(E.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${E.embeddingDim}`,`- **Vector dtype**: ${E.vectorDtype}`)}catch{}if(o===`smart`)if(m.push(``,`### Smart Indexing`),s){let e=s();e?m.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):m.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else m.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=a?.stateDir?P(a.stateDir,`stash`):null;if(e&&k(e)){let t=ne(e).mtimeMs;t>T&&(T=t)}}catch{}let e=[];if(r)try{let t=p>0?await r.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>T&&(T=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=T>0?Date.now()-T:0;if(t>=144e5){let n=Math.floor(t/36e5);if(m.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){m.push(`**Recent decisions/notes:**`);for(let t of e)m.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}m.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint",'- `knowledge({ action: "list" })` — browse all stored knowledge')}}m.push(``,`### Runtime`,em());let O=am(),A=om(),j=S(),M=O!=null&&O!==j,ee=A!=null&&A!==j;if(M||ee){let e=C(),t=[];M&&t.push(`user scaffold v${O}`),ee&&t.push(`workspace scaffold v${A}`);let n=t.join(`, `);e.state===`success`?m.push(``,`### ✅ Upgrade Applied`,`- Server v${j} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?m.push(``,`### ⏳ Upgrade In Progress`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(x(),m.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${j} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(x(),m.push(``,`### ⬆ Upgrade Available`,`- Server v${j} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}e.length>0&&m.push(``,`### ⚠ Warnings`,...e.map(e=>`- ${e}`));let te=wa();if(te.length>0){let e=te.sort((e,t)=>t.callCount-e.callCount);m.push(``,`### Tool Usage This Session`,``),m.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),m.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);m.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let N=ga();if(N.bufferSize>=10){let e=N.state===`healthy`?`🟢`:N.state===`degraded`?`🔴`:`🟡`;m.push(``,`### Auto-GC: ${e} ${N.state}`),m.push(`- p95 latency: ${N.p95}ms | buffer: ${N.bufferSize} samples`),N.gcCount>0&&m.push(`- GC cycles triggered: ${N.gcCount}`)}let re=m.join(`
2977
+ `),ie={totalRecords:u.totalRecords,totalFiles:u.totalFiles,lastIndexedAt:u.lastIndexedAt??null,onboarded:_,onboardDir:h,contentTypes:u.contentTypeBreakdown,wasmAvailable:!!Vn.get(),wasmDiagnostics:Bn.get(),graphStats:f,curatedCount:p,serverVersion:j,scaffoldVersion:O??null,workspaceScaffoldVersion:A??null,upgradeAvailable:M||ee,storeBackend:a?.store?.backend,storeDiagnostics:E??null,contextPressure:v,nextAction:w};return{content:[{type:`text`,text:re+(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:ie}}catch(e){return Zp.error(`Status failed`,L(e)),q(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const lm=I(`tools`);function um(e){let t=W(`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:z.array(z.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:z.number().min(1).max(20).default(5).describe(`Max results per query`),site:z.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:z.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},J(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await hn({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(`
2978
+ `)};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 lm.error(`Web search failed`,L(e)),q(`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);lm.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(`
2979
+
2980
+ `);return c===o.length?q(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function dm(e){let t=W(`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:z.string().url().describe(`Request URL (http/https only)`),method:z.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:z.record(z.string(),z.string()).optional().describe(`Request headers as key-value pairs`),body:z.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:z.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},J(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await ut({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(`
2981
+ `)}]}}catch(e){return lm.error(`HTTP request failed`,L(e)),q(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function fm(e){let t=W(`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:z.string().max(500).describe(`Regex pattern (without delimiters)`),flags:z.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:z.array(z.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:z.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:z.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},J(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=Rt({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return q(`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(`
2982
+ `)}]}}))}function pm(e){let t=W(`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:z.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:z.string().max(1e6).describe(`Input text`)},annotations:t.annotations},J(`encode`,async({operation:e,input:t})=>{try{let n=qe({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 lm.error(`Encode failed`,L(e)),q(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function mm(e){let t=W(`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:bo,inputSchema:{path:z.string().describe(`File or directory path to measure`),extensions:z.array(z.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),max_tokens:z.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},J(`measure`,async({path:e,extensions:t,max_tokens:n})=>{try{let r=await bt({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?R(i.join(`
2983
+ `),n):i.join(`
2984
+ `)}],structuredContent:a}}catch(e){return lm.error(`Measure failed`,L(e)),q(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`)}}))}function hm(e){let t=W(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:z.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:z.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:z.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:z.boolean().default(!0).describe(`Highlight breaking changes`),cwd:z.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},J(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=Ee({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 lm.error(`Changelog failed`,L(e)),q(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function gm(e){let t=W(`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:z.string().max(5e5).describe(`JSON data to validate (as string)`),schema:z.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},J(`schema_validate`,async({data:e,schema:t})=>{try{let n=Jt({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
2985
+
2986
+ 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(`
2987
+ `)}]}}catch(e){return lm.error(`Schema validation failed`,L(e)),q(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function _m(e){let t=W(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:xo,inputSchema:{include_env:z.boolean().default(!1).describe(`Include environment variables`),filter_env:z.string().optional().describe(`Filter env vars by name substring`),show_sensitive:z.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},J(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Ye({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(`
2988
+ `)}],structuredContent:a}}))}function vm(e){let t=W(`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:So,inputSchema:{operation:z.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:z.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:z.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:z.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},J(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=ln({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(`
2989
+ `)}],structuredContent:o}}catch(e){return lm.error(`Time failed`,L(e)),q(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}function ym(e){try{let t=P(e,`.flows`);if(!k(t))return null;let n=M(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=P(t,e.name,`meta.json`);if(k(n)&&JSON.parse(j(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function bm(e,t,n,r,i,a,o,s,c,l){let u=new la,d=n.sources[0]?.path??process.cwd(),f={activeSlug:null};f.activeSlug=ym(d);let p=new ki(P(n.stateDir??``,`flow-context`),()=>f.activeSlug),m=new bi;m.register(_i),m.register(Wr),m.register(mi),m.register(Vr),m.register(Lr),m.register(Rr),m.register(yi),m.register(pi(()=>f.activeSlug?{active:!0,slug:f.activeSlug}:null));let h=new Ti(m,t.curated,{},p),g=l??ho(n,[...Ba,...Pa],Ya,Ia(n)),_=e=>g.has(e),v=new Set([...g].filter(e=>!Ku.includes(e)&&!Yi.has(e))),y=new $i;u.use(Ci(h),{order:5,name:`auto-knowledge`}),u.use(Ea(),{order:10,name:`replay`}),u.use(na(y,{stateStore:t.stateStore,curatedStore:t.curated},{trackedTools:v}),{order:94,name:`procedural-memory`}),u.use(Gi(new Ui(t.stateStore,t.curated)),{order:95,name:`observation-capture`}),u.use(Ha(),{order:1,name:`structured-content-guard`}),u.use(Oi(Di(n.tokenBudget)),{order:90,name:`compression`}),$a(e,u,n.toolPrefix??``);let b=[...g].filter(e=>Fa.has(e)?Na.includes(e)?!!t.bridge:e===`er_update_policy`?!!t.policyStore:e===`er_evolve_review`?!!t.evolutionCollector:!1:!0);_(`search`)&&jp(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`)&&Fu(e,t.store,x);let C={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};_(`status`)&&cm(e,t.store,t.graphStore,t.curated,C,n,o,s),_(`config`)&&ac(e,n),_(`reindex`)&&dp(e,t.indexer,n,t.curated,t.store,i,o),_(`knowledge`)&&Nu(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`)&&Cs(e,t.store,t.embedder,x),_(`blast_radius`)&&ws(e,t.store,t.embedder,t.graphStore,x),_(`produce_knowledge`)&&lp(e,n),_(`onboard`)&&Qu(e,t.store,t.embedder,n,C,x),_(`graph`)&&Sl(e,t.graphStore,x),_(`audit`)&&ks(e,t.store,t.embedder,n.tokenBudget),_(`compact`)&&gc(e,t.embedder,t.fileCache,d,n.allRoots,x,S),_(`scope_map`)&&_c(e,t.embedder,t.store,x),_(`find`)&&vc(e,t.embedder,t.store,d,x),_(`parse_output`)&&Mc(e),_(`workset`)&&ed(e),_(`check`)&&kc(e,x,n.tokenBudget),_(`symbol`)&&yc(e,t.embedder,t.store,t.graphStore,x),_(`eval`)&&Ac(e),_(`test_run`)&&jc(e,x),_(`stash`)&&td(e,t.stateStore),_(`signal`)&&Xp(e,t.stateStore),_(`git_context`)&&zu(e),_(`diff_parse`)&&Bu(e),_(`rename`)&&Vu(e,n),_(`codemod`)&&Hu(e,n),_(`restore`)&&hp(e),_(`file_summary`)&&bc(e,t.fileCache,d,n.allRoots,x,S),_(`checkpoint`)&&nd(e,t.stateStore),_(`data_transform`)&&Uu(e),_(`trace`)&&xc(e,t.embedder,t.store,t.graphStore,x),_(`process`)&&wl(e),_(`watch`)&&Tl(e),_(`dead_symbols`)&&Sc(e,t.embedder,t.store,d,n.allRoots,x),_(`delegate`)&&Nc(e,a),_(`health`)&&El(e),_(`lane`)&&rd(e),_(`queue`)&&id(e),_(`web_fetch`)&&Dl(e),_(`guide`)&&Ol(e,o),Ku.some(e=>_(e))&&qu(e,n,b),_(`evidence_map`)&&ml(e),_(`digest`)&&hl(e,t.embedder),_(`forge_classify`)&&gl(e,x),_(`stratum_card`)&&_l(e,t.embedder,t.fileCache),_(`forge_ground`)&&vl(e,t.embedder,t.store),_(`present`)&&sp(e,r),_(`browser`)&&jn(e,n),_(`web_search`)&&um(e),_(`http`)&&dm(e),_(`regex_test`)&&fm(e),_(`encode`)&&pm(e),_(`measure`)&&mm(e),_(`changelog`)&&hm(e),_(`schema_validate`)&&gm(e),_(`env`)&&_m(e),_(`time`)&&vm(e),_(`flow`)&&fl(e,n,e=>{f.activeSlug=e}),t.bridge&&Na.some(e=>_(e))&&(Ns(e,t.bridge,t.evolutionCollector),Ps(e,t.bridge),Fs(e,t.bridge)),t.policyStore&&_(`er_update_policy`)&&ud(e,t.policyStore),t.evolutionCollector&&_(`er_evolve_review`)&&Dc(e,t.evolutionCollector),Ma(e,t.store,t.curated),_(`compliance_score`)&&Rs(e),_(`replay`)&&pp(e),_(`session_digest`)&&Np(e,t.stateStore,a)}function xm(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&kc(e,void 0,t.tokenBudget),r(`eval`)&&Ac(e),r(`test_run`)&&jc(e),r(`parse_output`)&&Mc(e),r(`delegate`)&&Nc(e),r(`git_context`)&&zu(e),r(`diff_parse`)&&Bu(e),r(`rename`)&&Vu(e,t),r(`codemod`)&&Hu(e,t),r(`data_transform`)&&Uu(e),r(`workset`)&&ed(e),r(`restore`)&&hp(e),r(`lane`)&&rd(e),r(`queue`)&&id(e),r(`session_digest`)&&Np(e),r(`health`)&&El(e),r(`process`)&&wl(e),r(`watch`)&&Tl(e),r(`web_fetch`)&&Dl(e),r(`guide`)&&Ol(e),Ku.some(e=>r(e))&&qu(e,t,[...n??new Set(Ba)]),r(`evidence_map`)&&ml(e),r(`forge_classify`)&&gl(e),r(`present`)&&sp(e),r(`browser`)&&jn(e,t),r(`produce_knowledge`)&&lp(e),r(`compliance_score`)&&Rs(e),r(`replay`)&&pp(e),r(`status`)&&sm(e),r(`flow`)&&fl(e,t),r(`web_search`)&&um(e),r(`http`)&&dm(e),r(`regex_test`)&&fm(e),r(`encode`)&&pm(e),r(`measure`)&&mm(e),r(`changelog`)&&hm(e),r(`schema_validate`)&&gm(e),r(`env`)&&_m(e),r(`time`)&&vm(e)}const Sm=I(`resource-notifier`);var Cm=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){Sm.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){Sm.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Q=I(`server`);function wm(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function Tm(n){Q.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.store.path,a=wm(process.env.AIKIT_SPLIT_STATE),o=P(i,`aikit.db`),s={splitEnabled:a,contentDbPath:o,controlDbPath:a?P(i,`aikit-control.db`):o},c=null;if(r===`sqlite-vec`){let e=s.contentDbPath;k(i)||A(i,{recursive:!0}),c=await er(e),Q.info(`SQLite adapter ready`,{type:c.type,vectorCapable:c.vectorCapable,dbPath:e}),c.vectorCapable||Q.warn(`┌──────────────────────────────────────────────────────────────────┐
2990
+ │ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
2991
+ │ Vector search is disabled. Hybrid search returns FTS only. │
2992
+ │ To enable: install/rebuild better-sqlite3 (native module). │
2993
+ └──────────────────────────────────────────────────────────────────┘`);let t=P(i,`lance`);k(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 er(s.controlDbPath),rr(l,$n),Q.info(`State store adapter ready`,{type:l.type,dbPath:s.controlDbPath,splitEnabled:!0})}else l=c;else{let e=P(i,`aikit-state.db`);k(i)||A(i,{recursive:!0}),l=await er(e),rr(l,$n),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 _r({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 nr({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 Qn({adapter:c}):new Qn({path:i});return await e.initialize(),Q.info(`Graph store initialized`,{shared:!!c}),e})(),(async()=>{let e=await Hn();if(e){let e=Bn.get();Q.info(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=Bn.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 yr(u,d),h=tr(l),g=new vr(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=Ms(n.er),x=b?new Kn(n.curated.path):void 0;x&&Q.info(`Policy store initialized`,{ruleCount:x.getRules().length});let S=b?new Gn:void 0,C=F(n.sources[0]?.path??process.cwd(),le.aiContext),w=k(C),T=n.onboardDir?k(n.onboardDir):!1,E=w||T,D,O=w?C:n.onboardDir;if(E&&O)try{D=ne(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 xe,bridge:b,policyStore:x,evolutionCollector:S,onboardComplete:E,onboardTimestamp:D}}function Em(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(`
2994
+ `)}const Dm=I(`background-task`);var Om=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,Dm.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Dm.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Dm.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const km=I(`idle-timer`);var Am=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){km.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){km.info(`Skipping idle cleanup — background work in progress`);return}km.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`&&km.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const jm=I(`memory-monitor`);var Mm=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??4294967296,this.criticalBytes=e?.criticalBytes??8589934592,this.intervalMs=e?.intervalMs??6e4}onPressure(e){this.pressureFns.push(e)}registerMemoryPressureCallback(e){this.memoryPressureFns.push(e)}start(){this.timer||(this.timer=setInterval(()=>this.check(),this.intervalMs),this.timer.unref&&this.timer.unref(),jm.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`?jm.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?jm.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&jm.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 Nm=I(`tool-timeout`),Pm=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var Fm=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 Im(e){return Pm.has(e)?6e5:12e4}function Lm(e,t,n){return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{if(!a){a=!0;let e=new Fm(n,t);Nm.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 $=I(`server`),Rm=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`]);function zm(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function Bm(e){let t=[`query`,`path`,`task`,`name`,`start`,`symbol`,`file`,`pattern`],n=[];for(let r of t){let t=e[r];typeof t==`string`&&t.length>0&&t.length<200&&n.push(t)}return n.join(` `).slice(0,200)}async function Vm(e,t,n){let r=[];try{t.statePath&&Je(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=>`"${zm(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`"${zm(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 Hm(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||Rm.has(i))return o;try{r--;let e=a[0],i=await Vm(t,n,Bm(e&&typeof e==`object`?e:{}));i&&(o.content=Array.isArray(o.content)?o.content:[],o.content.push({type:`text`,text:i}))}catch{}return o}}}function Um(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 Wm(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(`
2995
+ `),`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??de.model,n=P(Cn(),`.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=P(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=P(e.store.path,`graph.db`);try{await r(t,{force:!0}),$.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=P(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 Gm(e,t){let n=ho(e,Ba,Ya,Ia(e)),r=Em(e,n,Ya),i=new wn({name:e.serverName??`aikit`,version:S()},{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}`:``,``,`**${za.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(`
2996
+ `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${za.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(`
2997
+ `);Sr(i);let p=new la;p.use(Ha(),{order:1,name:`structured-content-guard`}),$a(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of Ba){if(!n.has(e))continue;let t=W(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));za.has(e)?r.remove():h.push(r)}xm(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:kn(z.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,C=new Promise(e=>{x=e}),w=()=>x?.(),T=(async()=>{await C;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 Tm(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(Um(r)){$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await Wm(e,r);try{n=await Tm(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 za)m[e]?.remove();let b=new Cm(i),x=Rc(i);bm(i,n,e,br(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),Nr(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 S=i._registeredTools??{};for(let[e,t]of Object.entries(S)){if(La.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 (${Ra/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:Ja(t.config.outputSchema)}:{}}),Ra));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(S)){let n=t.handler,r=Im(e);t.handler=async(...i)=>{try{return await Lm(()=>n(...i),r,e)}catch(n){if(n instanceof Fm)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:Ja(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(S).length;w<Ba.length&&$.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:Ba.length,registeredToolCount:w}),$.info(`MCP server configured`,{toolCount:Ba.length,resourceCount:4});let T=new Mm;T.onPressure((e,t)=>{e===`warning`&&Er(),e===`critical`&&($.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),Er())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let E=new Am;l=E,E.onIdle(async()=>{if(D.isRunning||n.indexer.isIndexing){$.info(`Idle cleanup deferred — background tasks still running`),E.touch();return}$.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),E.touch();let O=!1;for(let e of Object.values(S)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,E.markSessionActive()),E.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}Hm(S,n,{statePath:e.stateDir??``}),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)})(),E=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`,L(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,L(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,L(e))}finally{l?.setBusy(!1)}},D=new Om,O=()=>D.schedule({name:`initial-index`,fn:E}),k=process.ppid,A=setInterval(()=>{try{process.kill(k,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:k}),clearInterval(A),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 A.unref(),{server:i,startInit:w,ready:T,runInitialIndex:O,get aikit(){return c},scheduler:D,setSmartScheduler(e){u=e}}}const Km=I(`server`);function qm(e,t){let n=ho(t,[...Ba,...Pa],Ya,Ia(t)),r=Em(t,n,Ya),i=new wn({name:t.serverName??`aikit`,version:S()},{capabilities:{logging:{},completions:{},prompts:{}},instructions:r});return Sr(i),bm(i,e,t,br(i),new Cm(i),Rc(i),void 0,null,null,n),Nr(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function Jm(e){let t=await Tm(e),n=qm(t,e);Km.info(`MCP server configured`,{toolCount:Ba.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Km.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&&Km.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Km.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Km.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Km.warn(`FTS index creation failed`,L(e))}try{let e=await t.curated.reindexAll();Km.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Km.error(`Curated re-index failed`,L(e))}}catch(e){Km.error(`Initial index failed; will retry on aikit_reindex`,L(e))}},i=async()=>{Km.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{Km.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{Ba as ALL_TOOL_NAMES,Gm as createLazyServer,qm as createMcpServer,Jm as createServer,Tm as initializeAikit,bm as registerMcpTools};