@vpxa/aikit 0.1.351 → 0.1.353

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 (32) hide show
  1. package/package.json +1 -1
  2. package/packages/blocks-core/dist/index.mjs +949 -118
  3. package/packages/core/dist/index.d.ts +3 -0
  4. package/packages/core/dist/index.js +1 -1
  5. package/packages/present/dist/annotation-layer.js +48 -74
  6. package/packages/present/dist/index.html +977 -153
  7. package/packages/server/dist/bin.js +1 -1
  8. package/packages/server/dist/index.js +288 -109
  9. package/packages/server/dist/prelude-DetbWo8R.js +1 -0
  10. package/packages/server/dist/prelude-hfAEi93R.js +2 -0
  11. package/packages/server/dist/sampling-CWjnUevo.js +2 -0
  12. package/packages/server/dist/sampling-CnE3owSt.js +1 -0
  13. package/packages/server/dist/{server-Dc2XtS92.js → server-D5eu57oU.js} +150 -148
  14. package/packages/server/dist/{server-Ct4BK2hi.js → server-D7gZ4K_H.js} +150 -148
  15. package/packages/server/dist/{server-http-DBmzukZH.js → server-http-AarbD3gm.js} +1 -1
  16. package/packages/server/dist/{server-http-BNC9qZBj.js → server-http-wnYmWFkC.js} +1 -1
  17. package/packages/server/dist/{server-stdio-JHWimdo9.js → server-stdio-BWoMqXU8.js} +1 -1
  18. package/packages/server/dist/{server-stdio-DkDdZI98.js → server-stdio-CBGO6XiO.js} +1 -1
  19. package/packages/server/viewers/canvas.html +944 -127
  20. package/packages/server/viewers/code-review-viewer.html +352 -0
  21. package/packages/server/viewers/report-template.html +918 -101
  22. package/packages/server/viewers/task-plan-static.html +1 -1
  23. package/packages/server/viewers/tour-viewer.html +919 -102
  24. package/packages/tools/dist/index.js +82 -82
  25. package/scaffold/dist/definitions/skills/c4-architecture.mjs +1 -1
  26. package/scaffold/dist/definitions/skills/docs.mjs +19 -3
  27. package/scaffold/dist/definitions/skills/present.mjs +317 -13
  28. package/scaffold/dist/generated/block-docs.mjs +18 -64
  29. package/packages/server/dist/prelude-Clxlztkk.js +0 -1
  30. package/packages/server/dist/prelude-Dn7jTsqe.js +0 -2
  31. package/packages/server/dist/sampling-giGWyrcO.js +0 -1
  32. package/packages/server/dist/sampling-nivAea83.js +0 -2
@@ -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")}}});})();