@vpxa/aikit 0.1.361 → 0.1.362

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.
@@ -195,7 +195,7 @@ Output ONLY the README.md content, nothing else.`;if(t.available)try{let i=(awai
195
195
 
196
196
  `).trim();r=t?ud(t):null}let i=Array.from(e.matchAll(/^##\s+.*$/gm)),a=[];for(let[t,n]of i.entries()){let r=n[0];if(!cd.test(r))continue;let o=n.index??0,s=i[t+1]?.index??e.length;a.push(e.slice(o,s).replace(/\s+$/,``))}return{brief:r,pins:a.length>0?a.join(`
197
197
 
198
- `):null}}function fd(e,t){return t(e)}async function pd(e){let{context:t,entry:n,state:r,activeRoot:i,primaryRoot:a,roots:o}=e,{instructionPath:s,description:c}=t.resolveCurrentStepInfo(n,r.currentStep,i),l=fd(n,t.getStepSequence),u=await Qu({entry:n,stepId:r.currentStep,runDir:r.runDir,slug:r.slug,primaryRoot:a,roots:o,activeRoot:i,resolveInstructionPath:t.resolveInstructionPath,resolveEpilogueInstructionPath:t.resolveEpilogueInstructionPath}),{brief:d,pins:f}=dd(u),p=d;if(d&&r.currentStep){let e=n.manifest.steps.find(e=>e.id===r.currentStep),a={stepId:r.currentStep,flowName:r.flow,flowSlug:r.slug,phase:`flow`,runDir:r.runDir,artifactsPath:F(r.runDir,n.manifest.artifacts_dir).replaceAll(`\\`,`/`),completedSteps:r.completedSteps??[],stepDescription:e?.description??c??void 0,agents:e?.agents??[],mode:`brief`,topic:r.topic??``,activeRoot:i};p=await t.stepPipeline.enrich(d,a,n.manifest.hooks)}return{artifactsPath:F(r.runDir,n.manifest.artifacts_dir).replaceAll(`\\`,`/`),currentStepInstruction:s,currentStepDescription:c,currentStepContent:u,currentStepBrief:p,currentStepPins:f,stepSequence:l}}function md(e){let{state:t,data:n,started:r,includeStatus:i,action:a,includeInstructionPath:o}=e,s={};return r&&(s.started=!0),s.flow=t.flow,t.flowOrigin&&(s.flowOrigin=t.flowOrigin),i&&(s.status=t.status),a&&(s.action=a),s.slug=t.slug,s.topic=t.topic,s.runDir=t.runDir,s.artifactsPath=n.artifactsPath,s.currentStep=t.currentStep,s.currentStepInstruction=n.currentStepInstruction,o&&(s.instructionPath=n.currentStepInstruction),s.currentStepDescription=n.currentStepDescription,s.currentStepContent=null,s.currentStepBrief=n.currentStepBrief,s.currentStepPins=n.currentStepPins,s.fullContentHint=`Call flow({ action: 'read' }) for the complete step instructions.`,s}function hd(e){return e.sourceType===`local`?{source:`local`,sourceType:e.sourceType,format:e.format,...e.commitSha?{commitSha:e.commitSha}:{}}:{source:e.source,sourceType:e.sourceType,format:e.format,...e.commitSha?{commitSha:e.commitSha}:{}}}async function gd(e,t){let{getAllRoots:n,getFlows:r,getWorkspaceRoot:i,isValidFlowRoot:a,log:o,patchMetaRoots:s,stateDir:c,toErrorText:l,toTextResponse:u}=t,{flow:d,topic:f,roots:p,objective:m,acceptanceCriteria:h,scope:g,exclusions:_}=e;try{if(p&&p.length>0){let e=n().map(e=>e.replaceAll(`\\`,`/`)),t=p.filter(e=>!a(e));if(t.length>0)return u(`Invalid roots — not part of the workspace or a recognized sub-repository: ${t.join(`, `)}. Available roots: ${e.join(`, `)}`)}let e=n(),o=e.map(e=>e.replaceAll(`\\`,`/`)),l=i(),v=e.length>1,y=!p&&v,b=p?.[0]??l,{registry:x,stateMachine:S}=await r(b),C=x.get(d);if(!C)throw new Xu(`UNKNOWN_FLOW`,`Flow "${d}" not found. Use flow({ action: "list" }) to see available flows.`);let w=S.start(C.name,C.manifest,f,hd(C),{objective:m,acceptanceCriteria:h,scope:g,exclusions:_});if(!w.success||!w.data){let e=w.error??`Unknown flow start error.`;return e.includes(`already active`)?u(`Cannot start: ${new Xu(`FLOW_ALREADY_ACTIVE`,e).message}`):u(`Cannot start: ${e}`)}let T=w.data,E;if(t.config.layeredKnowledge){let e=Vr(),t=S.setOwnerCapability({ownerTokenSalt:e.salt,ownerTokenHash:e.hash,ownerTokenVersion:e.version});if(!t.success)return u(`Cannot start in layered mode: failed to persist owner capability — ${t.error??`unknown error`}`);E=e.rawToken}if(p&&p.length>1)try{s(T.slug,b,p),t.syncMetaToRoots(T.slug,b)}catch(e){return S.reset(),u(`Flow created but failed to sync to secondary roots — rolled back. Error: ${e instanceof Error?e.message:String(e)}`)}let D=F(c,`flow-context`),O=typeof We==`function`?await We(D).catch(()=>[]):[];for(let e of O)e!==T.slug&&typeof Ge==`function`&&await Ge(F(D,e),{recursive:!0,force:!0}).catch(()=>{});if(typeof He==`function`)try{await He(F(D,T.slug),{recursive:!0})}catch{}let k=await pd({context:t,entry:C,state:T,activeRoot:b,primaryRoot:null,roots:p??null}),ee=Br(T,C.manifest,{objective:m,acceptanceCriteria:h,scope:g,exclusions:_}),te={...md({state:T,data:k,started:!0}),phase:T.phase,isEpilogue:T.isEpilogue,totalSteps:k.stepSequence.length,stepSequence:k.stepSequence,artifactsDir:C.manifest.artifacts_dir,roots:p??[b.replaceAll(`\\`,`/`)],snapshot:ee,_hint:od,...y?{multiRootWarning:`No roots specified in multi-root workspace. Flow created at workspace root. Pass roots parameter with target repo for precise placement.`,availableRoots:o}:{},...E?{_ownerToken:E}:{}};return u(JSON.stringify(te,null,2))}catch(e){return Zu(e)?u(e.message):(o.error(`flow action start failed`,M(e)),u(`Error: ${l(e)}`))}}async function _d(e,t){let{getFlows:n,log:r,resolveFlowRoot:i,syncMetaToRoots:a,toErrorText:o,toTextResponse:s}=t,{targetStep:c,lifecycleOwnerToken:l,currentToken:u}=e;try{let e=await i(),{registry:r,stateMachine:o}=await n(e),d=o.getStatus();if(!d.success||!d.data)return s(`No active flow. Use flow({ action: "start", name: "<flow>" }) first.`);let f=d.data,p=r.get(f.flow);if(!p)return s(`Flow "${f.flow}" not found in registry.`);if(t.config.layeredKnowledge){if(!l)return s(`lifecycleOwnerToken required in layered mode.`);let e=f,t=e.ownerTokenSalt,n=e.ownerTokenHash;if(!t||!n)return s(`Flow has no owner capability — cannot backtrack.`);if(!Ur(l,t,n))return s(`Invalid lifecycleOwnerToken — backtrack denied.`);if(u&&u!==f.currentToken)return s(`Invalid currentToken — flow state changed since last status.`)}let m=o.backtrack(c,p.manifest);if(!m.success||!m.data)return s(`Cannot backtrack: ${m.error}`);a(m.data.slug,e);let h=m.data,g=await pd({context:t,entry:p,state:h,activeRoot:e,primaryRoot:h.primaryRoot,roots:h.roots}),_={...md({state:h,data:g,includeStatus:!0,action:`backtrack`}),_hint:h.currentStep?od:void 0,phase:h.phase,isEpilogue:h.isEpilogue,completedSteps:h.completedSteps,skippedSteps:h.skippedSteps,totalSteps:g.stepSequence.length};return s(JSON.stringify(_,null,2))}catch(e){return Zu(e)?s(e.message):(r.error(`flow action backtrack failed`,M(e)),s(`Error: ${o(e)}`))}}async function vd(e,t){let{getFlows:n,log:r,resolveFlowRoot:i,syncMetaToRoots:a,toErrorText:o,toTextResponse:s}=t,{currentToken:c}=e;try{let e=await i(),{stateMachine:r}=await n(e),o=r.getStatus();if(!o.success||!o.data)return s(`No active flow. Use flow({ action: "start", name: "<flow>" }) first.`);let l=o.data;if(c&&c!==l.currentToken)return s(`Invalid currentToken — claim denied.`);if(!t.config.layeredKnowledge)return s(`Claim requires layeredKnowledge mode.`);let u=t.server?(await import(`./sampling-BX1qQuXx.js`)).createSamplingClient(t.server):null;if(u?.available){if((await u.createMessage({prompt:`You have been asked to transfer flow ownership. Do you confirm?`,systemPrompt:`Respond with "yes" to confirm or anything else to decline.`,maxTokens:16,modelPreferences:{intelligencePriority:.2,speedPriority:.9,costPriority:.9}})).text.trim().toLowerCase()!==`yes`)return s(`Ownership transfer declined by user.`)}else return s(`Cannot verify ownership transfer — no elicitor available.`);let d=Hr(l.ownerTokenVersion??1),f=r.setOwnerCapability({ownerTokenSalt:d.salt,ownerTokenHash:d.hash,ownerTokenVersion:d.version});if(!f.success)return s(`Claim failed: ${f.error}`);let p=r.getStatus();if(p.success&&p.data){let t=p.data;a(t.slug,e)}let m={success:!0,_ownerToken:d.rawToken,version:d.version,message:`Ownership transferred successfully.`};return s(JSON.stringify(m,null,2))}catch(e){return Zu(e)?s(e.message):(r.error(`flow action claim failed`,M(e)),s(`Error: ${o(e)}`))}}async function yd(e){let{getFlows:t,log:n,resolveFlowRoot:r,resolveRoots:i,toErrorText:a,toTextResponse:o}=e;try{let n=await r(),{registry:a,stateMachine:s}=await t(n),c=s.getStatus();if(!c.success||!c.data)throw new Xu(`NO_ACTIVE_FLOW`,`No active flow. Use flow({ action: "start", name: "<flow>" }) to begin one, or flow({ action: "list" }) to see available flows.`);let l=c.data,u=a.get(l.flow),d=u?await pd({context:e,entry:u,state:l,activeRoot:n,primaryRoot:l.primaryRoot,roots:l.roots}):ld(),f={...md({state:l,data:d,includeStatus:!0,includeInstructionPath:!0}),_hint:l.currentStep?od:void 0,phase:l.phase,isEpilogue:l.isEpilogue,completedSteps:l.completedSteps,skippedSteps:l.skippedSteps,artifacts:l.artifacts,startedAt:l.startedAt,updatedAt:l.updatedAt,totalSteps:d.stepSequence.length,progress:u?`${l.completedSteps.length+l.skippedSteps.length}/${d.stepSequence.length}`:`unknown`,workspaceRoot:n.replaceAll(`\\`,`/`),primaryRoot:(l.primaryRoot??n).replaceAll(`\\`,`/`),roots:l.roots??[n.replaceAll(`\\`,`/`)],allRoots:i().normalizedAllRoots,discoveredRepos:i().discoveredRepos};return o(JSON.stringify(f,null,2))}catch(e){return Zu(e)?o(e.message):(n.error(`flow action status failed`,M(e)),o(`Error: ${a(e)}`))}}async function bd(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 Ge(F(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`,M(e)),s(`Error: ${o(e)}`)}}async function xd(e,t){let{getFlows:n,log:r,resolveFlowRoot:i,syncMetaToRoots:a,toErrorText:o,toTextResponse:s}=t,{action:c,targetStep:l,lifecycleOwnerToken:u,currentToken:d}=e;if(c===`backtrack`)return l?_d({targetStep:l,lifecycleOwnerToken:u,currentToken:d},t):s(`Missing required parameter: targetStep for backtrack action.`);try{let e=await i(),{registry:r,stateMachine:o}=await n(e),l=o.getStatus();if(!l.success||!l.data)throw new Xu(`NO_ACTIVE_FLOW`,`No active flow. Use flow({ action: "start", name: "<flow>" }) first.`);let u=r.get(l.data.flow);if(!u)throw new Xu(`FLOW_NOT_FOUND`,`Flow "${l.data.flow}" not found in registry.`);let d=o.step(c,u.manifest);if(!d.success||!d.data)return s(`Cannot ${c}: ${d.error}`);a(d.data.slug,e);let f=d.data,p=[];if(f.status===`completed`){let e=F(t.stateDir,`flow-context`,f.slug);for(let t of[`decision`,`pattern`]){let n=F(e,t);try{let e=await We(n);for(let r of e){if(!r.endsWith(`.md`))continue;let e=await Ue(F(n,r),`utf-8`);e.length>100&&p.push({type:t,title:r.replace(/\.md$/,``).replace(/-/g,` `),content:e.length>500?`${e.slice(0,497)}...`:e})}}catch{}}typeof Ge==`function`&&await Ge(e,{recursive:!0,force:!0}).catch(()=>{})}let m=await pd({context:t,entry:u,state:f,activeRoot:e,primaryRoot:f.primaryRoot,roots:f.roots}),h={...md({state:f,data:m,includeStatus:!0,action:c}),_hint:f.currentStep?od:void 0,phase:f.phase,isEpilogue:f.isEpilogue,completedSteps:f.completedSteps,skippedSteps:f.skippedSteps,totalSteps:m.stepSequence.length,remaining:m.stepSequence.filter(e=>!f.completedSteps.includes(e)&&!f.skippedSteps.includes(e)&&e!==f.currentStep),...p.length>0?{promotionCandidates:p}:{}};return s(JSON.stringify(h,null,2))}catch(e){return Zu(e)?s(e.message):(r.error(`flow action step failed`,M(e)),s(`Error: ${o(e)}`))}}async function Sd(e){let{getFlows:t,log:n,resolveFlowRoot:r,resolveRoots:i,toErrorText:a,toTextResponse:o}=e;try{let{registry:e,stateMachine:n,installer:a}=await t(await r()),s=e.list(),c=n.getStatus(),l={flows:s.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=a.hasUpdates(e.installPath);return{...t,commitSha:e.commitSha,updateAvailable:n.success&&n.data?n.data.hasUpdates:void 0}}return t}),activeFlow:c.success&&c.data?{flow:c.data.flow,flowOrigin:c.data.flowOrigin,status:c.data.status,currentStep:c.data.currentStep,slug:c.data.slug,topic:c.data.topic,runDir:c.data.runDir}:null,allRoots:i().normalizedAllRoots,discoveredRepos:i().discoveredRepos};return o(JSON.stringify(l,null,2))}catch(e){return n.error(`flow action list failed`,M(e)),o(`Error: ${a(e)}`)}}async function Cd(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)throw new Xu(`UNKNOWN_FLOW`,`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 Zu(e)?s(e.message):(r.error(`flow action info failed`,M(e)),s(`Error: ${o(e)}`))}}async function wd(e,t){let{getAllRoots:n,getFlows:r,log:i,toErrorText:a,toTextResponse:o}=t,{flow:s,status:c,limit:l=50}=e,u=e=>{for(let t of[`updatedAt`,`startedAt`,`createdAt`]){let n=e[t];if(typeof n==`number`&&Number.isFinite(n))return n;if(typeof n==`string`){let e=Date.parse(n);if(!Number.isNaN(e))return e}}return null};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)});if(a.length===0)return o(`No flow runs found.`);let d=a.map((e,t)=>({run:e,index:t,recency:u(e)})).sort((e,t)=>e.recency==null&&t.recency==null?e.index-t.index:e.recency==null?1:t.recency==null?-1:t.recency===e.recency?e.index-t.index:t.recency-e.recency).map(({run:e})=>e).slice(0,l);return o(JSON.stringify({total:a.length,returned:d.length,truncated:a.length>d.length,runs:d},null,2))}catch(e){return i.error(`flow action runs failed`,M(e)),o(`Error: ${a(e)}`)}}function Td(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 Ed(e,t,n,r){let i=n&&typeof n!=`function`?n:void 0,a=typeof n==`function`?n:r,o=Yu(e,t,i),s=G(`flow`);e.registerTool(`flow`,{title:s.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:s.annotations,inputSchema:{action:R.enum([`list`,`info`,`start`,`step`,`status`,`reset`,`read`,`runs`,`add`,`remove`,`update`,`backtrack`,`claim`]).describe(`The flow operation to perform.`),name:R.string().optional().describe(`Flow name — required for info, start, remove, update. Optional override for add.`),topic:R.string().optional().describe(`Human-readable topic for the run (used by start).`),objective:R.string().optional().describe(`L1 snapshot objective — the goal of this flow run. Falls back to topic when absent.`),acceptanceCriteria:R.array(R.string()).optional().describe(`L1 snapshot acceptance criteria (used by start).`),scope:R.array(R.string()).optional().describe(`L1 snapshot scope boundaries (used by start). Falls back to roots when absent.`),exclusions:R.array(R.string()).optional().describe(`L1 snapshot exclusions — what is out of scope (used by start).`),roots:R.array(R.string()).optional().describe(`Workspace roots participating in this flow (used by start).`),advance:R.enum([`next`,`skip`,`redo`,`backtrack`]).optional().describe(`Step navigation action — required for step.`),lifecycleOwnerToken:R.string().optional().describe(`Owner capability token for layered lifecycle mutations (required in layered mode for step/backtrack/claim/reset).`),currentToken:R.string().optional().describe(`Current step execution token from status response for optimistic concurrency.`),targetStep:R.string().optional().describe(`Target step ID for backtrack action — must be a completed prior step.`),step:R.string().optional().describe(`Step id or name to read (used by read). Defaults to current step.`),source:R.string().optional().describe(`Git URL, local path, or "openspec" shorthand — required for add.`),token:R.string().optional().describe(`Auth token for private repos (used by add).`),filter_flow:R.string().optional().describe(`Filter runs by flow name (used by runs).`),filter_status:R.string().optional().describe(`Filter runs by status: active, completed, abandoned (used by runs).`),limit:R.number().int().positive().optional().describe(`Max runs to return (default 50).`)}},Y(`flow`,async e=>{switch(e.action){case`list`:return Sd(o);case`info`:return e.name?Cd({name:e.name},o):o.toTextResponse(`Missing required parameter: name`);case`start`:{if(!e.name)return o.toTextResponse(`Missing required parameter: name (flow to start)`);let t=await gd({flow:e.name,topic:e.topic,roots:e.roots,objective:e.objective,acceptanceCriteria:e.acceptanceCriteria,scope:e.scope,exclusions:e.exclusions},o),n=Td(t);return n&&a&&a(n),t}case`step`:return e.advance?xd({action:e.advance,targetStep:e.targetStep,lifecycleOwnerToken:e.lifecycleOwnerToken,currentToken:e.currentToken},o):o.toTextResponse(`Missing required parameter: advance (next/skip/redo/backtrack)`);case`status`:{let e=await yd(o);return a&&a(Td(e)),e}case`reset`:{let e=await bd(o);return a&&a(null),e}case`read`:return $u({step:e.step},o);case`runs`:return wd({flow:e.filter_flow,status:e.filter_status,limit:e.limit},o);case`add`:return e.source?rd({source:e.source,name:e.name,token:e.token},o):o.toTextResponse(`Missing required parameter: source`);case`remove`:return e.name?id({name:e.name},o):o.toTextResponse(`Missing required parameter: name`);case`update`:return e.name?ad({name:e.name},o):o.toTextResponse(`Missing required parameter: name`);case`backtrack`:return e.targetStep?_d({targetStep:e.targetStep,lifecycleOwnerToken:e.lifecycleOwnerToken,currentToken:e.currentToken},o):o.toTextResponse(`Missing required parameter: targetStep for backtrack action`);case`claim`:return vd({currentToken:e.currentToken},o);default:return o.toTextResponse(`Unknown action: ${e.action}`)}}))}const Dd=j(`tools`);function Od(e){let t=G(`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:R.enum([`create`,`add`,`update`,`get`,`gate`,`list`,`delete`]).describe(`Operation to perform`),task_id:R.string().optional().describe(`Task identifier (required for all except list)`),tier:R.enum([`floor`,`standard`,`critical`]).optional().describe(`FORGE tier (required for create)`),claim:R.string().optional().describe(`Critical-path claim text (for add)`),status:R.enum([`V`,`A`,`U`]).optional().describe(`Evidence status: V=Verified, A=Assumed, U=Unresolved`),receipt:R.string().optional().describe(`Evidence receipt: tool→ref for V, reasoning for A, attempts for U`),id:R.number().optional().describe(`Entry ID (for update)`),critical_path:R.boolean().default(!0).describe(`Whether this claim is on the critical path`),unknown_type:R.enum([`contract`,`convention`,`freshness`,`runtime`,`data-flow`,`impact`]).optional().describe(`Typed unknown classification`),safety_gate:R.enum([`provenance`,`commitment`,`coverage`]).optional().describe(`Safety gate tag: provenance (claim→evidence), commitment (user-approved), coverage (nothing dropped)`),retry_count:R.number().default(0).describe(`Retry count for gate evaluation (0 = first attempt)`),max_retries:R.number().int().min(0).optional().describe(`Maximum retries before escalating. Default: 3`),timeout_action:R.enum([`iterate`,`retry`,`manual`,`terminate`]).optional().describe(`Action to take when gate retries are exhausted. Default: manual`),cwd:R.string().optional().describe(`Working directory for evidence map storage (default: server cwd). Use root_path from forge_ground to match.`)},annotations:t.annotations},Y(`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 kt({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=kt({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.summary&&n.push(``,e.summary),{content:[{type:`text`,text:n.join(`
198
+ `):null}}function fd(e,t){return t(e)}async function pd(e){let{context:t,entry:n,state:r,activeRoot:i,primaryRoot:a,roots:o}=e,{instructionPath:s,description:c}=t.resolveCurrentStepInfo(n,r.currentStep,i),l=fd(n,t.getStepSequence),u=await Qu({entry:n,stepId:r.currentStep,runDir:r.runDir,slug:r.slug,primaryRoot:a,roots:o,activeRoot:i,resolveInstructionPath:t.resolveInstructionPath,resolveEpilogueInstructionPath:t.resolveEpilogueInstructionPath}),{brief:d,pins:f}=dd(u),p=d;if(d&&r.currentStep){let e=n.manifest.steps.find(e=>e.id===r.currentStep),a={stepId:r.currentStep,flowName:r.flow,flowSlug:r.slug,phase:`flow`,runDir:r.runDir,artifactsPath:F(r.runDir,n.manifest.artifacts_dir).replaceAll(`\\`,`/`),completedSteps:r.completedSteps??[],stepDescription:e?.description??c??void 0,agents:e?.agents??[],mode:`brief`,topic:r.topic??``,activeRoot:i};p=await t.stepPipeline.enrich(d,a,n.manifest.hooks)}return{artifactsPath:F(r.runDir,n.manifest.artifacts_dir).replaceAll(`\\`,`/`),currentStepInstruction:s,currentStepDescription:c,currentStepContent:u,currentStepBrief:p,currentStepPins:f,stepSequence:l}}function md(e){let{state:t,data:n,started:r,includeStatus:i,action:a,includeInstructionPath:o}=e,s={};return r&&(s.started=!0),s.flow=t.flow,t.flowOrigin&&(s.flowOrigin=t.flowOrigin),i&&(s.status=t.status),a&&(s.action=a),s.slug=t.slug,s.topic=t.topic,s.runDir=t.runDir,s.artifactsPath=n.artifactsPath,s.currentStep=t.currentStep,s.currentStepInstruction=n.currentStepInstruction,o&&(s.instructionPath=n.currentStepInstruction),s.currentStepDescription=n.currentStepDescription,s.currentStepContent=null,s.currentStepBrief=n.currentStepBrief,s.currentStepPins=n.currentStepPins,s.fullContentHint=`Call flow({ action: 'read' }) for the complete step instructions.`,s}function hd(e){return e.sourceType===`local`?{source:`local`,sourceType:e.sourceType,format:e.format,...e.commitSha?{commitSha:e.commitSha}:{}}:{source:e.source,sourceType:e.sourceType,format:e.format,...e.commitSha?{commitSha:e.commitSha}:{}}}async function gd(e,t){let{getAllRoots:n,getFlows:r,getWorkspaceRoot:i,isValidFlowRoot:a,log:o,patchMetaRoots:s,stateDir:c,toErrorText:l,toTextResponse:u}=t,{flow:d,topic:f,roots:p,objective:m,acceptanceCriteria:h,scope:g,exclusions:_}=e;try{if(p&&p.length>0){let e=n().map(e=>e.replaceAll(`\\`,`/`)),t=p.filter(e=>!a(e));if(t.length>0)return u(`Invalid roots — not part of the workspace or a recognized sub-repository: ${t.join(`, `)}. Available roots: ${e.join(`, `)}`)}let e=n(),o=e.map(e=>e.replaceAll(`\\`,`/`)),l=i(),v=e.length>1,y=!p&&v,b=p?.[0]??l,{registry:x,stateMachine:S}=await r(b),C=x.get(d);if(!C)throw new Xu(`UNKNOWN_FLOW`,`Flow "${d}" not found. Use flow({ action: "list" }) to see available flows.`);let w=S.start(C.name,C.manifest,f,hd(C),{objective:m,acceptanceCriteria:h,scope:g,exclusions:_});if(!w.success||!w.data){let e=w.error??`Unknown flow start error.`;return e.includes(`already active`)?u(`Cannot start: ${new Xu(`FLOW_ALREADY_ACTIVE`,e).message}`):u(`Cannot start: ${e}`)}let T=w.data,E;if(t.config.layeredKnowledge){let e=Vr(),t=S.setOwnerCapability({ownerTokenSalt:e.salt,ownerTokenHash:e.hash,ownerTokenVersion:e.version});if(!t.success)return u(`Cannot start in layered mode: failed to persist owner capability — ${t.error??`unknown error`}`);E=e.rawToken}if(p&&p.length>1)try{s(T.slug,b,p),t.syncMetaToRoots(T.slug,b)}catch(e){return S.reset(),u(`Flow created but failed to sync to secondary roots — rolled back. Error: ${e instanceof Error?e.message:String(e)}`)}let D=F(c,`flow-context`),O=typeof We==`function`?await We(D).catch(()=>[]):[];for(let e of O)e!==T.slug&&typeof Ge==`function`&&await Ge(F(D,e),{recursive:!0,force:!0}).catch(()=>{});if(typeof He==`function`)try{await He(F(D,T.slug),{recursive:!0})}catch{}let k=await pd({context:t,entry:C,state:T,activeRoot:b,primaryRoot:null,roots:p??null}),ee=Br(T,C.manifest,{objective:m,acceptanceCriteria:h,scope:g,exclusions:_}),te={...md({state:T,data:k,started:!0}),phase:T.phase,isEpilogue:T.isEpilogue,totalSteps:k.stepSequence.length,stepSequence:k.stepSequence,artifactsDir:C.manifest.artifacts_dir,roots:p??[b.replaceAll(`\\`,`/`)],snapshot:ee,_hint:od,...y?{multiRootWarning:`No roots specified in multi-root workspace. Flow created at workspace root. Pass roots parameter with target repo for precise placement.`,availableRoots:o}:{},...E?{_ownerToken:E}:{}};return u(JSON.stringify(te,null,2))}catch(e){return Zu(e)?u(e.message):(o.error(`flow action start failed`,M(e)),u(`Error: ${l(e)}`))}}async function _d(e,t){let{getFlows:n,log:r,resolveFlowRoot:i,syncMetaToRoots:a,toErrorText:o,toTextResponse:s}=t,{targetStep:c,lifecycleOwnerToken:l,currentToken:u}=e;try{let e=await i(),{registry:r,stateMachine:o}=await n(e),d=o.getStatus();if(!d.success||!d.data)return s(`No active flow. Use flow({ action: "start", name: "<flow>" }) first.`);let f=d.data,p=r.get(f.flow);if(!p)return s(`Flow "${f.flow}" not found in registry.`);if(t.config.layeredKnowledge){if(!l)return s(`lifecycleOwnerToken required in layered mode.`);let e=f,t=e.ownerTokenSalt,n=e.ownerTokenHash;if(!t||!n)return s(`Flow has no owner capability — cannot backtrack.`);if(!Ur(l,t,n))return s(`Invalid lifecycleOwnerToken — backtrack denied.`);if(u&&u!==f.currentToken)return s(`Invalid currentToken — flow state changed since last status.`)}let m=o.backtrack(c,p.manifest);if(!m.success||!m.data)return s(`Cannot backtrack: ${m.error}`);a(m.data.slug,e);let h=m.data,g=await pd({context:t,entry:p,state:h,activeRoot:e,primaryRoot:h.primaryRoot,roots:h.roots}),_={...md({state:h,data:g,includeStatus:!0,action:`backtrack`}),_hint:h.currentStep?od:void 0,phase:h.phase,isEpilogue:h.isEpilogue,completedSteps:h.completedSteps,skippedSteps:h.skippedSteps,totalSteps:g.stepSequence.length};return s(JSON.stringify(_,null,2))}catch(e){return Zu(e)?s(e.message):(r.error(`flow action backtrack failed`,M(e)),s(`Error: ${o(e)}`))}}async function vd(e,t){let{getFlows:n,log:r,resolveFlowRoot:i,syncMetaToRoots:a,toErrorText:o,toTextResponse:s}=t,{currentToken:c}=e;try{let e=await i(),{stateMachine:r}=await n(e),o=r.getStatus();if(!o.success||!o.data)return s(`No active flow. Use flow({ action: "start", name: "<flow>" }) first.`);let l=o.data;if(c&&c!==l.currentToken)return s(`Invalid currentToken — claim denied.`);if(!t.config.layeredKnowledge)return s(`Claim requires layeredKnowledge mode.`);let u=t.server?(await import(`./sampling-lcC_v6KY.js`)).createSamplingClient(t.server):null;if(u?.available){if((await u.createMessage({prompt:`You have been asked to transfer flow ownership. Do you confirm?`,systemPrompt:`Respond with "yes" to confirm or anything else to decline.`,maxTokens:16,modelPreferences:{intelligencePriority:.2,speedPriority:.9,costPriority:.9}})).text.trim().toLowerCase()!==`yes`)return s(`Ownership transfer declined by user.`)}else return s(`Cannot verify ownership transfer — no elicitor available.`);let d=Hr(l.ownerTokenVersion??1),f=r.setOwnerCapability({ownerTokenSalt:d.salt,ownerTokenHash:d.hash,ownerTokenVersion:d.version});if(!f.success)return s(`Claim failed: ${f.error}`);let p=r.getStatus();if(p.success&&p.data){let t=p.data;a(t.slug,e)}let m={success:!0,_ownerToken:d.rawToken,version:d.version,message:`Ownership transferred successfully.`};return s(JSON.stringify(m,null,2))}catch(e){return Zu(e)?s(e.message):(r.error(`flow action claim failed`,M(e)),s(`Error: ${o(e)}`))}}async function yd(e){let{getFlows:t,log:n,resolveFlowRoot:r,resolveRoots:i,toErrorText:a,toTextResponse:o}=e;try{let n=await r(),{registry:a,stateMachine:s}=await t(n),c=s.getStatus();if(!c.success||!c.data)throw new Xu(`NO_ACTIVE_FLOW`,`No active flow. Use flow({ action: "start", name: "<flow>" }) to begin one, or flow({ action: "list" }) to see available flows.`);let l=c.data,u=a.get(l.flow),d=u?await pd({context:e,entry:u,state:l,activeRoot:n,primaryRoot:l.primaryRoot,roots:l.roots}):ld(),f={...md({state:l,data:d,includeStatus:!0,includeInstructionPath:!0}),_hint:l.currentStep?od:void 0,phase:l.phase,isEpilogue:l.isEpilogue,completedSteps:l.completedSteps,skippedSteps:l.skippedSteps,artifacts:l.artifacts,startedAt:l.startedAt,updatedAt:l.updatedAt,totalSteps:d.stepSequence.length,progress:u?`${l.completedSteps.length+l.skippedSteps.length}/${d.stepSequence.length}`:`unknown`,workspaceRoot:n.replaceAll(`\\`,`/`),primaryRoot:(l.primaryRoot??n).replaceAll(`\\`,`/`),roots:l.roots??[n.replaceAll(`\\`,`/`)],allRoots:i().normalizedAllRoots,discoveredRepos:i().discoveredRepos};return o(JSON.stringify(f,null,2))}catch(e){return Zu(e)?o(e.message):(n.error(`flow action status failed`,M(e)),o(`Error: ${a(e)}`))}}async function bd(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 Ge(F(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`,M(e)),s(`Error: ${o(e)}`)}}async function xd(e,t){let{getFlows:n,log:r,resolveFlowRoot:i,syncMetaToRoots:a,toErrorText:o,toTextResponse:s}=t,{action:c,targetStep:l,lifecycleOwnerToken:u,currentToken:d}=e;if(c===`backtrack`)return l?_d({targetStep:l,lifecycleOwnerToken:u,currentToken:d},t):s(`Missing required parameter: targetStep for backtrack action.`);try{let e=await i(),{registry:r,stateMachine:o}=await n(e),l=o.getStatus();if(!l.success||!l.data)throw new Xu(`NO_ACTIVE_FLOW`,`No active flow. Use flow({ action: "start", name: "<flow>" }) first.`);let u=r.get(l.data.flow);if(!u)throw new Xu(`FLOW_NOT_FOUND`,`Flow "${l.data.flow}" not found in registry.`);let d=o.step(c,u.manifest);if(!d.success||!d.data)return s(`Cannot ${c}: ${d.error}`);a(d.data.slug,e);let f=d.data,p=[];if(f.status===`completed`){let e=F(t.stateDir,`flow-context`,f.slug);for(let t of[`decision`,`pattern`]){let n=F(e,t);try{let e=await We(n);for(let r of e){if(!r.endsWith(`.md`))continue;let e=await Ue(F(n,r),`utf-8`);e.length>100&&p.push({type:t,title:r.replace(/\.md$/,``).replace(/-/g,` `),content:e.length>500?`${e.slice(0,497)}...`:e})}}catch{}}typeof Ge==`function`&&await Ge(e,{recursive:!0,force:!0}).catch(()=>{})}let m=await pd({context:t,entry:u,state:f,activeRoot:e,primaryRoot:f.primaryRoot,roots:f.roots}),h={...md({state:f,data:m,includeStatus:!0,action:c}),_hint:f.currentStep?od:void 0,phase:f.phase,isEpilogue:f.isEpilogue,completedSteps:f.completedSteps,skippedSteps:f.skippedSteps,totalSteps:m.stepSequence.length,remaining:m.stepSequence.filter(e=>!f.completedSteps.includes(e)&&!f.skippedSteps.includes(e)&&e!==f.currentStep),...p.length>0?{promotionCandidates:p}:{}};return s(JSON.stringify(h,null,2))}catch(e){return Zu(e)?s(e.message):(r.error(`flow action step failed`,M(e)),s(`Error: ${o(e)}`))}}async function Sd(e){let{getFlows:t,log:n,resolveFlowRoot:r,resolveRoots:i,toErrorText:a,toTextResponse:o}=e;try{let{registry:e,stateMachine:n,installer:a}=await t(await r()),s=e.list(),c=n.getStatus(),l={flows:s.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=a.hasUpdates(e.installPath);return{...t,commitSha:e.commitSha,updateAvailable:n.success&&n.data?n.data.hasUpdates:void 0}}return t}),activeFlow:c.success&&c.data?{flow:c.data.flow,flowOrigin:c.data.flowOrigin,status:c.data.status,currentStep:c.data.currentStep,slug:c.data.slug,topic:c.data.topic,runDir:c.data.runDir}:null,allRoots:i().normalizedAllRoots,discoveredRepos:i().discoveredRepos};return o(JSON.stringify(l,null,2))}catch(e){return n.error(`flow action list failed`,M(e)),o(`Error: ${a(e)}`)}}async function Cd(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)throw new Xu(`UNKNOWN_FLOW`,`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 Zu(e)?s(e.message):(r.error(`flow action info failed`,M(e)),s(`Error: ${o(e)}`))}}async function wd(e,t){let{getAllRoots:n,getFlows:r,log:i,toErrorText:a,toTextResponse:o}=t,{flow:s,status:c,limit:l=50}=e,u=e=>{for(let t of[`updatedAt`,`startedAt`,`createdAt`]){let n=e[t];if(typeof n==`number`&&Number.isFinite(n))return n;if(typeof n==`string`){let e=Date.parse(n);if(!Number.isNaN(e))return e}}return null};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)});if(a.length===0)return o(`No flow runs found.`);let d=a.map((e,t)=>({run:e,index:t,recency:u(e)})).sort((e,t)=>e.recency==null&&t.recency==null?e.index-t.index:e.recency==null?1:t.recency==null?-1:t.recency===e.recency?e.index-t.index:t.recency-e.recency).map(({run:e})=>e).slice(0,l);return o(JSON.stringify({total:a.length,returned:d.length,truncated:a.length>d.length,runs:d},null,2))}catch(e){return i.error(`flow action runs failed`,M(e)),o(`Error: ${a(e)}`)}}function Td(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 Ed(e,t,n,r){let i=n&&typeof n!=`function`?n:void 0,a=typeof n==`function`?n:r,o=Yu(e,t,i),s=G(`flow`);e.registerTool(`flow`,{title:s.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:s.annotations,inputSchema:{action:R.enum([`list`,`info`,`start`,`step`,`status`,`reset`,`read`,`runs`,`add`,`remove`,`update`,`backtrack`,`claim`]).describe(`The flow operation to perform.`),name:R.string().optional().describe(`Flow name — required for info, start, remove, update. Optional override for add.`),topic:R.string().optional().describe(`Human-readable topic for the run (used by start).`),objective:R.string().optional().describe(`L1 snapshot objective — the goal of this flow run. Falls back to topic when absent.`),acceptanceCriteria:R.array(R.string()).optional().describe(`L1 snapshot acceptance criteria (used by start).`),scope:R.array(R.string()).optional().describe(`L1 snapshot scope boundaries (used by start). Falls back to roots when absent.`),exclusions:R.array(R.string()).optional().describe(`L1 snapshot exclusions — what is out of scope (used by start).`),roots:R.array(R.string()).optional().describe(`Workspace roots participating in this flow (used by start).`),advance:R.enum([`next`,`skip`,`redo`,`backtrack`]).optional().describe(`Step navigation action — required for step.`),lifecycleOwnerToken:R.string().optional().describe(`Owner capability token for layered lifecycle mutations (required in layered mode for step/backtrack/claim/reset).`),currentToken:R.string().optional().describe(`Current step execution token from status response for optimistic concurrency.`),targetStep:R.string().optional().describe(`Target step ID for backtrack action — must be a completed prior step.`),step:R.string().optional().describe(`Step id or name to read (used by read). Defaults to current step.`),source:R.string().optional().describe(`Git URL, local path, or "openspec" shorthand — required for add.`),token:R.string().optional().describe(`Auth token for private repos (used by add).`),filter_flow:R.string().optional().describe(`Filter runs by flow name (used by runs).`),filter_status:R.string().optional().describe(`Filter runs by status: active, completed, abandoned (used by runs).`),limit:R.number().int().positive().optional().describe(`Max runs to return (default 50).`)}},Y(`flow`,async e=>{switch(e.action){case`list`:return Sd(o);case`info`:return e.name?Cd({name:e.name},o):o.toTextResponse(`Missing required parameter: name`);case`start`:{if(!e.name)return o.toTextResponse(`Missing required parameter: name (flow to start)`);let t=await gd({flow:e.name,topic:e.topic,roots:e.roots,objective:e.objective,acceptanceCriteria:e.acceptanceCriteria,scope:e.scope,exclusions:e.exclusions},o),n=Td(t);return n&&a&&a(n),t}case`step`:return e.advance?xd({action:e.advance,targetStep:e.targetStep,lifecycleOwnerToken:e.lifecycleOwnerToken,currentToken:e.currentToken},o):o.toTextResponse(`Missing required parameter: advance (next/skip/redo/backtrack)`);case`status`:{let e=await yd(o);return a&&a(Td(e)),e}case`reset`:{let e=await bd(o);return a&&a(null),e}case`read`:return $u({step:e.step},o);case`runs`:return wd({flow:e.filter_flow,status:e.filter_status,limit:e.limit},o);case`add`:return e.source?rd({source:e.source,name:e.name,token:e.token},o):o.toTextResponse(`Missing required parameter: source`);case`remove`:return e.name?id({name:e.name},o):o.toTextResponse(`Missing required parameter: name`);case`update`:return e.name?ad({name:e.name},o):o.toTextResponse(`Missing required parameter: name`);case`backtrack`:return e.targetStep?_d({targetStep:e.targetStep,lifecycleOwnerToken:e.lifecycleOwnerToken,currentToken:e.currentToken},o):o.toTextResponse(`Missing required parameter: targetStep for backtrack action`);case`claim`:return vd({currentToken:e.currentToken},o);default:return o.toTextResponse(`Unknown action: ${e.action}`)}}))}const Dd=j(`tools`);function Od(e){let t=G(`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:R.enum([`create`,`add`,`update`,`get`,`gate`,`list`,`delete`]).describe(`Operation to perform`),task_id:R.string().optional().describe(`Task identifier (required for all except list)`),tier:R.enum([`floor`,`standard`,`critical`]).optional().describe(`FORGE tier (required for create)`),claim:R.string().optional().describe(`Critical-path claim text (for add)`),status:R.enum([`V`,`A`,`U`]).optional().describe(`Evidence status: V=Verified, A=Assumed, U=Unresolved`),receipt:R.string().optional().describe(`Evidence receipt: tool→ref for V, reasoning for A, attempts for U`),id:R.number().optional().describe(`Entry ID (for update)`),critical_path:R.boolean().default(!0).describe(`Whether this claim is on the critical path`),unknown_type:R.enum([`contract`,`convention`,`freshness`,`runtime`,`data-flow`,`impact`]).optional().describe(`Typed unknown classification`),safety_gate:R.enum([`provenance`,`commitment`,`coverage`]).optional().describe(`Safety gate tag: provenance (claim→evidence), commitment (user-approved), coverage (nothing dropped)`),retry_count:R.number().default(0).describe(`Retry count for gate evaluation (0 = first attempt)`),max_retries:R.number().int().min(0).optional().describe(`Maximum retries before escalating. Default: 3`),timeout_action:R.enum([`iterate`,`retry`,`manual`,`terminate`]).optional().describe(`Action to take when gate retries are exhausted. Default: manual`),cwd:R.string().optional().describe(`Working directory for evidence map storage (default: server cwd). Use root_path from forge_ground to match.`)},annotations:t.annotations},Y(`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 kt({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=kt({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.summary&&n.push(``,e.summary),{content:[{type:`text`,text:n.join(`
199
199
  `)}]}}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=kt({action:`update`,taskId:t,id:o,status:i,receipt:a??``},p),n=[`Updated entry #${o} in "${t}" → ${i}`];return e.summary&&n.push(``,e.summary),{content:[{type:`text`,text:n.join(`
200
200
  `)}]}}case`get`:{if(!t)throw Error(`task_id required for get`);let e=kt({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(`
201
201
  `)}]}:{content:[{type:`text`,text:`Evidence map "${t}" not found.`}]}}case`gate`:{if(!t)throw Error(`task_id required for gate`);let e=kt({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(`
@@ -2703,8 +2703,7 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2703
2703
  }
2704
2704
  mermaid.initialize({ startOnLoad: false, theme: theme });
2705
2705
  mermaid.run();
2706
- };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:zh()}},Vh=new Map([[`mermaid`,Bh]]);function Hh(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Vh.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 Uh(){let e=[];for(let t of Vh.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Wh=300*1e3,Gh=15*1e3,Kh=`/@aikit/blocks-interactive/dist/`;var qh=class{maxTokens;refillPerSecond;tokens;lastRefill;constructor(e,t){this.maxTokens=e,this.refillPerSecond=t,this.tokens=e,this.lastRefill=Date.now()}tryConsume(){return this.#e(),this.tokens>=1?(--this.tokens,!0):!1}#e(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.maxTokens,this.tokens+t*this.refillPerSecond),this.lastRefill=e}};let Jh=null,Yh=null;const Xh=new Map,Zh=new qh(10,10),Qh=new qh(50,50);function $h(){return Jh||(Jh={manager:new Lh,server:null,port:0},process.on(`exit`,()=>{Jh?.manager.shutdown()})),Jh.manager}async function eg(){if(!Jh)throw Error(`Browser server state not initialized`);let e=Jh;if(e.server)return e.port;if(Yh)return Yh;let t=ei((e,t)=>{ag(e,t)});return e.server=t,Yh=new Promise((n,r)=>{t.listen(0,`127.0.0.1`,()=>{let i=t.address();typeof i==`object`&&i?(e.port=i.port,n(i.port)):r(Error(`Failed to resolve local browser address`))}),t.on(`error`,r)}),Yh}let tg;function ng(){return tg===void 0&&(tg=w(`blocks-interactive`)),tg}function rg(e){if(!e.startsWith(Kh))return null;let t=ng();if(!t)return null;let n=I(F(t,`dist`,e.slice(32))),r=I(F(t,`dist`)),i=process.platform===`win32`?`\\`:`/`;return!n.startsWith(r+i)&&n!==r?null:n}function ig(e){return`script-src 'nonce-${e}' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'self'`}function ag(e,t){let n=Jh;if(!n){hg(t);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`127.0.0.1`}`).pathname,i=e.method??`GET`;if(i===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(r.startsWith(`/__aikit_clipboard.png`)){if(i!==`POST`){og(t,405,`METHOD_NOT_ALLOWED`,`Clipboard capture requires POST.`);return}yg(t,gg(e,n));return}if(r.startsWith(`/__aikit_screenshot.png`)){vg(t,gg(e,n));return}if(r.startsWith(`/__aikit_system_clipboard`)){if(i!==`POST`){og(t,405,`METHOD_NOT_ALLOWED`,`System clipboard write requires POST.`);return}bg(e,t);return}let a=r.match(/^\/present\/([^/]+)(?:\/(.*))?$/);if(a){let r=a[1],i=a[2]??``,o=Xh.get(r);if(!o){og(t,404,Z.SESSION_NOT_FOUND,`Session ${r} not found`);return}if(o.hasClientConnected=!0,n.manager.transitionSession(r,`connected`,`client-connect`),i===``||i===`/`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":ig(o.callbackSession.nonce)}),t.end(o.html);return}if(i===`viewer`){if(!o.viewerHtml){t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(o.viewerHtml);return}if(i===`callback`){if(!Zh.tryConsume()){og(t,429,Z.RATE_LIMITED,`Too many requests`);return}o.callbackSession.handle(e,t,`http://127.0.0.1:${n.port}`).catch(()=>{hg(t)});return}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}let o=Uh().find(t=>e.url===t.route);if(o){let e=o.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:o.cdn}),t.end();return}if(r.startsWith(Kh)){if(!Qh.tryConsume()){og(t,429,Z.RATE_LIMITED,`Too many requests`);return}let e=rg(r);if(e)try{let n=P(e,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(n);return}catch{}}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`)}catch{hg(t)}}function og(e,t,n,r){if(!e.headersSent)try{e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`}),e.end(JSON.stringify({error:n,message:r}))}catch{try{e.end()}catch{}}}function sg(e){let t=X(e.id),n=X(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="${X(e.value)}">${X(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=X(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="${X(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-${X(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}function cg(e){if(e.length===0)return``;let t=e.filter(e=>e.type===`button`||e.type===`select`||e.type===`multi-select`||e.type===`custom`),n=e.filter(e=>e.type===`text-submit`||e.type===`form-submit`),r=[];return t.length>0&&r.push(`<div class="bk-actions">${t.map(sg).join(``)}</div>`),n.length>0&&r.push(n.map(sg).join(``)),r.join(`
2707
- `)}function lg(e,t){if(e.length===0)return``;let n=JSON.stringify(t);return`<style>
2706
+ };`,onload:`window.__aikit_initMermaid&&window.__aikit_initMermaid()`,local:{route:`/vendor/mermaid.min.js`,getSource:zh()}},Vh=new Map([[`mermaid`,Bh]]);function Hh(e,t){if(!e?.length)return;let n=[];for(let r of e){let e=Vh.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 Uh(){let e=[];for(let t of Vh.values())t.local&&e.push({route:t.local.route,getSource:t.local.getSource,cdn:t.cdn});return e}const Wh=300*1e3,Gh=15*1e3,Kh=`/@aikit/blocks-interactive/dist/`;var qh=class{maxTokens;refillPerSecond;tokens;lastRefill;constructor(e,t){this.maxTokens=e,this.refillPerSecond=t,this.tokens=e,this.lastRefill=Date.now()}tryConsume(){return this.#e(),this.tokens>=1?(--this.tokens,!0):!1}#e(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.maxTokens,this.tokens+t*this.refillPerSecond),this.lastRefill=e}};let Jh=null,Yh=null;const Xh=new Map,Zh=new qh(10,10),Qh=new qh(50,50);function $h(){return Jh||(Jh={manager:new Lh,server:null,port:0},process.on(`exit`,()=>{Jh?.manager.shutdown()})),Jh.manager}async function eg(){if(!Jh)throw Error(`Browser server state not initialized`);let e=Jh;if(e.server)return e.port;if(Yh)return Yh;let t=ei((e,t)=>{ag(e,t)});return e.server=t,Yh=new Promise((n,r)=>{t.listen(0,`127.0.0.1`,()=>{let i=t.address();typeof i==`object`&&i?(e.port=i.port,n(i.port)):r(Error(`Failed to resolve local browser address`))}),t.on(`error`,r)}),Yh}let tg;function ng(){return tg===void 0&&(tg=w(`blocks-interactive`)),tg}function rg(e){if(!e.startsWith(Kh))return null;let t=ng();if(!t)return null;let n=I(F(t,`dist`,e.slice(32))),r=I(F(t,`dist`)),i=process.platform===`win32`?`\\`:`/`;return!n.startsWith(r+i)&&n!==r?null:n}function ig(e){return`script-src 'nonce-${e}' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'self'`}function ag(e,t){let n=Jh;if(!n){hg(t);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`127.0.0.1`}`).pathname,i=e.method??`GET`;if(i===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(r.startsWith(`/__aikit_clipboard.png`)){if(i!==`POST`){og(t,405,`METHOD_NOT_ALLOWED`,`Clipboard capture requires POST.`);return}yg(t,gg(e,n));return}if(r.startsWith(`/__aikit_screenshot.png`)){vg(t,gg(e,n));return}if(r.startsWith(`/__aikit_system_clipboard`)){if(i!==`POST`){og(t,405,`METHOD_NOT_ALLOWED`,`System clipboard write requires POST.`);return}bg(e,t);return}let a=r.match(/^\/present\/([^/]+)(?:\/(.*))?$/);if(a){let r=a[1],i=a[2]??``,o=Xh.get(r);if(!o){og(t,404,Z.SESSION_NOT_FOUND,`Session ${r} not found`);return}if(o.hasClientConnected=!0,n.manager.transitionSession(r,`connected`,`client-connect`),i===``||i===`/`){t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":ig(o.callbackSession.nonce)}),t.end(o.html);return}if(i===`viewer`){if(!o.viewerHtml){t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}t.writeHead(200,{"Content-Type":`text/html; charset=utf-8`}),t.end(o.viewerHtml);return}if(i===`callback`){if(!Zh.tryConsume()){og(t,429,Z.RATE_LIMITED,`Too many requests`);return}o.callbackSession.handle(e,t,`http://127.0.0.1:${n.port}`).catch(()=>{hg(t)});return}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`);return}let o=Uh().find(t=>e.url===t.route);if(o){let e=o.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:o.cdn}),t.end();return}if(r.startsWith(Kh)){if(!Qh.tryConsume()){og(t,429,Z.RATE_LIMITED,`Too many requests`);return}let e=rg(r);if(e)try{let n=P(e,`utf8`);t.writeHead(200,{"Content-Type":`application/javascript; charset=utf-8`}),t.end(n);return}catch{}}t.writeHead(404,{"Content-Type":`text/plain`}),t.end(`Not Found`)}catch{hg(t)}}function og(e,t,n,r){if(!e.headersSent)try{e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`}),e.end(JSON.stringify({error:n,message:r}))}catch{try{e.end()}catch{}}}function sg(e){let t=X(e.id),n=X(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="${X(e.value)}">${X(e.label)}</option>`).join(``)}</select></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=X(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="${X(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-${X(e.variant??`default`)}" data-action-id="${t}" data-action-label="${n}">${n}</button>`}function cg(e){return e.length===0?``:`<div class="bk-actions">${e.map(sg).join(``)}</div>`}function lg(e,t){if(e.length===0)return``;let n=JSON.stringify(t);return`<style>
2708
2707
  .present-surface-title { margin: 0 0 0.75rem; font-size: 1.875rem; }
2709
2708
  .present-surface-description { margin: 0; color: var(--muted-foreground, #6b7280); }
2710
2709
  .present-actions-list { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: flex-end; }
@@ -2755,29 +2754,6 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2755
2754
  color: var(--accent-foreground, #101828);
2756
2755
  outline: none;
2757
2756
  }
2758
- .present-action-status { margin: 0; min-height: 1.25rem; color: var(--muted-foreground, #6b7280); }
2759
- .present-text-submit {
2760
- display: flex;
2761
- gap: 0.5rem;
2762
- align-items: stretch;
2763
- }
2764
- .present-text-input {
2765
- font: inherit;
2766
- font-size: 0.9375rem;
2767
- line-height: 1.2;
2768
- border-radius: 0.75rem;
2769
- border: 1px solid var(--border, #d0d5dd);
2770
- min-height: 2.5rem;
2771
- padding: 0.5rem 1rem;
2772
- background: var(--card, #ffffff);
2773
- color: var(--foreground, #101828);
2774
- flex: 1;
2775
- min-width: 200px;
2776
- }
2777
- .present-text-input:focus {
2778
- outline: 2px solid var(--ring, #2563eb);
2779
- outline-offset: -1px;
2780
- }
2781
2757
  .present-form {
2782
2758
  display: flex;
2783
2759
  flex-direction: column;
@@ -2788,16 +2764,59 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2788
2764
  color: var(--primary-foreground, #ffffff) !important;
2789
2765
  border-color: var(--primary, #2563eb) !important;
2790
2766
  }
2767
+ /* ── Per-action status feedback ── */
2768
+ .present-action-btn:disabled {
2769
+ cursor: default;
2770
+ opacity: 0.7;
2771
+ }
2772
+ .present-action-btn[data-action-status="sending"] {
2773
+ pointer-events: none;
2774
+ opacity: 0.8;
2775
+ }
2776
+ .present-action-btn[data-action-status="sending"]::after {
2777
+ content: '';
2778
+ display: inline-block;
2779
+ width: 1em;
2780
+ height: 1em;
2781
+ margin-left: 0.5rem;
2782
+ border: 2px solid transparent;
2783
+ border-top-color: currentColor;
2784
+ border-radius: 50%;
2785
+ animation: present-spin 0.6s linear infinite;
2786
+ }
2787
+ @keyframes present-spin {
2788
+ to { transform: rotate(360deg); }
2789
+ }
2790
+ .present-action-btn[data-action-status="success"] {
2791
+ border-color: var(--success, #16a34a) !important;
2792
+ background: var(--success-subtle, rgba(22, 163, 74, 0.1)) !important;
2793
+ color: var(--success, #16a34a) !important;
2794
+ }
2795
+ .present-action-btn[data-action-status="error"] {
2796
+ border-color: var(--danger, #dc2626) !important;
2797
+ background: var(--danger-subtle, rgba(220, 38, 38, 0.1)) !important;
2798
+ color: var(--danger, #dc2626) !important;
2799
+ }
2791
2800
  </style>
2792
2801
  <script nonce="${X(t)}">
2793
2802
  (() => {
2794
2803
  const nonce = ${n};
2795
2804
  let settled = false;
2796
- const statusNode = document.getElementById('present-action-status');
2797
2805
  const controls = Array.from(document.querySelectorAll('[data-action-id]'));
2798
2806
 
2799
- function setStatus(message) {
2800
- if (statusNode) statusNode.textContent = message;
2807
+ function setActionStatus(actionId, status) {
2808
+ // Look up the action element by matching data-action-id
2809
+ // Using Array.find + getAttribute to avoid CSS selector injection
2810
+ var el = null;
2811
+ for (var i = 0; i < controls.length; i++) {
2812
+ if (controls[i].getAttribute('data-action-id') === actionId) {
2813
+ el = controls[i];
2814
+ break;
2815
+ }
2816
+ }
2817
+ if (el) {
2818
+ el.setAttribute('data-action-status', status);
2819
+ }
2801
2820
  }
2802
2821
 
2803
2822
  function disableControls() {
@@ -2832,16 +2851,20 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2832
2851
 
2833
2852
  settled = true;
2834
2853
  disableControls();
2835
- setStatus('Sending response...');
2854
+ setActionStatus(payload.actionId, 'sending');
2836
2855
  try {
2837
- await fetch('/callback', {
2856
+ const response = await fetch('/callback', {
2838
2857
  method: 'POST',
2839
2858
  headers: { 'Content-Type': 'application/json' },
2840
2859
  body: JSON.stringify({ nonce, ...payload }),
2841
2860
  });
2842
- setStatus('Response sent.');
2861
+ if (response.ok) {
2862
+ setActionStatus(payload.actionId, 'success');
2863
+ } else {
2864
+ setActionStatus(payload.actionId, 'error');
2865
+ }
2843
2866
  } catch {
2844
- setStatus('Unable to send response.');
2867
+ setActionStatus(payload.actionId, 'error');
2845
2868
  }
2846
2869
  }
2847
2870
 
@@ -2851,20 +2874,6 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2851
2874
  }
2852
2875
 
2853
2876
  control.addEventListener('click', () => {
2854
- // Submit button for text-submit: read sibling input value
2855
- const submitFor = control.dataset.submitFor;
2856
- if (submitFor) {
2857
- const input = document.querySelector('input[data-action-id="' + submitFor + '"]');
2858
- const value = input ? input.value : '';
2859
- void sendPayload({
2860
- actionId: submitFor,
2861
- value: value,
2862
- label: input ? input.dataset.actionLabel : '',
2863
- timestamp: new Date().toISOString(),
2864
- });
2865
- return;
2866
- }
2867
-
2868
2877
  void sendPayload({
2869
2878
  actionId: control.dataset.actionId,
2870
2879
  value: 'clicked',
@@ -2874,21 +2883,6 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2874
2883
  });
2875
2884
  }
2876
2885
 
2877
- // Handle text-submit on Enter key
2878
- for (const input of document.querySelectorAll('input.present-text-input[data-action-id]')) {
2879
- input.addEventListener('keydown', (e) => {
2880
- if (e.key === 'Enter') {
2881
- e.preventDefault();
2882
- void sendPayload({
2883
- actionId: input.dataset.actionId,
2884
- value: input.value,
2885
- label: input.dataset.actionLabel,
2886
- timestamp: new Date().toISOString(),
2887
- });
2888
- }
2889
- });
2890
- }
2891
-
2892
2886
  // Handle form-submit
2893
2887
  for (const form of document.querySelectorAll('form.present-form[data-action-id]')) {
2894
2888
  form.addEventListener('submit', (e) => {
@@ -2897,8 +2891,9 @@ None.`:`### Stale Lessons\n${u.map(e=>`- **${e.title}** (\`${e.path}\`) — effe
2897
2891
  for (const input of form.querySelectorAll('input[name]')) {
2898
2892
  formData[input.name] = input.type === 'checkbox' ? input.checked : input.value;
2899
2893
  }
2894
+ const actionId = form.dataset.actionId;
2900
2895
  void sendPayload({
2901
- actionId: form.dataset.actionId,
2896
+ actionId: actionId,
2902
2897
  value: formData,
2903
2898
  label: form.dataset.actionLabel,
2904
2899
  timestamp: new Date().toISOString(),
@@ -3012,11 +3007,11 @@ window.addEventListener('message', function(e) {
3012
3007
  }
3013
3008
  })();
3014
3009
  <\/script>`}function T_(e){C_=e||``}function E_(e,t){if(!C_)return e;let n=`${`<script${t?` nonce="${X(t)}"`:``}>${C_}<\/script>`}\n${w_(t||``)}`;return e.includes(`</body>`)?e.replace(`</body>`,`${n}\n</body>`):`${e}${n}`}function D_(e,t){return[`<!DOCTYPE html>`,`<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`,`<title>Error — ${X(e)}</title>`,`<style>`,` * { box-sizing: border-box; margin: 0; padding: 0; }`,` body { font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem; background: #fafafa; color: #333; }`,` .error-card { max-width: 560px; width: 100%; padding: 2.5rem; border-radius: 1rem; background: #fff; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }`,` .error-badge { display: inline-block; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.375rem; padding: 0.25rem 0.625rem; margin-bottom: 1rem; }`,` .error-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.75rem; color: #111; }`,` .error-message { font-size: 0.875rem; line-height: 1.6; color: #6b7280; white-space: pre-wrap; word-break: break-word; }`,`</style></head><body>`,`<div class="error-card">`,` <span class="error-badge">Render Error</span>`,` <h1 class="error-title">${X(e)}</h1>`,` <p class="error-message">${X(t)}</p>`,`</div>`,`</body></html>`].join(`
3015
- `)}function O_(e,t,n,r){return Xg(D_(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function k_(e,t){if(!t_(e)||!(`schemaVersion`in e))return{ok:!1,response:O_(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:O_(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&n_.test(e.title))return{ok:!1,response:O_(`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(!t_(e)||e.type!==`markdown`)return[e];let t=o_(e);return!t||!s_(t)?[e]:d_(e)})}:e;return{ok:!0,surface:n,options:p_(n,t)}}const A_={id:`__feedback`,type:`text-submit`,label:`💬 Feedback`,variant:`default`};function j_(e){return!e.actions||e.actions.length===0||e.actions.some(e=>e.id===`__feedback`)?e:{...e,actions:[...e.actions,A_]}}function M_(e){return(e.actions?.length??0)>0||e.response?.required===!0?e_.getAll().some(e=>e.id===`browser`):!1}async function N_(e,t={}){let n=M_(e)?{...t,preferBrowser:!0}:t,r=h_(e),i=e_.select(r,n),a=i?.id===`browser`?j_(r):r,o;if(o=i?await i.render(a,n):Fg(a),e.blocks&&e.blocks.length>0&&o.isError!==!0)try{let t=new Set;for(let n of e.blocks){if(typeof n!=`object`||!n)continue;let e=typeof n.type==`string`?n.type:null;e&&!Nm(e)&&t.add(e)}if(t.size>0){let e=[...t].map(e=>`"${e}"`).join(`, `);Ug.warn(`Unknown block types: ${e}`),o.content=[{type:`text`,text:`[Block type(s) not recognized: ${e}. They rendered as raw text. Use aikit://schemas/channel-surface for supported block types.]`},...o.content]}}catch(e){Ug.warn(`Block type validation failed`,M(e))}if(t.compact){let{structuredContent:e,...t}=o;return t}return o}function P_(e,t=``){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):t}function F_(e){return{type:`kv`,value:e}}function I_(e){if(Array.isArray(e))return e}const L_=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,expand(e){let t=P_(e.title,`Summary`),n=[{type:`heading`,value:t}],r=P_(e.summary);r&&n.push({type:`markdown`,value:r});let i=Number(e.passed)||0,a=Number(e.failed)||0;if(i>0||a>0){let e=[];i>0&&e.push({label:`Passed`,value:i,status:`success`}),a>0&&e.push({label:`Failed`,value:a,status:`error`}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`plan`,description:`Title + heading per step + checklist items`,expand(e){let t=P_(e.title,`Plan`),n=[{type:`heading`,value:t}],r=I_(e.steps);return r&&n.push({type:`checklist`,value:{items:r}}),{title:t,blocks:n}}},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,expand(e){let t=P_(e.title,`Understanding`),n=[{type:`heading`,value:t}],r=P_(e.explanation);return r&&n.push({type:`markdown`,value:r}),e.details&&typeof e.details==`object`&&!Array.isArray(e.details)&&n.push(F_(e.details)),{title:t,blocks:n}}},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,expand(e){let t=P_(e.title,`Bug Analysis`),n=[{type:`heading`,value:t}],r={};e.severity&&(r.Severity=e.severity),e.status&&(r.Status=e.status),Object.keys(r).length>0&&n.push({type:`kv`,value:r});let i=P_(e.code);i&&n.push({type:`code`,value:i});let a=P_(e.analysis);return a&&n.push({type:`markdown`,value:a}),{title:t,blocks:n}}},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,expand(e){let t=P_(e.title,`Task Complete`),n=[{type:`heading`,value:t}],r=I_(e.items);r&&n.push({type:`checklist`,value:{items:r}});let i=e.completed,a=e.total;if(i!==void 0||a!==void 0){let e=[];i!==void 0&&e.push({label:`Completed`,value:Number(i)||i,status:`success`}),a!==void 0&&e.push({label:`Total`,value:Number(a)||a}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`review`,description:`Title + criteria checklist + annotation items + approval controls`,expand(e){let t=P_(e.title,`Review`),n=[{type:`heading`,value:t}],r=I_(e.criteria);r&&n.push({type:`checklist`,value:{items:r}});let i=e.annotations;Array.isArray(i)&&i.length>0&&n.push({type:`annotation`,value:i});let a=e.approval;return a&&typeof a==`object`?n.push({type:`approval`,value:a}):n.push({type:`actions`,value:[{type:`button`,id:`approve`,label:`Approve`,variant:`primary`},{type:`button`,id:`reject`,label:`Reject`,variant:`danger`}]}),{title:t,blocks:n}}},{name:`explore`,description:`Title + heading per finding + code blocks`,expand(e){let t=P_(e.title,`Exploration`),n=[{type:`heading`,value:t}],r=I_(e.findings);if(r)for(let e of r)n.push({type:`heading`,value:P_(e.heading,`Finding`)}),e.code&&n.push({type:`code`,value:e.code});return{title:t,blocks:n}}},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,expand(e){let t=P_(e.title,`Decision`),n=[{type:`heading`,value:t}];e.recommendation&&n.push({type:`kv`,value:{Recommendation:e.recommendation}});let r=I_(e.options);return r&&r.length>0&&n.push({type:`comparison`,value:r.map(e=>({title:P_(e.title,`Option`),items:Array.isArray(e.items)?e.items:[]}))}),{title:t,blocks:n}}}],R_=new Map;for(let e of L_)R_.set(e.name,e);function z_(e,t){let n=R_.get(e);return n?n.expand(t):null}const B_={h:`heading`,m:`markdown`,t:`table`,p:`paragraph`,c:`code`,s:`separator`,M:`metrics`,C:`chart`,T:`timeline`,g:`graph`,tr:`tree`,tl:`timeline`,cl:`checklist`,pr:`progress`,sb:`status-board`,kv:`kv`,ac:`actions`,di:`mermaid`},V_=/^(#{1,6})\s/,H_=/^(`{3,}|~{3,})/,U_=/^\|.+\|.+\|/m;function W_(e){let t=e.trim(),n=t.match(V_);if(n)return{type:`heading`,value:t.slice(n[0].length)};if(H_.test(t)){let e=t.indexOf(`
3016
- `),n=t.lastIndexOf(t[0]);return{type:`code`,value:e>=0?t.slice(e+1,n).trimEnd():t}}return U_.test(t)?{type:`table`,value:t}:{type:`markdown`,value:t}}function G_(e,t){let n=B_[e];if(!n)return null;switch(e){case`M`:return{type:`metrics`,value:t};case`C`:return{type:`chart`,value:t};case`T`:case`tl`:return{type:`timeline`,value:t};case`g`:return{type:`graph`,value:t};case`tr`:return{type:`tree`,value:t};case`cl`:return{type:`checklist`,value:t};case`pr`:return{type:`progress`,value:t};case`sb`:return{type:`status-board`,value:t};case`kv`:return{type:`kv`,value:t};case`ac`:return{type:`actions`,value:t};case`di`:return{type:`mermaid`,value:t};case`s`:return{type:`separator`,value:t||!0};default:return{type:n,value:typeof t==`string`?t:String(t??``)}}}function K_(e){if(typeof e==`string`){let t=W_(e);return{type:t.type,value:t.value}}if(Array.isArray(e)){let[t,n]=e;if(typeof t==`string`){let e=G_(t,n);if(e)return e}return{type:`markdown`,value:String(t??``)}}if(typeof e==`object`&&e){let{blockId:t,...n}=e;return n}return{type:`markdown`,value:String(e??``)}}function q_(e){return{title:e.title??``,blocks:Array.isArray(e.blocks)?e.blocks.map(K_):[]}}function J_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y_(e){return J_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion===1}function X_(e){return J_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion!==1}function Z_(e){return e.schemaVersion===1?typeof e.title!=`string`||e.title.length===0?{ok:!1,error:{code:`MISSING_TITLE`,reason:`ChannelSurface requires a non-empty title`}}:e.blocks!==void 0&&!Array.isArray(e.blocks)?{ok:!1,error:{code:`INVALID_BLOCKS`,reason:`blocks must be an array of TypedBlock objects`}}:{ok:!0,surface:e}:{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`}}}function Q_(e){try{let t=re(e);return J_(t)?(t.schemaVersion===void 0&&(t.schemaVersion=1),$_(t)):{ok:!1,error:{code:`INVALID_RAW_INPUT`,reason:`raw field must contain a JSON object (ChannelSurface)`}}}catch(e){return{ok:!1,error:{code:`INVALID_RAW_JSON`,reason:`Failed to parse raw field: ${e.message}`,hint:`JSON repair attempted. Ensure the raw string contains a valid ChannelSurface object. Common LLM errors (newlines in strings, trailing commas) are auto-repaired.`}}}}function $_(e){if(Array.isArray(e)){if(e.length!==2)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset input must be a [name, data] tuple`,hint:`Use [presetName, { title, ...fields }]`}};let[t,n]=e;if(typeof t!=`string`)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset name must be a string`}};if(!J_(n))return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset data must be an object`}};let r=z_(t,n);return r?{ok:!0,surface:{schemaVersion:1,title:r.title,blocks:r.blocks}}:{ok:!1,error:{code:`UNKNOWN_PRESET`,reason:`Unknown preset: ${t}`,hint:`Available presets: summary, plan, understanding, bug-analyze, task-done, review, explore, decision`}}}if(X_(e))return{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`,hint:`Use schemaVersion: 1`}};if(Y_(e))return Z_(e);if(typeof e==`string`){let t=q_({blocks:[e]});return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}if(J_(e)){if(typeof e.raw==`string`)return Q_(e.raw);if(!(`blocks`in e)&&!(`title`in e))return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}};let t=q_(e);return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}}}const ev=R.object({label:R.string(),value:R.string(),description:R.string().optional()}),tv=R.object({id:R.string().describe(`Unique action identifier`),type:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:R.string().describe(`Visible action label`),variant:R.enum([`primary`,`danger`,`default`]).optional(),options:R.array(ev).optional(),schema:R.record(R.string(),R.unknown()).optional()}),nv=R.object({type:R.string(),title:R.string().optional(),value:R.unknown().optional(),language:R.string().optional()}).catchall(R.unknown()),rv={schemaVersion:R.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:R.string().describe(`Surface title shown to the user.`),description:R.string().optional().describe(`Optional supporting copy for the surface.`),template:R.string().optional().describe(`Optional template id such as report@1.`),layout:R.object({maxWidth:R.string().optional(),padding:R.string().optional(),columns:R.number().optional()}).optional(),blocks:R.array(nv).optional().describe(`Typed block content for the surface.`),data:R.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:R.array(tv).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:R.object({timeout:R.number().optional(),required:R.boolean().optional()}).optional(),metadata:R.object({surfaceId:R.string().optional(),createdAt:R.string().optional(),source:R.string().optional()}).optional(),colorScheme:R.enum([`light`,`dark`,`auto`]).optional(),lang:R.string().optional(),dir:R.enum([`ltr`,`rtl`,`auto`]).optional(),raw:R.string().optional().describe(`Raw JSON string with auto-repair. Accepts common LLM JSON errors (unescaped newlines in strings, trailing commas). Use for complex payloads with mermaid/code/markdown blocks.`),preferBrowser:R.boolean().optional().describe(`Force browser transport instead of inline rendering. Set true when user explicitly requests external browser or browser transport.`)};R.object({surfaceId:R.string(),actionId:R.string(),actionType:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:R.unknown().optional(),formData:R.record(R.string(),R.unknown()).optional(),selection:R.union([R.string(),R.array(R.string())]).optional(),label:R.string().optional(),timestamp:R.string(),sourceTransport:R.enum([`mcp-app`,`browser`,`export`])});function iv(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=Or(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(Dr)?`unsupported`:`supported`}const av=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Section heading`},summary:{type:`string`,description:`Free-form markdown summary`},passed:{type:`number`,description:`Pass count for metrics`},failed:{type:`number`,description:`Fail count for metrics`}},required:[`title`]},example:JSON.stringify({title:`Build Summary`,summary:`All tests passed.`,passed:42,failed:0}),expandsTo:`blocks: [heading, markdown, metrics]`},{name:`plan`,description:`Title + heading per step + checklist items`,inputSchema:{type:`object`,properties:{title:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}}},required:[`title`]},example:JSON.stringify({title:`Sprint Plan`,steps:[{label:`Write tests`,checked:!1},{label:`Deploy`,checked:!1}]}),expandsTo:`blocks: [heading, checklist]`},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,inputSchema:{type:`object`,properties:{title:{type:`string`},explanation:{type:`string`},details:{type:`object`,additionalProperties:{type:`string`}}},required:[`title`,`explanation`]},example:JSON.stringify({title:`Architecture Overview`,explanation:`The system uses microservices.`,details:{Language:`TypeScript`,Runtime:`Node`}}),expandsTo:`blocks: [heading, markdown, kv]`},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,inputSchema:{type:`object`,properties:{title:{type:`string`},severity:{type:`string`},status:{type:`string`},code:{type:`string`},analysis:{type:`string`}},required:[`title`,`severity`,`status`]},example:JSON.stringify({title:`Null pointer in auth`,severity:`high`,status:`open`,code:`const x = obj.prop;`,analysis:`obj may be null when token missing.`}),expandsTo:`blocks: [heading, kv, code, markdown]`},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},completed:{type:`number`},total:{type:`number`}},required:[`title`,`items`]},example:JSON.stringify({title:`PR #42 Done`,items:[{label:`Lint pass`,checked:!0},{label:`Tests pass`,checked:!0}],completed:2,total:2}),expandsTo:`blocks: [heading, checklist, metrics]`},{name:`review`,description:`Title + criteria checklist + approval actions`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Review title`},criteria:{type:`array`,description:`Checklist criteria items`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},annotations:{type:`array`,description:`Optional annotation items`,items:{type:`object`,properties:{label:{type:`string`},description:{type:`string`},severity:{type:`string`}}}},approval:{type:`object`,description:`Optional approval config`,properties:{prompt:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},value:{type:`string`}}}}}}},required:[`title`,`criteria`]},example:JSON.stringify({title:`Code Review`,criteria:[{label:`Tests included`,checked:!0},{label:`No regressions`,checked:!1}]}),expandsTo:`blocks: [heading, checklist] + actions: [approve, reject]`},{name:`explore`,description:`Title + heading per finding + code blocks`,inputSchema:{type:`object`,properties:{title:{type:`string`},findings:{type:`array`,items:{type:`object`,properties:{heading:{type:`string`},code:{type:`string`}}}}},required:[`title`,`findings`]},example:JSON.stringify({title:`Codebase Exploration`,findings:[{heading:`Auth flow`,code:`function login()`},{heading:`API routes`,code:`router.get("/api")`}]}),expandsTo:`blocks: [heading, code] per finding`},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,inputSchema:{type:`object`,properties:{title:{type:`string`},recommendation:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`string`}}}}}},required:[`title`,`recommendation`]},example:JSON.stringify({title:`DB Choice`,recommendation:`PostgreSQL`,options:[{title:`Postgres`,items:[`ACID`,`Rich types`]},{title:`Mongo`,items:[`Schema-less`,`Horizontal`]}]}),expandsTo:`blocks: [heading, kv, comparison]`}];function ov(e,t){let n=G(`present`);try{let e=w(`present`);e&&T_(P(I(e,`dist`,`annotation-layer.js`),`utf8`))}catch{}Ar(e,`present`,{title:n.title,description:"Render a ChannelSurface. Required: schemaVersion: 1, title. Supports blocks, template+data, named presets, and raw JSON string with auto-repair. Use `raw` for complex payloads (mermaid, code, many blocks) — common LLM JSON errors are auto-fixed. Actions use browser transport. Resources: aikit://schemas/channel-surface (schema+blocks), aikit://present/presets (presets), aikit://present/templates (viewers).",inputSchema:rv,annotations:n.annotations,_meta:jg(Hg)},Y(`present`,async(t,n)=>{let r=t,i=typeof r.preferBrowser==`boolean`?r.preferBrowser:void 0,a=$_(t);if(!a.ok)return O_(a.error.code,a.error.reason,void 0,`Present`);let o=k_(a.surface,n);if(!o.ok)return o.response;let s=iv(e);return await N_(o.surface,{...o.options,preferBrowser:i??(o.options.preferBrowser||s===`unsupported`)})}));try{let t=new nr(Hg,{list:void 0});e.registerResource(`Present View`,t,{description:`AI Kit present tool viewer`},async(e,t,n)=>{let r=Array.isArray(t.id)?t.id[0]:t.id,i=r?Qg(r):void 0;return{contents:[{uri:e.href,mimeType:Dr,_meta:Mg(),text:i??Yg()??`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}})}catch{}function r(){try{let e=w(`present`);if(e)return P(I(e,`dist`,`index.html`),`utf8`)}catch{}return Yg()||`<html><body><p>Loading...</p></body></html>`}try{e.registerResource(`Present App`,Vg,{description:`AI Kit present app - entry point`},async()=>({contents:[{uri:Vg,mimeType:Dr,_meta:Mg(),text:r()}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=Bm().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{}try{e.registerResource(`present-presets`,`aikit://present/presets`,{description:`List all registered present presets with input schemas and examples`},async()=>({contents:[{uri:`aikit://present/presets`,mimeType:`application/json`,text:JSON.stringify(av,null,2)}]}))}catch{}}const sv=j(`tools`);function cv(e,t){let n=new mr({structure:new gr,dependencies:new dr,symbols:new _r,patterns:new hr,entryPoints:new pr,diagrams:new fr}),r=G(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:R.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:R.array(R.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},Y(`produce_knowledge`,async({scope:e,aspects:r},i)=>{let a;try{a=gl(i).createTask(`Produce Knowledge`,3),a.progress(0,`Running analyzers`);let o=e??`.`;sv.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=F(kn(I(o)),fe.onboard);Ae(e,{recursive:!0});let t=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[n,r]of Object.entries(s))r&&typeof r==`string`&&Ie(F(e,`${n}.md`),t+r,`utf-8`);sv.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){sv.warn(`Failed to persist knowledge to .ai/context/`,{error:M(e)})}try{let e=I(kn(I(o)),fe.l0Cards);Ae(e,{recursive:!0});let n=It({workspaceName:o,structure:s.structure?.output,entryPoints:s.entryPoints?.output,dependencies:s.dependencies?.output,symbols:s.symbols?.output});Ie(F(e,et),n,`utf-8`),sv.info(`L0 workspace-core card generated`,{path:F(e,et)}),t?.notifyL0CardChanged().catch(()=>{})}catch(e){sv.warn(`Failed to generate L0 workspace-core card`,{error:M(e)})}a.progress(1,`Synthesizing results`);let c=n.buildSynthesisInstructions(s,r);return a.complete(`Knowledge production complete`),{content:[{type:`text`,text:c+`
3010
+ `)}function O_(e,t,n,r){return Xg(D_(r??`Present`,t)),{content:[{type:`text`,text:`[ERROR:VALIDATION] ${t}`}],isError:!0}}function k_(e,t){if(!t_(e)||!(`schemaVersion`in e))return{ok:!1,response:O_(`INVALID_CHANNEL_SURFACE`,`present expects a ChannelSurface object with schemaVersion: 1`)};if(e.schemaVersion!==1)return{ok:!1,response:O_(`UNSUPPORTED_SCHEMA_VERSION`,`Unsupported ChannelSurface schemaVersion: ${String(e.schemaVersion)}`)};if(typeof e.title==`string`&&n_.test(e.title))return{ok:!1,response:O_(`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(!t_(e)||e.type!==`markdown`)return[e];let t=o_(e);return!t||!s_(t)?[e]:d_(e)})}:e;return{ok:!0,surface:n,options:p_(n,t)}}function A_(e){return(e.actions?.length??0)>0||e.response?.required===!0?e_.getAll().some(e=>e.id===`browser`):!1}async function j_(e,t={}){let n=A_(e)?{...t,preferBrowser:!0}:t,r=h_(e),i=e_.select(r,n),a;if(a=i?await i.render(r,n):Fg(r),e.blocks&&e.blocks.length>0&&a.isError!==!0)try{let t=new Set;for(let n of e.blocks){if(typeof n!=`object`||!n)continue;let e=typeof n.type==`string`?n.type:null;e&&!Nm(e)&&t.add(e)}if(t.size>0){let e=[...t].map(e=>`"${e}"`).join(`, `);Ug.warn(`Unknown block types: ${e}`),a.content=[{type:`text`,text:`[Block type(s) not recognized: ${e}. They rendered as raw text. Use aikit://schemas/channel-surface for supported block types.]`},...a.content]}}catch(e){Ug.warn(`Block type validation failed`,M(e))}if(t.compact){let{structuredContent:e,...t}=a;return t}return a}function Q(e,t=``){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):t}function M_(e){return{type:`kv`,value:e}}function N_(e){if(Array.isArray(e))return e}const P_=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,expand(e){let t=Q(e.title,`Summary`),n=[{type:`heading`,value:t}],r=Q(e.summary);r&&n.push({type:`markdown`,value:r});let i=Number(e.passed)||0,a=Number(e.failed)||0;if(i>0||a>0){let e=[];i>0&&e.push({label:`Passed`,value:i,status:`success`}),a>0&&e.push({label:`Failed`,value:a,status:`error`}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`plan`,description:`Title + heading per step + checklist items`,expand(e){let t=Q(e.title,`Plan`),n=[{type:`heading`,value:t}],r=N_(e.steps);return r&&n.push({type:`checklist`,value:{items:r}}),{title:t,blocks:n}}},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,expand(e){let t=Q(e.title,`Understanding`),n=[{type:`heading`,value:t}],r=Q(e.explanation);return r&&n.push({type:`markdown`,value:r}),e.details&&typeof e.details==`object`&&!Array.isArray(e.details)&&n.push(M_(e.details)),{title:t,blocks:n}}},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,expand(e){let t=Q(e.title,`Bug Analysis`),n=[{type:`heading`,value:t}],r={};e.severity&&(r.Severity=e.severity),e.status&&(r.Status=e.status),Object.keys(r).length>0&&n.push({type:`kv`,value:r});let i=Q(e.code);i&&n.push({type:`code`,value:i});let a=Q(e.analysis);return a&&n.push({type:`markdown`,value:a}),{title:t,blocks:n}}},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,expand(e){let t=Q(e.title,`Task Complete`),n=[{type:`heading`,value:t}],r=N_(e.items);r&&n.push({type:`checklist`,value:{items:r}});let i=e.completed,a=e.total;if(i!==void 0||a!==void 0){let e=[];i!==void 0&&e.push({label:`Completed`,value:Number(i)||i,status:`success`}),a!==void 0&&e.push({label:`Total`,value:Number(a)||a}),n.push({type:`metrics`,value:e})}return{title:t,blocks:n}}},{name:`review`,description:`Title + criteria checklist + annotation items + approval controls`,expand(e){let t=Q(e.title,`Review`),n=[{type:`heading`,value:t}],r=N_(e.criteria);r&&n.push({type:`checklist`,value:{items:r}});let i=e.annotations;Array.isArray(i)&&i.length>0&&n.push({type:`annotation`,value:i});let a=e.approval;return a&&typeof a==`object`?n.push({type:`approval`,value:a}):n.push({type:`actions`,value:[{type:`button`,id:`approve`,label:`Approve`,variant:`primary`},{type:`button`,id:`reject`,label:`Reject`,variant:`danger`}]}),{title:t,blocks:n}}},{name:`explore`,description:`Title + heading per finding + code blocks`,expand(e){let t=Q(e.title,`Exploration`),n=[{type:`heading`,value:t}],r=N_(e.findings);if(r)for(let e of r)n.push({type:`heading`,value:Q(e.heading,`Finding`)}),e.code&&n.push({type:`code`,value:e.code});return{title:t,blocks:n}}},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,expand(e){let t=Q(e.title,`Decision`),n=[{type:`heading`,value:t}];e.recommendation&&n.push({type:`kv`,value:{Recommendation:e.recommendation}});let r=N_(e.options);return r&&r.length>0&&n.push({type:`comparison`,value:r.map(e=>({title:Q(e.title,`Option`),items:Array.isArray(e.items)?e.items:[]}))}),{title:t,blocks:n}}}],F_=new Map;for(let e of P_)F_.set(e.name,e);function I_(e,t){let n=F_.get(e);return n?n.expand(t):null}const L_={h:`heading`,m:`markdown`,t:`table`,p:`paragraph`,c:`code`,s:`separator`,M:`metrics`,C:`chart`,T:`timeline`,g:`graph`,tr:`tree`,tl:`timeline`,cl:`checklist`,pr:`progress`,sb:`status-board`,kv:`kv`,ac:`actions`,di:`mermaid`},R_=/^(#{1,6})\s/,z_=/^(`{3,}|~{3,})/,B_=/^\|.+\|.+\|/m;function V_(e){let t=e.trim(),n=t.match(R_);if(n)return{type:`heading`,value:t.slice(n[0].length)};if(z_.test(t)){let e=t.indexOf(`
3011
+ `),n=t.lastIndexOf(t[0]);return{type:`code`,value:e>=0?t.slice(e+1,n).trimEnd():t}}return B_.test(t)?{type:`table`,value:t}:{type:`markdown`,value:t}}function H_(e,t){let n=L_[e];if(!n)return null;switch(e){case`M`:return{type:`metrics`,value:t};case`C`:return{type:`chart`,value:t};case`T`:case`tl`:return{type:`timeline`,value:t};case`g`:return{type:`graph`,value:t};case`tr`:return{type:`tree`,value:t};case`cl`:return{type:`checklist`,value:t};case`pr`:return{type:`progress`,value:t};case`sb`:return{type:`status-board`,value:t};case`kv`:return{type:`kv`,value:t};case`ac`:return{type:`actions`,value:t};case`di`:return{type:`mermaid`,value:t};case`s`:return{type:`separator`,value:t||!0};default:return{type:n,value:typeof t==`string`?t:String(t??``)}}}function U_(e){if(typeof e==`string`){let t=V_(e);return{type:t.type,value:t.value}}if(Array.isArray(e)){let[t,n]=e;if(typeof t==`string`){let e=H_(t,n);if(e)return e}return{type:`markdown`,value:String(t??``)}}if(typeof e==`object`&&e){let{blockId:t,...n}=e;return n}return{type:`markdown`,value:String(e??``)}}function W_(e){return{title:e.title??``,blocks:Array.isArray(e.blocks)?e.blocks.map(U_):[]}}function G_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function K_(e){return G_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion===1}function q_(e){return G_(e)&&typeof e.schemaVersion==`number`&&e.schemaVersion!==1}function J_(e){return e.schemaVersion===1?typeof e.title!=`string`||e.title.length===0?{ok:!1,error:{code:`MISSING_TITLE`,reason:`ChannelSurface requires a non-empty title`}}:e.blocks!==void 0&&!Array.isArray(e.blocks)?{ok:!1,error:{code:`INVALID_BLOCKS`,reason:`blocks must be an array of TypedBlock objects`}}:{ok:!0,surface:e}:{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`}}}function Y_(e){try{let t=re(e);return G_(t)?(t.schemaVersion===void 0&&(t.schemaVersion=1),X_(t)):{ok:!1,error:{code:`INVALID_RAW_INPUT`,reason:`raw field must contain a JSON object (ChannelSurface)`}}}catch(e){return{ok:!1,error:{code:`INVALID_RAW_JSON`,reason:`Failed to parse raw field: ${e.message}`,hint:`JSON repair attempted. Ensure the raw string contains a valid ChannelSurface object. Common LLM errors (newlines in strings, trailing commas) are auto-repaired.`}}}}function X_(e){if(Array.isArray(e)){if(e.length!==2)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset input must be a [name, data] tuple`,hint:`Use [presetName, { title, ...fields }]`}};let[t,n]=e;if(typeof t!=`string`)return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset name must be a string`}};if(!G_(n))return{ok:!1,error:{code:`INVALID_PRESET_INPUT`,reason:`Preset data must be an object`}};let r=I_(t,n);return r?{ok:!0,surface:{schemaVersion:1,title:r.title,blocks:r.blocks}}:{ok:!1,error:{code:`UNKNOWN_PRESET`,reason:`Unknown preset: ${t}`,hint:`Available presets: summary, plan, understanding, bug-analyze, task-done, review, explore, decision`}}}if(q_(e))return{ok:!1,error:{code:`UNSUPPORTED_SCHEMA_VERSION`,reason:`Unsupported schemaVersion: ${String(e.schemaVersion)}`,hint:`Use schemaVersion: 1`}};if(K_(e))return J_(e);if(typeof e==`string`){let t=W_({blocks:[e]});return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}if(G_(e)){if(typeof e.raw==`string`)return Y_(e.raw);if(!(`blocks`in e)&&!(`title`in e))return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}};let t=W_(e);return{ok:!0,surface:{schemaVersion:1,title:t.title||`Present`,blocks:t.blocks}}}return{ok:!1,error:{code:`INVALID_INPUT`,reason:`Expected a ChannelSurface object, preset tuple, or shorthand input`}}}const Z_=R.object({label:R.string(),value:R.string(),description:R.string().optional()}),Q_=R.object({id:R.string().describe(`Unique action identifier`),type:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]).describe(`Interactive action type`),label:R.string().describe(`Visible action label`),variant:R.enum([`primary`,`danger`,`default`]).optional(),options:R.array(Z_).optional(),schema:R.record(R.string(),R.unknown()).optional()}),$_=R.object({type:R.string(),title:R.string().optional(),value:R.unknown().optional(),language:R.string().optional()}).catchall(R.unknown()),ev={schemaVersion:R.literal(1).describe(`ChannelSurface schema version. Must be 1.`),title:R.string().describe(`Surface title shown to the user.`),description:R.string().optional().describe(`Optional supporting copy for the surface.`),template:R.string().optional().describe(`Optional template id such as report@1.`),layout:R.object({maxWidth:R.string().optional(),padding:R.string().optional(),columns:R.number().optional()}).optional(),blocks:R.array($_).optional().describe(`Typed block content for the surface.`),data:R.unknown().optional().describe(`Template data payload, if the template expands data.`),actions:R.array(Q_).optional().describe(`Interactive actions. Presence triggers browser transport.`),response:R.object({timeout:R.number().optional(),required:R.boolean().optional()}).optional(),metadata:R.object({surfaceId:R.string().optional(),createdAt:R.string().optional(),source:R.string().optional()}).optional(),colorScheme:R.enum([`light`,`dark`,`auto`]).optional(),lang:R.string().optional(),dir:R.enum([`ltr`,`rtl`,`auto`]).optional(),raw:R.string().optional().describe(`Raw JSON string with auto-repair. Accepts common LLM JSON errors (unescaped newlines in strings, trailing commas). Use for complex payloads with mermaid/code/markdown blocks.`),preferBrowser:R.boolean().optional().describe(`Force browser transport instead of inline rendering. Set true when user explicitly requests external browser or browser transport.`)};R.object({surfaceId:R.string(),actionId:R.string(),actionType:R.enum([`button`,`select`,`multi-select`,`form-submit`,`text-submit`,`confirm`,`custom`]),value:R.unknown().optional(),formData:R.record(R.string(),R.unknown()).optional(),selection:R.union([R.string(),R.array(R.string())]).optional(),label:R.string().optional(),timestamp:R.string(),sourceTransport:R.enum([`mcp-app`,`browser`,`export`])});function tv(e){let t=e.server?.getClientCapabilities?.();if(!t)return`unknown`;let n=Or(t);return!n||Array.isArray(n.mimeTypes)&&n.mimeTypes.length>0&&!n.mimeTypes.includes(Dr)?`unsupported`:`supported`}const nv=[{name:`summary`,description:`Title + markdown summary + optional metrics (pass/fail counts)`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Section heading`},summary:{type:`string`,description:`Free-form markdown summary`},passed:{type:`number`,description:`Pass count for metrics`},failed:{type:`number`,description:`Fail count for metrics`}},required:[`title`]},example:JSON.stringify({title:`Build Summary`,summary:`All tests passed.`,passed:42,failed:0}),expandsTo:`blocks: [heading, markdown, metrics]`},{name:`plan`,description:`Title + heading per step + checklist items`,inputSchema:{type:`object`,properties:{title:{type:`string`},steps:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}}},required:[`title`]},example:JSON.stringify({title:`Sprint Plan`,steps:[{label:`Write tests`,checked:!1},{label:`Deploy`,checked:!1}]}),expandsTo:`blocks: [heading, checklist]`},{name:`understanding`,description:`Title + markdown explanation + kv pairs`,inputSchema:{type:`object`,properties:{title:{type:`string`},explanation:{type:`string`},details:{type:`object`,additionalProperties:{type:`string`}}},required:[`title`,`explanation`]},example:JSON.stringify({title:`Architecture Overview`,explanation:`The system uses microservices.`,details:{Language:`TypeScript`,Runtime:`Node`}}),expandsTo:`blocks: [heading, markdown, kv]`},{name:`bug-analyze`,description:`Title + heading + severity/status kv + code block + markdown`,inputSchema:{type:`object`,properties:{title:{type:`string`},severity:{type:`string`},status:{type:`string`},code:{type:`string`},analysis:{type:`string`}},required:[`title`,`severity`,`status`]},example:JSON.stringify({title:`Null pointer in auth`,severity:`high`,status:`open`,code:`const x = obj.prop;`,analysis:`obj may be null when token missing.`}),expandsTo:`blocks: [heading, kv, code, markdown]`},{name:`task-done`,description:`Title + checklist of completed items + optional metrics`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},completed:{type:`number`},total:{type:`number`}},required:[`title`,`items`]},example:JSON.stringify({title:`PR #42 Done`,items:[{label:`Lint pass`,checked:!0},{label:`Tests pass`,checked:!0}],completed:2,total:2}),expandsTo:`blocks: [heading, checklist, metrics]`},{name:`review`,description:`Title + criteria checklist + approval actions`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Review title`},criteria:{type:`array`,description:`Checklist criteria items`,items:{type:`object`,properties:{label:{type:`string`},checked:{type:`boolean`}}}},annotations:{type:`array`,description:`Optional annotation items`,items:{type:`object`,properties:{label:{type:`string`},description:{type:`string`},severity:{type:`string`}}}},approval:{type:`object`,description:`Optional approval config`,properties:{prompt:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{label:{type:`string`},value:{type:`string`}}}}}}},required:[`title`,`criteria`]},example:JSON.stringify({title:`Code Review`,criteria:[{label:`Tests included`,checked:!0},{label:`No regressions`,checked:!1}]}),expandsTo:`blocks: [heading, checklist] + actions: [approve, reject]`},{name:`explore`,description:`Title + heading per finding + code blocks`,inputSchema:{type:`object`,properties:{title:{type:`string`},findings:{type:`array`,items:{type:`object`,properties:{heading:{type:`string`},code:{type:`string`}}}}},required:[`title`,`findings`]},example:JSON.stringify({title:`Codebase Exploration`,findings:[{heading:`Auth flow`,code:`function login()`},{heading:`API routes`,code:`router.get("/api")`}]}),expandsTo:`blocks: [heading, code] per finding`},{name:`decision`,description:`Title + kv for recommendation + comparison blocks per option`,inputSchema:{type:`object`,properties:{title:{type:`string`},recommendation:{type:`string`},options:{type:`array`,items:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`string`}}}}}},required:[`title`,`recommendation`]},example:JSON.stringify({title:`DB Choice`,recommendation:`PostgreSQL`,options:[{title:`Postgres`,items:[`ACID`,`Rich types`]},{title:`Mongo`,items:[`Schema-less`,`Horizontal`]}]}),expandsTo:`blocks: [heading, kv, comparison]`}];function rv(e,t){let n=G(`present`);try{let e=w(`present`);e&&T_(P(I(e,`dist`,`annotation-layer.js`),`utf8`))}catch{}Ar(e,`present`,{title:n.title,description:"Render a ChannelSurface. Required: schemaVersion: 1, title. Supports blocks, template+data, named presets, and raw JSON string with auto-repair. Use `raw` for complex payloads (mermaid, code, many blocks) — common LLM JSON errors are auto-fixed. Actions use browser transport. Resources: aikit://schemas/channel-surface (schema+blocks), aikit://present/presets (presets), aikit://present/templates (viewers).",inputSchema:ev,annotations:n.annotations,_meta:jg(Hg)},Y(`present`,async(t,n)=>{let r=t,i=typeof r.preferBrowser==`boolean`?r.preferBrowser:void 0,a=X_(t);if(!a.ok)return O_(a.error.code,a.error.reason,void 0,`Present`);let o=k_(a.surface,n);if(!o.ok)return o.response;let s=tv(e);return await j_(o.surface,{...o.options,preferBrowser:i??(o.options.preferBrowser||s===`unsupported`)})}));try{let t=new nr(Hg,{list:void 0});e.registerResource(`Present View`,t,{description:`AI Kit present tool viewer`},async(e,t,n)=>{let r=Array.isArray(t.id)?t.id[0]:t.id,i=r?Qg(r):void 0;return{contents:[{uri:e.href,mimeType:Dr,_meta:Mg(),text:i??Yg()??`<html><body><p>No content generated yet. Call the present tool first.</p></body></html>`}]}})}catch{}function r(){try{let e=w(`present`);if(e)return P(I(e,`dist`,`index.html`),`utf8`)}catch{}return Yg()||`<html><body><p>Loading...</p></body></html>`}try{e.registerResource(`Present App`,Vg,{description:`AI Kit present app - entry point`},async()=>({contents:[{uri:Vg,mimeType:Dr,_meta:Mg(),text:r()}]}))}catch{}try{e.registerResource(`present-templates`,`aikit://present/templates`,{description:`List all registered present viewer templates with their input schemas`},async()=>{let e=Bm().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{}try{e.registerResource(`present-presets`,`aikit://present/presets`,{description:`List all registered present presets with input schemas and examples`},async()=>({contents:[{uri:`aikit://present/presets`,mimeType:`application/json`,text:JSON.stringify(nv,null,2)}]}))}catch{}}const iv=j(`tools`);function av(e,t){let n=new mr({structure:new gr,dependencies:new dr,symbols:new _r,patterns:new hr,entryPoints:new pr,diagrams:new fr}),r=G(`produce_knowledge`);e.registerTool(`produce_knowledge`,{title:r.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:R.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:R.array(R.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:r.annotations},Y(`produce_knowledge`,async({scope:e,aspects:r},i)=>{let a;try{a=gl(i).createTask(`Produce Knowledge`,3),a.progress(0,`Running analyzers`);let o=e??`.`;iv.info(`Running knowledge production`,{rootPath:o,aspects:r});let s=await n.runExtraction(o,r);try{let e=F(kn(I(o)),fe.onboard);Ae(e,{recursive:!0});let t=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[n,r]of Object.entries(s))r&&typeof r==`string`&&Ie(F(e,`${n}.md`),t+r,`utf-8`);iv.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){iv.warn(`Failed to persist knowledge to .ai/context/`,{error:M(e)})}try{let e=I(kn(I(o)),fe.l0Cards);Ae(e,{recursive:!0});let n=It({workspaceName:o,structure:s.structure?.output,entryPoints:s.entryPoints?.output,dependencies:s.dependencies?.output,symbols:s.symbols?.output});Ie(F(e,et),n,`utf-8`),iv.info(`L0 workspace-core card generated`,{path:F(e,et)}),t?.notifyL0CardChanged().catch(()=>{})}catch(e){iv.warn(`Failed to generate L0 workspace-core card`,{error:M(e)})}a.progress(1,`Synthesizing results`);let c=n.buildSynthesisInstructions(s,r);return a.complete(`Knowledge production complete`),{content:[{type:`text`,text:c+`
3017
3012
 
3018
3013
  ---
3019
- _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),sv.error(`Knowledge production failed`,M(e)),J(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const lv=j(`tools`);function uv(e,t,n,r,i,a,o){let s=G(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:R.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:R.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},Y(`reindex`,async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
3014
+ _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return a?.fail?.(`Production failed`),iv.error(`Knowledge production failed`,M(e)),J(`INTERNAL`,`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`)}}))}const ov=j(`tools`);function sv(e,t,n,r,i,a,o){let s=G(`reindex`);e.registerTool(`reindex`,{title:s.title,description:`Trigger re-indexing of the AI Kit index. Can do incremental (only changed files) or full re-index. When smart indexing is active, use force: true to override the automatic trickle indexer.`,inputSchema:{full:R.boolean().default(!1).describe(`If true, force full re-index ignoring file hashes`),force:R.boolean().default(!1).describe(`If true, override smart indexing guard and run reindex anyway`)},annotations:s.annotations},Y(`reindex`,async({full:e,force:s},c)=>{try{if(t.isIndexing)return{content:[{type:`text`,text:`## Reindex Already in Progress
3020
3015
 
3021
3016
  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
3022
3017
 
@@ -3024,53 +3019,53 @@ Smart indexing (trickle mode) is enabled — files are automatically indexed as
3024
3019
 
3025
3020
  **If the index is severely outdated**, use \`reindex({ force: true })\` to override.
3026
3021
 
3027
- Use \`status({})\` to check smart indexing queue status.`}]};let l=gl(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),lv.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&lv.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(lv.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(),lv.info(`FTS index rebuilt after reindex`)}catch(e){lv.warn(`FTS index rebuild failed`,M(e))}try{let e=await r.reindexAll();lv.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){lv.warn(`Curated re-index failed`,M(e))}if(a)try{await a.notifyAfterReindex()}catch(e){lv.warn(`Post-reindex resource notification failed`,M(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),lv.error(`Background reindex failed`,M(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 lv.error(`Reindex failed`,M(e)),J(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const dv=j(`tools`);function fv(e){let t=G(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:R.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:R.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:R.string().optional().describe(`Filter by tool name (list only)`),source:R.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:R.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},Y(`replay`,async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return wn(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Tn({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 En().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
3022
+ Use \`status({})\` to check smart indexing queue status.`}]};let l=gl(c).createTask(`Reindex`,1);l.progress(0,`Starting ${e?`full`:`incremental`} reindex`),ov.info(`Starting background re-index`,{mode:e?`full`:`incremental`});let u=e=>t=>{t.phase===`chunking`&&t.currentFile&&ov.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(ov.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(),ov.info(`FTS index rebuilt after reindex`)}catch(e){ov.warn(`FTS index rebuild failed`,M(e))}try{let e=await r.reindexAll();ov.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){ov.warn(`Curated re-index failed`,M(e))}if(a)try{await a.notifyAfterReindex()}catch(e){ov.warn(`Post-reindex resource notification failed`,M(e))}}).catch(e=>{l.fail(`Reindex failed: ${e instanceof Error?e.message:String(e)}`),ov.error(`Background reindex failed`,M(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 ov.error(`Reindex failed`,M(e)),J(`INTERNAL`,`Reindex failed: ${e instanceof Error?e.message:String(e)}`)}}))}const cv=j(`tools`);function lv(e){let t=G(`replay`);e.registerTool(`replay`,{title:t.title,description:`View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.`,inputSchema:{action:R.enum([`list`,`clear`]).default(`list`).describe(`Action: "list" (default) to view entries, "clear" to wipe the log`),last:R.number().optional().describe(`Number of entries to return (default: 20, list only)`),tool:R.string().optional().describe(`Filter by tool name (list only)`),source:R.enum([`mcp`,`cli`]).optional().describe(`Filter by source: "mcp" or "cli" (list only)`),since:R.string().optional().describe(`ISO timestamp — only show entries after this time (list only)`)},annotations:t.annotations},Y(`replay`,async({action:e,last:t,tool:n,source:r,since:i})=>{try{if(e===`clear`)return wn(),{content:[{type:`text`,text:`Replay log cleared.`}]};let a=Tn({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 En().catch(()=>{}),{content:[{type:`text`,text:`**Replay Log** (${a.length} entries)\n\n${o.join(`
3028
3023
 
3029
- `)}`}]}}catch(e){return dv.error(`Replay failed`,M(e)),J(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const pv=j(`tools`);function mv(e){let t=G(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:R.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:R.string().optional().describe(`Restore point ID (required for action=restore)`),limit:R.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=$t().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(`
3024
+ `)}`}]}}catch(e){return cv.error(`Replay failed`,M(e)),J(`INTERNAL`,`Replay failed: ${e instanceof Error?e.message:String(e)}`)}}))}const uv=j(`tools`);function dv(e){let t=G(`restore`);e.registerTool(`restore`,{title:t.title,description:`List and restore file snapshots taken before destructive operations (codemod, rename, forget). Use action=list to see available restore points, action=restore with an id to undo.`,inputSchema:{action:R.enum([`list`,`restore`]).describe(`list: show restore points, restore: apply a restore point`),id:R.string().optional().describe(`Restore point ID (required for action=restore)`),limit:R.number().min(1).max(50).default(10).describe(`Max restore points to list`)},annotations:t.annotations},async({action:e,id:t,limit:n})=>{try{if(e===`list`){let e=$t().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(`
3030
3025
  `)}`}]}}if(!t)throw Error(`id is required for restore action`);let r=await An(t);return{content:[{type:`text`,text:`Restored ${r.length} files:\n${r.map(e=>`- \`${e}\``).join(`
3031
- `)}`}]}}catch(e){return pv.error(`Restore failed`,M(e)),J(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const hv=/<\/?curated-context>/gi;function gv(e){return e.replace(hv,``)}function _v(e){return`<curated-context>\n${gv(e)}\n</curated-context>`}const vv=j(`tools`);function yv(e,t,n,r){b(e,t,n);let i=e.memoryMetaGet(t);if(!i)return;let a=g(i,{..._,...r});a&&(y(e,t,a),v(e,t,n))}function bv(e,t){let n=[],r=De(),i=r?Le(r):``;i&&n.push(`[project: ${i}]`);let a=t?zn(t,`__context_boost`):void 0;return a&&n.push(`[focus: ${a.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function xv(e,t,n){return n?e:t===`curated`?e*1.2:e}function Sv(e,t){return t?e:e.map(e=>({record:e.record,score:xv(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}function Cv(e,t){let n=e?Math.floor(e/Math.max(1,t)):96;return Math.max(40,Math.min(160,n))}function wv(e,t){let n=e.origin===`curated`?_v(e.content):e.content,r=L(n,t);return{body:r,truncated:r!==n}}async function Tv(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:Er(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 vv.warn(`ER fallback failed`,M(e)),{results:n,triggered:!0,cacheHit:a}}}function Ev(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*(n+1)}))}function Dv(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 Ov(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 kv(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&&!Av.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 Av=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 jv(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 Ke(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 Mv(e,t,n,r,i,a,o,s,c,l,u){let d=G(`search`);e.registerTool(`search`,{title:d.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:fc,inputSchema:{query:R.string().max(5e3).describe(`Natural language search query`),limit:R.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:R.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:R.enum(pe).optional().describe(`Filter by content type`),source_type:R.enum(ye).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:R.enum(_e).optional().describe(`Filter by knowledge origin`),category:R.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:R.array(R.string()).optional().describe(`Filter by exact tag membership (any supplied tag may match)`),min_score:R.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:R.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),min_confidence:R.enum([`extracted`,`inferred`,`ambiguous`]).optional().describe(`Minimum confidence level for results: "extracted" (guaranteed correct from source code), "inferred" (LLM-derived), "ambiguous" (uncertain, needs verification). Lower values include more results.`),dedup:R.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:R.array(R.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:d.annotations},async({query:e,limit:d,search_mode:f,content_type:p,source_type:m,origin:h,category:g,tags:_,min_score:v,min_confidence:y,graph_hops:b,max_tokens:x,dedup:S,workspaces:C})=>{let w=Date.now();try{let T={limit:d,minScore:v,contentType:p,sourceType:m,origin:h,category:g,tags:_},E,D=!1,O=!1,k=``,ee=f!==`keyword`,te=bv(e,s);if(f===`keyword`)E=await n.ftsSearch(e,T),E=E.slice(0,d);else if(f===`semantic`)try{let r=await t.embedQuery(te);E=await n.search(r,T);let a=await Tv(i,E[0]?.score??0,E,e,d);E=a.results,D=a.triggered,O=a.cacheHit}catch(t){ee=!1,vv.warn(`Embedder unavailable in semantic mode, falling back to FTS`,M(t)),E=await n.ftsSearch(e,{...T,limit:d}),k=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
3026
+ `)}`}]}}catch(e){return uv.error(`Restore failed`,M(e)),J(`INTERNAL`,`Restore failed: ${e instanceof Error?e.message:String(e)}`)}})}const fv=/<\/?curated-context>/gi;function pv(e){return e.replace(fv,``)}function mv(e){return`<curated-context>\n${pv(e)}\n</curated-context>`}const hv=j(`tools`);function gv(e,t,n,r){b(e,t,n);let i=e.memoryMetaGet(t);if(!i)return;let a=g(i,{..._,...r});a&&(y(e,t,a),v(e,t,n))}function _v(e,t){let n=[],r=De(),i=r?Le(r):``;i&&n.push(`[project: ${i}]`);let a=t?zn(t,`__context_boost`):void 0;return a&&n.push(`[focus: ${a.value}]`),n.length===0?e:`${n.join(` `)} ${e}`}function vv(e,t,n){return n?e:t===`curated`?e*1.2:e}function yv(e,t){return t?e:e.map(e=>({record:e.record,score:vv(e.score,e.record.origin,t)})).sort((e,t)=>t.score-e.score)}function bv(e,t){let n=e?Math.floor(e/Math.max(1,t)):96;return Math.max(40,Math.min(160,n))}function xv(e,t){let n=e.origin===`curated`?mv(e.content):e.content,r=L(n,t);return{body:r,truncated:r!==n}}async function Sv(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:Er(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 hv.warn(`ER fallback failed`,M(e)),{results:n,triggered:!0,cacheHit:a}}}function Cv(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*(n+1)}))}function wv(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 Tv(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 Ev(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&&!Dv.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 Dv=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 Ov(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 Ke(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 kv(e,t,n,r,i,a,o,s,c,l,u){let d=G(`search`);e.registerTool(`search`,{title:d.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:fc,inputSchema:{query:R.string().max(5e3).describe(`Natural language search query`),limit:R.number().min(1).max(20).default(5).describe(`Maximum results to return`),search_mode:R.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).describe(`Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)`),content_type:R.enum(pe).optional().describe(`Filter by content type`),source_type:R.enum(ye).optional().describe(`Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.`),origin:R.enum(_e).optional().describe(`Filter by knowledge origin`),category:R.string().optional().describe(`Filter by category (e.g., decisions, patterns, conventions)`),tags:R.array(R.string()).optional().describe(`Filter by exact tag membership (any supplied tag may match)`),min_score:R.number().min(0).max(1).default(.25).describe(`Minimum similarity score`),graph_hops:R.number().min(0).max(3).default(1).describe(`Number of graph hops to augment results with connected entities (0 = disabled, 1 = direct connections, 2-3 = deeper traversal). Default 1 provides module/symbol context automatically.`),max_tokens:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),min_confidence:R.enum([`extracted`,`inferred`,`ambiguous`]).optional().describe(`Minimum confidence level for results: "extracted" (guaranteed correct from source code), "inferred" (LLM-derived), "ambiguous" (uncertain, needs verification). Lower values include more results.`),dedup:R.enum([`file`,`chunk`]).default(`chunk`).describe(`Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)`),workspaces:R.array(R.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all registered workspaces. Only works in user-level install mode.`)},annotations:d.annotations},async({query:e,limit:d,search_mode:f,content_type:p,source_type:m,origin:h,category:g,tags:_,min_score:v,min_confidence:y,graph_hops:b,max_tokens:x,dedup:S,workspaces:C})=>{let w=Date.now();try{let T={limit:d,minScore:v,contentType:p,sourceType:m,origin:h,category:g,tags:_},E,D=!1,O=!1,k=``,ee=f!==`keyword`,te=_v(e,s);if(f===`keyword`)E=await n.ftsSearch(e,T),E=E.slice(0,d);else if(f===`semantic`)try{let r=await t.embedQuery(te);E=await n.search(r,T);let a=await Sv(i,E[0]?.score??0,E,e,d);E=a.results,D=a.triggered,O=a.cacheHit}catch(t){ee=!1,hv.warn(`Embedder unavailable in semantic mode, falling back to FTS`,M(t)),E=await n.ftsSearch(e,{...T,limit:d}),k=`> _⚠️ Semantic search unavailable (embedder recovering). Showing keyword results instead._
3032
3027
 
3033
- `}else{let r=[],a=[];try{let i=await t.embedQuery(te),o=n.coarseSearch,s=o?o.bind(n):n.search.bind(n);[r,a]=await Promise.all([s(i,{...T,limit:d*2}),n.ftsSearch(e,{...T,limit:d*2}).catch(()=>[])])}catch(t){ee=!1,vv.warn(`Embedder unavailable, falling back to FTS-only`,M(t)),a=await n.ftsSearch(e,{...T,limit:d*2}),k=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
3028
+ `}else{let r=[],a=[];try{let i=await t.embedQuery(te),o=n.coarseSearch,s=o?o.bind(n):n.search.bind(n);[r,a]=await Promise.all([s(i,{...T,limit:d*2}),n.ftsSearch(e,{...T,limit:d*2}).catch(()=>[])])}catch(t){ee=!1,hv.warn(`Embedder unavailable, falling back to FTS-only`,M(t)),a=await n.ftsSearch(e,{...T,limit:d*2}),k=`> _⚠️ Vector search unavailable (embedder recovering). Results from keyword search only._
3034
3029
 
3035
- `}if(ee?r.length===0&&a.length>0?(E=a.slice(0,d),k=` (FTS-only: vector index rebuilding)`):E=a.length===0&&r.length>0?r.slice(0,d):Ev(r,a).slice(0,d):E=a.slice(0,d),ee){let t=await Tv(i,r[0]?.score??0,E,e,d);E=t.results,D=t.triggered,O=t.cacheHit}}E=Sv(E,h).slice(0,d),a&&a.recordSearch(e,D,O),E.length>1&&(E=Dv(E,e)),E=Ov(E);let ne=``;if(C&&C.length>0){let n=Xl(C,u);if(n.length>0){let{stores:r,closeAll:i}=await Zl(n);try{let i;i=f===`keyword`||!ee?await $l(r,e,{...T,limit:d}):await Ql(r,await t.embedQuery(e),{...T,limit:d});for(let e of i)E.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});E=E.sort((e,t)=>t.score-e.score).slice(0,d),ne=` + ${n.length} workspace(s)`}finally{await i()}}}if(S===`file`&&E.length>1){let e=new Map;for(let t of E){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}]})}E=[...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(E.length>1){let e=E[0].score,t=Math.max(e*.4,.1);E=E.filter(e=>e.score>=t)}let re={extracted:3,inferred:2,ambiguous:1};if(y){let e=re[y]??0;E=E.filter(t=>(t.record.confidence?re[t.record.confidence]??2:2)>=e)}if(E.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,timeoutMs:1e4})).text.trim().split(`
3036
- `)[0].slice(0,500);if(r&&r!==e){let i=f===`keyword`||!ee?await n.ftsSearch(r,T):await n.search(await t.embedQuery(r),T);i.length>0&&(E=i,k=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,vv.debug(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){vv.debug(`Smart search fallback failed`,{error:String(e)})}if(E.length===0){let t=yt({text:`No results found for the given query.`,query:e,searchMode:f,limit:d,results:[],durationMs:Date.now()-w}),n=ru(t.summary);return{content:[{type:`text`,text:iu(t.summary,n)}],isError:!t.ok,structuredContent:{...t.data??{results:[],totalResults:0,searchMode:f,query:e},ref:n}}}}let ie,ae;if(b>0&&!r&&(ae="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),b>0&&r)try{let e=await Bt(r,E.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:b,maxPerHit:5});ie=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(`
3030
+ `}if(ee?r.length===0&&a.length>0?(E=a.slice(0,d),k=` (FTS-only: vector index rebuilding)`):E=a.length===0&&r.length>0?r.slice(0,d):Cv(r,a).slice(0,d):E=a.slice(0,d),ee){let t=await Sv(i,r[0]?.score??0,E,e,d);E=t.results,D=t.triggered,O=t.cacheHit}}E=yv(E,h).slice(0,d),a&&a.recordSearch(e,D,O),E.length>1&&(E=wv(E,e)),E=Tv(E);let ne=``;if(C&&C.length>0){let n=Xl(C,u);if(n.length>0){let{stores:r,closeAll:i}=await Zl(n);try{let i;i=f===`keyword`||!ee?await $l(r,e,{...T,limit:d}):await Ql(r,await t.embedQuery(e),{...T,limit:d});for(let e of i)E.push({record:{...e.record,sourcePath:`[${e.workspace}] ${e.record.sourcePath}`},score:e.score});E=E.sort((e,t)=>t.score-e.score).slice(0,d),ne=` + ${n.length} workspace(s)`}finally{await i()}}}if(S===`file`&&E.length>1){let e=new Map;for(let t of E){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}]})}E=[...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(E.length>1){let e=E[0].score,t=Math.max(e*.4,.1);E=E.filter(e=>e.score>=t)}let re={extracted:3,inferred:2,ambiguous:1};if(y){let e=re[y]??0;E=E.filter(t=>(t.record.confidence?re[t.record.confidence]??2:2)>=e)}if(E.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,timeoutMs:1e4})).text.trim().split(`
3031
+ `)[0].slice(0,500);if(r&&r!==e){let i=f===`keyword`||!ee?await n.ftsSearch(r,T):await n.search(await t.embedQuery(r),T);i.length>0&&(E=i,k=`> _Original query "${e}" returned 0 results. Auto-reformulated to "${r}"._\n\n`,hv.debug(`Smart search fallback succeeded`,{originalQuery:e,altQuery:r,resultCount:i.length}))}}catch(e){hv.debug(`Smart search fallback failed`,{error:String(e)})}if(E.length===0){let t=yt({text:`No results found for the given query.`,query:e,searchMode:f,limit:d,results:[],durationMs:Date.now()-w}),n=ru(t.summary);return{content:[{type:`text`,text:iu(t.summary,n)}],isError:!t.ok,structuredContent:{...t.data??{results:[],totalResults:0,searchMode:f,query:e},ref:n}}}}let ie,ae;if(b>0&&!r&&(ae="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),b>0&&r)try{let e=await Bt(r,E.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:b,maxPerHit:5});ie=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(`
3037
3032
  `),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(`
3038
3033
  `),i=[`- **Graph Context** (${b} hop${b>1?`s`:``}):`];e&&i.push(` Entities:\n${e}`),r&&i.push(` Relationships:\n${r}`),ie.set(t.recordId,i.join(`
3039
- `))}}catch(e){vv.warn(`Graph augmentation failed`,M(e)),ae=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let oe=Date.now();for(let e of E)if(e.record.origin===`curated`&&e.record.indexedAt){let t=oe-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(E.sort((e,t)=>t.score-e.score),E=it(E),s)for(let e of E){if(e.record.origin!==`curated`)continue;let t=Wd(e.record.sourcePath);t&&yv(s,t,c,l)}let se=Cv(x,E.length),ce=!1,le=E.map((e,t)=>{let n=e.record,r=`### Result ${t+1} (score: ${e.score.toFixed(3)})`,i=[`- **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,ie?.get(n.id)??null].filter(Boolean).join(`
3040
- `),{body:a,truncated:o}=wv(n,se);return ce||=o,`${r}\n${i}\n\n${a}${o?`\n\n_Full content: use \`lookup\` on \`${n.sourcePath}\`._`:``}`}).join(`
3034
+ `))}}catch(e){hv.warn(`Graph augmentation failed`,M(e)),ae=`> **Note:** Graph augmentation failed. Results shown without graph context.`}let oe=Date.now();for(let e of E)if(e.record.origin===`curated`&&e.record.indexedAt){let t=oe-new Date(e.record.indexedAt).getTime(),n=Math.max(0,t/864e5);e.score*=.95**n}if(E.sort((e,t)=>t.score-e.score),E=it(E),s)for(let e of E){if(e.record.origin!==`curated`)continue;let t=Wd(e.record.sourcePath);t&&gv(s,t,c,l)}let se=bv(x,E.length),ce=!1,le=E.map((e,t)=>{let n=e.record,r=`### Result ${t+1} (score: ${e.score.toFixed(3)})`,i=[`- **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,ie?.get(n.id)??null].filter(Boolean).join(`
3035
+ `),{body:a,truncated:o}=xv(n,se);return ce||=o,`${r}\n${i}\n\n${a}${o?`\n\n_Full content: use \`lookup\` on \`${n.sourcePath}\`._`:``}`}).join(`
3041
3036
 
3042
3037
  ---
3043
3038
 
3044
- `),ue=(f===`hybrid`?`hybrid (vector + keyword RRF)`:f===`keyword`?`keyword (FTS)`:`semantic (vector)`)+ne,de=kv(E,e),fe=de.length>0?`\n_Distinctive terms: ${de.map(e=>`\`${e}\``).join(`, `)}_`:``,pe=await jv(n,E),me=[];if(E.length===0)me.push("`reindex` — no results found, index may be stale"),me.push("`find` — try federated search with glob/regex");else{let e=E[0]?.record.sourcePath;e&&me.push(`\`lookup\` — see all chunks from \`${e}\``),me.push("`symbol` — resolve a specific symbol from the results"),me.push("`compact` — compress a result file for focused reading"),me.push("reuse `ctxc_` ref above to avoid re-querying")}let he=[ae?`${ae}\n\n`:``,pe?`${pe}\n\n`:``,le,`\n\n---\n_Search mode: ${ue} | ${E.length} results_${fe}`,`\n_Next: ${me.join(` | `)}_`],ge=k+he.join(``),_e=!1;if(x){let e=L(ge,x);_e=e!==ge,ge=e}_e||=ce;let ve=E.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}:{}})),ye=[ae,pe].filter(e=>!!e),A=yt({text:ge,query:e,searchMode:f,limit:d,results:ve,durationMs:Date.now()-w,truncated:_e,caveats:ye}),be=ru(A.summary),xe=new Set,j=[];for(let e of E){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Wd(e.record.sourcePath);if(!t)continue;let n=Hd(t,e.record.headingPath??t);n&&!xe.has(n.uri)&&(xe.add(n.uri),j.push(n))}return{content:[{type:`text`,text:iu(A.summary,be)},...j],isError:!A.ok,structuredContent:{...A.data??{results:[],totalResults:0,searchMode:f,query:e},ref:be}}}catch(t){vv.error(`Search failed`,M(t));let n=yt({text:`Search failed: ${t instanceof Error?t.message:String(t)}`,query:e??``,searchMode:f??`hybrid`,limit:d,results:[],durationMs:Date.now()-w}),r=ru(n.summary);return{content:[{type:`text`,text:iu(n.summary,r)}],structuredContent:{...n.data??{results:[],totalResults:0,searchMode:f??`hybrid`,query:e??``},ref:r}}}})}const Nv=j(`tools`);function Pv(e,t,n){let r=G(`session_digest`);e.registerTool(`session_digest`,{title:r.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:R.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:R.string().optional().describe(`ISO timestamp — only include activity after this time`),last:R.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:R.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:R.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:R.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:R.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},Y(`session_digest`,async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await In(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):Fn(l,u)).digest}]}}catch(e){return Nv.error(`Session digest failed`,M(e)),J(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Fv=1e4,Iv={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function Lv(e){return e??Iv}function Rv(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function zv(e,t,n){let r=Rv(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function Bv(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function Vv(e,t=!1,n){Rv(e,`workspace`);let r=Lv(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function Hv(e,t,n){let r=Lv(n),i=Vv(t.workspace,t.global??!1,r),a=zv(t.key,`key`,500),o=zv(t.value,`value`,Fv),s=t.agent?zv(t.agent,`agent`,500):void 0,c=Bv(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Uv(e,t,n){let r=Rv(t,`workspace`),i=zv(n,`key`,500);return e.signalGet(r,i)}function Wv(e,t){let n=Rv(t,`workspace`);return e.signalList(n)}function Gv(e,t,n){let r=Rv(t,`workspace`),i=n===void 0?void 0:zv(n,`key`,500);return e.signalClear(r,i)}function Kv(e,t,n){let r=Lv(n),i=zv(t.resource,`resource`,500),a=zv(t.holder,`holder`,500),o=Rv(t.workspace,`workspace`),s=t.intent?zv(t.intent,`intent`,Fv):void 0,c=Bv(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 qv(e,t,n,r){let i=Rv(t,`workspace`),a=zv(n,`resource`,500),o=zv(r,`holder`,500);return e.leaseRelease(a,o,i)}function Jv(e,t){let n=Rv(t,`workspace`);return e.leaseList(n)}const Yv=j(`tools:signal`);function Xv(e){return JSON.stringify(e,null,2)}function Zv(e,t,n){let r=G(`signal`),i={...Iv,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:R.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:R.string().describe(`Workspace identifier (required)`),key:R.string().optional().describe(`Signal key (for post/get/clear)`),value:R.string().optional().describe(`Signal value (for post)`),agent:R.string().optional().describe(`Agent identifier`),resource:R.string().optional().describe(`Resource path (for lease/unlease)`),holder:R.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:R.string().optional().describe(`What the holder plans to do`),ttl:R.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:R.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},Y(`signal`,async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=Hv(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:Xv({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Uv(t,Vv(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:Xv(e)}],structuredContent:{signals:e}}}case`list`:{let e=Wv(t,Vv(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:Xv(e)}],structuredContent:{signals:e}}}case`clear`:{let e=Gv(t,Vv(n,d??!1,i),r);return{content:[{type:`text`,text:Xv({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=Kv(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:Xv(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=qv(t,n,s,c);return{content:[{type:`text`,text:Xv({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=Jv(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:Xv(e)}],structuredContent:{leases:e}}}}}catch(e){return Yv.error(`Signal operation failed`,M(e)),J(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}let Qv={totalInputChars:0,totalOutputChars:0,callCount:0,startTime:new Date().toISOString()};function $v(){return{...Qv}}const ey=new Map,ty=[];function ny(){return Array.from(ey.entries()).map(([e,t])=>({tool:e,...t}))}function ry(){return ty}j(`auto-gc`);function iy(){let e=[...ry()];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 ay(){return{state:`warming`,p95:iy(),lastGcAt:null,gcCount:0,bufferSize:ry().length}}function oy(e,t){return e.length<=t?e:e.slice(0,t)}function sy(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function cy(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(!e)continue;let t=I(e,`workspace-core.md`);if(N(t))try{let e=P(t,`utf-8`);return e.length>400?`${e.slice(0,400)}\n...`:e}catch{}}return null}async function ly(e,t,n=d,r){if(!e||!t)return null;try{let[i,o,s]=await Promise.all([e.list({category:`lessons`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`conventions`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`session`,limit:200,orderBy:`updated`,order:`desc`})]),l=i.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:c(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3);return{lessons:await Promise.all(l.map(async({entry:t,confidence:n})=>{let r=a((await e.read(t.path)).content);return{title:t.title,insight:oy(r.insight??``,150),confidence:n}})),conventions:o.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).filter(({entry:e})=>(e.contentPreview?.trim()??``).length>5).sort((e,t)=>sy(t.lastAccessedAt)-sy(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),checkpoint:s.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>sy(t.lastAccessedAt)-sy(e.lastAccessedAt)).map(({entry:e})=>oy(e.contentPreview,200))[0]??null,workspaceCore:cy(r)}}catch{return null}}function uy(e,t=600){if(!e)return{lines:[],totalChars:0,autoInjectCount:0};let n=[],r=0;for(let t of e.lessons){if(t.confidence<45)continue;let e=gp(t.title,t.insight,t.confidence,200);n.push(`• ${e}`),r++}e.workspaceCore&&(n.push(`• Workspace: ${e.workspaceCore.split(`
3039
+ `),ue=(f===`hybrid`?`hybrid (vector + keyword RRF)`:f===`keyword`?`keyword (FTS)`:`semantic (vector)`)+ne,de=Ev(E,e),fe=de.length>0?`\n_Distinctive terms: ${de.map(e=>`\`${e}\``).join(`, `)}_`:``,pe=await Ov(n,E),me=[];if(E.length===0)me.push("`reindex` — no results found, index may be stale"),me.push("`find` — try federated search with glob/regex");else{let e=E[0]?.record.sourcePath;e&&me.push(`\`lookup\` — see all chunks from \`${e}\``),me.push("`symbol` — resolve a specific symbol from the results"),me.push("`compact` — compress a result file for focused reading"),me.push("reuse `ctxc_` ref above to avoid re-querying")}let he=[ae?`${ae}\n\n`:``,pe?`${pe}\n\n`:``,le,`\n\n---\n_Search mode: ${ue} | ${E.length} results_${fe}`,`\n_Next: ${me.join(` | `)}_`],ge=k+he.join(``),_e=!1;if(x){let e=L(ge,x);_e=e!==ge,ge=e}_e||=ce;let ve=E.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}:{}})),ye=[ae,pe].filter(e=>!!e),A=yt({text:ge,query:e,searchMode:f,limit:d,results:ve,durationMs:Date.now()-w,truncated:_e,caveats:ye}),be=ru(A.summary),xe=new Set,j=[];for(let e of E){if(e.record.origin!==`curated`||e.record.sourcePath.startsWith(`[`))continue;let t=Wd(e.record.sourcePath);if(!t)continue;let n=Hd(t,e.record.headingPath??t);n&&!xe.has(n.uri)&&(xe.add(n.uri),j.push(n))}return{content:[{type:`text`,text:iu(A.summary,be)},...j],isError:!A.ok,structuredContent:{...A.data??{results:[],totalResults:0,searchMode:f,query:e},ref:be}}}catch(t){hv.error(`Search failed`,M(t));let n=yt({text:`Search failed: ${t instanceof Error?t.message:String(t)}`,query:e??``,searchMode:f??`hybrid`,limit:d,results:[],durationMs:Date.now()-w}),r=ru(n.summary);return{content:[{type:`text`,text:iu(n.summary,r)}],structuredContent:{...n.data??{results:[],totalResults:0,searchMode:f??`hybrid`,query:e??``},ref:r}}}})}const Av=j(`tools`);function jv(e,t,n){let r=G(`session_digest`);e.registerTool(`session_digest`,{title:r.title,description:`Compress the current session's tool trajectory into a focused digest. Aggregates replay log, stash state, and checkpoints. Supports deterministic and LLM-assisted (sampling) modes with configurable token budget.`,inputSchema:{scope:R.enum([`tools`,`stash`,`all`]).default(`all`).describe(`What to include: tools (replay only), stash (stash + checkpoints only), or all`),since:R.string().optional().describe(`ISO timestamp — only include activity after this time`),last:R.number().min(1).max(500).optional().describe(`Max replay entries to consider (default: 50)`),focus:R.string().optional().describe(`Focus query — prioritize entries matching this topic`),mode:R.enum([`deterministic`,`sampling`]).default(`deterministic`).describe(`Summary mode: deterministic (fast, template-based) or sampling (LLM-assisted, richer)`),token_budget:R.number().min(100).max(8e3).default(2e3).describe(`Target token budget for the digest output`),persist:R.boolean().default(!0).describe(`Auto-save digest to stash for crash recovery`)},annotations:r.annotations},Y(`session_digest`,async({scope:e,since:r,last:i,focus:a,mode:o,token_budget:s,persist:c})=>{try{let l={scope:e,since:r,last:i,focus:a,mode:o,tokenBudget:s,persist:c},u=t?{stateStore:t}:void 0;return{content:[{type:`text`,text:(o===`sampling`&&n?.available?await In(l,async(e,t,r)=>(await n.createMessage({prompt:e,systemPrompt:t,maxTokens:r})).text,u):Fn(l,u)).digest}]}}catch(e){return Av.error(`Session digest failed`,M(e)),J(`INTERNAL`,`Session digest failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Mv=1e4,Nv={defaultTtlSeconds:300,defaultLeaseTtlMinutes:10,globalEnabled:!1};function Pv(e){return e??Nv}function Fv(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function Iv(e,t,n){let r=Fv(e,t);if(r.length>n)throw Error(`${t} exceeds max length of ${n}`);return r}function Lv(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be greater than 0`);return Math.trunc(e)}function Rv(e,t=!1,n){Fv(e,`workspace`);let r=Pv(n);if(!t)return e;if(!r.globalEnabled)throw Error(`Global signal scope is disabled`);return`__global__`}function zv(e,t,n){let r=Pv(n),i=Rv(t.workspace,t.global??!1,r),a=Iv(t.key,`key`,500),o=Iv(t.value,`value`,Mv),s=t.agent?Iv(t.agent,`agent`,500):void 0,c=Lv(t.ttlSeconds??r.defaultTtlSeconds,`ttlSeconds`);return e.signalPost(i,a,o,s,c)}function Bv(e,t,n){let r=Fv(t,`workspace`),i=Iv(n,`key`,500);return e.signalGet(r,i)}function Vv(e,t){let n=Fv(t,`workspace`);return e.signalList(n)}function Hv(e,t,n){let r=Fv(t,`workspace`),i=n===void 0?void 0:Iv(n,`key`,500);return e.signalClear(r,i)}function Uv(e,t,n){let r=Pv(n),i=Iv(t.resource,`resource`,500),a=Iv(t.holder,`holder`,500),o=Fv(t.workspace,`workspace`),s=t.intent?Iv(t.intent,`intent`,Mv):void 0,c=Lv(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 Wv(e,t,n,r){let i=Fv(t,`workspace`),a=Iv(n,`resource`,500),o=Iv(r,`holder`,500);return e.leaseRelease(a,o,i)}function Gv(e,t){let n=Fv(t,`workspace`);return e.leaseList(n)}const Kv=j(`tools:signal`);function qv(e){return JSON.stringify(e,null,2)}function Jv(e,t,n){let r=G(`signal`),i={...Nv,...n};e.registerTool(`signal`,{title:r.title,description:`Inter-agent signaling and lease coordination`,inputSchema:{action:R.enum([`post`,`get`,`list`,`clear`,`lease`,`unlease`,`leases`]).describe(`Signal action to perform`),workspace:R.string().describe(`Workspace identifier (required)`),key:R.string().optional().describe(`Signal key (for post/get/clear)`),value:R.string().optional().describe(`Signal value (for post)`),agent:R.string().optional().describe(`Agent identifier`),resource:R.string().optional().describe(`Resource path (for lease/unlease)`),holder:R.string().optional().describe(`Lease holder ID (for lease/unlease)`),intent:R.string().optional().describe(`What the holder plans to do`),ttl:R.number().optional().describe(`TTL (seconds for signals, minutes for leases)`),global:R.boolean().optional().describe(`Use global scope (default: false)`)},annotations:r.annotations},Y(`signal`,async({action:e,workspace:n,key:r,value:a,agent:o,resource:s,holder:c,intent:l,ttl:u,global:d})=>{try{switch(e){case`post`:{if(!r||a===void 0)throw Error(`key and value are required for post`);let e=zv(t,{workspace:n,key:r,value:a,agent:o,ttlSeconds:u,global:d},i);return{content:[{type:`text`,text:qv({id:e})}],structuredContent:{id:e}}}case`get`:{if(!r)throw Error(`key is required for get`);let e=Bv(t,Rv(n,d??!1,i),r);return{content:[{type:`text`,text:e.length===0?`[]`:qv(e)}],structuredContent:{signals:e}}}case`list`:{let e=Vv(t,Rv(n,d??!1,i));return{content:[{type:`text`,text:e.length===0?`[]`:qv(e)}],structuredContent:{signals:e}}}case`clear`:{let e=Hv(t,Rv(n,d??!1,i),r);return{content:[{type:`text`,text:qv({cleared:e})}],structuredContent:{cleared:e}}}case`lease`:{if(!s||!c)throw Error(`resource and holder are required for lease`);let e=Uv(t,{resource:s,holder:c,workspace:n,intent:l,ttlMinutes:u},i);return{content:[{type:`text`,text:qv(e)}],structuredContent:e}}case`unlease`:{if(!s||!c)throw Error(`resource and holder are required for unlease`);let e=Wv(t,n,s,c);return{content:[{type:`text`,text:qv({released:e})}],structuredContent:{released:e}}}case`leases`:{let e=Gv(t,n);return{content:[{type:`text`,text:e.length===0?`[]`:qv(e)}],structuredContent:{leases:e}}}}}catch(e){return Kv.error(`Signal operation failed`,M(e)),J(`INTERNAL`,`Signal operation failed: ${e instanceof Error?e.message:String(e)}`)}}))}let Yv={totalInputChars:0,totalOutputChars:0,callCount:0,startTime:new Date().toISOString()};function Xv(){return{...Yv}}const Zv=new Map,Qv=[];function $v(){return Array.from(Zv.entries()).map(([e,t])=>({tool:e,...t}))}function ey(){return Qv}j(`auto-gc`);function ty(){let e=[...ey()];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 ny(){return{state:`warming`,p95:ty(),lastGcAt:null,gcCount:0,bufferSize:ey().length}}function ry(e,t){return e.length<=t?e:e.slice(0,t)}function iy(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function ay(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(!e)continue;let t=I(e,`workspace-core.md`);if(N(t))try{let e=P(t,`utf-8`);return e.length>400?`${e.slice(0,400)}\n...`:e}catch{}}return null}async function oy(e,t,n=d,r){if(!e||!t)return null;try{let[i,o,s]=await Promise.all([e.list({category:`lessons`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`conventions`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`session`,limit:200,orderBy:`updated`,order:`desc`})]),l=i.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:c(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3);return{lessons:await Promise.all(l.map(async({entry:t,confidence:n})=>{let r=a((await e.read(t.path)).content);return{title:t.title,insight:ry(r.insight??``,150),confidence:n}})),conventions:o.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).filter(({entry:e})=>(e.contentPreview?.trim()??``).length>5).sort((e,t)=>iy(t.lastAccessedAt)-iy(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),checkpoint:s.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>iy(t.lastAccessedAt)-iy(e.lastAccessedAt)).map(({entry:e})=>ry(e.contentPreview,200))[0]??null,workspaceCore:ay(r)}}catch{return null}}function sy(e,t=600){if(!e)return{lines:[],totalChars:0,autoInjectCount:0};let n=[],r=0;for(let t of e.lessons){if(t.confidence<45)continue;let e=gp(t.title,t.insight,t.confidence,200);n.push(`• ${e}`),r++}e.workspaceCore&&(n.push(`• Workspace: ${e.workspaceCore.split(`
3045
3040
  `)[0]??``}`),r++);for(let t of e.conventions){let e=t.preview?.trim()||``;if(e){let r=e.length>120?`${e.slice(0,117)}...`:e;n.push(`• ${t.title}: ${r}`)}else n.push(`• ${t.title}`)}if(n.length===0)return{lines:[],totalChars:0,autoInjectCount:0};let i=[`━━ Knowledge ━━`,...n,`───`],a=i.join(`
3046
3041
  `);if(a.length>t)for(;i.length>3&&a.length>t;)i.splice(1,1)[0]?.startsWith(`•`)&&r--;return{lines:i,totalChars:i.join(`
3047
- `).length,autoInjectCount:r}}const dy=j(`tools`),fy=14400*1e3,py={includePrelude:R.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function my(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{dy.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),dy.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function hy(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 gy(){let e=yr.get(),t=vr.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(`
3042
+ `).length,autoInjectCount:r}}const cy=j(`tools`),ly=14400*1e3,uy={includePrelude:R.boolean().default(!1).describe(`Include session prelude with top lessons, conventions, and last checkpoint`)};function dy(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{cy.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),cy.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}function fy(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 py(){let e=yr.get(),t=vr.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(`
3048
3043
  `):` 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(`
3049
- `)}const _y=5*6e4;let vy=null,yy=null;function by(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 xy(){let e=Date.now();if(vy&&e-vy.ts<_y)return vy.value;try{let t=I($n(),`.copilot`,`.aikit-scaffold.json`);if(!N(t))return vy={value:null,ts:e},null;let n=JSON.parse(P(t,`utf-8`)).version??null;return vy={value:n,ts:e},n}catch{return vy={value:null,ts:e},null}}function Sy(){let e=Date.now();if(yy&&e-yy.ts<_y)return yy.value;try{let t=I(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!N(t))return yy={value:null,ts:e},null;let n=JSON.parse(P(t,`utf-8`)).version??null;return yy={value:n,ts:e},n}catch{return yy={value:null,ts:e},null}}function Cy(e){let t=G(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:py,annotations:t.annotations},Y(`status`,async()=>{let e=oe(),t=xy(),n=Sy(),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)**: ${yr.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=se(),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`?(ie(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(ie(),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:!!yr.get(),wasmDiagnostics:vr.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:hy({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3050
- `)}],structuredContent:o}}))}function wy(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=G(`status`);e.registerTool(`status`,{title:g.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:py,annotations:g.annotations},Y(`status`,async({includePrelude:e=!1})=>{let g=[];try{let[_,v]=await Promise.all([my(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),my(t.listSourcePaths(),[],`store.listSourcePaths`)]),y=_.value;_.timedOut&&g.push(`⚠ Index stats timed out — values may be incomplete`);let b=v.value;v.timedOut&&g.push(`⚠ File listing timed out`);let x=null,S=0,C=[`## AI Kit Status`,``,`- **Total Records**: ${y.totalRecords}`,`- **Total Files**: ${y.totalFiles}`,`- **Last Indexed**: ${y.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(y.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...b.slice(0,50).map(e=>`- ${e}`),b.length>50?`\n... and ${b.length-50} more files`:``];if(n)try{let e=await my(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)g.push(`⚠ Graph stats timed out`),C.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;x={nodes:t.nodeCount,edges:t.edgeCount},C.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await my(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||C.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&C.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{C.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let w=a?.onboardDir??``,T=N(w),E=i?.onboardComplete||T;if(C.push(``,`### Onboard Status`,E?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${w}\``),r)try{let e=await my(r.count(),0,`curated.count`);e.timedOut?(g.push(`⚠ Curated knowledge count timed out`),C.push(``,`### Curated Knowledge`,`- Listing timed out`)):(S=e.value,C.push(``,`### Curated Knowledge`,S>0?`- ${S} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions'))}catch{C.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let D=Jn().filter(e=>e.status===`watching`);if(D.length>0){C.push(``,`### File Watchers`,`- **Active**: ${D.length}`);for(let e of D){let t=e.pendingFiles?.length??0;if(C.push(` - \`${e.path}\`: ${e.eventCount} events, ${t} pending files`),t>0&&t<=10)for(let t of e.pendingFiles)C.push(` - \`${t}\``);else t>10&&C.push(` - ${t} pending files (use \`watch({ action: 'list' })\` for details)`)}}let O=by(y.totalRecords,x?.nodes??0,x?.edges??0,S),k=y.lastIndexedAt?new Date(y.lastIndexedAt).getTime():0,ee=k>0?Date.now()-k:1/0,te=hy({onboarded:E,indexStale:E&&ee>1440*60*1e3,contextPressure:O});C.push(``),C.push(`## 📊 Context Pressure: ${O}/100`),O>=80?C.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):O>=50?C.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):C.push(`✅ Low pressure — plenty of headroom for more content.`);let ne=0;if(y.lastIndexedAt){ne=new Date(y.lastIndexedAt).getTime();let e=(Date.now()-ne)/(1e3*60*60);C.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`)}C.push(``,`### Next Action`,`- **${te.kind}**: ${te.reason}`);let re=null,ae=t;if(typeof ae.getDiagnostics==`function`)try{let e=ae.getDiagnostics();re={adapterType:e.adapterType,vectorSearchEnabled:e.vectorSearchEnabled,ftsEnabled:e.ftsEnabled,degradedMode:e.degradedMode,dbPath:e.dbPath,dbSizeBytes:e.dbSizeBytes,embeddingDim:e.embeddingDim,vectorDtype:e.vectorDtype},C.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${re.adapterType}`,`- **Vector search**: ${re.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,re.dbPath?`- **DB**: ${re.dbPath}`:``,re.dbSizeBytes==null?``:`- **DB size**: ${(re.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${re.embeddingDim}`,`- **Vector dtype**: ${re.vectorDtype}`)}catch{}if(o===`smart`)if(C.push(``,`### Smart Indexing`),s){let e=s();e?C.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}`):C.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else C.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);if(h)try{let e=h.getReport(),t=h.checkThresholds(),n=Object.entries(e.counters),r=Object.entries(e.gauges);if(n.length>0||r.length>0||t.length>0){if(C.push(``,`### 📊 Metrics`),n.length>0){C.push(`**Counters:**`);for(let[e,t]of n)C.push(`- \`${e}\`: ${t}`)}if(r.length>0){C.push(`**Gauges:**`);for(let[e,t]of r)C.push(`- \`${e}\`: ${t}`)}if(t.length>0){C.push(`**⚠ Threshold violations:**`);for(let e of t)C.push(`- ${e}`)}else(n.length>0||r.length>0)&&C.push(`- ✅ All thresholds within limits`)}}catch{C.push(``,`### 📊 Metrics`,`- Metrics unavailable`)}{let e=[];if(u)try{let t=u.getStats();e.push(`- **Decision Hooks**: ${t.count} registered${t.hooks.length>0?` (IDs: ${t.hooks.map(e=>e.id).join(`, `)})`:``}`)}catch{e.push(`- **Decision Hooks**: unavailable`)}else e.push(`- **Decision Hooks**: not configured`);if(d)try{let t=d.getStats(),n=Object.entries(t.byTool).map(([e,t])=>`${e}=${t}`).join(`, `);e.push(`- **Observations**: ${t.totalObservations} total, byTool: ${n||`none`}`)}catch{e.push(`- **Observations**: unavailable`)}else e.push(`- **Observations**: not configured`);if(f)try{let t=f.getStats(),n=Object.keys(t.byName);e.push(`- **Extractors**: ${t.count} registered${n.length>0?` (IDs: ${n.join(`, `)})`:``}`)}catch{e.push(`- **Extractors**: unavailable`)}else e.push(`- **Extractors**: not configured`);if(m)try{let t=m.getStats(),n=t.cardExists?t.isStale?`⚠ Stale`:`✅ Fresh`:`❌ No card`;e.push(`- **L0 Compiler**: ${n}, last compiled: ${t.lastCompiledAt?new Date(t.lastCompiledAt).toLocaleString():`Never`}`)}catch{e.push(`- **L0 Compiler**: unavailable`)}else e.push(`- **L0 Compiler**: not configured`);if(p)try{let t=p.getStats();e.push(`- **Promotion Engine**: ${t.held} candidates held, ${t.promoted} promoted, ${t.observedFacts} distinct facts tracked`)}catch{e.push(`- **Promotion Engine**: unavailable`)}else e.push(`- **Promotion Engine**: not configured`);C.push(``,`### 🧩 Feature Coverage`,...e)}let ce=0;{try{let e=a?.stateDir?F(a.stateDir,`stash`):null;if(e&&N(e)){let t=Pe(e).mtimeMs;t>ne&&(ne=t)}}catch{}let e=[];if(r)try{let t=S>0?await r.list({limit:5,orderBy:`updated`,order:`desc`}):[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>ne&&(ne=t)}e.push(...t)}catch{}if(ce=ne>0?Date.now()-ne:0,ce>=fy){let t=Math.floor(ce/36e5);if(C.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){C.push(`**Recent decisions/notes:**`);for(let t of e)C.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}C.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')}}C.push(``,`### Runtime`,gy());let le=ge.instance().getAll(),ue=le.filter(e=>e.status!==`healthy`);if(ue.length>0){C.push(``,`### ⚠️ Subsystem Health`);for(let e of ue){let t=Math.round((Date.now()-e.since)/1e3);C.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else le.length>0&&C.push(``,`### ✅ Subsystem Health`,`- All ${le.length} subsystems healthy`);let de=me.getAll();if(de.size>0){C.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of de){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}C.push(r)}}let fe=xy(),pe=Sy(),he=oe(),_e=fe!=null&&fe!==he,ve=pe!=null&&pe!==he;if(_e||ve){let e=se(),t=[];_e&&t.push(`user scaffold v${fe}`),ve&&t.push(`workspace scaffold v${pe}`);let n=t.join(`, `);e.state===`success`?C.push(``,`### ✅ Upgrade Applied`,`- Server v${he} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?C.push(``,`### ⏳ Upgrade In Progress`,`- Server v${he} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(ie(),C.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${he} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(ie(),C.push(``,`### ⬆ Upgrade Available`,`- Server v${he} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}g.length>0&&C.push(``,`### ⚠ Warnings`,...g.map(e=>`- ${e}`));let ye=ny();if(ye.length>0){let e=ye.sort((e,t)=>t.callCount-e.callCount);C.push(``,`### Tool Usage This Session`,``),C.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),C.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);C.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let A=$v();A.callCount>0&&(C.push(``),C.push(`### Session Token Usage`),C.push(`- Tool calls: ${A.callCount}`),C.push(`- Input chars: ${A.totalInputChars.toLocaleString()}`),C.push(`- Output chars: ${A.totalOutputChars.toLocaleString()}`),C.push(`- Est. input tokens: ${Math.round(A.totalInputChars/4).toLocaleString()}`),C.push(`- Est. total tokens: ${Math.round((A.totalInputChars+A.totalOutputChars)/4).toLocaleString()}`));let be=ay();if(be.bufferSize>=10){let e=be.state===`healthy`?`🟢`:be.state===`degraded`?`🔴`:`🟡`;C.push(``,`### Auto-GC: ${e} ${be.state}`),C.push(`- p95 latency: ${be.p95}ms | buffer: ${be.bufferSize} samples`),be.gcCount>0&&C.push(`- GC cycles triggered: ${be.gcCount}`)}if(l){let e=l.getStats();if(e.totalSubscribers>0){C.push(``,`### 🔌 Hooks (EventBus Subscribers)`),C.push(`- Total subscribers: ${e.totalSubscribers}`);for(let[t,n]of Object.entries(e.byEvent))C.push(` - ${t}: ${n} subscriber(s)`);for(let t of e.subscriptions)C.push(` - ${t.name} (${t.eventType}, ${t.policy})`);if(e.autoDisabled.length>0){C.push(``),C.push(` **Auto-disabled subscribers:**`);for(let t of e.autoDisabled)C.push(` - ${t.name} (${t.id}): ${t.reason}`)}}}if(u&&u.size>0){let e=u.getStats();C.push(``,`### 🪝 Decision Hooks`),C.push(`- Total hooks: ${e.count}`);for(let t of e.hooks){let e=t.decisionTypes.join(`, `);C.push(` - ${t.id} (order=${t.order}, policy=${t.failurePolicy}, types=[${e}])`)}}if(d){let e=d.getStats();C.push(``,`### 👁 Observations`),C.push(`- Total observations: ${e.totalObservations}`),C.push(` - Success: ${e.byError.success}, Error: ${e.byError.error}`),C.push(` - Artifacts stored: ${e.artifactCount}`),C.push(` - Truncations: ${e.truncationCount}`),C.push(` - Store entries: ${e.storeSize}`);let t=Object.entries(e.byOrigin);t.length>0&&C.push(` - By origin: ${t.map(([e,t])=>`${e}=${t}`).join(`, `)}`)}if(f){let e=f.getStats();C.push(``,`### 🧩 Extractors`),C.push(`- Total extractors: ${e.count}`);for(let[t,n]of Object.entries(e.byName))C.push(` - ${t} (${n.tools} tool(s), maxFacts: ${n.maxFactsPerEvent??`default`})`)}if(p){let e=p.getStats();if(C.push(``,`### 🏆 Promotion Engine`),C.push(`- Total evaluated: ${e.totalEvaluated}`),C.push(`- Promoted: ${e.promoted}`),C.push(`- Held: ${e.held}`),C.push(`- Rejected: ${e.rejected}`),C.push(`- Superseded: ${e.superseded}`),C.push(`- Decayed: ${e.decayed}`),C.push(`- Distinct facts tracked: ${e.observedFacts}`),e.recentDecisions.length>0){C.push(` Recent decisions:`);for(let t of e.recentDecisions.slice(-5))C.push(` - ${t.decision.status}: "${t.factTitle}" (${t.decision.reason.slice(0,80)})`)}}if(m){let e=m.getStats();C.push(``,`### 📋 L0 Briefing Card`),C.push(`- **Card exists**: ${e.cardExists?`✅`:`❌`}`),C.push(`- **Stale**: ${e.isStale?`⚠ Yes — regenerating on next trigger`:`✅ Fresh`}`),C.push(`- **Last compiled**: ${e.lastCompiledAt?new Date(e.lastCompiledAt).toLocaleString():`Never`}`),C.push(`- **Total compiles**: ${e.totalCompiles}`),e.failedCompiles>0&&C.push(`- **Failed compiles**: ${e.failedCompiles}`),e.cardSize>0&&C.push(`- **Card size**: ${e.cardSize} bytes`),e.isCompiling&&C.push(`- ⏳ **Currently compiling**`),e.pendingRegeneration&&C.push(`- ⏳ **Regeneration pending**`)}{let e=Lt();(e.cacheSize>0||e.refReuseCount>0)&&(C.push(``,`### 🔄 Ref Reuse`),C.push(`- **Refs stored**: ${e.refStoreCount}`),C.push(`- **Refs reused**: ${e.refReuseCount}`),e.refStaleCount>0&&C.push(`- **⚠ Stale refs detected**: ${e.refStaleCount}`),C.push(`- **Cache entries**: ${e.cacheSize}`))}let xe=C.join(`
3051
- `),j=ce>=fy,Se=[a?.onboardDir?Dn(I(a.onboardDir,`..`)):void 0,a?.l0CardDir].filter(e=>typeof e==`string`&&e.length>0),Ce=e||j?await ly(r,c,void 0,Se.length>0?Se:void 0):void 0,we=D.length>0?D.map(e=>({id:e.id,path:e.path,eventCount:e.eventCount,pendingFiles:e.pendingFiles??[]})):void 0,Te={totalRecords:y.totalRecords,totalFiles:y.totalFiles,lastIndexedAt:y.lastIndexedAt??null,onboarded:E,onboardDir:w,contentTypes:y.contentTypeBreakdown,wasmAvailable:!!yr.get(),wasmDiagnostics:vr.get(),graphStats:x,curatedCount:S,serverVersion:he,scaffoldVersion:fe??null,workspaceScaffoldVersion:pe??null,upgradeAvailable:_e||ve,storeBackend:a?.store?.backend,storeDiagnostics:re??null,contextPressure:O,nextAction:te,watchers:we,sessionTokens:{callCount:A.callCount,totalInputChars:A.totalInputChars,totalOutputChars:A.totalOutputChars,estInputTokens:Math.round(A.totalInputChars/4),estTotalTokens:Math.round((A.totalInputChars+A.totalOutputChars)/4),startTime:A.startTime},...Ce===void 0?{}:{prelude:Ce}};return{content:[{type:`text`,text:xe+(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:Te}}catch(e){return dy.error(`Status failed`,M(e)),J(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Ty=j(`tools`);function Ey(e){return e instanceof Error?(`code`in e?e.code:void 0)===`ENOENT`||e.message.startsWith(`File not found:`)||e.message.startsWith(`Path not found:`):!1}function Dy(e){let t=G(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:R.array(R.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:R.number().min(1).max(20).default(5).describe(`Max results per query`),site:R.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:R.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},Y(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await Qn({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(`
3052
- `)};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 Ty.error(`Web search failed`,M(e)),J(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Ty.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(`
3053
-
3054
- `);return c===o.length?J(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function Oy(e){let t=G(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:R.string().url().describe(`Request URL (http/https only)`),method:R.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:R.record(R.string(),R.string()).optional().describe(`Request headers as key-value pairs`),body:R.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:R.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},Y(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Wt({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(`
3055
- `)}]}}catch(e){return Ty.error(`HTTP request failed`,M(e)),J(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function ky(e){let t=G(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:R.string().max(500).describe(`Regex pattern (without delimiters)`),flags:R.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:R.array(R.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:R.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:R.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},Y(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=bn({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return J(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
3056
- `)}]}}))}function Ay(e){let t=G(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:R.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:R.string().max(1e6).describe(`Input text`)},annotations:t.annotations},Y(`encode`,async({operation:e,input:t})=>{try{let n=Et({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 Ty.error(`Encode failed`,M(e)),J(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function jy(e){let t=G(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:rc,inputSchema:{path:R.string().describe(`File or directory path to measure`),extensions:R.array(R.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),include_hidden:R.boolean().optional().describe(`Include hidden trees such as .generated and .cache. Default false.`),max_tokens:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},Y(`measure`,async({path:e,extensions:t,include_hidden:n,max_tokens:r})=>{try{let i=await tn({path:e,extensions:t,includeHidden:n}),a=[`## Code Metrics`,``,`**Files:** ${i.summary.totalFiles}`,`**Total lines:** ${i.summary.totalLines} (${i.summary.totalCodeLines} code)`,`**Functions:** ${i.summary.totalFunctions}`,`**Avg complexity:** ${i.summary.avgComplexity}`,`**Max complexity:** ${i.summary.maxComplexity.value} (${i.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of i.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);a.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}i.files.length>20&&a.push(``,`_...and ${i.files.length-20} more files_`);let o={summary:{totalFiles:i.summary.totalFiles,totalLines:i.summary.totalLines,totalCodeLines:i.summary.totalCodeLines,totalFunctions:i.summary.totalFunctions,avgComplexity:i.summary.avgComplexity,maxComplexity:{value:i.summary.maxComplexity.value,file:i.summary.maxComplexity.file}},files:i.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r?L(a.join(`
3044
+ `)}const my=5*6e4;let hy=null,gy=null;function _y(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 vy(){let e=Date.now();if(hy&&e-hy.ts<my)return hy.value;try{let t=I($n(),`.copilot`,`.aikit-scaffold.json`);if(!N(t))return hy={value:null,ts:e},null;let n=JSON.parse(P(t,`utf-8`)).version??null;return hy={value:n,ts:e},n}catch{return hy={value:null,ts:e},null}}function yy(){let e=Date.now();if(gy&&e-gy.ts<my)return gy.value;try{let t=I(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!N(t))return gy={value:null,ts:e},null;let n=JSON.parse(P(t,`utf-8`)).version??null;return gy={value:n,ts:e},n}catch{return gy={value:null,ts:e},null}}function by(e){let t=G(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:uy,annotations:t.annotations},Y(`status`,async()=>{let e=oe(),t=vy(),n=yy(),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)**: ${yr.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=se(),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`?(ie(),a.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${c}`,`- Error: ${o.error??`unknown`}`)):(ie(),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:!!yr.get(),wasmDiagnostics:vr.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||i,contextPressure:0,nextAction:fy({onboarded:!1,indexStale:!1,contextPressure:0})};return{content:[{type:`text`,text:a.join(`
3045
+ `)}],structuredContent:o}}))}function xy(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=G(`status`);e.registerTool(`status`,{title:g.title,description:`Get the current status and statistics of the AI Kit index.`,inputSchema:uy,annotations:g.annotations},Y(`status`,async({includePrelude:e=!1})=>{let g=[];try{let[_,v]=await Promise.all([dy(t.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),dy(t.listSourcePaths(),[],`store.listSourcePaths`)]),y=_.value;_.timedOut&&g.push(`⚠ Index stats timed out — values may be incomplete`);let b=v.value;v.timedOut&&g.push(`⚠ File listing timed out`);let x=null,S=0,C=[`## AI Kit Status`,``,`- **Total Records**: ${y.totalRecords}`,`- **Total Files**: ${y.totalFiles}`,`- **Last Indexed**: ${y.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(y.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...b.slice(0,50).map(e=>`- ${e}`),b.length>50?`\n... and ${b.length-50} more files`:``];if(n)try{let e=await dy(n.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)g.push(`⚠ Graph stats timed out`),C.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;x={nodes:t.nodeCount,edges:t.edgeCount},C.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await dy(n.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||C.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&C.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{C.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let w=a?.onboardDir??``,T=N(w),E=i?.onboardComplete||T;if(C.push(``,`### Onboard Status`,E?`- ✅ Complete${i?.onboardTimestamp?` (last: ${i.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${w}\``),r)try{let e=await dy(r.count(),0,`curated.count`);e.timedOut?(g.push(`⚠ Curated knowledge count timed out`),C.push(``,`### Curated Knowledge`,`- Listing timed out`)):(S=e.value,C.push(``,`### Curated Knowledge`,S>0?`- ${S} entries`:'- Empty — use `knowledge({ action: "remember", ... })` to persist decisions'))}catch{C.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let D=Jn().filter(e=>e.status===`watching`);if(D.length>0){C.push(``,`### File Watchers`,`- **Active**: ${D.length}`);for(let e of D){let t=e.pendingFiles?.length??0;if(C.push(` - \`${e.path}\`: ${e.eventCount} events, ${t} pending files`),t>0&&t<=10)for(let t of e.pendingFiles)C.push(` - \`${t}\``);else t>10&&C.push(` - ${t} pending files (use \`watch({ action: 'list' })\` for details)`)}}let O=_y(y.totalRecords,x?.nodes??0,x?.edges??0,S),k=y.lastIndexedAt?new Date(y.lastIndexedAt).getTime():0,ee=k>0?Date.now()-k:1/0,te=fy({onboarded:E,indexStale:E&&ee>1440*60*1e3,contextPressure:O});C.push(``),C.push(`## 📊 Context Pressure: ${O}/100`),O>=80?C.push(`⚠️ High pressure — consider pruning stale entries or compacting context.`):O>=50?C.push(`ℹ️ Moderate pressure — AI Kit memory is well-populated.`):C.push(`✅ Low pressure — plenty of headroom for more content.`);let ne=0;if(y.lastIndexedAt){ne=new Date(y.lastIndexedAt).getTime();let e=(Date.now()-ne)/(1e3*60*60);C.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`)}C.push(``,`### Next Action`,`- **${te.kind}**: ${te.reason}`);let re=null,ae=t;if(typeof ae.getDiagnostics==`function`)try{let e=ae.getDiagnostics();re={adapterType:e.adapterType,vectorSearchEnabled:e.vectorSearchEnabled,ftsEnabled:e.ftsEnabled,degradedMode:e.degradedMode,dbPath:e.dbPath,dbSizeBytes:e.dbSizeBytes,embeddingDim:e.embeddingDim,vectorDtype:e.vectorDtype},C.push(``,`### Storage`,`- **Backend**: ${a?.store?.backend??`unknown`}`,`- **Adapter**: ${re.adapterType}`,`- **Vector search**: ${re.vectorSearchEnabled?`✅ enabled`:`⚠ disabled (FTS-only fallback)`}`,re.dbPath?`- **DB**: ${re.dbPath}`:``,re.dbSizeBytes==null?``:`- **DB size**: ${(re.dbSizeBytes/1024/1024).toFixed(2)} MB`,`- **Embedding dim**: ${re.embeddingDim}`,`- **Vector dtype**: ${re.vectorDtype}`)}catch{}if(o===`smart`)if(C.push(``,`### Smart Indexing`),s){let e=s();e?C.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}`):C.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else C.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);if(h)try{let e=h.getReport(),t=h.checkThresholds(),n=Object.entries(e.counters),r=Object.entries(e.gauges);if(n.length>0||r.length>0||t.length>0){if(C.push(``,`### 📊 Metrics`),n.length>0){C.push(`**Counters:**`);for(let[e,t]of n)C.push(`- \`${e}\`: ${t}`)}if(r.length>0){C.push(`**Gauges:**`);for(let[e,t]of r)C.push(`- \`${e}\`: ${t}`)}if(t.length>0){C.push(`**⚠ Threshold violations:**`);for(let e of t)C.push(`- ${e}`)}else(n.length>0||r.length>0)&&C.push(`- ✅ All thresholds within limits`)}}catch{C.push(``,`### 📊 Metrics`,`- Metrics unavailable`)}{let e=[];if(u)try{let t=u.getStats();e.push(`- **Decision Hooks**: ${t.count} registered${t.hooks.length>0?` (IDs: ${t.hooks.map(e=>e.id).join(`, `)})`:``}`)}catch{e.push(`- **Decision Hooks**: unavailable`)}else e.push(`- **Decision Hooks**: not configured`);if(d)try{let t=d.getStats(),n=Object.entries(t.byTool).map(([e,t])=>`${e}=${t}`).join(`, `);e.push(`- **Observations**: ${t.totalObservations} total, byTool: ${n||`none`}`)}catch{e.push(`- **Observations**: unavailable`)}else e.push(`- **Observations**: not configured`);if(f)try{let t=f.getStats(),n=Object.keys(t.byName);e.push(`- **Extractors**: ${t.count} registered${n.length>0?` (IDs: ${n.join(`, `)})`:``}`)}catch{e.push(`- **Extractors**: unavailable`)}else e.push(`- **Extractors**: not configured`);if(m)try{let t=m.getStats(),n=t.cardExists?t.isStale?`⚠ Stale`:`✅ Fresh`:`❌ No card`;e.push(`- **L0 Compiler**: ${n}, last compiled: ${t.lastCompiledAt?new Date(t.lastCompiledAt).toLocaleString():`Never`}`)}catch{e.push(`- **L0 Compiler**: unavailable`)}else e.push(`- **L0 Compiler**: not configured`);if(p)try{let t=p.getStats();e.push(`- **Promotion Engine**: ${t.held} candidates held, ${t.promoted} promoted, ${t.observedFacts} distinct facts tracked`)}catch{e.push(`- **Promotion Engine**: unavailable`)}else e.push(`- **Promotion Engine**: not configured`);C.push(``,`### 🧩 Feature Coverage`,...e)}let ce=0;{try{let e=a?.stateDir?F(a.stateDir,`stash`):null;if(e&&N(e)){let t=Pe(e).mtimeMs;t>ne&&(ne=t)}}catch{}let e=[];if(r)try{let t=S>0?await r.list({limit:5,orderBy:`updated`,order:`desc`}):[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>ne&&(ne=t)}e.push(...t)}catch{}if(ce=ne>0?Date.now()-ne:0,ce>=ly){let t=Math.floor(ce/36e5);if(C.push(``,`### 🌅 Session Briefing`,`_${t}+ hours since last activity — here's what to pick up:_`,``),e.length>0){C.push(`**Recent decisions/notes:**`);for(let t of e)C.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}C.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')}}C.push(``,`### Runtime`,py());let le=ge.instance().getAll(),ue=le.filter(e=>e.status!==`healthy`);if(ue.length>0){C.push(``,`### ⚠️ Subsystem Health`);for(let e of ue){let t=Math.round((Date.now()-e.since)/1e3);C.push(`- **${e.name}**: ${e.status} (${t}s ago${e.reason?` — ${e.reason}`:``})`)}}else le.length>0&&C.push(``,`### ✅ Subsystem Health`,`- All ${le.length} subsystems healthy`);let de=me.getAll();if(de.size>0){C.push(``,`### 🔌 Circuit Breakers`);for(let[e,t]of de){let n=t.getState(),r=`- **${e}**: ${n===`closed`?`🟢`:n===`open`?`🔴`:`🟡`} ${n}`;if(n===`open`){let e=t.remainingCooldownMs();r+=` (recovery in ${Math.ceil(e/1e3)}s)`}C.push(r)}}let fe=vy(),pe=yy(),he=oe(),_e=fe!=null&&fe!==he,ve=pe!=null&&pe!==he;if(_e||ve){let e=se(),t=[];_e&&t.push(`user scaffold v${fe}`),ve&&t.push(`workspace scaffold v${pe}`);let n=t.join(`, `);e.state===`success`?C.push(``,`### ✅ Upgrade Applied`,`- Server v${he} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?C.push(``,`### ⏳ Upgrade In Progress`,`- Server v${he} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(ie(),C.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${he} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(ie(),C.push(``,`### ⬆ Upgrade Available`,`- Server v${he} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}g.length>0&&C.push(``,`### ⚠ Warnings`,...g.map(e=>`- ${e}`));let ye=$v();if(ye.length>0){let e=ye.sort((e,t)=>t.callCount-e.callCount);C.push(``,`### Tool Usage This Session`,``),C.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),C.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);C.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let A=Xv();A.callCount>0&&(C.push(``),C.push(`### Session Token Usage`),C.push(`- Tool calls: ${A.callCount}`),C.push(`- Input chars: ${A.totalInputChars.toLocaleString()}`),C.push(`- Output chars: ${A.totalOutputChars.toLocaleString()}`),C.push(`- Est. input tokens: ${Math.round(A.totalInputChars/4).toLocaleString()}`),C.push(`- Est. total tokens: ${Math.round((A.totalInputChars+A.totalOutputChars)/4).toLocaleString()}`));let be=ny();if(be.bufferSize>=10){let e=be.state===`healthy`?`🟢`:be.state===`degraded`?`🔴`:`🟡`;C.push(``,`### Auto-GC: ${e} ${be.state}`),C.push(`- p95 latency: ${be.p95}ms | buffer: ${be.bufferSize} samples`),be.gcCount>0&&C.push(`- GC cycles triggered: ${be.gcCount}`)}if(l){let e=l.getStats();if(e.totalSubscribers>0){C.push(``,`### 🔌 Hooks (EventBus Subscribers)`),C.push(`- Total subscribers: ${e.totalSubscribers}`);for(let[t,n]of Object.entries(e.byEvent))C.push(` - ${t}: ${n} subscriber(s)`);for(let t of e.subscriptions)C.push(` - ${t.name} (${t.eventType}, ${t.policy})`);if(e.autoDisabled.length>0){C.push(``),C.push(` **Auto-disabled subscribers:**`);for(let t of e.autoDisabled)C.push(` - ${t.name} (${t.id}): ${t.reason}`)}}}if(u&&u.size>0){let e=u.getStats();C.push(``,`### 🪝 Decision Hooks`),C.push(`- Total hooks: ${e.count}`);for(let t of e.hooks){let e=t.decisionTypes.join(`, `);C.push(` - ${t.id} (order=${t.order}, policy=${t.failurePolicy}, types=[${e}])`)}}if(d){let e=d.getStats();C.push(``,`### 👁 Observations`),C.push(`- Total observations: ${e.totalObservations}`),C.push(` - Success: ${e.byError.success}, Error: ${e.byError.error}`),C.push(` - Artifacts stored: ${e.artifactCount}`),C.push(` - Truncations: ${e.truncationCount}`),C.push(` - Store entries: ${e.storeSize}`);let t=Object.entries(e.byOrigin);t.length>0&&C.push(` - By origin: ${t.map(([e,t])=>`${e}=${t}`).join(`, `)}`)}if(f){let e=f.getStats();C.push(``,`### 🧩 Extractors`),C.push(`- Total extractors: ${e.count}`);for(let[t,n]of Object.entries(e.byName))C.push(` - ${t} (${n.tools} tool(s), maxFacts: ${n.maxFactsPerEvent??`default`})`)}if(p){let e=p.getStats();if(C.push(``,`### 🏆 Promotion Engine`),C.push(`- Total evaluated: ${e.totalEvaluated}`),C.push(`- Promoted: ${e.promoted}`),C.push(`- Held: ${e.held}`),C.push(`- Rejected: ${e.rejected}`),C.push(`- Superseded: ${e.superseded}`),C.push(`- Decayed: ${e.decayed}`),C.push(`- Distinct facts tracked: ${e.observedFacts}`),e.recentDecisions.length>0){C.push(` Recent decisions:`);for(let t of e.recentDecisions.slice(-5))C.push(` - ${t.decision.status}: "${t.factTitle}" (${t.decision.reason.slice(0,80)})`)}}if(m){let e=m.getStats();C.push(``,`### 📋 L0 Briefing Card`),C.push(`- **Card exists**: ${e.cardExists?`✅`:`❌`}`),C.push(`- **Stale**: ${e.isStale?`⚠ Yes — regenerating on next trigger`:`✅ Fresh`}`),C.push(`- **Last compiled**: ${e.lastCompiledAt?new Date(e.lastCompiledAt).toLocaleString():`Never`}`),C.push(`- **Total compiles**: ${e.totalCompiles}`),e.failedCompiles>0&&C.push(`- **Failed compiles**: ${e.failedCompiles}`),e.cardSize>0&&C.push(`- **Card size**: ${e.cardSize} bytes`),e.isCompiling&&C.push(`- ⏳ **Currently compiling**`),e.pendingRegeneration&&C.push(`- ⏳ **Regeneration pending**`)}{let e=Lt();(e.cacheSize>0||e.refReuseCount>0)&&(C.push(``,`### 🔄 Ref Reuse`),C.push(`- **Refs stored**: ${e.refStoreCount}`),C.push(`- **Refs reused**: ${e.refReuseCount}`),e.refStaleCount>0&&C.push(`- **⚠ Stale refs detected**: ${e.refStaleCount}`),C.push(`- **Cache entries**: ${e.cacheSize}`))}let xe=C.join(`
3046
+ `),j=ce>=ly,Se=[a?.onboardDir?Dn(I(a.onboardDir,`..`)):void 0,a?.l0CardDir].filter(e=>typeof e==`string`&&e.length>0),Ce=e||j?await oy(r,c,void 0,Se.length>0?Se:void 0):void 0,we=D.length>0?D.map(e=>({id:e.id,path:e.path,eventCount:e.eventCount,pendingFiles:e.pendingFiles??[]})):void 0,Te={totalRecords:y.totalRecords,totalFiles:y.totalFiles,lastIndexedAt:y.lastIndexedAt??null,onboarded:E,onboardDir:w,contentTypes:y.contentTypeBreakdown,wasmAvailable:!!yr.get(),wasmDiagnostics:vr.get(),graphStats:x,curatedCount:S,serverVersion:he,scaffoldVersion:fe??null,workspaceScaffoldVersion:pe??null,upgradeAvailable:_e||ve,storeBackend:a?.store?.backend,storeDiagnostics:re??null,contextPressure:O,nextAction:te,watchers:we,sessionTokens:{callCount:A.callCount,totalInputChars:A.totalInputChars,totalOutputChars:A.totalOutputChars,estInputTokens:Math.round(A.totalInputChars/4),estTotalTokens:Math.round((A.totalInputChars+A.totalOutputChars)/4),startTime:A.startTime},...Ce===void 0?{}:{prelude:Ce}};return{content:[{type:`text`,text:xe+(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:Te}}catch(e){return cy.error(`Status failed`,M(e)),J(`INTERNAL`,`Status check failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Sy=j(`tools`);function Cy(e){return e instanceof Error?(`code`in e?e.code:void 0)===`ENOENT`||e.message.startsWith(`File not found:`)||e.message.startsWith(`Path not found:`):!1}function wy(e){let t=G(`web_search`);e.registerTool(`web_search`,{title:t.title,description:`PREFERRED web search — fans out to multiple keyless providers (DuckDuckGo + Bing-HTML + Mojeek) by default, returning a deduplicated, consensus-ranked union within a 10s deadline. Optional providers (SearXNG, Google, Brave, Bing API) join the fan-out automatically when their env vars are set. Pass one query or multiple for parallel searching.`,inputSchema:{queries:R.array(R.string().max(2e3)).min(1).max(5).describe('Search queries (1–5). Single: `["react hooks"]`. Multiple searched in parallel.'),limit:R.number().min(1).max(20).default(5).describe(`Max results per query`),site:R.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`),provider:R.enum([`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`]).optional().describe("Search provider. Defaults to env AIKIT_SEARCH_PROVIDER, then `multi` (fan-out). Single keyless: `duckduckgo`, `bing-html`, `mojeek`. Self-hosted: `searxng` (requires SEARXNG_URL). Keyed APIs: `google` (GOOGLE_API_KEY+GOOGLE_CSE_ID), `brave` (BRAVE_API_KEY), `bing` (BING_API_KEY). Missing keys auto-fall back to duckduckgo.")},annotations:t.annotations},Y(`web_search`,async({queries:e,limit:t,site:n,provider:r})=>{let i=e,a=async e=>{let i=await Qn({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(`
3047
+ `)};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 Sy.error(`Web search failed`,M(e)),J(`INTERNAL`,`Web search failed: ${e instanceof Error?e.message:String(e)}`)}let o=await Promise.allSettled(i.map(e=>a(e))),s=[],c=0;for(let e=0;e<o.length;e++){let t=o[e];if(t.status===`fulfilled`)s.push(t.value);else{c++;let n=t.reason instanceof Error?t.reason.message:String(t.reason);Sy.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(`
3048
+
3049
+ `);return c===o.length?J(`INTERNAL`,u):{content:[{type:`text`,text:u}]}}))}function Ty(e){let t=G(`http`);e.registerTool(`http`,{title:t.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:R.string().url().describe(`Request URL (http/https only)`),method:R.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:R.record(R.string(),R.string()).optional().describe(`Request headers as key-value pairs`),body:R.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:R.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:t.annotations},Y(`http`,async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await Wt({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(`
3050
+ `)}]}}catch(e){return Sy.error(`HTTP request failed`,M(e)),J(`INTERNAL`,`HTTP request failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Ey(e){let t=G(`regex_test`);e.registerTool(`regex_test`,{title:t.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:R.string().max(500).describe(`Regex pattern (without delimiters)`),flags:R.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:R.array(R.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:R.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:R.string().optional().describe(`Replacement string (for replace mode)`)},annotations:t.annotations},Y(`regex_test`,async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=bn({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return J(`VALIDATION`,`Invalid regex: ${a.error}`);let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
3051
+ `)}]}}))}function Dy(e){let t=G(`encode`);e.registerTool(`encode`,{title:t.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:R.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:R.string().max(1e6).describe(`Input text`)},annotations:t.annotations},Y(`encode`,async({operation:e,input:t})=>{try{let n=Et({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 Sy.error(`Encode failed`,M(e)),J(`INTERNAL`,`Encode failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Oy(e){let t=G(`measure`);e.registerTool(`measure`,{title:t.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:rc,inputSchema:{path:R.string().describe(`File or directory path to measure`),extensions:R.array(R.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`),include_hidden:R.boolean().optional().describe(`Include hidden trees such as .generated and .cache. Default false.`),max_tokens:R.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:t.annotations},Y(`measure`,async({path:e,extensions:t,include_hidden:n,max_tokens:r})=>{try{let i=await tn({path:e,extensions:t,includeHidden:n}),a=[`## Code Metrics`,``,`**Files:** ${i.summary.totalFiles}`,`**Total lines:** ${i.summary.totalLines} (${i.summary.totalCodeLines} code)`,`**Functions:** ${i.summary.totalFunctions}`,`**Avg complexity:** ${i.summary.avgComplexity}`,`**Max complexity:** ${i.summary.maxComplexity.value} (${i.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of i.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);a.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}i.files.length>20&&a.push(``,`_...and ${i.files.length-20} more files_`);let o={summary:{totalFiles:i.summary.totalFiles,totalLines:i.summary.totalLines,totalCodeLines:i.summary.totalCodeLines,totalFunctions:i.summary.totalFunctions,avgComplexity:i.summary.avgComplexity,maxComplexity:{value:i.summary.maxComplexity.value,file:i.summary.maxComplexity.file}},files:i.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r?L(a.join(`
3057
3052
  `),r):a.join(`
3058
- `)}],structuredContent:o}}catch(e){return Ey(e)?(Ty.warn(`Measure failed`,{error:`File not found`}),J(`NOT_FOUND`,`File not found`)):(Ty.error(`Measure failed`,M(e)),J(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function My(e){let t=G(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:R.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:R.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:R.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:R.boolean().default(!0).describe(`Highlight breaking changes`),cwd:R.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},Y(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=ot({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 Ty.error(`Changelog failed`,M(e)),J(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Ny(e){let t=G(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:R.string().max(5e5).describe(`JSON data to validate (as string)`),schema:R.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},Y(`schema_validate`,async({data:e,schema:t})=>{try{let n=Mn({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
3053
+ `)}],structuredContent:o}}catch(e){return Cy(e)?(Sy.warn(`Measure failed`,{error:`File not found`}),J(`NOT_FOUND`,`File not found`)):(Sy.error(`Measure failed`,M(e)),J(`INTERNAL`,`Measure failed: ${e instanceof Error?e.message:String(e)}`))}}))}function ky(e){let t=G(`changelog`);e.registerTool(`changelog`,{title:t.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:R.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:R.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:R.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:R.boolean().default(!0).describe(`Highlight breaking changes`),cwd:R.string().optional().describe(`Repository root or working directory`)},annotations:t.annotations},Y(`changelog`,async({from:e,to:t,format:n,include_breaking:r,cwd:i})=>{try{let a=ot({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 Sy.error(`Changelog failed`,M(e)),J(`INTERNAL`,`Changelog failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Ay(e){let t=G(`schema_validate`);e.registerTool(`schema_validate`,{title:t.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:R.string().max(5e5).describe(`JSON data to validate (as string)`),schema:R.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:t.annotations},Y(`schema_validate`,async({data:e,schema:t})=>{try{let n=Mn({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
3059
3054
 
3060
3055
  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(`
3061
- `)}]}}catch(e){return Ty.error(`Schema validation failed`,M(e)),J(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function Py(e){let t=G(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:ic,inputSchema:{include_env:R.boolean().default(!1).describe(`Include environment variables`),filter_env:R.string().optional().describe(`Filter env vars by name substring`),show_sensitive:R.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},Y(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Dt({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(`
3062
- `)}],structuredContent:a}}))}function Fy(e){let t=G(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:ac,inputSchema:{operation:R.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:R.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:R.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:R.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},Y(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Kn({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(`
3063
- `)}],structuredContent:o}}catch(e){return Ty.error(`Time failed`,M(e)),J(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Iy=j(`register-tools`);function Ly(e){try{let t=F(e,`.flows`);if(!N(t))return null;let n=je(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=F(t,e.name,`meta.json`);if(N(n)&&JSON.parse(P(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function Ry(e){let{server:t,aikit:n,config:r,elicitor:i,resourceNotifier:a,samplingClient:o,indexMode:s,getSmartState:c,getSmartScheduler:l,precomputedActiveTools:u}=e,d=new is,f=r.sources[0]?.path??Oe(),p=xe(f),m={activeSlug:null};m.activeSlug=Ly(f);let h=new bo(F(r.stateDir??``,`flow-context`),()=>m.activeSlug),g=new ro;g.register(Qi()),g.register(Xa),g.register(ua),g.register(Fa),g.register(aa),g.register($i),g.register(ea),g.register(qa),g.register(na),g.register(eo),g.register(Pa(()=>m.activeSlug?{active:!0,slug:m.activeSlug}:null)),g.register(za),g.register(Qa),g.register(sa),g.register(La);let _=new Po,v=n.eventBus,y=r.l0CardDir?new wo(r.l0CardDir,{debounceMs:5e3},v??void 0,n.curated):null,b=new so(g,n.curated,{},h,_,v??void 0),x=u??Zs(r,[...ho,...bs],W,Ss(r)),S=e=>x.has(e),C=new Set([...x].filter(e=>!Xp.includes(e)&&!Eo.has(e))),w=new Ao;d.use(Ts(),{order:1,name:`structured-content-guard`}),d.use(yo(vo(r.tokenBudget)),{order:90,name:`compression`});let T=d.decisionHookRegistry;T.register({id:`search-budget`,order:10,scope:`search`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`budgetHint`],reason:`Enforce token budget on search results`,fn:()=>({type:`decision`,hookId:`search-budget`,decision:`allow`,reason:`Budget hook active`})}),T.register({id:`find-path-containment`,order:10,scope:`find`,timeoutMs:50,failurePolicy:`fail-closed`,decisionTypes:[`deny`],reason:`Validate find scope against workspace boundaries`,fn:()=>({type:`decision`,hookId:`find-path-containment`,decision:`allow`,reason:`Path permitted`})}),T.register({id:`knowledge-mutation-safety`,order:10,scope:`knowledge`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`deny`],reason:`Guard against unintended knowledge mutations`,fn:()=>({type:`decision`,hookId:`knowledge-mutation-safety`,decision:`allow`,reason:`Mutation permitted`})}),T.register({id:`check-scoped-run`,order:10,scope:`check`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log check run scope for audit`,fn:()=>({type:`decision`,hookId:`check-scoped-run`,decision:`allow`,reason:`Check run permitted`})}),T.register({id:`test-run-scoped`,order:10,scope:`test_run`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log test run scope for audit`,fn:()=>({type:`decision`,hookId:`test-run-scoped`,decision:`allow`,reason:`Test run permitted`})}),T.register({id:`onboard-path-correctness`,order:10,scope:`onboard`,timeoutMs:50,failurePolicy:`fail-closed`,decisionTypes:[`deny`],reason:`Validate onboard target path is valid and accessible`,fn:()=>({type:`decision`,hookId:`onboard-path-correctness`,decision:`allow`,reason:`Path valid`})}),T.register({id:`compact-budget-hints`,order:10,scope:`compact`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`budgetHint`],reason:`Enforce token budget on compact output`,fn:()=>({type:`decision`,hookId:`compact-budget-hints`,decision:`allow`,reason:`Budget hook active`})}),T.register({id:`flow-step-safety`,order:10,scope:`flow`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log flow step transitions`,fn:()=>({type:`decision`,hookId:`flow-step-safety`,decision:`allow`,reason:`Step permitted`})}),T.register({id:`present-transport-capability`,order:10,scope:`present`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Verify presentation transport is available`,fn:()=>({type:`decision`,hookId:`present-transport-capability`,decision:`allow`,reason:`Transport available`})});let E=new ss(r.metricThresholds);Is(t,d,r.toolPrefix??``,n.eventBus,()=>{let e=r.sources[0]?.path??Oe();try{return xe(e)}catch{return`partition:${Ye(`sha256`).update(e).digest(`hex`).slice(0,8)}`}}),v&&(v.subscribe({id:`sub-auto-knowledge`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`args`in e)||!(`result`in e))return;let t=e;try{E.incrementCounter(`tool.call`,{tool:t.toolName}),t.isError&&E.incrementCounter(`tool.error`,{tool:t.toolName}),b.push({toolName:t.toolName,args:t.args,result:t.result,durationMs:t.durationMs,isError:t.isError,timestamp:new Date(t.timestamp).toISOString(),origin:t.origin,workspaceId:t.workspaceId,requestId:t.requestId})}catch{}},name:`auto-knowledge`}),v.subscribe({id:`sub-replay`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`args`in e)||!(`result`in e))return;let t=e;try{let{replayAppend:e}=await import(`../../tools/dist/index.js`),n=JSON.stringify(t.args),r=JSON.stringify(t.result);e({ts:new Date(t.timestamp).toISOString(),source:`mcp`,tool:t.toolName,input:n.slice(0,2e3),outputChars:r.length,inputChars:n.length,durationMs:t.durationMs,status:t.isError?`error`:`ok`,output:r.slice(0,2e3),traceId:t.requestId??``})}catch{}},name:`replay`}),v.subscribe({id:`sub-procedural`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`isError`in e))return;let t=e;try{C.has(t.toolName)&&w.record(t.toolName,!t.isError)}catch{}},name:`procedural-memory`}),v.subscribe({id:`sub-observations`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`result`in e))return;let t=e;try{let{ObservationEngine:e,DEFAULT_OBSERVATION_CONFIG:r}=await import(`./observations-CfglxBMB.js`),i=new e(n.stateStore,n.curated),{captureFrom:a}=r;a.includes(t.toolName)&&await i.processToolResult(t.toolName,t.result,{})}catch{}},name:`observation-capture`}),v.subscribe({id:`sub-knowledge-metrics`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`result`in e))return;let t=e;if(t.toolName===`knowledge`)try{let e=t.result,n=t.args?.action;(n===`remember`||n===`update`)&&(E.incrementCounter(`fact.total`),(e?.status===`unchanged`||e?.result===`unchanged`)&&E.incrementCounter(`fact.duplicate`))}catch{}},name:`knowledge-metrics`}),v.subscribe({id:`sub-session`,eventType:`session:start`,policy:`async`,handler:async e=>{let t=e,n={serverVersion:t.serverVersion,workspaceRoot:t.workspaceRoot,handoff:t.handoff?`${t.handoff.from} (session ${t.handoff.sessionId})`:void 0};Iy.info(`Session started`,n)},name:`session-lifecycle`}),y&&y.subscribeToEventBus(v));let D=[...x].filter(e=>xs.has(e)?ys.includes(e)?!!n.bridge:e===`er_update_policy`?!!n.policyStore:e===`er_evolve_review`?!!n.evolutionCollector:!1:!0);S(`search`)&&Mv(t,n.embedder,n.store,n.graphStore,n.bridge,n.evolutionCollector,o,n.stateStore,r.memory?.retention,r.memory?.consolidation,p);let O={store:n.store,graphStore:n.graphStore,embedder:n.embedder};S(`lookup`)&&Pp(t,n.store,O);let k={onboardComplete:n.onboardComplete,onboardTimestamp:n.onboardTimestamp};S(`status`)&&wy(t,n.store,n.graphStore,n.curated,k,r,s,c,n.stateStore,n.eventBus,d.decisionHookRegistry,d.getObservationCompressor(),g,_,y,E),S(`config`)&&Jl(t,r),S(`reindex`)&&uv(t,n.indexer,r,n.curated,n.store,a,s),S(`knowledge`)&&Mp(t,n.curated,n.policyStore,n.evolutionCollector,a,h,n.stateStore,r.memory?.retention,r.memory?.supersession,r.memory?.consolidation,r.memory?.lessons,O,n.graphStore),S(`memory_explain`)&&Yp(t,n.embedder,n.store),S(`analyze`)&&fl(t,n.store,n.embedder,O),S(`blast_radius`)&&pl(t,n.store,n.embedder,n.graphStore,O),S(`produce_knowledge`)&&cv(t,a),S(`onboard`)&&vm(t,n.store,n.embedder,r,k,O,o,a),S(`graph`)&&Fd(t,n.graphStore,O),S(`audit`)&&vl(t,n.store,n.embedder,r.tokenBudget),S(`scope_map`)&&cu(t,n.embedder,n.store,O),S(`find`)&&lu(t,n.embedder,n.store,f,O,p),S(`parse_output`)&&bu(t),S(`workset`)&&bm(t),S(`check`)&&_u(t,O,r.tokenBudget),S(`symbol`)&&uu(t,n.embedder,n.store,n.graphStore,O),S(`eval`)&&vu(t),S(`test_run`)&&yu(t,O),S(`stash`)&&xm(t,n.stateStore),S(`signal`)&&Zv(t,n.stateStore),S(`git_context`)&&Rp(t),S(`diff_parse`)&&zp(t),S(`rename`)&&Bp(t,r),S(`codemod`)&&Vp(t,r),S(`restore`)&&mv(t),S(`file_summary`)&&wu(t,n.embedder,n.fileCache),S(`checkpoint`)&&Sm(t,n.stateStore),S(`data_transform`)&&Hp(t),S(`trace`)&&du(t,n.embedder,n.store,n.graphStore,O),S(`process`)&&Ld(t),S(`watch`)&&Rd(t),S(`dead_symbols`)&&fu(t,n.embedder,n.store,f,r.allRoots,O),S(`delegate`)&&xu(t,o),S(`health`)&&zd(t),S(`lane`)&&Cm(t),S(`queue`)&&wm(t),S(`web_fetch`)&&Bd(t),S(`guide`)&&Vd(t,s),Xp.some(e=>S(e))&&Zp(t,r,D),S(`evidence_map`)&&Od(t),S(`digest`)&&kd(t,n.embedder),S(`forge_classify`)&&Ad(t,O),S(`forge_ground`)&&jd(t,n.embedder,n.store),S(`present`)&&ov(t,i),S(`browser`)&&lr(t,r),S(`web_search`)&&Dy(t),S(`http`)&&Oy(t),S(`regex_test`)&&ky(t),S(`encode`)&&Ay(t),S(`measure`)&&jy(t),S(`changelog`)&&My(t),S(`schema_validate`)&&Ny(t),S(`env`)&&Py(t),S(`time`)&&Fy(t),S(`flow`)&&Ed(t,r,{store:n.store?{search:async(e,t)=>(await n.store.ftsSearch(e,t)).map(e=>({content:e.record.content}))}:null,graphStore:n.graphStore,embedder:n.embedder},e=>{m.activeSlug=e}),n.bridge&&ys.some(e=>S(e))&&(Sl(t,n.bridge,n.evolutionCollector),Cl(t,n.bridge),wl(t,n.bridge)),n.policyStore&&S(`er_update_policy`)&&Am(t,n.policyStore),n.evolutionCollector&&S(`er_evolve_review`)&&hu(t,n.evolutionCollector),vs(t,n.store,n.curated,r.l0CardDir,n.eventBus,d.decisionHookRegistry,y),S(`compliance_score`)&&Dl(t),S(`replay`)&&fv(t),S(`session_digest`)&&Pv(t,n.stateStore,o)}function zy(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&_u(e,void 0,t.tokenBudget),r(`eval`)&&vu(e),r(`test_run`)&&yu(e),r(`parse_output`)&&bu(e),r(`delegate`)&&xu(e),r(`git_context`)&&Rp(e),r(`diff_parse`)&&zp(e),r(`rename`)&&Bp(e,t),r(`codemod`)&&Vp(e,t),r(`data_transform`)&&Hp(e),r(`workset`)&&bm(e),r(`restore`)&&mv(e),r(`lane`)&&Cm(e),r(`queue`)&&wm(e),r(`session_digest`)&&Pv(e),r(`health`)&&zd(e),r(`process`)&&Ld(e),r(`watch`)&&Rd(e),r(`web_fetch`)&&Bd(e),r(`guide`)&&Vd(e),Xp.some(e=>r(e))&&Zp(e,t,[...n??new Set(ho)]),r(`evidence_map`)&&Od(e),r(`forge_classify`)&&Ad(e),r(`present`)&&ov(e),r(`browser`)&&lr(e,t),r(`produce_knowledge`)&&cv(e),r(`compliance_score`)&&Dl(e),r(`replay`)&&fv(e),r(`status`)&&Cy(e),r(`flow`)&&Ed(e,t),r(`web_search`)&&Dy(e),r(`http`)&&Oy(e),r(`regex_test`)&&ky(e),r(`encode`)&&Ay(e),r(`measure`)&&jy(e),r(`changelog`)&&My(e),r(`schema_validate`)&&Ny(e),r(`env`)&&Py(e),r(`time`)&&Fy(e)}const By=j(`resource-notifier`);var Vy=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){By.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyL0CardChanged(){await this.sendUpdate(`aikit://l0/workspace-core`),await this.sendUpdate(`aikit://l0`)}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){By.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const Hy=j(`server`);function Uy(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function Wy(n){Hy.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.embedding,a=ve[i.model],o={model:i.model,nativeDim:i.nativeDim??a?.nativeDim??he.nativeDim,dimensions:i.dimensions??a?.dimensions??he.dimensions,queryPrefix:i.queryPrefix??a?.queryPrefix??he.queryPrefix,pooling:i.pooling??a?.pooling??`mean`},s=n.store.path,c=Uy(process.env.AIKIT_SPLIT_STATE),l=F(s,`aikit.db`),u={splitEnabled:c,contentDbPath:l,controlDbPath:c?F(s,`aikit-control.db`):l},d=null;if(r===`sqlite-vec`){let e=u.contentDbPath;N(s)||Ae(s,{recursive:!0}),d=await Nr(e),Hy.debug(`SQLite adapter ready`,{type:d.type,vectorCapable:d.vectorCapable,dbPath:e}),d.vectorCapable||Hy.warn(`┌──────────────────────────────────────────────────────────────────┐
3056
+ `)}]}}catch(e){return Sy.error(`Schema validation failed`,M(e)),J(`INTERNAL`,`Schema validation failed: ${e instanceof Error?e.message:String(e)}`)}}))}function jy(e){let t=G(`env`);e.registerTool(`env`,{title:t.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:ic,inputSchema:{include_env:R.boolean().default(!1).describe(`Include environment variables`),filter_env:R.string().optional().describe(`Filter env vars by name substring`),show_sensitive:R.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:t.annotations},Y(`env`,async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=Dt({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(`
3057
+ `)}],structuredContent:a}}))}function My(e){let t=G(`time`);e.registerTool(`time`,{title:t.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:ac,inputSchema:{operation:R.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:R.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:R.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:R.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:t.annotations},Y(`time`,async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=Kn({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(`
3058
+ `)}],structuredContent:o}}catch(e){return Sy.error(`Time failed`,M(e)),J(`INTERNAL`,`Time failed: ${e instanceof Error?e.message:String(e)}`)}}))}const Ny=j(`register-tools`);function Py(e){try{let t=F(e,`.flows`);if(!N(t))return null;let n=je(t,{withFileTypes:!0});for(let e of n){if(!e.isDirectory())continue;let n=F(t,e.name,`meta.json`);if(N(n)&&JSON.parse(P(n,`utf-8`)).status===`active`)return e.name}}catch{return null}return null}function Fy(e){let{server:t,aikit:n,config:r,elicitor:i,resourceNotifier:a,samplingClient:o,indexMode:s,getSmartState:c,getSmartScheduler:l,precomputedActiveTools:u}=e,d=new is,f=r.sources[0]?.path??Oe(),p=xe(f),m={activeSlug:null};m.activeSlug=Py(f);let h=new bo(F(r.stateDir??``,`flow-context`),()=>m.activeSlug),g=new ro;g.register(Qi()),g.register(Xa),g.register(ua),g.register(Fa),g.register(aa),g.register($i),g.register(ea),g.register(qa),g.register(na),g.register(eo),g.register(Pa(()=>m.activeSlug?{active:!0,slug:m.activeSlug}:null)),g.register(za),g.register(Qa),g.register(sa),g.register(La);let _=new Po,v=n.eventBus,y=r.l0CardDir?new wo(r.l0CardDir,{debounceMs:5e3},v??void 0,n.curated):null,b=new so(g,n.curated,{},h,_,v??void 0),x=u??Zs(r,[...ho,...bs],W,Ss(r)),S=e=>x.has(e),C=new Set([...x].filter(e=>!Xp.includes(e)&&!Eo.has(e))),w=new Ao;d.use(Ts(),{order:1,name:`structured-content-guard`}),d.use(yo(vo(r.tokenBudget)),{order:90,name:`compression`});let T=d.decisionHookRegistry;T.register({id:`search-budget`,order:10,scope:`search`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`budgetHint`],reason:`Enforce token budget on search results`,fn:()=>({type:`decision`,hookId:`search-budget`,decision:`allow`,reason:`Budget hook active`})}),T.register({id:`find-path-containment`,order:10,scope:`find`,timeoutMs:50,failurePolicy:`fail-closed`,decisionTypes:[`deny`],reason:`Validate find scope against workspace boundaries`,fn:()=>({type:`decision`,hookId:`find-path-containment`,decision:`allow`,reason:`Path permitted`})}),T.register({id:`knowledge-mutation-safety`,order:10,scope:`knowledge`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`deny`],reason:`Guard against unintended knowledge mutations`,fn:()=>({type:`decision`,hookId:`knowledge-mutation-safety`,decision:`allow`,reason:`Mutation permitted`})}),T.register({id:`check-scoped-run`,order:10,scope:`check`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log check run scope for audit`,fn:()=>({type:`decision`,hookId:`check-scoped-run`,decision:`allow`,reason:`Check run permitted`})}),T.register({id:`test-run-scoped`,order:10,scope:`test_run`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log test run scope for audit`,fn:()=>({type:`decision`,hookId:`test-run-scoped`,decision:`allow`,reason:`Test run permitted`})}),T.register({id:`onboard-path-correctness`,order:10,scope:`onboard`,timeoutMs:50,failurePolicy:`fail-closed`,decisionTypes:[`deny`],reason:`Validate onboard target path is valid and accessible`,fn:()=>({type:`decision`,hookId:`onboard-path-correctness`,decision:`allow`,reason:`Path valid`})}),T.register({id:`compact-budget-hints`,order:10,scope:`compact`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`budgetHint`],reason:`Enforce token budget on compact output`,fn:()=>({type:`decision`,hookId:`compact-budget-hints`,decision:`allow`,reason:`Budget hook active`})}),T.register({id:`flow-step-safety`,order:10,scope:`flow`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Log flow step transitions`,fn:()=>({type:`decision`,hookId:`flow-step-safety`,decision:`allow`,reason:`Step permitted`})}),T.register({id:`present-transport-capability`,order:10,scope:`present`,timeoutMs:100,failurePolicy:`degrade-with-warning`,decisionTypes:[`allow`],reason:`Verify presentation transport is available`,fn:()=>({type:`decision`,hookId:`present-transport-capability`,decision:`allow`,reason:`Transport available`})});let E=new ss(r.metricThresholds);Is(t,d,r.toolPrefix??``,n.eventBus,()=>{let e=r.sources[0]?.path??Oe();try{return xe(e)}catch{return`partition:${Ye(`sha256`).update(e).digest(`hex`).slice(0,8)}`}}),v&&(v.subscribe({id:`sub-auto-knowledge`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`args`in e)||!(`result`in e))return;let t=e;try{E.incrementCounter(`tool.call`,{tool:t.toolName}),t.isError&&E.incrementCounter(`tool.error`,{tool:t.toolName}),b.push({toolName:t.toolName,args:t.args,result:t.result,durationMs:t.durationMs,isError:t.isError,timestamp:new Date(t.timestamp).toISOString(),origin:t.origin,workspaceId:t.workspaceId,requestId:t.requestId})}catch{}},name:`auto-knowledge`}),v.subscribe({id:`sub-replay`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`args`in e)||!(`result`in e))return;let t=e;try{let{replayAppend:e}=await import(`../../tools/dist/index.js`),n=JSON.stringify(t.args),r=JSON.stringify(t.result);e({ts:new Date(t.timestamp).toISOString(),source:`mcp`,tool:t.toolName,input:n.slice(0,2e3),outputChars:r.length,inputChars:n.length,durationMs:t.durationMs,status:t.isError?`error`:`ok`,output:r.slice(0,2e3),traceId:t.requestId??``})}catch{}},name:`replay`}),v.subscribe({id:`sub-procedural`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`isError`in e))return;let t=e;try{C.has(t.toolName)&&w.record(t.toolName,!t.isError)}catch{}},name:`procedural-memory`}),v.subscribe({id:`sub-observations`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`result`in e))return;let t=e;try{let{ObservationEngine:e,DEFAULT_OBSERVATION_CONFIG:r}=await import(`./observations-CfglxBMB.js`),i=new e(n.stateStore,n.curated),{captureFrom:a}=r;a.includes(t.toolName)&&await i.processToolResult(t.toolName,t.result,{})}catch{}},name:`observation-capture`}),v.subscribe({id:`sub-knowledge-metrics`,eventType:`tool:after`,policy:`async`,handler:async e=>{if(!(`toolName`in e)||!(`result`in e))return;let t=e;if(t.toolName===`knowledge`)try{let e=t.result,n=t.args?.action;(n===`remember`||n===`update`)&&(E.incrementCounter(`fact.total`),(e?.status===`unchanged`||e?.result===`unchanged`)&&E.incrementCounter(`fact.duplicate`))}catch{}},name:`knowledge-metrics`}),v.subscribe({id:`sub-session`,eventType:`session:start`,policy:`async`,handler:async e=>{let t=e,n={serverVersion:t.serverVersion,workspaceRoot:t.workspaceRoot,handoff:t.handoff?`${t.handoff.from} (session ${t.handoff.sessionId})`:void 0};Ny.info(`Session started`,n)},name:`session-lifecycle`}),y&&y.subscribeToEventBus(v));let D=[...x].filter(e=>xs.has(e)?ys.includes(e)?!!n.bridge:e===`er_update_policy`?!!n.policyStore:e===`er_evolve_review`?!!n.evolutionCollector:!1:!0);S(`search`)&&kv(t,n.embedder,n.store,n.graphStore,n.bridge,n.evolutionCollector,o,n.stateStore,r.memory?.retention,r.memory?.consolidation,p);let O={store:n.store,graphStore:n.graphStore,embedder:n.embedder};S(`lookup`)&&Pp(t,n.store,O);let k={onboardComplete:n.onboardComplete,onboardTimestamp:n.onboardTimestamp};S(`status`)&&xy(t,n.store,n.graphStore,n.curated,k,r,s,c,n.stateStore,n.eventBus,d.decisionHookRegistry,d.getObservationCompressor(),g,_,y,E),S(`config`)&&Jl(t,r),S(`reindex`)&&sv(t,n.indexer,r,n.curated,n.store,a,s),S(`knowledge`)&&Mp(t,n.curated,n.policyStore,n.evolutionCollector,a,h,n.stateStore,r.memory?.retention,r.memory?.supersession,r.memory?.consolidation,r.memory?.lessons,O,n.graphStore),S(`memory_explain`)&&Yp(t,n.embedder,n.store),S(`analyze`)&&fl(t,n.store,n.embedder,O),S(`blast_radius`)&&pl(t,n.store,n.embedder,n.graphStore,O),S(`produce_knowledge`)&&av(t,a),S(`onboard`)&&vm(t,n.store,n.embedder,r,k,O,o,a),S(`graph`)&&Fd(t,n.graphStore,O),S(`audit`)&&vl(t,n.store,n.embedder,r.tokenBudget),S(`scope_map`)&&cu(t,n.embedder,n.store,O),S(`find`)&&lu(t,n.embedder,n.store,f,O,p),S(`parse_output`)&&bu(t),S(`workset`)&&bm(t),S(`check`)&&_u(t,O,r.tokenBudget),S(`symbol`)&&uu(t,n.embedder,n.store,n.graphStore,O),S(`eval`)&&vu(t),S(`test_run`)&&yu(t,O),S(`stash`)&&xm(t,n.stateStore),S(`signal`)&&Jv(t,n.stateStore),S(`git_context`)&&Rp(t),S(`diff_parse`)&&zp(t),S(`rename`)&&Bp(t,r),S(`codemod`)&&Vp(t,r),S(`restore`)&&dv(t),S(`file_summary`)&&wu(t,n.embedder,n.fileCache),S(`checkpoint`)&&Sm(t,n.stateStore),S(`data_transform`)&&Hp(t),S(`trace`)&&du(t,n.embedder,n.store,n.graphStore,O),S(`process`)&&Ld(t),S(`watch`)&&Rd(t),S(`dead_symbols`)&&fu(t,n.embedder,n.store,f,r.allRoots,O),S(`delegate`)&&xu(t,o),S(`health`)&&zd(t),S(`lane`)&&Cm(t),S(`queue`)&&wm(t),S(`web_fetch`)&&Bd(t),S(`guide`)&&Vd(t,s),Xp.some(e=>S(e))&&Zp(t,r,D),S(`evidence_map`)&&Od(t),S(`digest`)&&kd(t,n.embedder),S(`forge_classify`)&&Ad(t,O),S(`forge_ground`)&&jd(t,n.embedder,n.store),S(`present`)&&rv(t,i),S(`browser`)&&lr(t,r),S(`web_search`)&&wy(t),S(`http`)&&Ty(t),S(`regex_test`)&&Ey(t),S(`encode`)&&Dy(t),S(`measure`)&&Oy(t),S(`changelog`)&&ky(t),S(`schema_validate`)&&Ay(t),S(`env`)&&jy(t),S(`time`)&&My(t),S(`flow`)&&Ed(t,r,{store:n.store?{search:async(e,t)=>(await n.store.ftsSearch(e,t)).map(e=>({content:e.record.content}))}:null,graphStore:n.graphStore,embedder:n.embedder},e=>{m.activeSlug=e}),n.bridge&&ys.some(e=>S(e))&&(Sl(t,n.bridge,n.evolutionCollector),Cl(t,n.bridge),wl(t,n.bridge)),n.policyStore&&S(`er_update_policy`)&&Am(t,n.policyStore),n.evolutionCollector&&S(`er_evolve_review`)&&hu(t,n.evolutionCollector),vs(t,n.store,n.curated,r.l0CardDir,n.eventBus,d.decisionHookRegistry,y),S(`compliance_score`)&&Dl(t),S(`replay`)&&lv(t),S(`session_digest`)&&jv(t,n.stateStore,o)}function Iy(e,t,n){let r=e=>!n||n.has(e);r(`check`)&&_u(e,void 0,t.tokenBudget),r(`eval`)&&vu(e),r(`test_run`)&&yu(e),r(`parse_output`)&&bu(e),r(`delegate`)&&xu(e),r(`git_context`)&&Rp(e),r(`diff_parse`)&&zp(e),r(`rename`)&&Bp(e,t),r(`codemod`)&&Vp(e,t),r(`data_transform`)&&Hp(e),r(`workset`)&&bm(e),r(`restore`)&&dv(e),r(`lane`)&&Cm(e),r(`queue`)&&wm(e),r(`session_digest`)&&jv(e),r(`health`)&&zd(e),r(`process`)&&Ld(e),r(`watch`)&&Rd(e),r(`web_fetch`)&&Bd(e),r(`guide`)&&Vd(e),Xp.some(e=>r(e))&&Zp(e,t,[...n??new Set(ho)]),r(`evidence_map`)&&Od(e),r(`forge_classify`)&&Ad(e),r(`present`)&&rv(e),r(`browser`)&&lr(e,t),r(`produce_knowledge`)&&av(e),r(`compliance_score`)&&Dl(e),r(`replay`)&&lv(e),r(`status`)&&by(e),r(`flow`)&&Ed(e,t),r(`web_search`)&&wy(e),r(`http`)&&Ty(e),r(`regex_test`)&&Ey(e),r(`encode`)&&Dy(e),r(`measure`)&&Oy(e),r(`changelog`)&&ky(e),r(`schema_validate`)&&Ay(e),r(`env`)&&jy(e),r(`time`)&&My(e)}const Ly=j(`resource-notifier`);var Ry=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){Ly.debug(`sendResourceListChanged failed`,{error:String(e)})}}async notifyL0CardChanged(){await this.sendUpdate(`aikit://l0/workspace-core`),await this.sendUpdate(`aikit://l0`)}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){Ly.debug(`sendResourceUpdated failed`,{uri:e,error:String(t)})}}};const zy=j(`server`);function By(e){let t=e?.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}async function Vy(n){zy.info(`Initializing AI Kit components`);let r=n.store.backend,i=n.embedding,a=ve[i.model],o={model:i.model,nativeDim:i.nativeDim??a?.nativeDim??he.nativeDim,dimensions:i.dimensions??a?.dimensions??he.dimensions,queryPrefix:i.queryPrefix??a?.queryPrefix??he.queryPrefix,pooling:i.pooling??a?.pooling??`mean`},s=n.store.path,c=By(process.env.AIKIT_SPLIT_STATE),l=F(s,`aikit.db`),u={splitEnabled:c,contentDbPath:l,controlDbPath:c?F(s,`aikit-control.db`):l},d=null;if(r===`sqlite-vec`){let e=u.contentDbPath;N(s)||Ae(s,{recursive:!0}),d=await Nr(e),zy.debug(`SQLite adapter ready`,{type:d.type,vectorCapable:d.vectorCapable,dbPath:e}),d.vectorCapable||zy.warn(`┌──────────────────────────────────────────────────────────────────┐
3064
3059
  │ ⚠ SQLite vector extension unavailable — DEGRADED MODE │
3065
3060
  │ Vector search is disabled. Hybrid search returns FTS only. │
3066
3061
  │ To enable: install/rebuild better-sqlite3 (native module). │
3067
- └──────────────────────────────────────────────────────────────────┘`);let t=F(s,`lance`);N(t)&&Hy.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let f;if(d)if(u.splitEnabled&&u.controlDbPath!==u.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(u),f=await Nr(u.controlDbPath),Ir(f,Mr),Hy.info(`State store adapter ready`,{type:f.type,dbPath:u.controlDbPath,splitEnabled:!0})}else f=d;else{let e=F(s,`aikit-state.db`);N(s)||Ae(s,{recursive:!0}),f=await Nr(e),Ir(f,Mr),Hy.info(`State store adapter ready`,{type:f.type,dbPath:e})}let[p,m,h,g]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new ti({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads,idleTimeoutMs:i.idleTimeoutMs});return await e.initialize(),Hy.debug(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads});return await t.initialize(),Hy.debug(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=r===`sqlite-vec`?await Fr({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,embeddingProfile:o,partition:u}):await Fr({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,partition:void 0});return await e.initialize(),Hy.debug(`Store initialized`,{backend:r}),e})(),(async()=>{let e=d?new jr({adapter:d}):new jr({path:s});return await e.initialize(),Hy.debug(`Graph store initialized`,{shared:!!d}),e})(),(async()=>{let e=await br();if(e){let e=vr.get();Hy.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=vr.get();Hy.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})()]),_=new ri(p,m),v=Pr(f),y=new ni(n.store.path);y.load(),_.setHashCache(y);let b=n.curated.path,x=new e(b);await x.initialize();let S=new t(b,m,p,x);_.setGraphStore(h);let C=xl(n.er),w=C?new wr(n.curated.path):void 0;w&&Hy.debug(`Policy store initialized`,{ruleCount:w.getRules().length});let T=C?new Cr:void 0,E=I(n.sources[0]?.path??Oe(),de.aiContext),D=N(E),O=n.onboardDir?N(n.onboardDir):!1,k=D||O,ee,te=D?E:n.onboardDir;if(k&&te)try{ee=Pe(te).mtime.toISOString()}catch{}return Hy.debug(`Onboard state detected`,{onboardComplete:k,onboardTimestamp:ee,aiKbExists:D,onboardDirExists:O}),{embedder:p,store:m,stateStore:v,closeStateStore:f===d?void 0:async()=>f.close(),indexer:_,curated:S,graphStore:h,fileCache:new $e,bridge:C,policyStore:w,evolutionCollector:T,onboardComplete:k,onboardTimestamp:ee,eventBus:new Ro}}function Gy(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 (T1=structure, T2=content)`,`- 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`,`- 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(`
3068
- `)}const Ky=j(`background-task`);var qy=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,Ky.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Ky.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Ky.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const Jy=j(`idle-timer`);var Yy=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){Jy.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){Jy.info(`Skipping idle cleanup — background work in progress`);return}Jy.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`&&Jy.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const Xy=j(`memory-monitor`);var Zy=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??3221225472,this.criticalBytes=e?.criticalBytes??6442450944,this.intervalMs=e?.intervalMs??3e4}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(),Xy.debug(`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`?Xy.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?Xy.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&Xy.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 Qy=new ii;function $y(e,t){return Qy.run(e,async()=>{try{return await t()}finally{}})}j(`tool-timeout`);const eb=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var tb=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 nb(e){return eb.has(e)?6e5:12e4}function rb(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new tb(n,t);i.aborted||r.abort(e),o(e)},t);s.unref();try{e(i).then(a,o).finally(()=>clearTimeout(s))}catch(e){clearTimeout(s),o(e instanceof Error?e:Error(String(e)))}})}const Q=j(`server`),ib=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function ab(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function ob(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 sb(e,t,n,r){let i=[];if(n){let t=await cb(e,n);t&&i.push(t)}try{if(t.statePath){let{ensureLegacyStashImported:n}=await import(`../../tools/dist/index.js`);n(e.stateStore,{stateDir:t.statePath})}let r=e.stateStore.stashList().map(e=>e.key);if(r.length>0){let e=n?n.toLowerCase().split(/\s+/).filter(e=>e.length>2):[];if(e.length===0)i.push(`📦 stash: ${r.length} entries`);else{let t=r.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0&&i.push(`📦 stash: ${t.map(e=>`"${ab(e)}"`).join(`, `)}${r.length>t.length?` (+${r.length-t.length})`:``}`)}}}catch{}if(i.length===0&&!r)return null;if(r){let n=e,r=n.curated;if(r?.list&&n.stateStore)try{let{buildPreludeInjection:e,generatePrelude:a}=await import(`./prelude-BIJWSWyX.js`),o=e(await a(r,n.stateStore,void 0,t.l0CardDir),500);o.lines.length>0&&i.push(o.lines.join(`
3069
- `))}catch(e){Q.debug?.(`Periodic prelude injection failed`,{error:String(e)})}}return i.length===0?null:`\n${i.join(`
3070
- `)}`}async function cb(e,t){try{let n=await Promise.race([e.store.ftsSearch(t,{limit:3}),new Promise(e=>{let t=setTimeout(()=>e(null),1e3);t.unref&&t.unref()})]);if(!Array.isArray(n)||n.length===0)return null;let r=[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.record;if(!t)continue;let n=t.origin;if(n!==`curated`&&n!==`produced`)continue;let i=t.content??``;if(!(!i||i.length<20)){if(i.length<=400){let e=t.headingPath?.trim()||``,n=i.slice(0,400),a=e?`📚 ${e}: ${n}`:`📚 ${n}`;r.push(a)}else{let e=hp(i,400),n=t.headingPath?.trim()||``,a=n?`📚 ${n}: ${e}`:`📚 ${e}`;r.push(a)}if(r.length>=2)break}}return r.length===0?null:r.join(`
3071
- `)}catch{return null}}function lb(e,t,n){let r=5,i=0;for(let[a,o]of Object.entries(e)){let e=o.handler;o.handler=async(...o)=>{let s=await e(...o);if(!s||typeof s!=`object`||r<=0||s.isError||ib.has(a))return s;try{r--,i++;let e=o[0],a=await sb(t,n,ob(e&&typeof e==`object`?e:{}),i%5==0);a&&(s.content=Array.isArray(s.content)?s.content:[],s.content.push({type:`text`,text:a}))}catch{}return s}}}function ub(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`,`cannot find package`,`module not found`].some(e=>t.includes(e))}function db(e){return cm(e)?[`Auto-heal tried to repair missing runtime dependency files in the npx install.`,`If this persists, clear the broken npx cache and restart:`,` npm cache clean --force`,` npx -y @vpxa/aikit@latest serve`].join(`
3062
+ └──────────────────────────────────────────────────────────────────┘`);let t=F(s,`lance`);N(t)&&zy.info(`Old LanceDB data found at ${t} — ignored. Safe to delete after verifying sqlite-vec works.`)}let f;if(d)if(u.splitEnabled&&u.controlDbPath!==u.contentDbPath){let{migrateToSplitState:e}=await import(`../../store/dist/index.js`);await e(u),f=await Nr(u.controlDbPath),Ir(f,Mr),zy.info(`State store adapter ready`,{type:f.type,dbPath:u.controlDbPath,splitEnabled:!0})}else f=d;else{let e=F(s,`aikit-state.db`);N(s)||Ae(s,{recursive:!0}),f=await Nr(e),Ir(f,Mr),zy.info(`State store adapter ready`,{type:f.type,dbPath:e})}let[p,m,h,g]=await Promise.all([(async()=>{if(n.embedding.childProcess!==!1){let e=new ti({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads,idleTimeoutMs:i.idleTimeoutMs});return await e.initialize(),zy.debug(`Embedder loaded (child process)`,{modelId:e.modelId,dimensions:e.dimensions}),e}let{OnnxEmbedder:e}=await import(`../../embeddings/dist/index.js`),t=new e({model:o.model,dimensions:o.dimensions,nativeDim:o.nativeDim,queryPrefix:o.queryPrefix,pooling:o.pooling,interOpNumThreads:i.interOpNumThreads,intraOpNumThreads:i.intraOpNumThreads});return await t.initialize(),zy.debug(`Embedder loaded (in-process)`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let e=r===`sqlite-vec`?await Fr({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,embeddingProfile:o,partition:u}):await Fr({backend:r,path:s,adapter:d??void 0,embeddingDim:o.dimensions,partition:void 0});return await e.initialize(),zy.debug(`Store initialized`,{backend:r}),e})(),(async()=>{let e=d?new jr({adapter:d}):new jr({path:s});return await e.initialize(),zy.debug(`Graph store initialized`,{shared:!!d}),e})(),(async()=>{let e=await br();if(e){let e=vr.get();zy.debug(`WASM tree-sitter enabled`,{grammars:e.grammarCount,dir:e.wasmDir})}else{let e=vr.get();zy.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})()]),_=new ri(p,m),v=Pr(f),y=new ni(n.store.path);y.load(),_.setHashCache(y);let b=n.curated.path,x=new e(b);await x.initialize();let S=new t(b,m,p,x);_.setGraphStore(h);let C=xl(n.er),w=C?new wr(n.curated.path):void 0;w&&zy.debug(`Policy store initialized`,{ruleCount:w.getRules().length});let T=C?new Cr:void 0,E=I(n.sources[0]?.path??Oe(),de.aiContext),D=N(E),O=n.onboardDir?N(n.onboardDir):!1,k=D||O,ee,te=D?E:n.onboardDir;if(k&&te)try{ee=Pe(te).mtime.toISOString()}catch{}return zy.debug(`Onboard state detected`,{onboardComplete:k,onboardTimestamp:ee,aiKbExists:D,onboardDirExists:O}),{embedder:p,store:m,stateStore:v,closeStateStore:f===d?void 0:async()=>f.close(),indexer:_,curated:S,graphStore:h,fileCache:new $e,bridge:C,policyStore:w,evolutionCollector:T,onboardComplete:k,onboardTimestamp:ee,eventBus:new Ro}}function Hy(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 (T1=structure, T2=content)`,`- 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`,`- 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(`
3063
+ `)}const Uy=j(`background-task`);var Wy=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,Uy.info(`Background task started`,{task:e.name,pending:this.queue.length});let t=Date.now();try{await e.fn();let n=Date.now()-t;Uy.info(`Background task completed`,{task:e.name,durationMs:n}),e.resolve()}catch(n){let r=Date.now()-t;Uy.error(`Background task failed`,{task:e.name,durationMs:r,err:n}),e.reject(n instanceof Error?n:Error(String(n)))}}this.running=null}};const Gy=j(`idle-timer`);var Ky=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){Gy.info(`Idle timeout reached with no active session — skipping cleanup (waiting for first tool call)`);return}if(this._busy){Gy.info(`Skipping idle cleanup — background work in progress`);return}Gy.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`&&Gy.warn(`Idle cleanup callback failed`,{error:String(t.reason)})}};const qy=j(`memory-monitor`);var Jy=class{timer=null;warningBytes;criticalBytes;intervalMs;pressureFns=[];memoryPressureFns=[];lastLevel=`normal`;constructor(e){this.warningBytes=e?.warningBytes??3221225472,this.criticalBytes=e?.criticalBytes??6442450944,this.intervalMs=e?.intervalMs??3e4}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(),qy.debug(`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`?qy.warn(`Memory CRITICAL: ${n}MB RSS — consider restarting the server`):t===`warning`?qy.warn(`Memory WARNING: ${n}MB RSS`):this.lastLevel!==`normal`&&qy.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 Yy=new ii;function Xy(e,t){return Yy.run(e,async()=>{try{return await t()}finally{}})}j(`tool-timeout`);const Zy=new Set([`onboard`,`reindex`,`produce_knowledge`,`analyze`,`codemod`,`audit`]);var Qy=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 $y(e){return Zy.has(e)?6e5:12e4}function eb(e,t,n){let r=new AbortController,i=r.signal;return new Promise((a,o)=>{let s=setTimeout(()=>{let e=new Qy(n,t);i.aborted||r.abort(e),o(e)},t);s.unref();try{e(i).then(a,o).finally(()=>clearTimeout(s))}catch(e){clearTimeout(s),o(e instanceof Error?e:Error(String(e)))}})}const $=j(`server`),tb=new Set([`status`,`list_tools`,`describe_tool`,`config`,`env`,`present`]);function nb(e,t=28){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}function rb(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 ib(e,t,n,r){let i=[];if(n){let t=await ab(e,n);t&&i.push(t)}try{if(t.statePath){let{ensureLegacyStashImported:n}=await import(`../../tools/dist/index.js`);n(e.stateStore,{stateDir:t.statePath})}let r=e.stateStore.stashList().map(e=>e.key);if(r.length>0){let e=n?n.toLowerCase().split(/\s+/).filter(e=>e.length>2):[];if(e.length===0)i.push(`📦 stash: ${r.length} entries`);else{let t=r.filter(t=>e.some(e=>t.toLowerCase().includes(e))).slice(0,3);t.length>0&&i.push(`📦 stash: ${t.map(e=>`"${nb(e)}"`).join(`, `)}${r.length>t.length?` (+${r.length-t.length})`:``}`)}}}catch{}if(i.length===0&&!r)return null;if(r){let n=e,r=n.curated;if(r?.list&&n.stateStore)try{let{buildPreludeInjection:e,generatePrelude:a}=await import(`./prelude-BgvW6Hp5.js`),o=e(await a(r,n.stateStore,void 0,t.l0CardDir),500);o.lines.length>0&&i.push(o.lines.join(`
3064
+ `))}catch(e){$.debug?.(`Periodic prelude injection failed`,{error:String(e)})}}return i.length===0?null:`\n${i.join(`
3065
+ `)}`}async function ab(e,t){try{let n=await Promise.race([e.store.ftsSearch(t,{limit:3}),new Promise(e=>{let t=setTimeout(()=>e(null),1e3);t.unref&&t.unref()})]);if(!Array.isArray(n)||n.length===0)return null;let r=[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.record;if(!t)continue;let n=t.origin;if(n!==`curated`&&n!==`produced`)continue;let i=t.content??``;if(!(!i||i.length<20)){if(i.length<=400){let e=t.headingPath?.trim()||``,n=i.slice(0,400),a=e?`📚 ${e}: ${n}`:`📚 ${n}`;r.push(a)}else{let e=hp(i,400),n=t.headingPath?.trim()||``,a=n?`📚 ${n}: ${e}`:`📚 ${e}`;r.push(a)}if(r.length>=2)break}}return r.length===0?null:r.join(`
3066
+ `)}catch{return null}}function ob(e,t,n){let r=5,i=0;for(let[a,o]of Object.entries(e)){let e=o.handler;o.handler=async(...o)=>{let s=await e(...o);if(!s||typeof s!=`object`||r<=0||s.isError||tb.has(a))return s;try{r--,i++;let e=o[0],a=await ib(t,n,rb(e&&typeof e==`object`?e:{}),i%5==0);a&&(s.content=Array.isArray(s.content)?s.content:[],s.content.push({type:`text`,text:a}))}catch{}return s}}}function sb(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`,`cannot find package`,`module not found`].some(e=>t.includes(e))}function cb(e){return cm(e)?[`Auto-heal tried to repair missing runtime dependency files in the npx install.`,`If this persists, clear the broken npx cache and restart:`,` npm cache clean --force`,` npx -y @vpxa/aikit@latest serve`].join(`
3072
3067
  `):[`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.`].join(`
3073
- `)}async function fb(){try{let{existsSync:e,readFileSync:t}=await import(`node:fs`),n=F($n(),`.aikit`,`current-version.json`);if(!e(n))return null;let r=JSON.parse(t(n,`utf-8`));if(!r.version)return null;let i=oe();return r.version===i?null:r.version}catch{return null}}async function pb(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(`
3074
- `),`utf8`),Q.info(`Auto-heal: created ESM shim for @huggingface/transformers (.mjs wrapper → .cjs)`,{path:t}))}catch(e){Q.warn(`Auto-heal: failed to create ESM shim`,{error:e instanceof Error?e.message:String(e),path:t})}}}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model;if(t){let e=F($n(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(e,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared embedding model cache`,{path:e})}catch{}}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=F(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Q.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=F(e.store.path,`graph.db`);try{await r(t,{force:!0}),Q.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=F(e.store.path,`aikit.db`);try{await r(n,{force:!0}),await r(`${n}-wal`,{force:!0}).catch(()=>{}),await r(`${n}-shm`,{force:!0}).catch(()=>{}),Q.info(`Auto-heal: cleared corrupted aikit database`,{path:n})}catch{}}if(cm(t)){let e=await dm(t);e.repaired||Q.warn(`Auto-heal: missing runtime dependency repair did not complete`,{packages:e.packages,reason:e.reason,error:e.error,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}else n.includes(`cannot find module`)&&!n.includes(`.cache`)&&Q.warn(`Auto-heal: missing module detected during initialization cleanup`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}function mb(e,t){let n=Zs(e,ho,W,Ss(e)),r=Gy(e,n,W),i=new tr({name:e.serverName??`AI Kit`,version:oe()},{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}`:``,``,`**${go.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.`,``,db(o),``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3068
+ `)}async function lb(){try{let{existsSync:e,readFileSync:t}=await import(`node:fs`),n=F($n(),`.aikit`,`current-version.json`);if(!e(n))return null;let r=JSON.parse(t(n,`utf-8`));if(!r.version)return null;let i=oe();return r.version===i?null:r.version}catch{return null}}async function ub(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(`
3069
+ `),`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;if(t){let e=F($n(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(e,{recursive:!0,force:!0}),$.info(`Auto-heal: cleared embedding model cache`,{path:e})}catch{}}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=F(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=F(e.store.path,`graph.db`);try{await r(t,{force:!0}),$.info(`Auto-heal: cleared graph database`,{path:t})}catch{}let n=F(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{}}if(cm(t)){let e=await dm(t);e.repaired||$.warn(`Auto-heal: missing runtime dependency repair did not complete`,{packages:e.packages,reason:e.reason,error:e.error,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}else n.includes(`cannot find module`)&&!n.includes(`.cache`)&&$.warn(`Auto-heal: missing module detected during initialization cleanup`,{hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}function db(e,t){let n=Zs(e,ho,W,Ss(e)),r=Hy(e,n,W),i=new tr({name:e.serverName??`AI Kit`,version:oe()},{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}`:``,``,`**${go.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.`,``,cb(o),``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
3075
3070
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${go.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(`
3076
- `);di(i);let p=new is;p.use(Ts(),{order:1,name:`structured-content-guard`}),Is(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of ho){if(!n.has(e))continue;let t=G(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));go.has(e)?r.remove():h.push(r)}zy(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:sr(R.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=JSON.parse(t(c,`utf8`)),d=Object.keys(u.dependencies??{}),f=[`@mixmark-io/domino`],p=[...d,...f.filter(e=>!d.includes(e))],m=p.filter(e=>!e.startsWith(`@aikit/`)),h=p.filter(e=>e.startsWith(`@aikit/`)),g=[];for(let e of m)try{o.resolve(e)}catch{try{o.resolve(`${e}/package.json`)}catch{g.push(e)}}g.length>0&&Q.warn(`Dependencies not resolvable — server may operate in degraded mode`,{missing:g,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve`});let _=[];if(h.length>0){for(let e of h)n(i(l,e.slice(7),`dist`))||_.push(e);_.length>0&&Q.warn(`Workspace sibling packages missing dist — server may have degraded features`,{missing:_,hint:`Reinstall: npm cache clean --force && npx -y @vpxa/aikit@latest serve`})}}catch{}let n;try{n=await Wy(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(ub(r)){let t=await fb();if(t){a=`failed`,o=`Server v${oe()} superseded by installed v${t}. Restart the MCP server to use the new version.`,Q.info(o),y?.(Error(o));return}Q.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await pb(e,r);try{n=await Wy(e),Q.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){a=`failed`,o=e instanceof Error?e.message:String(e),Q.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:o,originalError:r}),y?.(e instanceof Error?e:Error(o));return}}else{a=`failed`,o=r,Q.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:o}),y?.(t instanceof Error?t:Error(o));return}}ae();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 go)m[e]?.remove();let b=new Vy(i),x=ci(i);Ry({server:i,aikit:n,config:e,elicitor:li(i),resourceNotifier:b,samplingClient:x,indexMode:t,getSmartState:t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,getSmartScheduler:t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null}),Si(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let C=i._registeredTools??{};for(let[e,t]of Object.entries(C)){if(_o.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 (${Cs/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:js(t.config.outputSchema)}:{}}),Cs));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=nb(e);t.handler=async(...i)=>{try{return await rb(e=>$y(e,()=>n(...i)),r,e)}catch(n){if(n instanceof tb)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:js(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(C).length;w<ho.length&&Q.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:ho.length,registeredToolCount:w}),Q.debug(`MCP server configured`,{toolCount:ho.length,resourceCount:4});let T=new Zy;T.onPressure((e,t)=>{e===`warning`&&hi(),e===`critical`&&(Q.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),hi())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new Yy;l=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){Q.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}Q.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}lb(C,n,{statePath:e.stateDir??``,l0CardDir:e.l0CardDir});for(let[,e]of Object.entries(C)){let t=e.config?.outputSchema;if(!t)continue;let n=e.handler;e.handler=async(...e)=>{let r=await n(...e);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=js(t),i.structuredContent??={},r)}}process.stdin.on(`end`,()=>(Q.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>(Q.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{Q.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);Q.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Q.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Q.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,Q.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Q.warn(`FTS index creation failed`,M(e))}try{let e=await t.curated.reindexAll();Q.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Q.error(`Curated re-index failed`,M(e))}}catch(e){Q.error(`Initial index failed; will retry on aikit_reindex`,M(e))}finally{l?.setBusy(!1)}},E=new qy,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{Q.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),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 k.unref(),{server:i,startInit:C,ready:w,runInitialIndex:D,get aikit(){return c},scheduler:E,setSmartScheduler(e){u=e}}}const $=j(`server`);function hb(e,t){let n=Zs(t,[...ho,...bs],W,Ss(t)),r=Gy(t,n,W),i=new tr({name:t.serverName??`AI Kit`,version:oe()},{capabilities:{logging:{},completions:{},prompts:{},extensions:{roots:{}}},instructions:r}),a=i;a.setNotificationHandler(rr,async()=>{try{let{roots:e}=await a.listRoots();if(e&&e.length>0){let n=le(e[0].uri);process.env.AIKIT_TRANSPORT===`http`?(t.sources[0]={path:n,excludePatterns:t.sources[0]?.excludePatterns??[]},t.allRoots=e.map(e=>le(e.uri)),$.info(`Workspace root updated (HTTP mode)`,{rootPath:n,sourceCount:t.sources.length})):(x(t,n),$.info(`Workspace root updated (stdio mode)`,{rootPath:n}))}}catch(e){$.debug(`MCP roots/list not available`,{error:M(e)})}}),di(i),Ry({server:i,aikit:e,config:t,elicitor:li(i),resourceNotifier:new Vy(i),samplingClient:ci(i),precomputedActiveTools:n});let o=t.sources[0]?.path??Oe();return e.eventBus?.emit({type:`session:start`,serverVersion:oe(),workspaceRoot:o,timestamp:Date.now(),eventId:`sess-start-${Date.now()}`,workspaceId:xe(o),source:`server`}),Si(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function gb(e){let t=await Wy(e),n=hb(t,e);$.debug(`MCP server configured`,{toolCount:ho.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,M(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,M(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,M(e))}},i=async()=>{$.info(`Shutting down`),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await Promise.all([t.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),t.graphStore.close().catch(()=>{}),t.closeStateStore?.().catch(()=>{})??Promise.resolve(),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{ho as ALL_TOOL_NAMES,mb as createLazyServer,hb as createMcpServer,gb as createServer,Wy as initializeAikit,ly as n,ci as r,Ry as registerMcpTools,uy as t};
3071
+ `);di(i);let p=new is;p.use(Ts(),{order:1,name:`structured-content-guard`}),Is(i,p,e.toolPrefix??``);let m=i.sendToolListChanged.bind(i);i.sendToolListChanged=()=>{};let h=[];for(let e of ho){if(!n.has(e))continue;let t=G(e),r=i.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:f()}]}));go.has(e)?r.remove():h.push(r)}Iy(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:sr(R.string(),()=>[])}},async()=>({messages:[]})),v,y,b=new Promise((e,t)=>{v=e,y=t}),x,S=new Promise(e=>{x=e}),C=()=>x?.(),w=(async()=>{await S;try{let{createRequire:e}=await import(`node:module`),{readFileSync:t,existsSync:n}=await import(`node:fs`),{fileURLToPath:r}=await import(`node:url`),{resolve:i,dirname:a}=await import(`node:path`),o=e(import.meta.url),s=a(r(import.meta.url)),c=i(s,`..`,`package.json`),l=i(s,`..`,`..`),u=JSON.parse(t(c,`utf8`)),d=Object.keys(u.dependencies??{}),f=[`@mixmark-io/domino`],p=[...d,...f.filter(e=>!d.includes(e))],m=p.filter(e=>!e.startsWith(`@aikit/`)),h=p.filter(e=>e.startsWith(`@aikit/`)),g=[];for(let e of m)try{o.resolve(e)}catch{try{o.resolve(`${e}/package.json`)}catch{g.push(e)}}g.length>0&&$.warn(`Dependencies not resolvable — server may operate in degraded mode`,{missing:g,hint:`Run: npm cache clean --force && npx -y @vpxa/aikit@latest 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@latest serve`})}}catch{}let n;try{n=await Vy(e)}catch(t){let r=t instanceof Error?t.message:String(t);if(sb(r)){let t=await lb();if(t){a=`failed`,o=`Server v${oe()} superseded by installed v${t}. Restart the MCP server to use the new version.`,$.info(o),y?.(Error(o));return}$.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await ub(e,r);try{n=await Vy(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}}ae();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 go)m[e]?.remove();let b=new Ry(i),x=ci(i);Fy({server:i,aikit:n,config:e,elicitor:li(i),resourceNotifier:b,samplingClient:x,indexMode:t,getSmartState:t===`smart`?(()=>{let e=u;return e?.getState?e.getState():null}):null,getSmartScheduler:t===`smart`?()=>{let e=u;return e?{prioritize:e.prioritize.bind(e)}:null}:null}),Si(i,{curated:n.curated,store:n.store,graphStore:n.graphStore,stateStore:n.stateStore},t),i.sendToolListChanged=r,i.sendPromptListChanged=f,i.sendResourceListChanged=p,Promise.resolve(i.sendToolListChanged()).catch(()=>{}),Promise.resolve(i.sendPromptListChanged()).catch(()=>{}),Promise.resolve(i.sendResourceListChanged()).catch(()=>{});let C=i._registeredTools??{};for(let[e,t]of Object.entries(C)){if(_o.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 (${Cs/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}],...t.config?.outputSchema?{structuredContent:js(t.config.outputSchema)}:{}}),Cs));return Promise.race([r(...i),o])}}for(let[e,t]of Object.entries(C)){let n=t.handler,r=$y(e);t.handler=async(...i)=>{try{return await eb(e=>Xy(e,()=>n(...i)),r,e)}catch(n){if(n instanceof Qy)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:js(t.config.outputSchema)}:{}};throw n}}}let w=Object.keys(C).length;w<ho.length&&$.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:ho.length,registeredToolCount:w}),$.debug(`MCP server configured`,{toolCount:ho.length,resourceCount:4});let T=new Jy;T.onPressure((e,t)=>{e===`warning`&&hi(),e===`critical`&&($.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(t/1024/1024)}),hi())}),T.registerMemoryPressureCallback(()=>n.embedder.shutdown?.()),T.start();let D=new Ky;l=D,D.onIdle(async()=>{if(E.isRunning||n.indexer.isIndexing){$.info(`Idle cleanup deferred — background tasks still running`),D.touch();return}$.info(`Idle cleanup: releasing cached memory (connections stay open)`);try{n.store.releaseMemory?.(),n.graphStore.releaseMemory?.()}catch{}}),D.touch();let O=!1;for(let e of Object.values(C)){let t=e.handler;e.handler=async(...e)=>{if(O||(O=!0,D.markSessionActive()),D.touch(),u){let t=d(e[0]);t.length>0&&u.prioritize(...t)}return t(...e)}}ob(C,n,{statePath:e.stateDir??``,l0CardDir:e.l0CardDir});for(let[,e]of Object.entries(C)){let t=e.config?.outputSchema;if(!t)continue;let n=e.handler;e.handler=async(...e)=>{let r=await n(...e);if(!r||typeof r!=`object`)return r;let i=r;return!(`content`in i)||i.isError||i.structuredContent!=null&&typeof i.structuredContent==`object`?r:(i.structuredContent=js(t),i.structuredContent??={},r)}}process.stdin.on(`end`,()=>($.info(`stdin closed — MCP client disconnected. Shutting down.`),process.exit(0))),process.stdin.on(`error`,()=>($.info(`stdin error — MCP client disconnected. Shutting down.`),process.exit(0))),c=n,v?.(n)})(),T=async()=>{let t;try{t=await b}catch{$.warn(`Skipping initial index — AI Kit initialization failed`);return}l?.setBusy(!0);try{let n=e.sources.map(e=>e.path).join(`, `);$.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&$.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&$.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});s=!0,$.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){$.warn(`FTS index creation failed`,M(e))}try{let e=await t.curated.reindexAll();$.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){$.error(`Curated re-index failed`,M(e))}}catch(e){$.error(`Initial index failed; will retry on aikit_reindex`,M(e))}finally{l?.setBusy(!1)}},E=new Wy,D=()=>E.schedule({name:`initial-index`,fn:T}),O=process.ppid,k=setInterval(()=>{try{process.kill(O,0)}catch{$.info(`Parent process died; shutting down`,{parentPid:O}),clearInterval(k),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 k.unref(),{server:i,startInit:C,ready:w,runInitialIndex:D,get aikit(){return c},scheduler:E,setSmartScheduler(e){u=e}}}const fb=j(`server`);function pb(e,t){let n=Zs(t,[...ho,...bs],W,Ss(t)),r=Hy(t,n,W),i=new tr({name:t.serverName??`AI Kit`,version:oe()},{capabilities:{logging:{},completions:{},prompts:{},extensions:{roots:{}}},instructions:r}),a=i;a.setNotificationHandler(rr,async()=>{try{let{roots:e}=await a.listRoots();if(e&&e.length>0){let n=le(e[0].uri);process.env.AIKIT_TRANSPORT===`http`?(t.sources[0]={path:n,excludePatterns:t.sources[0]?.excludePatterns??[]},t.allRoots=e.map(e=>le(e.uri)),fb.info(`Workspace root updated (HTTP mode)`,{rootPath:n,sourceCount:t.sources.length})):(x(t,n),fb.info(`Workspace root updated (stdio mode)`,{rootPath:n}))}}catch(e){fb.debug(`MCP roots/list not available`,{error:M(e)})}}),di(i),Fy({server:i,aikit:e,config:t,elicitor:li(i),resourceNotifier:new Ry(i),samplingClient:ci(i),precomputedActiveTools:n});let o=t.sources[0]?.path??Oe();return e.eventBus?.emit({type:`session:start`,serverVersion:oe(),workspaceRoot:o,timestamp:Date.now(),eventId:`sess-start-${Date.now()}`,workspaceId:xe(o),source:`server`}),Si(i,{curated:e.curated,store:e.store,graphStore:e.graphStore,stateStore:e.stateStore},t.indexMode),i}async function mb(e){let t=await Vy(e),n=pb(t,e);fb.debug(`MCP server configured`,{toolCount:ho.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);fb.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&&fb.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&fb.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});fb.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){fb.warn(`FTS index creation failed`,M(e))}try{let e=await t.curated.reindexAll();fb.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){fb.error(`Curated re-index failed`,M(e))}}catch(e){fb.error(`Initial index failed; will retry on aikit_reindex`,M(e))}},i=async()=>{fb.info(`Shutting down`),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),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{fb.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}export{ho as ALL_TOOL_NAMES,db as createLazyServer,pb as createMcpServer,mb as createServer,Vy as initializeAikit,oy as n,ci as r,Fy as registerMcpTools,sy as t};