@vpxa/aikit 0.1.269 → 0.1.271

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.
@@ -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,existsSync as l,mkdirSync as u,openSync as ee,readFileSync as te,readdirSync as d,renameSync as f,statSync as p,unlinkSync as m,writeFileSync as h}from"node:fs";import{homedir as ne}from"node:os";var g=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 _(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new _(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)}},_=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const v={ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},y={root:`.aikit-data`,registry:`registry.json`},b={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},x={model:`mixedbread-ai/mxbai-embed-large-v1`,nativeDim:1024,dimensions:512,queryPrefix:``},S={backend:`sqlite-vec`,path:v.data,tableName:`knowledge`},re={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},ie={maxResults:10,minScore:.25},ae=/^[a-z][a-z0-9-]*$/,oe=[`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`},se=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],ce=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function le(e){let r=n(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${v.aiContext}/`)?`produced-knowledge`:e.includes(`${v.aiCurated}/`)?`curated-knowledge`:se.some(t=>t.test(e))?`test-code`:ce.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 ue(e){return w[e]??`source`}function de(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`}},fe=class extends T{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},E=class extends T{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},D=class extends T{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},O=class extends T{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},k=class extends T{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},A=class extends T{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function j(e){return e instanceof k}function M(e){return e instanceof A}function N(){return process.env.AIKIT_GLOBAL_DATA_DIR??i(ne(),y.root)}function P(e){let n=i(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${a(`sha256`).update(n).digest(`hex`).slice(0,8)}`}function F(){let e=i(N(),y.registry);if(!l(e))return{version:1,workspaces:{}};let t=te(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function I(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ee(n,c.O_CREAT|c.O_EXCL|c.O_WRONLY);return h(e,`${process.pid}\n`),s(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=p(n);if(Date.now()-e>3e4){m(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 L(e){try{m(e)}catch{}}function R(e){let t=N();u(t,{recursive:!0});let n=i(t,y.registry),r=I(n);try{let t=`${n}.tmp`;h(t,JSON.stringify(e,null,2),`utf-8`),f(t,n)}finally{L(r)}}function z(e){let t=F(),n=P(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},u(H(n),{recursive:!0}),R(t),t.workspaces[n]}function B(e){let t=F(),n=P(e);return t.workspaces[n]}function V(){let e=F();return Object.values(e.workspaces)}function H(e){return i(N(),e)}function U(){return l(i(N(),y.registry))}function W(e){return U()?i(H(z(e).partition),`state`):i(e,v.state)}var pe=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)}};const G={debug:0,info:1,warn:2,error:3},K=[];let q=process.env.AIKIT_LOG_LEVEL??`info`,J=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function me(){return J?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let Y;function X(){return Y||=r(W(process.cwd()),`logs`),Y}function he(e){let t=e.toISOString().slice(0,10);return r(X(),`${t}.jsonl`)}let Z=0;function ge(){let e=Date.now();if(!(e-Z<36e5)){Z=e;try{let t=X(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of d(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{m(r(t,e))}catch{}}catch{}}}function _e(e,t){try{u(X(),{recursive:!0}),o(he(t),`${e}\n`),ge()}catch{}}function ve(e){q=e}function ye(){return q}function be(e){J=e}function xe(){Y=void 0}function Q(e){if(e instanceof Error){let t={error:e.message};return e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t}return{error:String(e)}}function Se(e){return K.push(e),()=>{let t=K.indexOf(e);t>=0&&K.splice(t,1)}}function Ce(e){function t(t,n,r){if(G[t]<G[q])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 K)try{i({level:t,component:e,message:n,data:r})}catch{}me()&&(t===`warn`||t===`error`)&&_e(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 $={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function we(e,t={}){let{maxAttempts:n=$.maxAttempts,baseDelayMs:r=$.baseDelayMs,maxDelayMs:i=$.maxDelayMs,jitterFraction:a=$.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof k),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 k&&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 Te(l)}throw s}function Te(e){return new Promise(t=>setTimeout(t,e))}const Ee=[`indexed`,`curated`,`produced`],De=[`source`,`documentation`,`test`,`config`,`generated`],Oe=[`auto`,`manual`,`smart`],ke=[`efficient`,`normal`,`full`],Ae=[`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`];export{y as AIKIT_GLOBAL_PATHS,v as AIKIT_PATHS,T as AikitError,ae as CATEGORY_PATTERN,b as CHUNK_SIZES,Ae as CONTENT_TYPES,g as CircuitBreaker,_ as CircuitOpenError,O as ConfigError,oe as DEFAULT_CATEGORIES,x as EMBEDDING_DEFAULTS,fe as EmbeddingError,re as FILE_LIMITS,pe as HealthBus,Oe as INDEX_MODES,D as IndexError,Ee as KNOWLEDGE_ORIGINS,A as PermanentError,ie as SEARCH_DEFAULTS,De as SOURCE_TYPES,S as STORE_DEFAULTS,E as StoreError,ke as TOKEN_BUDGETS,k as TransientError,Se as addLogListener,P as computePartitionKey,ue as contentTypeToSourceType,Ce as createLogger,le as detectContentType,N as getGlobalDataDir,ye as getLogLevel,H as getPartitionDir,M as isPermanent,j as isTransient,U as isUserInstalled,V as listWorkspaces,F as loadRegistry,B as lookupWorkspace,z as registerWorkspace,xe as resetLogDir,W as resolveStateDir,R as saveRegistry,Q as serializeError,be as setFileSinkEnabled,ve as setLogLevel,de as sourceTypeContentTypes,we as withRetry};
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,existsSync as l,mkdirSync as u,openSync as ee,readFileSync as te,readdirSync as d,renameSync as f,statSync as p,unlinkSync as m,writeFileSync as h}from"node:fs";import{homedir as ne}from"node:os";var g=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 _(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new _(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)}},_=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const v={ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},y={root:`.aikit-data`,registry:`registry.json`},b={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},x={model:`mixedbread-ai/mxbai-embed-large-v1`,nativeDim:1024,dimensions:512,queryPrefix:``},S={backend:`sqlite-vec`,path:v.data,tableName:`knowledge`},re={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},ie={maxResults:10,minScore:.25},ae=/^[a-z][a-z0-9-]*$/,oe=[`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`},se=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],ce=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function le(e){let r=n(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${v.aiContext}/`)?`produced-knowledge`:e.includes(`${v.aiCurated}/`)?`curated-knowledge`:se.some(t=>t.test(e))?`test-code`:ce.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 ue(e){return w[e]??`source`}function de(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`}},fe=class extends T{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},pe=class extends T{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},E=class extends T{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},D=class extends T{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},O=class extends T{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},k=class extends T{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function A(e){return e instanceof O}function j(e){return e instanceof k}function M(){return process.env.AIKIT_GLOBAL_DATA_DIR??i(ne(),y.root)}function N(e){let n=i(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${a(`sha256`).update(n).digest(`hex`).slice(0,8)}`}function P(){let e=i(M(),y.registry);if(!l(e))return{version:1,workspaces:{}};let t=te(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function F(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ee(n,c.O_CREAT|c.O_EXCL|c.O_WRONLY);return h(e,`${process.pid}\n`),s(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=p(n);if(Date.now()-e>3e4){m(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 I(e){try{m(e)}catch{}}function L(e){let t=M();u(t,{recursive:!0});let n=i(t,y.registry),r=F(n);try{let t=`${n}.tmp`;h(t,JSON.stringify(e,null,2),`utf-8`),f(t,n)}finally{I(r)}}function R(e){let t=P(),n=N(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},u(V(n),{recursive:!0}),L(t),t.workspaces[n]}function z(e){let t=P(),n=N(e);return t.workspaces[n]}function B(){let e=P();return Object.values(e.workspaces)}function V(e){return i(M(),e)}function H(){return l(i(M(),y.registry))}function U(e){return H()?i(V(R(e).partition),`state`):i(e,v.state)}var me=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)}};const W={debug:0,info:1,warn:2,error:3},G=[];let K=process.env.AIKIT_LOG_LEVEL??`info`,q=!1,J=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function he(){return J?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let Y;function X(){return Y||=r(U(process.cwd()),`logs`),Y}function ge(e){let t=e.toISOString().slice(0,10);return r(X(),`${t}.jsonl`)}let Z=0;function _e(){let e=Date.now();if(!(e-Z<36e5)){Z=e;try{let t=X(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of d(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{m(r(t,e))}catch{}}catch{}}}function ve(e,t){try{u(X(),{recursive:!0}),o(ge(t),`${e}\n`),_e()}catch{}}function ye(e){K=e}function be(){return K}function xe(e){J=e}function Q(){Y=void 0}function Se(e){q=e}function Ce(e){if(e instanceof Error){let t={error:e.message};return q?(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 we(e){return G.push(e),()=>{let t=G.indexOf(e);t>=0&&G.splice(t,1)}}function Te(e){function t(t,n,r){if(W[t]<W[K])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 G)try{i({level:t,component:e,message:n,data:r})}catch{}he()&&(t===`warn`||t===`error`)&&ve(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 $={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function Ee(e,t={}){let{maxAttempts:n=$.maxAttempts,baseDelayMs:r=$.baseDelayMs,maxDelayMs:i=$.maxDelayMs,jitterFraction:a=$.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof O),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 O&&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 De(l)}throw s}function De(e){return new Promise(t=>setTimeout(t,e))}const Oe=[`indexed`,`curated`,`produced`],ke=[`source`,`documentation`,`test`,`config`,`generated`],Ae=[`auto`,`manual`,`smart`],je=[`efficient`,`normal`,`full`],Me=[`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`];export{y as AIKIT_GLOBAL_PATHS,v as AIKIT_PATHS,T as AikitError,ae as CATEGORY_PATTERN,b as CHUNK_SIZES,Me as CONTENT_TYPES,g as CircuitBreaker,_ as CircuitOpenError,D as ConfigError,oe as DEFAULT_CATEGORIES,x as EMBEDDING_DEFAULTS,fe as EmbeddingError,re as FILE_LIMITS,me as HealthBus,Ae as INDEX_MODES,E as IndexError,Oe as KNOWLEDGE_ORIGINS,k as PermanentError,ie as SEARCH_DEFAULTS,ke as SOURCE_TYPES,S as STORE_DEFAULTS,pe as StoreError,je as TOKEN_BUDGETS,O as TransientError,we as addLogListener,N as computePartitionKey,ue as contentTypeToSourceType,Te as createLogger,le as detectContentType,M as getGlobalDataDir,be as getLogLevel,V as getPartitionDir,j as isPermanent,A as isTransient,H as isUserInstalled,B as listWorkspaces,P as loadRegistry,z as lookupWorkspace,R as registerWorkspace,Q as resetLogDir,U as resolveStateDir,L as saveRegistry,Ce as serializeError,Se as setDetailedErrorLoggingEnabled,xe as setFileSinkEnabled,ye as setLogLevel,de as sourceTypeContentTypes,Ee as withRetry};