@vpxa/aikit 0.1.350 → 0.1.352

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.
Files changed (36) hide show
  1. package/package.json +1 -1
  2. package/packages/blocks-core/dist/index.mjs +91 -58
  3. package/packages/cli/dist/index.js +1 -1
  4. package/packages/core/dist/index.d.ts +3 -0
  5. package/packages/core/dist/index.js +1 -1
  6. package/packages/present/dist/annotation-layer.js +48 -74
  7. package/packages/present/dist/index.html +154 -114
  8. package/packages/server/dist/bin.js +1 -1
  9. package/packages/server/dist/index.js +288 -109
  10. package/packages/server/dist/prelude-CXds3AXY.js +2 -0
  11. package/packages/server/dist/prelude-Cms2H0-F.js +1 -0
  12. package/packages/server/dist/sampling-BoH5wpOJ.js +1 -0
  13. package/packages/server/dist/sampling-SoUYZhFs.js +2 -0
  14. package/packages/server/dist/{server-BYZo2XjK.js → server-Crfl8sRN.js} +174 -169
  15. package/packages/server/dist/{server-BtRv0mbH.js → server-Znp0a9J2.js} +174 -169
  16. package/packages/server/dist/{server-http-CatdRS-N.js → server-http-BGF1k0j9.js} +1 -1
  17. package/packages/server/dist/{server-http-L_WQ9v_b.js → server-http-BSGdxVRV.js} +1 -1
  18. package/packages/server/dist/{server-stdio-avLmmdEi.js → server-stdio-B2N-eM5T.js} +1 -1
  19. package/packages/server/dist/{server-stdio-CZuGZR4e.js → server-stdio-CTgwgIGC.js} +1 -1
  20. package/packages/server/viewers/canvas.html +127 -94
  21. package/packages/server/viewers/code-review-viewer.html +352 -0
  22. package/packages/server/viewers/report-template.html +100 -67
  23. package/packages/server/viewers/tour-viewer.html +94 -61
  24. package/packages/store/dist/index.d.ts +3 -0
  25. package/packages/store/dist/index.js +8 -8
  26. package/packages/tools/dist/index.d.ts +36 -2
  27. package/packages/tools/dist/index.js +90 -90
  28. package/scaffold/dist/definitions/agents.mjs +1 -1
  29. package/scaffold/dist/definitions/bodies.mjs +48 -3
  30. package/scaffold/dist/definitions/skills/c4-architecture.mjs +24 -2
  31. package/scaffold/dist/definitions/skills/docs.mjs +170 -15
  32. package/scaffold/dist/definitions/skills/present.mjs +317 -13
  33. package/packages/server/dist/prelude-DpX0QnqF.js +0 -2
  34. package/packages/server/dist/prelude-pJPHXvnQ.js +0 -1
  35. package/packages/server/dist/sampling-9GcILoHr.js +0 -2
  36. package/packages/server/dist/sampling-DuXB6-rK.js +0 -1
@@ -1,4 +1,4 @@
1
- import{d as e,f as t,i as n,p as r,s as i,u as a}from"./scaffold-BNPHP-QC.js";import{A as o,C as s,D as c,E as l,F as u,I as d,L as f,M as p,N as m,O as ee,P as te,S as ne,T as re,_ as ie,a as h,b as ae,c as g,d as _,f as v,g as oe,h as se,i as y,j as ce,k as le,l as ue,m as b,n as de,o as fe,p as x,r as pe,s as me,t as he,u as ge,v as _e,w as ve,x as ye,y as be}from"./templates-CztsaGb2.js";import{copyFileSync as xe,existsSync as S,mkdirSync as C,readFileSync as w,readdirSync as T,renameSync as Se,rmSync as E,statSync as Ce,unlinkSync as we,writeFileSync as D}from"node:fs";import{basename as Te,dirname as O,join as k,posix as A,relative as Ee,resolve as j,win32 as M}from"node:path";import{fileURLToPath as De}from"node:url";import{arch as Oe,homedir as N,platform as ke}from"node:os";import{AIKIT_PATHS as P,AIKIT_RUNTIME_PATHS as Ae,EMBEDDING_DEFAULTS as je,INSTALL_ARGS as Me,cleanupOldVersions as Ne,createLogger as F,getGlobalDataDir as Pe,getPartitionDir as Fe,isUserInstalled as Ie,migrateLegacyWorkspaceLayout as Le,registerWorkspace as Re,safeCwd as I,safeCwdOrHome as ze,saveRegistry as Be}from"../../core/dist/index.js";import{initializeWasm as Ve}from"../../chunker/dist/index.js";import{OnnxEmbedder as He}from"../../embeddings/dist/index.js";import{IncrementalIndexer as Ue}from"../../indexer/dist/index.js";import{SqliteGraphStore as We,createSqliteAdapter as Ge,createStore as Ke}from"../../store/dist/index.js";import{mkdir as qe,readFile as Je,rename as Ye,rm as Xe,unlink as Ze,writeFile as L}from"node:fs/promises";import{addToWorkset as Qe,audit as $e,check as et,checkpointLatest as tt,checkpointList as nt,checkpointLoad as rt,checkpointSave as it,codemod as at,compact as ot,dataTransform as st,delegate as ct,delegateListModels as lt,deleteWorkset as ut,diffParse as dt,evaluate as ft,fileSummary as pt,find as mt,findDeadSymbols as ht,findExamples as gt,getWorkset as _t,gitContext as vt,graphQuery as yt,guide as bt,health as xt,laneCreate as St,laneDiff as Ct,laneDiscard as wt,laneList as Tt,laneMerge as Et,laneStatus as Dt,listWorksets as Ot,parseOutput as kt,processList as At,processLogs as jt,processStart as Mt,processStatus as Nt,processStop as Pt,queueClear as Ft,queueCreate as It,queueDelete as Lt,queueDone as Rt,queueFail as zt,queueGet as Bt,queueList as Vt,queueNext as Ht,queuePush as Ut,removeFromWorkset as Wt,rename as Gt,replayClear as Kt,replayList as qt,replayTrim as Jt,saveWorkset as Yt,scopeMap as Xt,stashClear as Zt,stashDelete as Qt,stashGet as $t,stashList as en,stashSet as tn,symbol as nn,testRun as rn,trace as an,watchList as on,watchStart as sn,watchStop as cn}from"../../tools/dist/index.js";import{execFileSync as ln,execSync as R,fork as un,spawn as dn}from"node:child_process";import{extractSvg as fn,renderToResult as pn,sanitizeTitle as mn}from"../../server/dist/index.js";import{randomUUID as hn}from"node:crypto";import{parse as gn,stringify as _n}from"yaml";function vn(){let e=I(),t=process.env.AIKIT_CONFIG_PATH??(e&&S(j(e,`aikit.config.json`))?j(e,`aikit.config.json`):null),n=t?O(t):e??N();if(Le(n),!t)return yn();let r=w(t,`utf-8`),i;try{i=JSON.parse(r)}catch{console.error(`Failed to parse ${t} as JSON. Ensure the file contains valid JSON.`),process.exit(1)}let a=n;return i.sources=i.sources.map(e=>({...e,path:j(a,e.path)})),i.store.path=j(a,i.store.path),i.curated=i.curated??{path:P.aiCurated},i.curated.path=j(a,i.curated.path),i.onboardDir||=P.aiContext,i.onboardDir=j(a,i.onboardDir),i.stateDir||=P.state,i.stateDir=j(a,i.stateDir),bn(i,a),i}function yn(){let e=process.env.AIKIT_WORKSPACE_ROOT??I()??N();Le(e);let t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`aikit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:je.model,dimensions:je.dimensions},store:{backend:`sqlite-vec`,path:j(e,P.data)},curated:{path:j(e,P.aiCurated)},onboardDir:j(e,P.aiContext),stateDir:j(e,P.state)};return bn(t,e),t}function bn(e,t){if(!Ie())return;let n=Re(t);e.store.path=j(Fe(n.partition),Ae.data),e.stateDir=j(Fe(n.partition),Ae.state),e.onboardDir=j(Fe(n.partition),Ae.onboard),e.curated={path:j(Fe(n.partition),Ae.curated)}}async function xn(){let e=vn(),t=new He({model:e.embedding.model,dimensions:e.embedding.dimensions,interOpNumThreads:e.embedding.interOpNumThreads,intraOpNumThreads:e.embedding.intraOpNumThreads});await t.initialize();let n=null;if(e.store.backend===`sqlite-vec`){let t=j(e.store.path,`aikit.db`),r=O(t);if(!S(r)){let{mkdirSync:e}=await import(`node:fs`);e(r,{recursive:!0})}n=await Ge(t)}let r=await Ke({backend:e.store.backend,path:e.store.path,embeddingDim:e.embedding.dimensions,adapter:n??void 0});await r.initialize();let i=new Ue(t,r),{CuratedKnowledgeManager:a}=await import(`../../server/dist/index.js`),o=new a(e.curated.path,r,t),s;try{let t=n?new We({adapter:n}):new We({path:e.store.path});await t.initialize(),s=t,i.setGraphStore(s)}catch(e){console.error(`[aikit] Graph store init failed (non-fatal): ${e.message}`),s={initialize:async()=>{},upsertNode:async()=>{},upsertEdge:async()=>{},upsertNodes:async()=>{},upsertEdges:async()=>{},getNode:async()=>null,getNeighbors:async()=>({nodes:[],edges:[]}),traverse:async()=>({nodes:[],edges:[]}),findNodes:async()=>[],findEdges:async()=>[],deleteNode:async()=>{},deleteBySourcePath:async()=>0,clear:async()=>{},getStats:async()=>({nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}),validate:async()=>({valid:!0,orphanNodes:[],danglingEdges:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}}),setNodeCommunity:async()=>{},detectCommunities:async()=>({}),traceProcess:async()=>({id:``,entryNodeId:``,label:``,properties:{},steps:[]}),getProcesses:async()=>[],deleteProcess:async()=>{},depthGroupedTraversal:async()=>({}),getCohesionScore:async()=>0,getSymbol360:async()=>({node:{id:``,type:``,name:``,properties:{}},incoming:[],outgoing:[],community:null,processes:[]}),close:async()=>{}}}return await Ve().catch(()=>{}),{config:e,embedder:t,store:r,graphStore:s,indexer:i,curated:o,sqliteAdapter:n}}const Sn=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;if(!t||!n)throw new g(`Usage: aikit analyze <type> <path>
1
+ import{d as e,f as t,i as n,p as r,s as i,u as a}from"./scaffold-BNPHP-QC.js";import{A as o,C as s,D as c,E as l,F as u,I as d,L as f,M as p,N as m,O as ee,P as te,S as ne,T as re,_ as ie,a as h,b as ae,c as g,d as _,f as v,g as oe,h as se,i as y,j as ce,k as le,l as ue,m as b,n as de,o as fe,p as x,r as pe,s as me,t as he,u as ge,v as _e,w as ve,x as ye,y as be}from"./templates-CztsaGb2.js";import{copyFileSync as xe,existsSync as S,mkdirSync as C,readFileSync as w,readdirSync as T,renameSync as Se,rmSync as E,statSync as Ce,unlinkSync as we,writeFileSync as D}from"node:fs";import{basename as Te,dirname as O,join as k,posix as A,relative as Ee,resolve as j,win32 as M}from"node:path";import{fileURLToPath as De}from"node:url";import{arch as Oe,homedir as N,platform as ke}from"node:os";import{AIKIT_PATHS as P,AIKIT_RUNTIME_PATHS as Ae,EMBEDDING_DEFAULTS as je,INSTALL_ARGS as Me,cleanupOldVersions as Ne,createLogger as F,getGlobalDataDir as Pe,getPartitionDir as Fe,isUserInstalled as Ie,migrateLegacyWorkspaceLayout as Le,registerWorkspace as Re,safeCwd as I,safeCwdOrHome as ze,saveRegistry as Be}from"../../core/dist/index.js";import{initializeWasm as Ve}from"../../chunker/dist/index.js";import{OnnxEmbedder as He}from"../../embeddings/dist/index.js";import{IncrementalIndexer as Ue}from"../../indexer/dist/index.js";import{SqliteGraphStore as We,createSqliteAdapter as Ge,createStore as Ke}from"../../store/dist/index.js";import{mkdir as qe,readFile as Je,rename as Ye,rm as Xe,unlink as Ze,writeFile as L}from"node:fs/promises";import{addToWorkset as Qe,audit as $e,check as et,checkpointLatest as tt,checkpointList as nt,checkpointLoad as rt,checkpointSave as it,codemod as at,compact as ot,dataTransform as st,delegate as ct,delegateListModels as lt,deleteWorkset as ut,diffParse as dt,evaluate as ft,fileSummary as pt,find as mt,findDeadSymbols as ht,findExamples as gt,getWorkset as _t,gitContext as vt,graphQuery as yt,guide as bt,health as xt,laneCreate as St,laneDiff as Ct,laneDiscard as wt,laneList as Tt,laneMerge as Et,laneStatus as Dt,listWorksets as Ot,parseOutput as kt,processList as At,processLogs as jt,processStart as Mt,processStatus as Nt,processStop as Pt,queueClear as Ft,queueCreate as It,queueDelete as Lt,queueDone as Rt,queueFail as zt,queueGet as Bt,queueList as Vt,queueNext as Ht,queuePush as Ut,removeFromWorkset as Wt,rename as Gt,replayClear as Kt,replayList as qt,replayTrim as Jt,saveWorkset as Yt,scopeMap as Xt,stashClear as Zt,stashDelete as Qt,stashGet as $t,stashList as en,stashSet as tn,symbol as nn,testRun as rn,trace as an,watchList as on,watchStart as sn,watchStop as cn}from"../../tools/dist/index.js";import{execFileSync as ln,execSync as R,fork as un,spawn as dn}from"node:child_process";import{extractSvg as fn,renderToResult as pn,sanitizeTitle as mn}from"../../server/dist/index.js";import{randomUUID as hn}from"node:crypto";import{parse as gn,stringify as _n}from"yaml";function vn(){let e=I(),t=process.env.AIKIT_CONFIG_PATH??(e&&S(j(e,`aikit.config.json`))?j(e,`aikit.config.json`):null),n=t?O(t):e??N();if(Le(n),!t)return yn();let r=w(t,`utf-8`),i;try{i=JSON.parse(r)}catch{console.error(`Failed to parse ${t} as JSON. Ensure the file contains valid JSON.`),process.exit(1)}let a=n;return i.sources=i.sources.map(e=>({...e,path:j(a,e.path)})),i.store.path=j(a,i.store.path),i.curated=i.curated??{path:P.aiCurated},i.curated.path=j(a,i.curated.path),i.onboardDir||=P.aiContext,i.onboardDir=j(a,i.onboardDir),i.stateDir||=P.state,i.stateDir=j(a,i.stateDir),bn(i,a),i}function yn(){let e=process.env.AIKIT_WORKSPACE_ROOT??I()??N();Le(e);let t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`aikit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:je.model,dimensions:je.dimensions},store:{backend:`sqlite-vec`,path:j(e,P.data)},curated:{path:j(e,P.aiCurated)},onboardDir:j(e,P.aiContext),stateDir:j(e,P.state)};return bn(t,e),t}function bn(e,t){if(!Ie())return;let n=Re(t);e.store.path=j(Fe(n.partition),Ae.data),e.stateDir=j(Fe(n.partition),Ae.state),e.onboardDir=j(Fe(n.partition),Ae.onboard),e.curated={path:j(Fe(n.partition),Ae.curated)}}async function xn(){let e=vn(),t=new He({model:e.embedding.model,dimensions:e.embedding.dimensions,interOpNumThreads:e.embedding.interOpNumThreads,intraOpNumThreads:e.embedding.intraOpNumThreads});await t.initialize();let n=null;if(e.store.backend===`sqlite-vec`){let t=j(e.store.path,`aikit.db`),r=O(t);if(!S(r)){let{mkdirSync:e}=await import(`node:fs`);e(r,{recursive:!0})}n=await Ge(t)}let r=await Ke({backend:e.store.backend,path:e.store.path,embeddingDim:e.embedding.dimensions,adapter:n??void 0});await r.initialize();let i=new Ue(t,r),{CuratedKnowledgeManager:a}=await import(`../../server/dist/index.js`),o=new a(e.curated.path,r,t),s;try{let t=n?new We({adapter:n}):new We({path:e.store.path});await t.initialize(),s=t,i.setGraphStore(s)}catch(e){console.error(`[aikit] Graph store init failed (non-fatal): ${e.message}`),s={initialize:async()=>{},upsertNode:async()=>{},upsertEdge:async()=>{},upsertNodes:async()=>{},upsertEdges:async()=>{},getNode:async()=>null,getNodes:async()=>[],getNeighbors:async()=>({nodes:[],edges:[]}),traverse:async()=>({nodes:[],edges:[]}),findNodes:async()=>[],findEdges:async()=>[],deleteNode:async()=>{},deleteBySourcePath:async()=>0,clear:async()=>{},getStats:async()=>({nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}),validate:async()=>({valid:!0,orphanNodes:[],danglingEdges:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}}),setNodeCommunity:async()=>{},detectCommunities:async()=>({}),traceProcess:async()=>({id:``,entryNodeId:``,label:``,properties:{},steps:[]}),getProcesses:async()=>[],deleteProcess:async()=>{},depthGroupedTraversal:async()=>({}),getCohesionScore:async()=>0,getSymbol360:async()=>({node:{id:``,type:``,name:``,properties:{}},incoming:[],outgoing:[],community:null,processes:[]}),close:async()=>{}}}return await Ve().catch(()=>{}),{config:e,embedder:t,store:r,graphStore:s,indexer:i,curated:o,sqliteAdapter:n}}const Sn=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;if(!t||!n)throw new g(`Usage: aikit analyze <type> <path>
2
2
  Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`);let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=j(n),d;switch(t){case`structure`:d=await new c().analyze(u,{format:`markdown`});break;case`deps`:case`dependencies`:d=await new i().analyze(u,{format:`markdown`});break;case`symbols`:d=await new l().analyze(u,{format:`markdown`});break;case`patterns`:d=await new s().analyze(u,{format:`markdown`});break;case`entry-points`:d=await new o().analyze(u,{format:`markdown`});break;case`blast-radius`:d=await new r().analyze(I()??N(),{files:[n],format:`markdown`});break;case`diagram`:d=await new a().analyze(u,{diagramType:`architecture`});break;default:throw new g(`Unknown analyze type: ${t}\nTypes: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`)}console.log(d.output)}},{name:`onboard`,description:`Run all analyses for first-time codebase onboarding`,usage:`aikit onboard <path> [--generate] [--out-dir <dir>]`,run:async e=>{let{onboard:t}=await import(`../../tools/dist/index.js`),n=``,r=`memory`,i;for(let t=0;t<e.length;t++){let a=e[t].trim();a===`--generate`?r=`generate`:a===`--out-dir`&&t+1<e.length?i=e[++t].trim():a.startsWith(`--`)||(n=a)}n||=I()??N();let a=j(n),o=vn();console.log(`Onboarding: ${a} (mode: ${r})`),console.log(`Running analyses...
3
3
  `);let s=await t({path:a,mode:r,outDir:i??o.onboardDir});for(let e of s.steps){let t=e.status===`success`?`✓`:`✗`,n=e.status===`success`?`${e.durationMs}ms, ${e.output.length} chars`:e.error;console.log(` ${t} ${e.name} — ${n}`)}console.log(`\nTotal: ${s.totalDurationMs}ms`),s.outDir&&console.log(`Output written to: ${s.outDir}`)}}],Cn=[{name:`parse-output`,description:`Parse build or tool output from stdin`,usage:`aikit parse-output [--tool tsc|vitest|biome|git-status]`,run:async e=>{let t=v(e,`--tool`,``).trim()||void 0,n=await m();n.trim()||(console.error(`Usage: aikit parse-output [--tool tsc|vitest|biome|git-status]`),process.exit(1)),ee(kt(n,t))}},{name:`git`,description:`Show git branch, status, recent commits, and optional diff stats`,usage:`aikit git [--cwd path] [--commit-count N] [--diff]`,run:async e=>{re(await vt({cwd:v(e,`--cwd`,``).trim()||void 0,commitCount:_(e,`--commit-count`,5),includeDiff:ge(e,`--diff`)}))}},{name:`diff`,description:`Parse unified diff text from stdin into structured file changes`,usage:`git diff | aikit diff`,run:async()=>{let e=await m();e.trim()||(console.error(`Usage: git diff | aikit diff`),process.exit(1)),ne(dt({diff:e}))}},{name:`summarize`,description:`Show a structural summary of a file`,usage:`aikit summarize <path>`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit summarize <path>`),process.exit(1)),ve(await pt({path:j(t)}))}},{name:`checkpoint`,description:`Save and restore lightweight session checkpoints`,usage:`aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`),process.exit(1));let n=await ue();switch(t){case`save`:{let t=e.shift()?.trim(),r=v(e,`--data`,``),i=v(e,`--notes`,``).trim()||void 0,a=r.trim()?``:await m();t||(console.error(`Usage: aikit checkpoint save <label> [--data json] [--notes text]`),process.exit(1)),ae(it(n,t,_e(r||a),{notes:i}));return}case`load`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint load <id>`),process.exit(1));let r=rt(n,t);if(!r){console.log(`No checkpoint found: ${t}`);return}ae(r);return}case`list`:{let e=nt(n);if(e.length===0){console.log(`No checkpoints saved.`);return}console.log(`Checkpoints (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.id}`),console.log(` Label: ${t.label}`),console.log(` Created: ${t.createdAt}`);return}case`latest`:{let e=tt(n);if(!e){console.log(`No checkpoints saved.`);return}ae(e);return}default:console.error(`Unknown checkpoint action: ${t}`),console.error(`Actions: save, load, list, latest`),process.exit(1)}}}],wn=k(N(),`.aikit`),z=k(wn,`daemon.json`),Tn=3210,B=F(`cli:daemon`);function En(){if(!S(z))return null;try{return JSON.parse(w(z,`utf-8`))}catch{return null}}function Dn(e){S(wn)||C(wn,{recursive:!0});let t=`${z}.tmp`;D(t,JSON.stringify(e,null,2)),Se(t,z)}function On(){S(z)&&E(z)}async function V(e){try{return process.kill(e,0),!0}catch{return!1}}async function kn(e){try{return(await fetch(`http://127.0.0.1:${e}/health`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}async function An(e,t){let n=Date.now();for(B.debug(`Polling health endpoint on port ${e}...`);Date.now()-n<t;){if(await kn(e))return B.debug(`Daemon health check passed`),!0;await new Promise(e=>setTimeout(e,200))}return!1}async function jn(){let e=En();if(!e)return B.info(`Daemon is not running`),null;if(!await V(e.pid))return On(),B.debug(`Daemon was not running (stale state cleaned up)`),{pid:e.pid,wasRunning:!1};B.debug(`Sending SIGTERM to daemon...`);try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,2e3)),await V(e.pid)&&(B.debug(`Sending SIGKILL to daemon...`),process.kill(e.pid,`SIGKILL`))}catch{}return On(),{pid:e.pid,wasRunning:!0}}async function Mn(e){let t=te();B.debug(`Spawning daemon process...`);let n=dn(process.execPath,[t,`--transport`,`http`,`--port`,String(e)],{stdio:`ignore`,detached:!0,env:{...process.env,NODE_OPTIONS:f(process.env.NODE_OPTIONS),AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(e)}});n.unref(),await An(e,3e4)||(B.error(`Daemon failed to start within 30 seconds`),n.kill(`SIGTERM`),process.exit(1));let r=se();if(n.pid===void 0)throw Error(`Daemon child process has no PID`);return Dn({port:e,pid:n.pid,version:r,startedAt:new Date().toISOString()}),{pid:n.pid,port:e}}const Nn=[{name:`daemon`,description:`Run AI Kit as a background HTTP daemon — survives IDE restarts, shares across windows (start|stop|status|restart)`,usage:`aikit daemon <start|stop|status|restart> [--port <port>]`,run:async e=>{let t=e[0];if(!t){console.error(`Usage: aikit daemon <start|stop|status|restart>`),console.error(``),console.error(`Commands:`),console.error(` start Start the AI Kit daemon`),console.error(` stop Stop the AI Kit daemon`),console.error(` status Show daemon status`),console.error(` restart Restart the AI Kit daemon`);return}switch(t){case`start`:{let t=En();if(t){if(await V(t.pid)&&await kn(t.port)){B.info(`Daemon already running (PID ${t.pid}, port ${t.port})`);return}B.debug(`Cleaning up stale daemon state...`),On()}let n=e.indexOf(`--port`),r=await Mn(n!==-1&&e[n+1]?Number.parseInt(e[n+1],10):Tn);B.info(`Daemon started (PID ${r.pid}, port ${r.port})`);return}case`stop`:{let e=await jn();e?.wasRunning&&B.info(`Daemon stopped (PID ${e.pid})`);return}case`status`:{let e=En();if(!e){console.log(`Daemon: stopped`);return}if(!(await V(e.pid)&&await kn(e.port))){On(),console.log(`Daemon: stopped (stale state cleaned up)`);return}console.log(`Daemon: running`),console.log(` PID: ${e.pid}`),console.log(` Port: ${e.port}`),console.log(` Version: ${e.version}`),console.log(` Started: ${e.startedAt}`);return}case`restart`:{let t=En();if(t){if(await V(t.pid)){B.debug(`Sending SIGTERM to daemon...`);try{process.kill(t.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,2e3)),await V(t.pid)&&(B.debug(`Sending SIGKILL to daemon...`),process.kill(t.pid,`SIGKILL`))}catch{}}On(),B.info(`Daemon stopped (PID ${t.pid})`)}else B.info(`Daemon is not running`);let n=e.indexOf(`--port`),r=await Mn(n!==-1&&e[n+1]?Number.parseInt(e[n+1],10):Tn);B.info(`Daemon started (PID ${r.pid}, port ${r.port})`);return}default:console.error(`Unknown daemon command: ${t}`),console.error("Use `aikit daemon` for help.")}}}],Pn=[{name:`diagram`,description:`Render a diagram from structured JSON input. Reads stdin, produces HTML + markdown + SVG.`,usage:`aikit diagram [--type <type>] [--output <dir>] [--title <title>] [--subtitle <subtitle>] [--palette warm|technical] [--format all|html|md|svg] < input.json`,run:async e=>{let t=H(e,`--type`),n=H(e,`--output`),r=H(e,`--title`),i=H(e,`--subtitle`),a=H(e,`--format`)??`all`,o=H(e,`--palette`),s=``,c=process.stdin;c.setEncoding(`utf-8`);for await(let e of c)s+=e;s.trim()||(console.error(`No input provided. Pipe diagram JSON to stdin.`),console.error(`Usage: aikit diagram [--type <type>] [--output <dir>] < input.json`),process.exit(1));let l;try{l=JSON.parse(s)}catch(e){console.error(`Invalid JSON: ${e.message}`),process.exit(1)}let u=l.meta??{};t&&l.diagram_type!==t&&(console.error(`Error: --type "${t}" does not match input diagram_type "${l.diagram_type}". Remove --type or use the correct type. Mutating the discriminator produces invalid output.`),process.exit(1)),o&&(o!==`warm`&&o!==`technical`&&(console.error(`Invalid palette "${o}". Expected "warm" or "technical".`),process.exit(1)),u.palette&&u.palette!==o&&console.warn(`Warning: --palette "${o}" overrides input meta.palette "${String(u.palette)}"`),l.meta={...u,palette:o});try{let e=pn(l,{title:r||void 0,subtitle:i||void 0,dualOutput:!0});if(n){let t=j(n);await qe(t,{recursive:!0});let i=mn(r||l.meta?.title||`diagram`);if(a===`all`||a===`html`){let n=k(t,`${i}.html`);await L(n,e.html,`utf-8`),console.log(`Written: ${n}`)}if((a===`all`||a===`md`)&&e.markdown){let n=k(t,`${i}.md`);await L(n,e.markdown,`utf-8`),console.log(`Written: ${n}`)}if(a===`all`||a===`svg`){let n=fn(e.html);if(n){let e=k(t,`${i}.svg`);await L(e,n,`utf-8`),console.log(`Written: ${e}`)}}}else process.stdout.write(e.html)}catch(e){console.error(`Rendering failed: ${e.message}`),process.exit(1)}}}];function H(e,t){let n=e.indexOf(t);if(n>=0&&n+1<e.length)return e[n+1]}function Fn(e){let t=``,n=0,r=e.length;for(;n<r;)if(e[n]===`"`){for(t+=`"`,n++;n<r&&e[n]!==`"`;)e[n]===`\\`&&(t+=e[n++]),n<r&&(t+=e[n++]);n<r&&(t+=e[n++])}else if(e[n]===`/`&&n+1<r&&e[n+1]===`/`)for(n+=2;n<r&&e[n]!==`
4
4
  `;)n++;else if(e[n]===`/`&&n+1<r&&e[n+1]===`*`){for(n+=2;n+1<r&&!(e[n]===`*`&&e[n+1]===`/`);)n++;n+=2}else t+=e[n++];return t.replace(/,(\s*[}\]])/g,`$1`)}var U=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!S(t))return{};let n=await Je(t,`utf-8`);try{return JSON.parse(Fn(n))}catch{throw Error(`Invalid JSON in ${t}. Please fix or remove the file before retrying.`)}}async writeConfig(e,t){let n=this.getConfigPath(t),r=O(n),i=k(r,`.aikit-tmp-${hn()}.json`);await qe(r,{recursive:!0});try{await L(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await Ye(i,n)}catch(e){try{await Ze(i)}catch{}throw e}}async registerMcp(e,t,n){let r=await this.readConfig(n);r[this.configKey]||(r[this.configKey]={}),r[this.configKey][e]=t,await this.writeConfig(r,n)}async unregisterMcp(e,t){let n=await this.readConfig(t);n[this.configKey]&&(delete n[this.configKey][e],await this.writeConfig(n,t))}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},In=class extends U{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?S(this.getPathModule().resolve(N(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(N(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(N(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(N(),`.claude`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:e.resolve(t,`commands`),instructions:e.resolve(t,`CLAUDE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?M:A}},Ln=class extends U{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?S(this.getPathModule().resolve(N(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(N(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(N(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(N(),`.codex`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getPathModule(){return process.platform===`win32`?M:A}},W=class extends U{family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;hasInstructions=!1;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getConfigDir();if(process.platform===`darwin`){let t=this.getMacAppPath();return S(e)||t!==null&&S(t)}return S(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(N(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(N(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),hooks:e.resolve(t,`hooks`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=N();if(process.platform===`win32`){let n=process.env.APPDATA??e.resolve(t,`AppData`,`Roaming`);return e.resolve(n,this.configDirName,`User`)}if(process.platform===`darwin`)return e.resolve(t,`Library`,`Application Support`,this.configDirName,`User`);let n=process.env.XDG_CONFIG_HOME??e.resolve(t,`.config`);return e.resolve(n,this.configDirName,`User`)}getMacAppPath(){return null}getInstructionFilePath(){return null}getPathModule(){return process.platform===`win32`?M:A}},Rn=class extends U{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?S(j(N(),`.copilot`)):!1}getConfigPath(){return j(N(),`.copilot`,`mcp-config.json`)}async registerMcp(e,t,n){let r={...t,tools:[`*`]},i=await this.readConfig(n);i[this.configKey]||(i[this.configKey]={}),i[this.configKey][e]=r,await this.writeConfig(i,n)}getScaffoldRoot(){return j(N(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=j(N(),`.copilot`);return{agents:j(e,`agents`),skills:j(e,`skills`),prompts:null,flows:j(e,`flows`),hooks:j(e,`hooks`),commands:null,instructions:j(N(),`.github`,`copilot-instructions.md`),manifest:j(e,`.aikit-scaffold.json`)}}},zn=class extends W{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(N(),this.scaffoldBase,`rules`,`aikit.mdc`)}},Bn=class extends W{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(N(),this.scaffoldBase,`rules`,`aikit.mdc`)}},Vn=class e extends U{id=`intellij`;name=`IntelliJ IDEA`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`servers`;static PRODUCTS=[`IntelliJIdea`,`IdeaIC`,`WebStorm`,`PyCharm`,`PyCharmCE`,`GoLand`,`PhpStorm`,`CLion`,`Rider`,`RubyMine`,`RustRover`,`DataGrip`];async detect(){if(!this.isPlatformSupported())return!1;if(S(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!S(t))return!1;try{return T(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return j(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await qe(r,{recursive:!0});let i=t.args??[],a=i.indexOf(`-e`),o;if(a!==-1&&a+1<i.length){let t=i[a+1],n=j(r,`${e}-launcher.js`);await L(n,t,`utf-8`),o=[...i.slice(0,a),n,...i.slice(a+2)]}else o=[...i];let s={type:`stdio`,...t,args:o};await super.registerMcp(e,s,n)}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=N();return process.platform===`win32`?j(process.env.LOCALAPPDATA??j(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?j(e,`Library`,`Application Support`,`github-copilot`,`intellij`):j(process.env.XDG_CONFIG_HOME??j(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=N();return process.platform===`win32`?j(process.env.APPDATA??j(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?j(e,`Library`,`Application Support`,`JetBrains`):j(process.env.XDG_CONFIG_HOME??j(e,`.config`),`JetBrains`)}},Hn=class extends W{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(N(),this.scaffoldBase,`rules`,`aikit.md`)}},Un=class extends W{id=`vscode`;name=`VS Code`;configKey=`servers`;configDirName=`Code`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(N(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Wn=class extends W{id=`vscode-insiders`;name=`VS Code Insiders`;configKey=`servers`;configDirName=`Code - Insiders`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code - Insiders.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(N(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Gn=class extends W{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(N(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Kn=class extends W{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(N(),this.scaffoldBase,`rules`,`aikit.md`)}},qn=class extends U{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?S(this.getPathModule().resolve(N(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(N(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(N(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(N(),`.gemini`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getPathModule(){return process.platform===`win32`?M:A}},Jn=class extends U{id=`hermes`;name=`Hermes Agent`;family=`hermes`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcp_servers`;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getPathModule();return S(this.getHermesDir(e))}getConfigPath(){return this.getPathModule().resolve(this.getHermesDir(),`config.yaml`)}async readConfig(){let e=this.getConfigPath();if(!S(e))return{};let t=w(e,`utf-8`);try{return gn(t)??{}}catch{throw Error(`Invalid YAML in ${e}. Please fix or remove the file before retrying.`)}}async writeConfig(e){let t=this.getConfigPath(),n=this.getPathModule().dirname(t),r={};if(S(t))try{r=gn(w(t,`utf-8`))}catch{}e[this.configKey]&&(r[this.configKey]=e[this.configKey]),await qe(n,{recursive:!0}),D(t,_n(r,{lineWidth:120}),`utf-8`)}async registerMcp(e,t){let n=await this.readConfig();n[this.configKey]||(n[this.configKey]={});let r=n[this.configKey];r[e]={command:t.command,args:t.args??[],enabled:!0},await this.writeConfig(n)}getScaffoldRoot(){return this.getHermesDir()}getScaffoldPaths(){let e=this.getPathModule(),t=this.getHermesDir();return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}buildInstructionContent(e,t){return`# AI Kit — Hermes Agent Instructions
@@ -1002,6 +1002,9 @@ declare function compareVersionDir(a: string, b: string): number;
1002
1002
  * Remove old version directories from `versionsDir`, keeping the specified
1003
1003
  * version + 1 backup (the next newest). Best-effort — never throws.
1004
1004
  *
1005
+ * Handles Windows EPERM: skips directories that contain the running process
1006
+ * to avoid file-lock conflicts (rmSync fails on memory-mapped files).
1007
+ *
1005
1008
  * @param versionsDir Path to `~/.aikit/versions/` (or equivalent)
1006
1009
  * @param keepVersion Raw semver string (no `v` prefix) to preserve.
1007
1010
  * If omitted or `"0.0.0"`, cleanup is skipped.
@@ -1 +1 @@
1
- import{EventEmitter as e}from"node:events";import{basename as t,extname as n,join as r,resolve as i}from"node:path";import{createHash as a}from"node:crypto";import{appendFileSync as o,closeSync as s,constants as c,copyFileSync as l,existsSync as u,lstatSync as ee,mkdirSync as d,openSync as te,readFileSync as ne,readdirSync as f,renameSync as p,rmSync as m,statSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{homedir as v}from"node:os";var re=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new y(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new y(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},y=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const b={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},x={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},S={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},ie={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},ae={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},oe={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},se={backend:`sqlite-vec`,path:b.data,tableName:`knowledge`},ce=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],le={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},ue={maxResults:10,minScore:.25},de=/^[a-z][a-z0-9-]*$/,fe=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],C={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},pe=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],me=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function he(e){let r=n(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${b.aiContext}/`)?`produced-knowledge`:e.includes(`${b.aiCurated}/`)?`curated-knowledge`:pe.some(t=>t.test(e))?`test-code`:me.some(t=>t.test(e))?`cdk-stack`:r in C?C[r]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(r)?`code-other`:`unknown`}const w={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function ge(e){return w[e]??`source`}function _e(e){return Object.entries(w).filter(([,t])=>t===e).map(([e])=>e)}var T=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},ve=class extends T{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},ye=class extends T{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},be=class extends T{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},xe=class extends T{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},E=class extends T{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},D=class extends T{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function Se(e){return e instanceof E}function Ce(e){return e instanceof D}let O=!1;function we(e){try{return!ee(e).isSymbolicLink()}catch{return!1}}function Te(e,t){if(h(e).isDirectory()){d(t,{recursive:!0});for(let n of f(e))k(i(e,n),i(t,n));m(e,{recursive:!0,force:!0});return}d(i(t,`..`),{recursive:!0}),l(e,t),g(e)}function Ee(e,t){try{p(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!u(e)&&u(t))return;if(r!==`EXDEV`)throw n;Te(e,t)}}function k(e,t){if(!u(e)||e===t||!we(e))return;let n=h(e);if(!u(t)){d(i(t,`..`),{recursive:!0}),Ee(e,t);return}if(n.isDirectory()){d(t,{recursive:!0});for(let n of f(e))k(i(e,n),i(t,n));try{m(e,{recursive:!0,force:!0})}catch{}}}function A(e){if(u(e))try{f(e).length===0&&m(e,{recursive:!0,force:!0})}catch{}}function De(e){let t=i(e,x.data);d(t,{recursive:!0});for(let n of f(e))n!==x.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&k(i(e,n),i(t,n))}function j(e){return z(F(e))}function Oe(e){if(O)return;O=!0,d(e,{recursive:!0});let t=v(),n=i(t,S.legacyDataRoot),r=i(t,S.legacyStateRoot),a=i(e,S.workspaces),o=i(e,S.logs),s=i(e,S.state);if(u(n)&&n!==e){d(a,{recursive:!0});for(let t of f(n))k(i(n,t),t===S.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?i(e,t):i(a,t));A(n)}if(u(r)&&r!==e){for(let e of f(r))k(i(r,e),e===`logs`?o:i(s,e));A(r)}}function M(e){let t=i(e),n=j(t),r=i(n,x.data),a=i(N(),S.logs),o=[{from:i(t,S.legacyDataRoot),to:r},{from:i(t,S.legacyStateRoot),to:i(n,x.state)},{from:i(t,b.data),to:r},{from:i(t,b.state),to:i(n,x.state)},{from:i(t,b.aiCurated),to:i(n,x.curated)},{from:i(t,b.aiContext),to:i(n,x.onboard)},{from:i(t,b.restorePoints),to:i(n,x.restorePoints)},{from:i(t,b.brainstorm),to:i(n,x.brainstorm)},{from:i(t,b.handoffs),to:i(n,x.handoffs)},{from:i(t,b.logs),to:a}];d(n,{recursive:!0}),d(a,{recursive:!0}),De(n);for(let e of o)k(e.from,e.to);A(i(t,b.root)),A(i(t,b.ai)),A(i(t,b.brainstorm)),A(i(t,b.handoffs))}function ke(e){return M(e),i(z(R(e).partition),x.state)}function N(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??i(v(),S.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Oe(t),t}function P(e){return je()?e.toLowerCase():e}function F(e){let n=i(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${a(`sha256`).update(P(n)).digest(`hex`).slice(0,8)}`}function Ae(e,t=12){let n=i(e);return a(`sha256`).update(P(n)).digest(`hex`).slice(0,t)}function je(){return process.platform===`win32`||process.platform===`darwin`}function I(){let e=i(N(),S.registry);if(!u(e))return{version:1,workspaces:{}};let t=ne(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Me(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=te(n,c.O_CREAT|c.O_EXCL|c.O_WRONLY);return _(e,`${process.pid}\n`),s(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=h(n);if(Date.now()-e>3e4){g(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function Ne(e){try{g(e)}catch{}}function L(e){let t=N();d(t,{recursive:!0});let n=i(t,S.registry),r=Me(n);try{let t=`${n}.tmp`;_(t,JSON.stringify(e,null,2),`utf-8`),p(t,n)}finally{Ne(r)}}function R(e){let t=I(),n=F(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:i(e),registeredAt:r,lastAccessedAt:r},d(z(n),{recursive:!0}),L(t),t.workspaces[n]}function Pe(e){let t=I(),n=F(e);return t.workspaces[n]}function Fe(){let e=I();return Object.values(e.workspaces)}function z(e){return i(N(),S.workspaces,e)}function Ie(){return u(i(N(),S.registry))}function Le(){return i(N(),S.logs)}var Re=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};function ze(e,t){let n=B[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const B={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`]}},V={debug:0,info:1,warn:2,error:3},H=[];let U=process.env.AIKIT_LOG_LEVEL??`info`,W=!1,G=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function Be(){return G?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let K;function q(){return K||=Le(),K}function Ve(e){let t=e.toISOString().slice(0,10);return r(q(),`${t}.jsonl`)}let J=0;function He(){let e=Date.now();if(!(e-J<36e5)){J=e;try{let t=q(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of f(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{g(r(t,e))}catch{}}catch{}}}function Ue(e,t){try{d(q(),{recursive:!0}),o(Ve(t),`${e}\n`),He()}catch{}}function We(e){U=e}function Ge(){return U}function Ke(e){G=e}function qe(){K=void 0}function Je(e){W=e}function Ye(e){if(e instanceof Error){let t={error:e.message};return W?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function Xe(e){return H.push(e),()=>{let t=H.indexOf(e);t>=0&&H.splice(t,1)}}function Y(e){function t(t,n,r){if(V[t]<V[U])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of H)try{i({level:t,component:e,message:n,data:r})}catch{}Be()&&(t===`warn`||t===`error`)&&Ue(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const X={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function Ze(e,t={}){let{maxAttempts:n=X.maxAttempts,baseDelayMs:r=X.baseDelayMs,maxDelayMs:i=X.maxDelayMs,jitterFraction:a=X.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof E),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof E&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await Qe(l)}throw s}function Qe(e){return new Promise(t=>setTimeout(t,e))}let Z;function $e(){return Z===void 0&&(Z=v()),Z}function Q(){try{return process.cwd()}catch{return null}}function et(){return Q()??$e()}const tt=[`indexed`,`curated`,`produced`],nt=[`source`,`documentation`,`test`,`config`,`generated`],rt=[`auto`,`manual`,`smart`],it=[`efficient`,`normal`,`full`],at=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`],ot=Y(`core:version-manager`);function $(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function st(e,t){try{if(!u(e)||!t||t===`0.0.0`)return;let n=f(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort($),i=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)i.add(e);for(let t of n)i.has(t)||(m(r(e,t),{recursive:!0,force:!0}),ot.debug(`Cleaned old version: ${t}`))}catch(e){ot.warn(`Version directory cleanup failed`,{error:e})}}export{S as AIKIT_GLOBAL_PATHS,b as AIKIT_PATHS,x as AIKIT_RUNTIME_PATHS,T as AikitError,de as CATEGORY_PATTERN,ie as CHUNK_SIZES,at as CONTENT_TYPES,re as CircuitBreaker,y as CircuitOpenError,xe as ConfigError,fe as DEFAULT_CATEGORIES,ae as EMBEDDING_DEFAULTS,ve as EmbeddingError,le as FILE_LIMITS,Re as HealthBus,rt as INDEX_MODES,ce as INSTALL_ARGS,be as IndexError,tt as KNOWLEDGE_ORIGINS,B as LAYER_FIELD_REQUIREMENTS,oe as MODEL_REGISTRY,D as PermanentError,ue as SEARCH_DEFAULTS,nt as SOURCE_TYPES,se as STORE_DEFAULTS,ye as StoreError,it as TOKEN_BUDGETS,E as TransientError,Xe as addLogListener,st as cleanupOldVersions,$ as compareVersionDir,F as computePartitionKey,ge as contentTypeToSourceType,Y as createLogger,he as detectContentType,N as getGlobalDataDir,Ge as getLogLevel,z as getPartitionDir,j as getWorkspacePartitionDir,Ae as hashPath,Ce as isPermanent,Se as isTransient,Ie as isUserInstalled,Fe as listWorkspaces,I as loadRegistry,Pe as lookupWorkspace,M as migrateLegacyWorkspaceLayout,P as normalizePathForHash,R as registerWorkspace,qe as resetLogDir,Le as resolveLogDir,ke as resolveStateDir,Q as safeCwd,et as safeCwdOrHome,L as saveRegistry,Ye as serializeError,Je as setDetailedErrorLoggingEnabled,Ke as setFileSinkEnabled,We as setLogLevel,_e as sourceTypeContentTypes,ze as validateLayerMetadata,Ze as withRetry};
1
+ import{EventEmitter as e}from"node:events";import{basename as t,dirname as n,extname as r,join as i,resolve as a,sep as o}from"node:path";import{createHash as s}from"node:crypto";import{appendFileSync as c,closeSync as l,constants as u,copyFileSync as ee,existsSync as d,lstatSync as te,mkdirSync as f,openSync as ne,readFileSync as re,readdirSync as p,renameSync as m,rmSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{homedir as y}from"node:os";import{fileURLToPath as ie}from"node:url";var ae=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new b(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new b(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},b=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const x={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},S={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},C={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},oe={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},se={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},ce={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},le={backend:`sqlite-vec`,path:x.data,tableName:`knowledge`},ue=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],de={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},fe={maxResults:10,minScore:.25},pe=/^[a-z][a-z0-9-]*$/,me=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],w={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},he=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],ge=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function _e(e){let n=r(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${x.aiContext}/`)?`produced-knowledge`:e.includes(`${x.aiCurated}/`)?`curated-knowledge`:he.some(t=>t.test(e))?`test-code`:ge.some(t=>t.test(e))?`cdk-stack`:n in w?w[n]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(n)?`code-other`:`unknown`}const T={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function ve(e){return T[e]??`source`}function ye(e){return Object.entries(T).filter(([,t])=>t===e).map(([e])=>e)}var E=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},be=class extends E{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},xe=class extends E{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},Se=class extends E{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},Ce=class extends E{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},D=class extends E{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},O=class extends E{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function we(e){return e instanceof D}function Te(e){return e instanceof O}let k=!1;function Ee(e){try{return!te(e).isSymbolicLink()}catch{return!1}}function De(e,t){if(g(e).isDirectory()){f(t,{recursive:!0});for(let n of p(e))A(a(e,n),a(t,n));h(e,{recursive:!0,force:!0});return}f(a(t,`..`),{recursive:!0}),ee(e,t),_(e)}function Oe(e,t){try{m(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!d(e)&&d(t))return;if(r!==`EXDEV`)throw n;De(e,t)}}function A(e,t){if(!d(e)||e===t||!Ee(e))return;let n=g(e);if(!d(t)){f(a(t,`..`),{recursive:!0}),Oe(e,t);return}if(n.isDirectory()){f(t,{recursive:!0});for(let n of p(e))A(a(e,n),a(t,n));try{h(e,{recursive:!0,force:!0})}catch{}}}function j(e){if(d(e))try{p(e).length===0&&h(e,{recursive:!0,force:!0})}catch{}}function ke(e){let t=a(e,S.data);f(t,{recursive:!0});for(let n of p(e))n!==S.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&A(a(e,n),a(t,n))}function M(e){return B(I(e))}function Ae(e){if(k)return;k=!0,f(e,{recursive:!0});let t=y(),n=a(t,C.legacyDataRoot),r=a(t,C.legacyStateRoot),i=a(e,C.workspaces),o=a(e,C.logs),s=a(e,C.state);if(d(n)&&n!==e){f(i,{recursive:!0});for(let t of p(n))A(a(n,t),t===C.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?a(e,t):a(i,t));j(n)}if(d(r)&&r!==e){for(let e of p(r))A(a(r,e),e===`logs`?o:a(s,e));j(r)}}function N(e){let t=a(e),n=M(t),r=a(n,S.data),i=a(P(),C.logs),o=[{from:a(t,C.legacyDataRoot),to:r},{from:a(t,C.legacyStateRoot),to:a(n,S.state)},{from:a(t,x.data),to:r},{from:a(t,x.state),to:a(n,S.state)},{from:a(t,x.aiCurated),to:a(n,S.curated)},{from:a(t,x.aiContext),to:a(n,S.onboard)},{from:a(t,x.restorePoints),to:a(n,S.restorePoints)},{from:a(t,x.brainstorm),to:a(n,S.brainstorm)},{from:a(t,x.handoffs),to:a(n,S.handoffs)},{from:a(t,x.logs),to:i}];f(n,{recursive:!0}),f(i,{recursive:!0}),ke(n);for(let e of o)A(e.from,e.to);j(a(t,x.root)),j(a(t,x.ai)),j(a(t,x.brainstorm)),j(a(t,x.handoffs))}function je(e){return N(e),a(B(z(e).partition),S.state)}function P(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??a(y(),C.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Ae(t),t}function F(e){return Ne()?e.toLowerCase():e}function I(e){let n=a(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${s(`sha256`).update(F(n)).digest(`hex`).slice(0,8)}`}function Me(e,t=12){let n=a(e);return s(`sha256`).update(F(n)).digest(`hex`).slice(0,t)}function Ne(){return process.platform===`win32`||process.platform===`darwin`}function L(){let e=a(P(),C.registry);if(!d(e))return{version:1,workspaces:{}};let t=re(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Pe(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ne(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function Fe(e){try{_(e)}catch{}}function R(e){let t=P();f(t,{recursive:!0});let n=a(t,C.registry),r=Pe(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{Fe(r)}}function z(e){let t=L(),n=I(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:a(e),registeredAt:r,lastAccessedAt:r},f(B(n),{recursive:!0}),R(t),t.workspaces[n]}function Ie(e){let t=L(),n=I(e);return t.workspaces[n]}function Le(){let e=L();return Object.values(e.workspaces)}function B(e){return a(P(),C.workspaces,e)}function Re(){return d(a(P(),C.registry))}function V(){return a(P(),C.logs)}var ze=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};function Be(e,t){let n=H[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const H={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`]}},U={debug:0,info:1,warn:2,error:3},W=[];let G=process.env.AIKIT_LOG_LEVEL??`info`,K=!1,q=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function Ve(){return q?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let J;function Y(){return J||=V(),J}function He(e){let t=e.toISOString().slice(0,10);return i(Y(),`${t}.jsonl`)}let Ue=0;function We(){let e=Date.now();if(!(e-Ue<36e5)){Ue=e;try{let t=Y(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of p(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(i(t,e))}catch{}}catch{}}}function Ge(e,t){try{f(Y(),{recursive:!0}),c(He(t),`${e}\n`),We()}catch{}}function Ke(e){G=e}function qe(){return G}function Je(e){q=e}function Ye(){J=void 0}function Xe(e){K=e}function Ze(e){if(e instanceof Error){let t={error:e.message};return K?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function Qe(e){return W.push(e),()=>{let t=W.indexOf(e);t>=0&&W.splice(t,1)}}function $e(e){function t(t,n,r){if(U[t]<U[G])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of W)try{i({level:t,component:e,message:n,data:r})}catch{}Ve()&&(t===`warn`||t===`error`)&&Ge(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const X={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function et(e,t={}){let{maxAttempts:n=X.maxAttempts,baseDelayMs:r=X.baseDelayMs,maxDelayMs:i=X.maxDelayMs,jitterFraction:a=X.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof D),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof D&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await tt(l)}throw s}function tt(e){return new Promise(t=>setTimeout(t,e))}let Z;function nt(){return Z===void 0&&(Z=y()),Z}function rt(){try{return process.cwd()}catch{return null}}function it(){return rt()??nt()}const at=[`indexed`,`curated`,`produced`],ot=[`source`,`documentation`,`test`,`config`,`generated`],st=[`auto`,`manual`,`smart`],ct=[`efficient`,`normal`,`full`],lt=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`],Q=$e(`core:version-manager`);function $(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function ut(e){let t=a(e),r=n(ie(import.meta.url)),i=process.cwd();return a(r).startsWith(t+o)||a(i).startsWith(t+o)||a(r)===t||a(i)===t}function dt(e,t){try{if(!d(e)||!t||t===`0.0.0`)return;let n=p(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort($),r=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)r.add(e);for(let t of n)if(!r.has(t)){let n=i(e,t);if(ut(n)){Q.debug(`Skipping ${t} — currently in use by running process`);continue}h(n,{recursive:!0,force:!0}),Q.debug(`Cleaned old version: ${t}`)}}catch(e){Q.debug(`Version directory cleanup failed`,{error:e})}}export{C as AIKIT_GLOBAL_PATHS,x as AIKIT_PATHS,S as AIKIT_RUNTIME_PATHS,E as AikitError,pe as CATEGORY_PATTERN,oe as CHUNK_SIZES,lt as CONTENT_TYPES,ae as CircuitBreaker,b as CircuitOpenError,Ce as ConfigError,me as DEFAULT_CATEGORIES,se as EMBEDDING_DEFAULTS,be as EmbeddingError,de as FILE_LIMITS,ze as HealthBus,st as INDEX_MODES,ue as INSTALL_ARGS,Se as IndexError,at as KNOWLEDGE_ORIGINS,H as LAYER_FIELD_REQUIREMENTS,ce as MODEL_REGISTRY,O as PermanentError,fe as SEARCH_DEFAULTS,ot as SOURCE_TYPES,le as STORE_DEFAULTS,xe as StoreError,ct as TOKEN_BUDGETS,D as TransientError,Qe as addLogListener,dt as cleanupOldVersions,$ as compareVersionDir,I as computePartitionKey,ve as contentTypeToSourceType,$e as createLogger,_e as detectContentType,P as getGlobalDataDir,qe as getLogLevel,B as getPartitionDir,M as getWorkspacePartitionDir,Me as hashPath,Te as isPermanent,we as isTransient,Re as isUserInstalled,Le as listWorkspaces,L as loadRegistry,Ie as lookupWorkspace,N as migrateLegacyWorkspaceLayout,F as normalizePathForHash,z as registerWorkspace,Ye as resetLogDir,V as resolveLogDir,je as resolveStateDir,rt as safeCwd,it as safeCwdOrHome,R as saveRegistry,Ze as serializeError,Xe as setDetailedErrorLoggingEnabled,Je as setFileSinkEnabled,Ke as setLogLevel,ye as sourceTypeContentTypes,Be as validateLayerMetadata,et as withRetry};
@@ -1,4 +1,38 @@
1
- "use strict";var AnnotationInit=(()=>{var A=Object.defineProperty;var N=(l,t,e)=>t in l?A(l,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[t]=e;var d=(l,t,e)=>N(l,typeof t!="symbol"?t+"":t,e);function b(l,t){if(document.getElementById(l))return;let e=document.createElement("style");e.id=l,e.textContent=t,document.head.appendChild(e)}var C=document.createElement("div");function g(l){return C.textContent=l,C.innerHTML}var H="aikit-annotation-popover",O=`
1
+ "use strict";var AnnotationInit=(()=>{var N=Object.defineProperty;var O=(l,t,e)=>t in l?N(l,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[t]=e;var d=(l,t,e)=>O(l,typeof t!="symbol"?t+"":t,e);var C=`
2
+ .action-bar {
3
+ flex-shrink: 0;
4
+ position: sticky;
5
+ bottom: 0;
6
+ display: flex;
7
+ flex-wrap: nowrap;
8
+ align-items: center;
9
+ gap: var(--dt-space-2);
10
+ padding: var(--dt-space-3) var(--dt-space-4);
11
+ border-top: 1px solid var(--dt-border-default);
12
+ background: color-mix(in srgb, var(--dt-bg-primary, #0c0c0c) 92%, transparent);
13
+ backdrop-filter: blur(12px);
14
+ -webkit-backdrop-filter: blur(12px);
15
+ z-index: 10;
16
+ overflow-x: auto;
17
+ }
18
+ .action-bar:empty {
19
+ display: none;
20
+ }
21
+ /* Compact controls \u2014 single-row inline layout */
22
+ .action-bar .bk-action,
23
+ .action-bar .bk-select {
24
+ font-size: var(--dt-font-size-sm);
25
+ min-height: 2rem;
26
+ flex-shrink: 0;
27
+ }
28
+ .action-bar .bk-select {
29
+ max-width: 10rem;
30
+ padding: 0 0.5rem;
31
+ }
32
+ .action-bar .bk-multi-select {
33
+ max-width: 10rem;
34
+ }
35
+ `;function b(l,t){if(document.getElementById(l))return;let e=document.createElement("style");e.id=l,e.textContent=t,document.head.appendChild(e)}var M=document.createElement("div");function g(l){return M.textContent=l,M.innerHTML}var H="aikit-annotation-popover",B=`
2
36
  .cp-backdrop {
3
37
  position: fixed;
4
38
  top: 0;
@@ -96,7 +130,7 @@
96
130
  .cp-btn--remove:hover {
97
131
  background: var(--dt-annotation-deletion-bg);
98
132
  }
99
- `,v=class{constructor(t,e){d(this,"el");d(this,"textarea");d(this,"result");d(this,"backdrop");d(this,"options");this.result=t,this.options=e,b(H,O),this.backdrop=document.createElement("div"),this.backdrop.className="cp-backdrop",this.el=document.createElement("div"),this.el.className="cp-popover",this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label","Feedback on selection"),this.el.innerHTML=`
133
+ `,v=class{constructor(t,e){d(this,"el");d(this,"textarea");d(this,"result");d(this,"backdrop");d(this,"options");this.result=t,this.options=e,b(H,B),this.backdrop=document.createElement("div"),this.backdrop.className="cp-backdrop",this.el=document.createElement("div"),this.el.className="cp-popover",this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label","Feedback on selection"),this.el.innerHTML=`
100
134
  <div class="cp-header">Feedback</div>
101
135
  <div class="cp-excerpt">${this.escapeText(t.text)}</div>
102
136
  <textarea class="cp-textarea" placeholder="Add a comment (optional)..." aria-label="Comment text"></textarea>
@@ -105,12 +139,12 @@
105
139
  <button class="cp-btn cp-btn--remove" aria-label="Remove selection without comment">Remove</button>
106
140
  <button class="cp-btn cp-btn--comment" aria-label="Submit comment">Comment</button>
107
141
  </div>
108
- `,this.textarea=this.el.querySelector(".cp-textarea");let n=this.el.querySelector(".cp-btn--comment"),a=this.el.querySelector(".cp-btn--remove"),i=this.el.querySelector(".cp-btn--cancel");this.backdrop.addEventListener("click",()=>this.handleCancel()),n.addEventListener("click",()=>this.handleComment()),a.addEventListener("click",()=>this.handleRemove()),i.addEventListener("click",()=>this.handleCancel()),this.textarea.addEventListener("keydown",o=>this.handleKeyDown(o)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener("keydown",o=>{if(o.key!=="Tab")return;let r=this.el.querySelectorAll('button, textarea, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let s=r[0],p=r[r.length-1];o.shiftKey&&document.activeElement===s?(o.preventDefault(),p.focus()):!o.shiftKey&&document.activeElement===p&&(o.preventDefault(),s.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}positionNearSelection(){let t=this.result.range.getBoundingClientRect(),e=window.scrollX,n=window.scrollY,a=this.el.offsetWidth||320,i=this.el.offsetHeight||260,o=8,r=t.left+e+t.width/2-a/2;r=Math.max(o,r),r=Math.min(r,window.innerWidth+e-a-o);let s=window.innerHeight+n,p=t.bottom+n+o,c;p+i<=s?c=p:(c=t.top+n-i-o,c=Math.max(o,c)),this.el.style.left=`${r}px`,this.el.style.top=`${c}px`}handleComment(){let t=this.textarea.value.trim();this.options.onSubmit(this.result,t)}handleRemove(){let t=this.textarea.value.trim();this.options.onRemove(this.result,t)}handleCancel(){this.options.onDismiss()}handleKeyDown(t){t.key==="Escape"?(t.preventDefault(),this.handleCancel()):(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.handleComment())}};var x=class{constructor(t){d(this,"store");this.store=t}exportMarkdown(){let e=[...this.store.getState().annotations].sort((o,r)=>o.createdAt-r.createdAt);if(e.length===0)return"No feedback provided.";let n=e.filter(o=>o.type==="COMMENT"),a=e.filter(o=>o.type==="DELETION"),i=["## Reviewer Feedback",""];if(n.length>0){i.push("### Comments","");for(let o of n){let r=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;i.push(`- **${o.comment}**`),i.push(` > "${r}"`),i.push("")}}if(a.length>0){i.push("### Deletions","");for(let o of a){let r=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;i.push("- Remove this"),i.push(` > "${r}"`),i.push("")}}return i.join(`
142
+ `,this.textarea=this.el.querySelector(".cp-textarea");let n=this.el.querySelector(".cp-btn--comment"),a=this.el.querySelector(".cp-btn--remove"),r=this.el.querySelector(".cp-btn--cancel");this.backdrop.addEventListener("click",()=>this.handleCancel()),n.addEventListener("click",()=>this.handleComment()),a.addEventListener("click",()=>this.handleRemove()),r.addEventListener("click",()=>this.handleCancel()),this.textarea.addEventListener("keydown",o=>this.handleKeyDown(o)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener("keydown",o=>{if(o.key!=="Tab")return;let i=this.el.querySelectorAll('button, textarea, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let s=i[0],p=i[i.length-1];o.shiftKey&&document.activeElement===s?(o.preventDefault(),p.focus()):!o.shiftKey&&document.activeElement===p&&(o.preventDefault(),s.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}positionNearSelection(){let t=this.result.range.getBoundingClientRect(),e=window.scrollX,n=window.scrollY,a=this.el.offsetWidth||320,r=this.el.offsetHeight||260,o=8,i=t.left+e+t.width/2-a/2;i=Math.max(o,i),i=Math.min(i,window.innerWidth+e-a-o);let s=window.innerHeight+n,p=t.bottom+n+o,c;p+r<=s?c=p:(c=t.top+n-r-o,c=Math.max(o,c)),this.el.style.left=`${i}px`,this.el.style.top=`${c}px`}handleComment(){let t=this.textarea.value.trim();this.options.onSubmit(this.result,t)}handleRemove(){let t=this.textarea.value.trim();this.options.onRemove(this.result,t)}handleCancel(){this.options.onDismiss()}handleKeyDown(t){t.key==="Escape"?(t.preventDefault(),this.handleCancel()):(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.handleComment())}};var x=class{constructor(t){d(this,"store");this.store=t}exportMarkdown(){let e=[...this.store.getState().annotations].sort((o,i)=>o.createdAt-i.createdAt);if(e.length===0)return"No feedback provided.";let n=e.filter(o=>o.type==="COMMENT"),a=e.filter(o=>o.type==="DELETION"),r=["## Reviewer Feedback",""];if(n.length>0){r.push("### Comments","");for(let o of n){let i=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;r.push(`- **${o.comment}**`),r.push(` > "${i}"`),r.push("")}}if(a.length>0){r.push("### Deletions","");for(let o of a){let i=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;r.push("- Remove this"),r.push(` > "${i}"`),r.push("")}}return r.join(`
109
143
  `).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((n,a)=>n.createdAt-a.createdAt);return JSON.stringify(e,null,2)}submitFeedback(t){let e=this.exportMarkdown(),n=this.exportJSON(),a=e==="No feedback provided."?e:`${e}
110
144
 
111
145
  \`\`\`json
112
146
  ${n}
113
- \`\`\``;t("annotations",a)}getTotalCount(){let t=this.store.getState(),e=t.annotations.filter(a=>a.type==="COMMENT").length,n=t.annotations.filter(a=>a.type==="DELETION").length;return{comments:e,deletions:n,total:t.annotations.length}}};var w="aikit-annotation-highlight";function B(){if(document.getElementById(w))return;let l=document.createElement("style");l.id=w,l.textContent=`
147
+ \`\`\``;t("annotations",a)}getTotalCount(){let t=this.store.getState(),e=t.annotations.filter(a=>a.type==="COMMENT").length,n=t.annotations.filter(a=>a.type==="DELETION").length;return{comments:e,deletions:n,total:t.annotations.length}}};var w="aikit-annotation-highlight";function I(){if(document.getElementById(w))return;let l=document.createElement("style");l.id=w,l.textContent=`
114
148
  mark.hl-COMMENT {
115
149
  background: var(--dt-annotation-comment-bg, rgba(88, 166, 255, 0.15));
116
150
  border-bottom: 2px solid var(--dt-annotation-comment, #58a6ff);
@@ -151,7 +185,7 @@ ${n}
151
185
  50% { transform: scale(1.05); }
152
186
  100% { transform: scale(1); }
153
187
  }
154
- `,document.head.appendChild(l)}var y=class{constructor(t,e){d(this,"container");d(this,"store");d(this,"unsubscribe",null);this.container=t,this.store=e}start(){B(),this.unsubscribe=this.store.subscribe(t=>{switch(t.type){case"annotation-added":this.createHighlight(t.annotation);break;case"annotation-removed":this.removeHighlight(t.id);break;case"selection-changed":this.updateSelection(t.id),t.id!==null&&this.scrollToAnnotation(t.id);break}})}stop(){this.unsubscribe?.(),this.unsubscribe=null,this.clearAll()}findTextNodeRange(t,e,n){let a=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null),i=0,o=null,r=0,s=null,p=0,c=a.nextNode();for(;c;){let f=(c.textContent||"").length,m=i+f;if(o===null&&m>e&&(o=c,r=e-i),m>=n){s=c,p=n-i;break}i=m,c=a.nextNode()}if(!o||!s)return null;let u=document.createRange();return u.setStart(o,Math.min(r,(o.textContent||"").length)),u.setEnd(s,Math.min(p,(s.textContent||"").length)),u}createHighlight(t){let e=this.container.querySelector(`[data-block-id="${t.blockId}"]`);if(!e){console.warn(`[HighlightManager] Block not found for annotation ${t.id}: ${t.blockId}`);return}let n=this.findTextNodeRange(e,t.startOffset,t.endOffset);if(!n){console.warn(`[HighlightManager] Could not resolve text range for annotation ${t.id}`);return}let a=document.createElement("mark");a.className=`hl-${t.type}`,a.dataset.annotationId=t.id,a.addEventListener("click",()=>{this.store.select(t.id)});try{n.surroundContents(a)}catch{try{if(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.splitText(n.endOffset),n.startContainer.nodeType===Node.TEXT_NODE){let i=n.startContainer;n.startOffset>0&&i.splitText(n.startOffset);let o=document.createRange();o.setStart(i.nextSibling||i,0),o.setEnd(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.previousSibling||n.endContainer,n.endOffset),o.surroundContents(a)}else throw new Error("Non-text range")}catch{let i=n.extractContents();a.append(i),n.insertNode(a)}}}removeHighlight(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);if(!e)return;let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}updateSelection(t){let e=this.container.querySelectorAll("mark[data-annotation-id]");for(let n of e)n.classList.toggle("hl-selected",n.dataset.annotationId===t)}scrollToAnnotation(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.classList.add("annotation-pulse"),setTimeout(()=>{e.classList.remove("annotation-pulse")},600))}clearAll(){let t=this.container.querySelectorAll("mark[data-annotation-id]");for(let e of t){let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}}};var I=new Set(["button","input","textarea","select"]),E=class{constructor(t){d(this,"options");d(this,"boundHandleMouseUp");this.options=t,this.boundHandleMouseUp=this.handleMouseUp.bind(this),this.options.container.addEventListener("mouseup",this.boundHandleMouseUp,{passive:!0})}destroy(){this.options.container.removeEventListener("mouseup",this.boundHandleMouseUp)}handleMouseUp(t){if(this.options.mode()==="selection")return;let e=t.target;if(!e||this.isExcludedElement(e))return;let n=this.getSelectionRange();if(!n)return;let a=this.findBlockId(n.startContainer);if(!a)return;let i=this.findBlockContainer(n.startContainer),o=this.findBlockContainer(n.endContainer);if(i!==o)return;let r=this.computeBlockOffset(n.startContainer,n.startOffset),s=this.computeBlockOffset(n.endContainer,n.endOffset);if(r===null||s===null)return;let p={blockId:a,startOffset:r,endOffset:s,text:n.toString(),range:n};this.options.onSelection(p),this.clearSelection()}getSelectionRange(){let t=window.getSelection();return!t||t.isCollapsed||t.rangeCount===0?null:t.getRangeAt(0)}findBlockId(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e.getAttribute("data-block-id");e=e.parentNode}return null}computeBlockOffset(t,e){let n=this.findBlockContainer(t);if(!n)return null;let a=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=0,o=a.nextNode();for(;o;){if(o===t)return i+e;i+=(o.textContent||"").length,o=a.nextNode()}return null}findBlockContainer(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e;e=e.parentNode}return null}clearSelection(){let t=window.getSelection();t&&t.removeAllRanges()}isExcludedElement(t){let e=t;for(;e&&!(e instanceof HTMLElement);)e=e.parentNode;return e?I.has(e.tagName.toLowerCase()):!1}};var z="aikit-annotation-sidebar",D=`
188
+ `,document.head.appendChild(l)}var y=class{constructor(t,e){d(this,"container");d(this,"store");d(this,"unsubscribe",null);this.container=t,this.store=e}start(){I(),this.unsubscribe=this.store.subscribe(t=>{switch(t.type){case"annotation-added":this.createHighlight(t.annotation);break;case"annotation-removed":this.removeHighlight(t.id);break;case"selection-changed":this.updateSelection(t.id),t.id!==null&&this.scrollToAnnotation(t.id);break}})}stop(){this.unsubscribe?.(),this.unsubscribe=null,this.clearAll()}findTextNodeRange(t,e,n){let a=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null),r=0,o=null,i=0,s=null,p=0,c=a.nextNode();for(;c;){let f=(c.textContent||"").length,m=r+f;if(o===null&&m>e&&(o=c,i=e-r),m>=n){s=c,p=n-r;break}r=m,c=a.nextNode()}if(!o||!s)return null;let u=document.createRange();return u.setStart(o,Math.min(i,(o.textContent||"").length)),u.setEnd(s,Math.min(p,(s.textContent||"").length)),u}createHighlight(t){let e=this.container.querySelector(`[data-block-id="${t.blockId}"]`);if(!e){console.warn(`[HighlightManager] Block not found for annotation ${t.id}: ${t.blockId}`);return}let n=this.findTextNodeRange(e,t.startOffset,t.endOffset);if(!n){console.warn(`[HighlightManager] Could not resolve text range for annotation ${t.id}`);return}let a=document.createElement("mark");a.className=`hl-${t.type}`,a.dataset.annotationId=t.id,a.addEventListener("click",()=>{this.store.select(t.id)});try{n.surroundContents(a)}catch{try{if(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.splitText(n.endOffset),n.startContainer.nodeType===Node.TEXT_NODE){let r=n.startContainer;n.startOffset>0&&r.splitText(n.startOffset);let o=document.createRange();o.setStart(r.nextSibling||r,0),o.setEnd(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.previousSibling||n.endContainer,n.endOffset),o.surroundContents(a)}else throw new Error("Non-text range")}catch{let r=n.extractContents();a.append(r),n.insertNode(a)}}}removeHighlight(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);if(!e)return;let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}updateSelection(t){let e=this.container.querySelectorAll("mark[data-annotation-id]");for(let n of e)n.classList.toggle("hl-selected",n.dataset.annotationId===t)}scrollToAnnotation(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.classList.add("annotation-pulse"),setTimeout(()=>{e.classList.remove("annotation-pulse")},600))}clearAll(){let t=this.container.querySelectorAll("mark[data-annotation-id]");for(let e of t){let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}}};var D=new Set(["button","input","textarea","select"]),E=class{constructor(t){d(this,"options");d(this,"boundHandleMouseUp");this.options=t,this.boundHandleMouseUp=this.handleMouseUp.bind(this),this.options.container.addEventListener("mouseup",this.boundHandleMouseUp,{passive:!0})}destroy(){this.options.container.removeEventListener("mouseup",this.boundHandleMouseUp)}handleMouseUp(t){if(this.options.mode()==="selection")return;let e=t.target;if(!e||this.isExcludedElement(e))return;let n=this.getSelectionRange();if(!n)return;let a=this.findBlockId(n.startContainer);if(!a)return;let r=this.findBlockContainer(n.startContainer),o=this.findBlockContainer(n.endContainer);if(r!==o)return;let i=this.computeBlockOffset(n.startContainer,n.startOffset),s=this.computeBlockOffset(n.endContainer,n.endOffset);if(i===null||s===null)return;let p={blockId:a,startOffset:i,endOffset:s,text:n.toString(),range:n};this.options.onSelection(p),this.clearSelection()}getSelectionRange(){let t=window.getSelection();return!t||t.isCollapsed||t.rangeCount===0?null:t.getRangeAt(0)}findBlockId(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e.getAttribute("data-block-id");e=e.parentNode}return null}computeBlockOffset(t,e){let n=this.findBlockContainer(t);if(!n)return null;let a=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),r=0,o=a.nextNode();for(;o;){if(o===t)return r+e;r+=(o.textContent||"").length,o=a.nextNode()}return null}findBlockContainer(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e;e=e.parentNode}return null}clearSelection(){let t=window.getSelection();t&&t.removeAllRanges()}isExcludedElement(t){let e=t;for(;e&&!(e instanceof HTMLElement);)e=e.parentNode;return e?D.has(e.tagName.toLowerCase()):!1}};var R="aikit-annotation-sidebar",z=`
155
189
  .as-sidebar {
156
190
  width: var(--dt-annotation-sidebar-width, 300px);
157
191
  background: var(--dt-bg-secondary);
@@ -333,21 +367,21 @@ ${n}
333
367
  font-size: var(--dt-font-size-sm);
334
368
  padding: var(--dt-space-6) var(--dt-space-2);
335
369
  }
336
- `,R='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"/></svg>',k=class{constructor(t){d(this,"el");d(this,"store");d(this,"exporter");d(this,"unsubscribe",null);d(this,"listEl");d(this,"modeToggleBtn");this.store=t.store,this.exporter=t.exporter,this.el=this.render(),this.listEl=this.el.querySelector(".as-list"),this.modeToggleBtn=this.el.querySelector(".as-mode-toggle"),this.unsubscribe=this.store.subscribe(n=>{switch(n.type){case"annotation-added":case"annotation-removed":case"annotation-updated":this.renderList(),this.updateHeader();break;case"selection-changed":this.updateCardSelection(n.id);break;case"sidebar-toggled":this.updateVisibility();break;case"mode-changed":this.updateModeToggle();break}}),(t.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle()}destroy(){this.unsubscribe?.(),this.el.remove()}render(){b(z,D);let t=document.createElement("div");t.className="as-sidebar",t.setAttribute("role","complementary"),t.setAttribute("aria-label","Annotations");let e=this.exporter.getTotalCount();return t.innerHTML=`
370
+ `,$='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"/></svg>',k=class{constructor(t){d(this,"el");d(this,"store");d(this,"exporter");d(this,"unsubscribe",null);d(this,"listEl");d(this,"modeToggleBtn");this.store=t.store,this.exporter=t.exporter,this.el=this.render(),this.listEl=this.el.querySelector(".as-list"),this.modeToggleBtn=this.el.querySelector(".as-mode-toggle"),this.unsubscribe=this.store.subscribe(n=>{switch(n.type){case"annotation-added":case"annotation-removed":case"annotation-updated":this.renderList(),this.updateHeader();break;case"selection-changed":this.updateCardSelection(n.id);break;case"sidebar-toggled":this.updateVisibility();break;case"mode-changed":this.updateModeToggle();break}}),(t.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle()}destroy(){this.unsubscribe?.(),this.el.remove()}render(){b(R,z);let t=document.createElement("div");t.className="as-sidebar",t.setAttribute("role","complementary"),t.setAttribute("aria-label","Annotations");let e=this.exporter.getTotalCount();return t.innerHTML=`
337
371
  <div class="as-header">
338
372
  <span class="as-header-title">Annotations</span>
339
373
  <span class="as-count-badge" aria-live="polite">${e.total}</span>
340
374
  <span class="as-header-spacer"></span>
341
- <button class="as-mode-toggle" aria-label="Toggle annotation mode">${R} Feedback</button>
375
+ <button class="as-mode-toggle" aria-label="Toggle annotation mode">${$} Feedback</button>
342
376
  <button class="as-close-btn" aria-label="Close sidebar">&times;</button>
343
377
  </div>
344
378
  <div class="as-list" role="list" aria-label="Annotation list"></div>
345
- `,t.querySelector(".as-close-btn").addEventListener("click",i=>{i.stopPropagation(),this.store.toggleSidebar(!1)}),t.querySelector(".as-mode-toggle").addEventListener("click",i=>{i.stopPropagation();let o=this.store.getState().mode==="feedback"?"selection":"feedback";this.store.setMode(o)}),t}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML="",e.length===0){let a=document.createElement("div");a.className="as-empty",a.textContent="No annotations yet. Select text in Feedback mode.",this.listEl.appendChild(a);return}let n=[...e].sort((a,i)=>i.createdAt-a.createdAt);for(let a of n)this.listEl.appendChild(this.renderAnnotationItem(a))}renderAnnotationItem(t){let e=document.createElement("div");e.className=`as-card as-card--${t.type}`,e.dataset.annotationId=t.id,this.store.getState().selectedId===t.id&&e.classList.add("as-card--selected");let a=t.originalText.length>60?`${t.originalText.slice(0,60)}\u2026`:t.originalText;return e.innerHTML=`
379
+ `,t.querySelector(".as-close-btn").addEventListener("click",r=>{r.stopPropagation(),this.store.toggleSidebar(!1)}),t.querySelector(".as-mode-toggle").addEventListener("click",r=>{r.stopPropagation();let o=this.store.getState().mode==="feedback"?"selection":"feedback";this.store.setMode(o)}),t}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML="",e.length===0){let a=document.createElement("div");a.className="as-empty",a.textContent="No annotations yet. Select text in Feedback mode.",this.listEl.appendChild(a);return}let n=[...e].sort((a,r)=>r.createdAt-a.createdAt);for(let a of n)this.listEl.appendChild(this.renderAnnotationItem(a))}renderAnnotationItem(t){let e=document.createElement("div");e.className=`as-card as-card--${t.type}`,e.dataset.annotationId=t.id,this.store.getState().selectedId===t.id&&e.classList.add("as-card--selected");let a=t.originalText.length>60?`${t.originalText.slice(0,60)}\u2026`:t.originalText;return e.innerHTML=`
346
380
  <div class="as-card-excerpt">${g(a)}</div>
347
381
  ${t.comment?`<div class="as-card-comment">${g(t.comment)}</div>`:""}
348
382
  <div class="as-card-comment-detail">${t.comment?g(t.comment):'<em style="color:var(--dt-text-tertiary)">No comment \u2014 marked text only</em>'}</div>
349
383
  <button class="as-delete-btn" aria-label="Delete annotation">&times;</button>
350
- `,e.addEventListener("click",()=>{this.store.select(t.id);let o=e.querySelector(".as-card-comment-detail");if(o){o.classList.toggle("as-card-comment-detail--open");let r=this.listEl.querySelectorAll(".as-card-comment-detail--open");for(let s of r)s!==o&&s.classList.remove("as-card-comment-detail--open")}}),e.querySelector(".as-delete-btn").addEventListener("click",o=>{o.stopPropagation(),this.handleDelete(t.id)}),e}handleDelete(t){this.store.remove(t)}updateVisibility(){let t=this.store.getState();this.el.style.display=t.isSidebarOpen?"flex":"none"}updateHeader(){let t=this.el.querySelector(".as-count-badge");if(t){let e=this.exporter.getTotalCount();t.textContent=String(e.total)}}updateModeToggle(){let t=this.store.getState().mode==="feedback";this.modeToggleBtn.classList.toggle("as-mode-toggle--active",t),this.modeToggleBtn.setAttribute("aria-pressed",String(t)),this.modeToggleBtn.setAttribute("aria-label",t?"Disable annotation mode":"Enable annotation mode")}updateCardSelection(t){let e=this.el.querySelectorAll(".as-card");for(let n of e){let a=n.dataset.annotationId;n.classList.toggle("as-card--selected",a!==void 0&&a===t)}}};var T=class{constructor(){d(this,"annotations",[]);d(this,"selectedId",null);d(this,"mode","selection");d(this,"isSidebarOpen",!1);d(this,"subscribers",new Set);d(this,"idCounter",0)}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}notify(t){for(let e of this.subscribers)e(t)}generateId(){return this.idCounter+=1,`ann-${this.idCounter}`}openSidebar(){this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})}add(t,e,n,a,i,o,r,s,p){let c={id:this.generateId(),type:t,blockId:e,startOffset:n,endOffset:a,originalText:i,comment:o,section:r,contextBefore:s,contextAfter:p,createdAt:Date.now()};return this.annotations.push(c),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:c}),c}update(t,e){let n=this.annotations.find(a=>a.id===t);n&&(Object.assign(n,e),this.notify({type:"annotation-updated",id:t,changes:e}))}remove(t){let e=this.annotations.findIndex(n=>n.id===t);e!==-1&&(this.annotations.splice(e,1),this.notify({type:"annotation-removed",id:t}))}select(t){this.selectedId=t,this.notify({type:"selection-changed",id:t})}setMode(t){t!==this.mode&&(this.mode=t,this.notify({type:"mode-changed",mode:t}))}toggleSidebar(t){this.isSidebarOpen=t!==void 0?t:!this.isSidebarOpen,this.notify({type:"sidebar-toggled",open:this.isSidebarOpen})}getState(){return{annotations:[...this.annotations],selectedId:this.selectedId,mode:this.mode,isSidebarOpen:this.isSidebarOpen}}destroy(){this.subscribers.clear(),this.annotations=[],this.selectedId=null,this.mode="selection",this.isSidebarOpen=!1,this.idCounter=0}};var M=25,$="aikit-annotation-guide",q=`
384
+ `,e.addEventListener("click",()=>{this.store.select(t.id);let o=e.querySelector(".as-card-comment-detail");if(o){o.classList.toggle("as-card-comment-detail--open");let i=this.listEl.querySelectorAll(".as-card-comment-detail--open");for(let s of i)s!==o&&s.classList.remove("as-card-comment-detail--open")}}),e.querySelector(".as-delete-btn").addEventListener("click",o=>{o.stopPropagation(),this.handleDelete(t.id)}),e}handleDelete(t){this.store.remove(t)}updateVisibility(){let t=this.store.getState();this.el.style.display=t.isSidebarOpen?"flex":"none"}updateHeader(){let t=this.el.querySelector(".as-count-badge");if(t){let e=this.exporter.getTotalCount();t.textContent=String(e.total)}}updateModeToggle(){let t=this.store.getState().mode==="feedback";this.modeToggleBtn.classList.toggle("as-mode-toggle--active",t),this.modeToggleBtn.setAttribute("aria-pressed",String(t)),this.modeToggleBtn.setAttribute("aria-label",t?"Disable annotation mode":"Enable annotation mode")}updateCardSelection(t){let e=this.el.querySelectorAll(".as-card");for(let n of e){let a=n.dataset.annotationId;n.classList.toggle("as-card--selected",a!==void 0&&a===t)}}};var S=class{constructor(){d(this,"annotations",[]);d(this,"selectedId",null);d(this,"mode","selection");d(this,"isSidebarOpen",!1);d(this,"subscribers",new Set);d(this,"idCounter",0)}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}notify(t){for(let e of this.subscribers)e(t)}generateId(){return this.idCounter+=1,`ann-${this.idCounter}`}openSidebar(){this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})}add(t,e,n,a,r,o,i,s,p){let c={id:this.generateId(),type:t,blockId:e,startOffset:n,endOffset:a,originalText:r,comment:o,section:i,contextBefore:s,contextAfter:p,createdAt:Date.now()};return this.annotations.push(c),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:c}),c}update(t,e){let n=this.annotations.find(a=>a.id===t);n&&(Object.assign(n,e),this.notify({type:"annotation-updated",id:t,changes:e}))}remove(t){let e=this.annotations.findIndex(n=>n.id===t);e!==-1&&(this.annotations.splice(e,1),this.notify({type:"annotation-removed",id:t}))}select(t){this.selectedId=t,this.notify({type:"selection-changed",id:t})}setMode(t){t!==this.mode&&(this.mode=t,this.notify({type:"mode-changed",mode:t}))}toggleSidebar(t){this.isSidebarOpen=t!==void 0?t:!this.isSidebarOpen,this.notify({type:"sidebar-toggled",open:this.isSidebarOpen})}getState(){return{annotations:[...this.annotations],selectedId:this.selectedId,mode:this.mode,isSidebarOpen:this.isSidebarOpen}}destroy(){this.subscribers.clear(),this.annotations=[],this.selectedId=null,this.mode="selection",this.isSidebarOpen=!1,this.idCounter=0}};var L=25,_="aikit-annotation-guide",q=`
351
385
  .as-guide {
352
386
  margin: 0 0 var(--dt-space-3) 0;
353
387
  padding: var(--dt-space-2) var(--dt-space-3);
@@ -364,7 +398,7 @@ ${n}
364
398
  .as-guide--visible {
365
399
  display: block;
366
400
  }
367
- `;function _(l){let{range:t}=l,e,n=t.startContainer;for(;n;){if(n instanceof HTMLElement&&n.tagName.toLowerCase().match(/^h[1-6]$/)){e=n.textContent?.trim()||void 0;break}n=n.parentNode}let a,i;try{if(t.startContainer.nodeType===Node.TEXT_NODE&&t.startOffset>0){let o=t.startContainer.textContent||"",r=Math.max(0,t.startOffset-M);a=o.slice(r,t.startOffset)}if(t.endContainer.nodeType===Node.TEXT_NODE&&t.endOffset<(t.endContainer.textContent?.length||0)){let o=t.endContainer.textContent||"",r=Math.min(o.length,t.endOffset+M);i=o.slice(t.endOffset,r)}}catch{}return{section:e,contextBefore:a,contextAfter:i}}function L(l){let{container:t,mountTarget:e}=l,n=null,a=new T;a.setMode("feedback");let i=new x(a);b($,q);let o=document.createElement("div");o.className="as-guide",o.textContent="\u27B3 Ready. Select text to annotate or disable Feedback in the sidebar.",t.prepend(o);let r=()=>{let u=a.getState();o.classList.toggle("as-guide--visible",u.mode==="feedback"&&u.annotations.length===0)};r(),a.subscribe(()=>r());let s=new y(t,a);s.start();let p=new E({container:t,mode:()=>a.getState().mode,onSelection:u=>{let f=_(u);n?.destroy();let m=new v(u,{onSubmit:(h,S)=>{a.add("COMMENT",h.blockId,h.startOffset,h.endOffset,h.text,S||void 0,f.section,f.contextBefore,f.contextAfter),m.destroy(),n===m&&(n=null)},onRemove:(h,S)=>{a.add("DELETION",h.blockId,h.startOffset,h.endOffset,h.text,S||void 0,f.section,f.contextBefore,f.contextAfter),m.destroy(),n===m&&(n=null)},onDismiss:()=>{m.destroy(),n===m&&(n=null)}});n=m}}),c=new k({store:a,exporter:i,mountTarget:e});return a.openSidebar(),{destroy(){n?.destroy(),n=null,o.remove(),p.destroy(),s.stop(),c.destroy(),a.destroy()},getStore(){return a},getExporter(){return i}}}document.addEventListener("DOMContentLoaded",()=>{let l=document.querySelector(".content")||document.querySelector("main"),t=l||document.body;if(!l)return;let e=t.parentElement;e?.classList.contains("shell-layout")||(e=document.createElement("div"),e.className="shell-layout",t.parentNode?.insertBefore(e,t),e.appendChild(t));let n="aikit-shell-layout";if(!document.getElementById(n)){let o=document.createElement("style");o.id=n,o.textContent=`
401
+ `;function j(l){let{range:t}=l,e,n=t.startContainer;for(;n;){if(n instanceof HTMLElement&&n.tagName.toLowerCase().match(/^h[1-6]$/)){e=n.textContent?.trim()||void 0;break}n=n.parentNode}let a,r;try{if(t.startContainer.nodeType===Node.TEXT_NODE&&t.startOffset>0){let o=t.startContainer.textContent||"",i=Math.max(0,t.startOffset-L);a=o.slice(i,t.startOffset)}if(t.endContainer.nodeType===Node.TEXT_NODE&&t.endOffset<(t.endContainer.textContent?.length||0)){let o=t.endContainer.textContent||"",i=Math.min(o.length,t.endOffset+L);r=o.slice(t.endOffset,i)}}catch{}return{section:e,contextBefore:a,contextAfter:r}}function A(l){let{container:t,mountTarget:e}=l,n=null,a=new S;a.setMode("feedback");let r=new x(a);b(_,q);let o=document.createElement("div");o.className="as-guide",o.textContent="\u27B3 Ready. Select text to annotate or disable Feedback in the sidebar.",t.prepend(o);let i=()=>{let u=a.getState();o.classList.toggle("as-guide--visible",u.mode==="feedback"&&u.annotations.length===0)};i(),a.subscribe(()=>i());let s=new y(t,a);s.start();let p=new E({container:t,mode:()=>a.getState().mode,onSelection:u=>{let f=j(u);n?.destroy();let m=new v(u,{onSubmit:(h,T)=>{a.add("COMMENT",h.blockId,h.startOffset,h.endOffset,h.text,T||void 0,f.section,f.contextBefore,f.contextAfter),m.destroy(),n===m&&(n=null)},onRemove:(h,T)=>{a.add("DELETION",h.blockId,h.startOffset,h.endOffset,h.text,T||void 0,f.section,f.contextBefore,f.contextAfter),m.destroy(),n===m&&(n=null)},onDismiss:()=>{m.destroy(),n===m&&(n=null)}});n=m}}),c=new k({store:a,exporter:r,mountTarget:e});return a.openSidebar(),{destroy(){n?.destroy(),n=null,o.remove(),p.destroy(),s.stop(),c.destroy(),a.destroy()},getStore(){return a},getExporter(){return r}}}document.addEventListener("DOMContentLoaded",()=>{let l=document.querySelector(".content")||document.querySelector("main"),t=l||document.body;if(!l)return;let e=t.parentElement;e?.classList.contains("shell-layout")||(e=document.createElement("div"),e.className="shell-layout",t.parentNode?.insertBefore(e,t),e.appendChild(t));let n="aikit-shell-layout";if(!document.getElementById(n)){let o=document.createElement("style");o.id=n,o.textContent=`
368
402
  .shell-layout {
369
403
  flex: 1;
370
404
  display: flex;
@@ -385,70 +419,10 @@ ${n}
385
419
  [data-annotation-sidebar="open"] .shell-layout > .content {
386
420
  max-width: none;
387
421
  }
388
- /* Sticky bottom action bar \u2014 docked to bottom of scrollable main */
422
+ /* Shared action-bar CSS (includes .action-bar itself and compact controls) */
423
+ ${C}
424
+ /* Shell-specific: push action bar to bottom of flex column */
389
425
  .action-bar {
390
426
  margin-top: auto;
391
- position: sticky;
392
- bottom: 0;
393
- display: flex;
394
- flex-wrap: wrap;
395
- align-items: center;
396
- gap: var(--dt-space-2);
397
- padding: var(--dt-space-3) var(--dt-space-4);
398
- border-top: 1px solid var(--dt-border-default);
399
- background: color-mix(in srgb, var(--dt-bg-primary, #0c0c0c) 92%, transparent);
400
- backdrop-filter: blur(12px);
401
- -webkit-backdrop-filter: blur(12px);
402
- flex-shrink: 0;
403
- z-index: 10;
404
- }
405
- .action-bar:empty {
406
- display: none;
407
- }
408
- .action-bar .bk-actions {
409
- display: flex;
410
- flex-wrap: wrap;
411
- align-items: center;
412
- gap: var(--dt-space-2);
413
- margin: 0;
414
- padding: 0;
415
- border: none;
416
- background: none;
417
- }
418
- /* Compact controls in action bar \u2014 single-line inline layout */
419
- .action-bar .present-action-btn {
420
- padding: 0.375rem 0.75rem;
421
- font-size: var(--dt-font-size-sm);
422
- min-height: 2rem;
423
- }
424
- .action-bar .present-action-field {
425
- display: inline-flex;
426
- flex-direction: row;
427
- align-items: center;
428
- gap: 0.375rem;
429
- min-width: 0;
430
- }
431
- .action-bar .present-action-field span {
432
- font-size: var(--dt-font-size-xs);
433
- white-space: nowrap;
434
- color: var(--dt-text-secondary, #6b6a65);
435
- }
436
- .action-bar .present-action-field select {
437
- font-size: var(--dt-font-size-sm);
438
- min-height: 2rem;
439
- padding: 0 0.5rem;
440
- max-width: 10rem;
441
- }
442
- .action-bar .present-action-field select[multiple] {
443
- max-width: 6rem;
444
- max-height: 3rem;
445
- padding: 0.125rem 0.25rem;
446
- }
447
- .action-bar .present-text-input {
448
- font-size: var(--dt-font-size-sm);
449
- min-height: 2rem;
450
- padding: 0 0.5rem;
451
- min-width: 120px;
452
- max-width: 200px;
453
427
  }
454
- `,document.head.appendChild(o)}let a=L({container:t,mountTarget:e});a.getStore().subscribe(o=>{o.type==="sidebar-toggled"&&document.documentElement.setAttribute("data-annotation-sidebar",o.open?"open":"")}),a.getStore().getState().isSidebarOpen&&document.documentElement.setAttribute("data-annotation-sidebar","open"),window.__annotationLayer=a;let i=document.querySelectorAll(".bk-actions");if(i.length>0){let o=document.createElement("div");o.className="action-bar";let r=!1;for(let s of i)if(!s.querySelector('input[type="text"], input:not([type]), textarea')){for(;s.firstChild;)o.appendChild(s.firstChild);s.remove(),r=!0}if(r){let s=document.querySelector("main")||document.querySelector(".content");s&&(s.appendChild(o),s.style.paddingBottom="0")}}});})();
428
+ `,document.head.appendChild(o)}if(document.querySelector(".bk-actions")!==null){let o=A({container:t,mountTarget:e});o.getStore().subscribe(i=>{i.type==="sidebar-toggled"&&document.documentElement.setAttribute("data-annotation-sidebar",i.open?"open":"")}),o.getStore().getState().isSidebarOpen&&document.documentElement.setAttribute("data-annotation-sidebar","open"),window.__annotationLayer=o}let r=document.querySelectorAll(".bk-actions");if(r.length>0){let o=document.createElement("div");o.className="action-bar";let i=!1;for(let s of r)if(!s.querySelector('[data-action-row="multi"]')){for(;s.firstChild;)o.appendChild(s.firstChild);s.remove(),i=!0}if(i){let s=document.querySelector("main")||document.querySelector(".content");s&&(s.appendChild(o),s.style.paddingBottom="0")}}});})();