@vpxa/aikit 0.1.361 → 0.1.363

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/claude-desktop/dist/manifest.json +1 -1
  3. package/packages/cli/dist/index.js +1 -1
  4. package/packages/present/dist/annotation-layer.js +97 -14
  5. package/packages/present/dist/index.html +92 -9
  6. package/packages/server/dist/bin.js +1 -1
  7. package/packages/server/dist/index.js +1 -1
  8. package/packages/server/dist/prelude-BgvW6Hp5.js +2 -0
  9. package/packages/server/dist/prelude-Di-ZDdDk.js +1 -0
  10. package/packages/server/dist/sampling-CFWUnzbA.js +1 -0
  11. package/packages/server/dist/sampling-lcC_v6KY.js +2 -0
  12. package/packages/server/dist/{server-CiPwrtSl.js → server-Bsceh-AT.js} +91 -96
  13. package/packages/server/dist/{server-e0mFUKvp.js → server-DUWF6mtP.js} +91 -96
  14. package/packages/server/dist/{server-http-CzScS-EZ.js → server-http-BGcKUn5y.js} +1 -1
  15. package/packages/server/dist/{server-http-B3dZd6bx.js → server-http-Cx4tvbmK.js} +1 -1
  16. package/packages/server/dist/{server-stdio-COkJ2pX9.js → server-stdio-BmGuXkkF.js} +1 -1
  17. package/packages/server/dist/{server-stdio-DmsOjBSR.js → server-stdio-C66e05P_.js} +1 -1
  18. package/scaffold/dist/adapters/_shared.mjs +1 -1
  19. package/scaffold/dist/adapters/claude-code.mjs +7 -7
  20. package/scaffold/dist/adapters/claude-desktop.mjs +6 -6
  21. package/scaffold/dist/adapters/copilot.mjs +12 -12
  22. package/scaffold/dist/adapters/gemini.mjs +6 -6
  23. package/scaffold/dist/adapters/hermes.mjs +55 -5
  24. package/scaffold/dist/adapters/opencode.mjs +7 -7
  25. package/scaffold/dist/definitions/platform-capabilities.mjs +1 -1
  26. package/scaffold/dist/definitions/skills/index.mjs +1 -1
  27. package/scaffold/dist/definitions/skills/orchestrator.mjs +38 -0
  28. package/packages/server/dist/prelude-BIJWSWyX.js +0 -2
  29. package/packages/server/dist/prelude-Dxc3G0Q2.js +0 -1
  30. package/packages/server/dist/sampling-BX1qQuXx.js +0 -2
  31. package/packages/server/dist/sampling-QHtj6UuO.js +0 -1
  32. package/scaffold/dist/adapters/hermes-agent.mjs +0 -54
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.361",
3
+ "version": "0.1.363",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -2,7 +2,7 @@
2
2
  "manifest_version": "0.3",
3
3
  "name": "AI Kit",
4
4
  "display_name": "AI Kit",
5
- "version": "0.1.361",
5
+ "version": "0.1.363",
6
6
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
7
7
  "author": {
8
8
  "name": "AnVPX",
@@ -36,7 +36,7 @@ After install, verify with:
36
36
  Options:
37
37
  --version <version> Install a specific version instead of latest
38
38
  --offline <path> Install from a local tarball (no network needed)
39
- --help, -h Show this help`;function sr(e){if(!rr.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}async function cr(){let e=await fetch(`https://registry.npmjs.org/${ar}/latest`,{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw Error(`Failed to fetch latest version from npm registry (HTTP ${e.status})`);let t=await e.json();if(!t.version)throw Error(`npm registry response missing "version" field`);return t.version}function lr(e){let t=k(e,`packages`,`server`,`dist`,`bin.js`);if(!x(t))throw Error(`Server entry point not found at ${t}. The installation may be incomplete or corrupted.`);let n=k(e,`node_modules`);if(!x(n))throw Error(`node_modules not found at ${n}. Production dependencies may not have been installed.`)}function ur(e){let t=k(e,`package.json`),n=JSON.parse(C(t,`utf-8`));if(!n.version)throw Error(`No "version" field in ${t}`);return n.version}function dr(e){x(q)||S(q,{recursive:!0});let t=k(q,`current-version.json.tmp`);D(t,`${JSON.stringify({version:e},null,2)}\n`),T(t,ir)}function fr(e){let t=w(e).filter(e=>e.endsWith(`.tgz`));return t.length>0?t[0]:null}function pr(e,t){K.debug(`Extracting...`),z(`tar -xzf "${t}"`,{cwd:e,stdio:`pipe`,timeout:6e4});let n=k(e,`package`);if(!x(n))throw Error(`Expected "package/" directory not found after extraction`);return K.debug(`Installing production dependencies...`),z(`npm ${Fe.join(` `)}`,{cwd:n,stdio:`pipe`,timeout:3e5}),n}function mr(e,t){let n=k(J,`v${t}`);x(J)||S(J,{recursive:!0}),x(n)&&(K.debug(`Removing previous installation...`,{target:n}),E(n,{recursive:!0})),T(e,n),dr(t),Ie(J,t),K.debug(`Installation complete`,{package:`${ar}@${t}`,target:n})}function hr(){let e={win32:`win32`,darwin:`darwin`,linux:`linux`},t={x64:`x64`,arm64:`arm64`},n=e[Me()],r=t[je()];return!n||!r?(K.warn(`Unknown platform, falling back to npm pack`,{platform:Me(),arch:je()}),``):`${n}-${r}`}function gr(e){let t=hr();if(!t)return null;let n=`aikit-v${e}-${t}.tar.gz`,r=k(k(q,`cache`,`tarballs`),n);return x(r)?r:null}function _r(e,t){let n=k(J,`v${t}-staging`);x(n)&&E(n,{recursive:!0}),S(n,{recursive:!0});try{K.debug(`Extracting prebuilt tarball...`),z(`tar -xzf "${e}"`,{cwd:n,stdio:`pipe`,timeout:6e4});let r=k(n,`aikit-v${t}-${hr()}`);if(!x(r)){let e=k(n,`package`);if(x(e)){K.debug(`Validating installation...`),lr(e),mr(e,t);return}throw Error(`Expected directory not found after extracting prebuilt tarball`)}K.debug(`Validating installation...`),lr(r),mr(r,t)}finally{x(n)&&E(n,{recursive:!0})}}function vr(e){sr(e);let t=gr(e);if(t){K.debug(`Found prebuilt tarball`,{path:t}),_r(t,e);return}let n=k(J,`v${e}-staging`);x(n)&&E(n,{recursive:!0}),S(n,{recursive:!0});try{K.debug(`Downloading...`,{package:`${ar}@${e}`}),z(`npm pack ${ar}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:n,stdio:`pipe`,timeout:12e4});let t=fr(n);if(!t)throw Error(`No .tgz file found after npm pack`);let r=pr(n,t);K.debug(`Validating installation...`),lr(r),mr(r,e)}finally{x(n)&&E(n,{recursive:!0})}}function yr(e){sr(e);let t=k(J,`v${e}`);try{lr(t),dr(e)}catch{vr(e)}}function br(e){if(!x(e))throw Error(`Tarball not found: ${e}`);let t=k(J,`_offline-detect-${Date.now()}`);S(t,{recursive:!0});let n;try{z(`tar -xzf "${e}"`,{cwd:t,stdio:`pipe`,timeout:6e4}),n=ur(k(t,`package`))}finally{x(t)&&E(t,{recursive:!0})}K.debug(`Installing from local tarball...`,{package:`${ar}@${n}`});let r=k(J,`v${n}-staging`);x(r)&&E(r,{recursive:!0}),S(r,{recursive:!0});try{Te(e,k(r,`offline-${n}.tgz`));let t=pr(r,`offline-${n}.tgz`);return K.debug(`Validating installation...`),lr(t),mr(t,n),n}finally{x(r)&&E(r,{recursive:!0})}}async function xr(e){try{let t=k(J,`v${e}`,`packages`,`server`,`dist`,`bin.js`);if(!x(t)){K.warn(`Server entry not found — skipping MCP registration`,{serverPath:t});return}let n={command:g.command,args:g.args?[...g.args]:void 0,type:g.type};if(process.platform!==`win32`){let e=process.env.PATH;e&&(n.env={PATH:e});try{let e=fn(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();e&&x(e)&&(n.command=e)}catch{}}let r=await nr({scope:`user`});if(r.length===0){K.info(`No supported IDEs detected for MCP registration`);return}for(let e of r)try{(await e.readConfig())?.[e.configKey]?.aikit&&(await e.unregisterMcp(p),K.info(`Migrated ${e.name}: old '${p}' → '${F}'`))}catch{}let i=0;for(let e of r)try{await e.registerMcp(F,n),i++}catch(t){K.warn(`Failed to register MCP for ${e.name}`,{error:t.message})}i>0&&K.info(`MCP server configured for ${i} IDE(s) — using '${F}'`)}catch(e){K.warn(`MCP registration failed`,{error:e.message})}}const Sr=[{name:`install`,description:`Install AI Kit to ~/.aikit/versions/ (one-time setup for fast local startup)`,usage:or,run:async e=>{let t=e.indexOf(`--version`),n=e.indexOf(`--offline`),r=t!==-1&&t+1<e.length,i=n!==-1&&n+1<e.length;if(e.includes(`--help`)||e.includes(`-h`)){console.log(or);return}if(i){let t=e[n+1];await xr(br(t)),K.debug(`Install complete — restart your IDE to use the new version`);return}let a;r?a=e[t+1]:(K.debug(`Checking npm registry for latest version...`),a=await cr(),K.debug(`Latest version detected`,{version:a})),vr(a),await xr(a),K.debug(`Install complete — restart your IDE to use the new version`)}}];function Cr(){let e=wr();if(e)return e;let t={command:g.command,args:g.args?[...g.args]:void 0,type:g.type};if(process.platform!==`win32`){let e=process.env.PATH;e&&(t.env={PATH:e});try{let e=fn(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();e&&x(e)&&(t.command=e)}catch{}}return t}function wr(){let e=k(N(),`.aikit`,`current-version.json`);if(!x(e))return null;try{let t=JSON.parse(C(e,`utf-8`));if(typeof t.version!=`string`||t.version.length===0||!x(k(k(N(),`.aikit`,`versions`,`v${t.version}`),`packages`,`server`,`dist`,`bin.js`)))return null;let n={command:g.command,args:g.args?[...g.args]:void 0,type:g.type};if(process.platform!==`win32`){let e=process.env.PATH;e&&(n.env={PATH:e});try{let e=fn(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();e&&x(e)&&(n.command=e)}catch{}}return n}catch{return null}}const Tr=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function Er(e,t,n){let r=j(N(),`.copilot`,`instructions`,`copilot-instructions.md`);!x(r)||n.has(r)||(S(O(r),{recursive:!0}),D(r,`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`,`utf-8`),n.add(r))}function Dr(e,t=!1){if(!Tr.has(e.name))return;let n=j(O(e.getConfigPath()),`settings.json`),r={};if(x(n))try{let e=C(n,`utf-8`);r=JSON.parse(e)}catch{console.log(` ${e.name}: skipped settings.json (invalid JSON)`);return}let i=!1;for(let[e,n]of Object.entries(ve))if(typeof n==`object`&&n){let t=typeof r[e]==`object`&&r[e]!==null?r[e]:{},a={...t,...n};JSON.stringify(a)!==JSON.stringify(t)&&(r[e]=a,i=!0)}else(t||!(e in r))&&(r[e]=n,i=!0);i&&(D(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function Or(r,o,s,c,l=!1){let u=new Map,d=new Set,f=he(`aikit`,s),ee=ye(`aikit`,s);for(let e of o)e.getScaffoldRoot()!==null&&u.set(e.id,e);if(Er(f,ee,d),u.size===0){d.size>0?console.log(` Instruction files: ${[...d].join(`, `)}`):console.log(` No IDEs with global scaffold support detected.`);return}let te=await n(r,`copilot`),ne=await n(r,`opencode`),re=await n(r,`hermes-agent`),ie=await n(r,`claude-code`),ae=e=>{let t=new Map;for(let n of e){let e=n.path.indexOf(`/`);if(e===-1)continue;let r=n.path.substring(0,e);if(r===`agents`||r===`prompts`){let i=t.get(r)??[];i.push({path:n.path.substring(e+1),content:n.content}),t.set(r,i)}else if(r===`.opencode`){let r=n.path.indexOf(`/`,e+1);if(r!==-1&&n.path.substring(e+1,r)===`agents`){let e=t.get(`agents`)??[];e.push({path:n.path.substring(r+1),content:n.content}),t.set(`agents`,e)}}else if(r===`.claude`){let r=n.path.indexOf(`/`,e+1);if(r!==-1&&n.path.substring(e+1,r)===`agents`){let e=t.get(`agents`)??[];e.push({path:n.path.substring(r+1),content:n.content}),t.set(`agents`,e)}}}return t},oe=ae(te),se=ae(ne),ce=ae(re),p=ae(ie),le=await n(r,`skills`),ue=new Set;for(let e of le){let t=e.path.indexOf(`/`);t!==-1&&ue.add(e.path.substring(0,t))}let m=await n(r,`flows`),de=new Set;for(let e of m){let t=e.path.indexOf(`/`);t!==-1&&de.add(e.path.substring(0,t))}let fe=await n(r,`claude-code`),h=j(r,`scaffold`,`general`,`hooks`,`scripts`),g=x(h)?h:j(import.meta.dirname,`../../../../../scaffold/general/hooks/scripts`),pe=be(),_=new Set,v=new Set,ge=new Set,y=(n,r,o,s)=>{let u=s.get(o);if(!n||!r||!u||u.length===0)return;let d=`${o}:${r}:${n}`;if(_.has(d))return;_.add(d);let f=e(r)??a(c);f.version=c,i(u,n,f,o,l),t(r,f),ge.add(O(r))},_e=(n,r,o,s)=>{if(!n||!r||s.length===0)return;let u=`${o}:${r}:${n}`;if(_.has(u))return;if(_.add(u),o===`flows`&&!v.has(n)){for(let e of de){let t=j(n,e,`skills`);x(t)&&(E(t,{recursive:!0,force:!0}),console.log(` ${O(r)}: migrated ${e} flow to steps/ layout`))}v.add(n)}let d=e(r)??a(c);d.version=c,i(s,n,d,o,l),t(r,d),ge.add(O(r))},ve=(e,t,n)=>{!e||!t||_e(e,t,`hooks`,[...me(n,j(e,`scripts`).replace(/\\/g,`/`)),...pe.map(e=>({path:`scripts/${e}`,content:C(j(g,e),`utf-8`)}))])};for(let e of u.values()){let t=e.getScaffoldPaths(),n=e.family===`opencode`?se:e.family===`hermes`?ce:e.family===`claude`?p:oe;y(t.agents,t.manifest,`agents`,n),y(t.prompts,t.manifest,`prompts`,n),_e(t.skills,t.manifest,`skills`,le),_e(t.flows,t.manifest,`flows`,m),_e(t.commands,t.manifest,`commands`,fe),ve(t.hooks,t.manifest,e.family===`claude`?`claude`:`copilot`)}for(let e of ge)console.log(` ${e}: scaffold updated (${ue.size} skills)`);for(let e of u.values()){let t=e.getScaffoldPaths().instructions;!t||d.has(t)||(S(O(t),{recursive:!0}),D(t,e.buildInstructionContent(f,ee),`utf-8`),d.add(t))}d.size>0&&console.log(` Instruction files: ${[...d].join(`, `)}`)}function kr(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e){if(Tr.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(j(r,`kb.instructions.md`)),t.push(j(r,`aikit.instructions.md`))}else if(n.name===`Cursor`||n.name===`Cursor Nightly`)t.push(j(e,`rules`,`kb.mdc`));else if(n.name===`Windsurf`)t.push(j(e,`rules`,`kb.md`));else if(n.family===`claude`){let n=j(e,`agents`);if(x(n)){for(let e of w(n))if(e.endsWith(`.agent.md`)){let r=j(n,e);De(r),t.push(r)}}}}}for(let e of t)x(e)&&(De(e),console.log(` Removed legacy file: ${e}`))}async function Ar(e){let t=F,n=ce(),r=JSON.parse(C(j(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=Le();S(i,{recursive:!0}),console.log(` Global data store: ${i}`),console.log(` Managed runtime: v${r}`),yr(r),Ue({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await nr({scope:`user`});if(a.length===0)console.log(`
39
+ --help, -h Show this help`;function sr(e){if(!rr.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}async function cr(){let e=await fetch(`https://registry.npmjs.org/${ar}/latest`,{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw Error(`Failed to fetch latest version from npm registry (HTTP ${e.status})`);let t=await e.json();if(!t.version)throw Error(`npm registry response missing "version" field`);return t.version}function lr(e){let t=k(e,`packages`,`server`,`dist`,`bin.js`);if(!x(t))throw Error(`Server entry point not found at ${t}. The installation may be incomplete or corrupted.`);let n=k(e,`node_modules`);if(!x(n))throw Error(`node_modules not found at ${n}. Production dependencies may not have been installed.`)}function ur(e){let t=k(e,`package.json`),n=JSON.parse(C(t,`utf-8`));if(!n.version)throw Error(`No "version" field in ${t}`);return n.version}function dr(e){x(q)||S(q,{recursive:!0});let t=k(q,`current-version.json.tmp`);D(t,`${JSON.stringify({version:e},null,2)}\n`),T(t,ir)}function fr(e){let t=w(e).filter(e=>e.endsWith(`.tgz`));return t.length>0?t[0]:null}function pr(e,t){K.debug(`Extracting...`),z(`tar -xzf "${t}"`,{cwd:e,stdio:`pipe`,timeout:6e4});let n=k(e,`package`);if(!x(n))throw Error(`Expected "package/" directory not found after extraction`);return K.debug(`Installing production dependencies...`),z(`npm ${Fe.join(` `)}`,{cwd:n,stdio:`pipe`,timeout:3e5}),n}function mr(e,t){let n=k(J,`v${t}`);x(J)||S(J,{recursive:!0}),x(n)&&(K.debug(`Removing previous installation...`,{target:n}),E(n,{recursive:!0})),T(e,n),dr(t),Ie(J,t),K.debug(`Installation complete`,{package:`${ar}@${t}`,target:n})}function hr(){let e={win32:`win32`,darwin:`darwin`,linux:`linux`},t={x64:`x64`,arm64:`arm64`},n=e[Me()],r=t[je()];return!n||!r?(K.warn(`Unknown platform, falling back to npm pack`,{platform:Me(),arch:je()}),``):`${n}-${r}`}function gr(e){let t=hr();if(!t)return null;let n=`aikit-v${e}-${t}.tar.gz`,r=k(k(q,`cache`,`tarballs`),n);return x(r)?r:null}function _r(e,t){let n=k(J,`v${t}-staging`);x(n)&&E(n,{recursive:!0}),S(n,{recursive:!0});try{K.debug(`Extracting prebuilt tarball...`),z(`tar -xzf "${e}"`,{cwd:n,stdio:`pipe`,timeout:6e4});let r=k(n,`aikit-v${t}-${hr()}`);if(!x(r)){let e=k(n,`package`);if(x(e)){K.debug(`Validating installation...`),lr(e),mr(e,t);return}throw Error(`Expected directory not found after extracting prebuilt tarball`)}K.debug(`Validating installation...`),lr(r),mr(r,t)}finally{x(n)&&E(n,{recursive:!0})}}function vr(e){sr(e);let t=gr(e);if(t){K.debug(`Found prebuilt tarball`,{path:t}),_r(t,e);return}let n=k(J,`v${e}-staging`);x(n)&&E(n,{recursive:!0}),S(n,{recursive:!0});try{K.debug(`Downloading...`,{package:`${ar}@${e}`}),z(`npm pack ${ar}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:n,stdio:`pipe`,timeout:12e4});let t=fr(n);if(!t)throw Error(`No .tgz file found after npm pack`);let r=pr(n,t);K.debug(`Validating installation...`),lr(r),mr(r,e)}finally{x(n)&&E(n,{recursive:!0})}}function yr(e){sr(e);let t=k(J,`v${e}`);try{lr(t),dr(e)}catch{vr(e)}}function br(e){if(!x(e))throw Error(`Tarball not found: ${e}`);let t=k(J,`_offline-detect-${Date.now()}`);S(t,{recursive:!0});let n;try{z(`tar -xzf "${e}"`,{cwd:t,stdio:`pipe`,timeout:6e4}),n=ur(k(t,`package`))}finally{x(t)&&E(t,{recursive:!0})}K.debug(`Installing from local tarball...`,{package:`${ar}@${n}`});let r=k(J,`v${n}-staging`);x(r)&&E(r,{recursive:!0}),S(r,{recursive:!0});try{Te(e,k(r,`offline-${n}.tgz`));let t=pr(r,`offline-${n}.tgz`);return K.debug(`Validating installation...`),lr(t),mr(t,n),n}finally{x(r)&&E(r,{recursive:!0})}}async function xr(e){try{let t=k(J,`v${e}`,`packages`,`server`,`dist`,`bin.js`);if(!x(t)){K.warn(`Server entry not found — skipping MCP registration`,{serverPath:t});return}let n={command:g.command,args:g.args?[...g.args]:void 0,type:g.type};if(process.platform!==`win32`){let e=process.env.PATH;e&&(n.env={PATH:e});try{let e=fn(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();e&&x(e)&&(n.command=e)}catch{}}let r=await nr({scope:`user`});if(r.length===0){K.info(`No supported IDEs detected for MCP registration`);return}for(let e of r)try{(await e.readConfig())?.[e.configKey]?.aikit&&(await e.unregisterMcp(p),K.info(`Migrated ${e.name}: old '${p}' → '${F}'`))}catch{}let i=0;for(let e of r)try{await e.registerMcp(F,n),i++}catch(t){K.warn(`Failed to register MCP for ${e.name}`,{error:t.message})}i>0&&K.info(`MCP server configured for ${i} IDE(s) — using '${F}'`)}catch(e){K.warn(`MCP registration failed`,{error:e.message})}}const Sr=[{name:`install`,description:`Install AI Kit to ~/.aikit/versions/ (one-time setup for fast local startup)`,usage:or,run:async e=>{let t=e.indexOf(`--version`),n=e.indexOf(`--offline`),r=t!==-1&&t+1<e.length,i=n!==-1&&n+1<e.length;if(e.includes(`--help`)||e.includes(`-h`)){console.log(or);return}if(i){let t=e[n+1];await xr(br(t)),K.debug(`Install complete — restart your IDE to use the new version`);return}let a;r?a=e[t+1]:(K.debug(`Checking npm registry for latest version...`),a=await cr(),K.debug(`Latest version detected`,{version:a})),vr(a),await xr(a),K.debug(`Install complete — restart your IDE to use the new version`)}}];function Cr(){let e=wr();if(e)return e;let t={command:g.command,args:g.args?[...g.args]:void 0,type:g.type};if(process.platform!==`win32`){let e=process.env.PATH;e&&(t.env={PATH:e});try{let e=fn(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();e&&x(e)&&(t.command=e)}catch{}}return t}function wr(){let e=k(N(),`.aikit`,`current-version.json`);if(!x(e))return null;try{let t=JSON.parse(C(e,`utf-8`));if(typeof t.version!=`string`||t.version.length===0||!x(k(k(N(),`.aikit`,`versions`,`v${t.version}`),`packages`,`server`,`dist`,`bin.js`)))return null;let n={command:g.command,args:g.args?[...g.args]:void 0,type:g.type};if(process.platform!==`win32`){let e=process.env.PATH;e&&(n.env={PATH:e});try{let e=fn(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();e&&x(e)&&(n.command=e)}catch{}}return n}catch{return null}}const Tr=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function Er(e,t,n){let r=j(N(),`.copilot`,`instructions`,`copilot-instructions.md`);!x(r)||n.has(r)||(S(O(r),{recursive:!0}),D(r,`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`,`utf-8`),n.add(r))}function Dr(e,t=!1){if(!Tr.has(e.name))return;let n=j(O(e.getConfigPath()),`settings.json`),r={};if(x(n))try{let e=C(n,`utf-8`);r=JSON.parse(e)}catch{console.log(` ${e.name}: skipped settings.json (invalid JSON)`);return}let i=!1;for(let[e,n]of Object.entries(ve))if(typeof n==`object`&&n){let t=typeof r[e]==`object`&&r[e]!==null?r[e]:{},a={...t,...n};JSON.stringify(a)!==JSON.stringify(t)&&(r[e]=a,i=!0)}else(t||!(e in r))&&(r[e]=n,i=!0);i&&(D(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function Or(r,o,s,c,l=!1){let u=new Map,d=new Set,f=he(`aikit`,s),ee=ye(`aikit`,s);for(let e of o)e.getScaffoldRoot()!==null&&u.set(e.id,e);if(Er(f,ee,d),u.size===0){d.size>0?console.log(` Instruction files: ${[...d].join(`, `)}`):console.log(` No IDEs with global scaffold support detected.`);return}let te=await n(r,`copilot`),ne=await n(r,`opencode`),re=await n(r,`hermes`),ie=await n(r,`claude-code`),ae=e=>{let t=new Map;for(let n of e){let e=n.path.indexOf(`/`);if(e===-1)continue;let r=n.path.substring(0,e);if(r===`agents`||r===`prompts`){let i=t.get(r)??[];i.push({path:n.path.substring(e+1),content:n.content}),t.set(r,i)}else if(r===`.opencode`){let r=n.path.indexOf(`/`,e+1);if(r!==-1&&n.path.substring(e+1,r)===`agents`){let e=t.get(`agents`)??[];e.push({path:n.path.substring(r+1),content:n.content}),t.set(`agents`,e)}}else if(r===`.claude`){let r=n.path.indexOf(`/`,e+1);if(r!==-1&&n.path.substring(e+1,r)===`agents`){let e=t.get(`agents`)??[];e.push({path:n.path.substring(r+1),content:n.content}),t.set(`agents`,e)}}}return t},oe=ae(te),se=ae(ne),ce=ae(re),p=ae(ie),le=await n(r,`skills`),ue=new Set;for(let e of le){let t=e.path.indexOf(`/`);t!==-1&&ue.add(e.path.substring(0,t))}let m=await n(r,`flows`),de=new Set;for(let e of m){let t=e.path.indexOf(`/`);t!==-1&&de.add(e.path.substring(0,t))}let fe=await n(r,`claude-code`),h=j(r,`scaffold`,`general`,`hooks`,`scripts`),g=x(h)?h:j(import.meta.dirname,`../../../../../scaffold/general/hooks/scripts`),pe=be(),_=new Set,v=new Set,ge=new Set,y=(n,r,o,s)=>{let u=s.get(o);if(!n||!r||!u||u.length===0)return;let d=`${o}:${r}:${n}`;if(_.has(d))return;_.add(d);let f=e(r)??a(c);f.version=c,i(u,n,f,o,l),t(r,f),ge.add(O(r))},_e=(n,r,o,s)=>{if(!n||!r||s.length===0)return;let u=`${o}:${r}:${n}`;if(_.has(u))return;if(_.add(u),o===`flows`&&!v.has(n)){for(let e of de){let t=j(n,e,`skills`);x(t)&&(E(t,{recursive:!0,force:!0}),console.log(` ${O(r)}: migrated ${e} flow to steps/ layout`))}v.add(n)}let d=e(r)??a(c);d.version=c,i(s,n,d,o,l),t(r,d),ge.add(O(r))},ve=(e,t,n)=>{!e||!t||_e(e,t,`hooks`,[...me(n,j(e,`scripts`).replace(/\\/g,`/`)),...pe.map(e=>({path:`scripts/${e}`,content:C(j(g,e),`utf-8`)}))])};for(let e of u.values()){let t=e.getScaffoldPaths(),n=e.family===`opencode`?se:e.family===`hermes`?ce:e.family===`claude`?p:oe;y(t.agents,t.manifest,`agents`,n),y(t.prompts,t.manifest,`prompts`,n),_e(t.skills,t.manifest,`skills`,le),_e(t.flows,t.manifest,`flows`,m),_e(t.commands,t.manifest,`commands`,fe),ve(t.hooks,t.manifest,e.family===`claude`?`claude`:`copilot`)}for(let e of ge)console.log(` ${e}: scaffold updated (${ue.size} skills)`);for(let e of u.values()){let t=e.getScaffoldPaths().instructions;!t||d.has(t)||(S(O(t),{recursive:!0}),D(t,e.buildInstructionContent(f,ee),`utf-8`),d.add(t))}d.size>0&&console.log(` Instruction files: ${[...d].join(`, `)}`)}function kr(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e){if(Tr.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(j(r,`kb.instructions.md`)),t.push(j(r,`aikit.instructions.md`))}else if(n.name===`Cursor`||n.name===`Cursor Nightly`)t.push(j(e,`rules`,`kb.mdc`));else if(n.name===`Windsurf`)t.push(j(e,`rules`,`kb.md`));else if(n.family===`claude`){let n=j(e,`agents`);if(x(n)){for(let e of w(n))if(e.endsWith(`.agent.md`)){let r=j(n,e);De(r),t.push(r)}}}}}for(let e of t)x(e)&&(De(e),console.log(` Removed legacy file: ${e}`))}async function Ar(e){let t=F,n=ce(),r=JSON.parse(C(j(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=Le();S(i,{recursive:!0}),console.log(` Global data store: ${i}`),console.log(` Managed runtime: v${r}`),yr(r),Ue({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await nr({scope:`user`});if(a.length===0)console.log(`
40
40
  No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=wr();if(!n)throw Error(`Managed runtime v${r} was installed but its MCP server entry could not be resolved.`);for(let e of a)try{await e.registerMcp(t,n),console.log(` ${e.name}: configured ${t}`)}catch(t){console.log(` ${e.name}: failed to configure (${t.message})`)}for(let t of a)Dr(t,e.force)}console.log(`
41
41
  Installing scaffold files:`),await Or(n,a,t,r,e.force),kr(a),console.log(`
42
42
  User-level AI Kit installation complete!`),console.log(`
@@ -139,12 +139,12 @@
139
139
  <button class="cp-btn cp-btn--remove" aria-label="Remove selection without comment">Remove</button>
140
140
  <button class="cp-btn cp-btn--comment" aria-label="Submit comment">Comment</button>
141
141
  </div>
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 l=i[0],c=i[i.length-1];o.shiftKey&&document.activeElement===l?(o.preventDefault(),c.focus()):!o.shiftKey&&document.activeElement===c&&(o.preventDefault(),l.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 l=window.innerHeight+n,c=t.bottom+n+o,p;c+r<=l?p=c:(p=t.top+n-r-o,p=Math.max(o,p)),this.el.style.left=`${i}px`,this.el.style.top=`${p}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){s(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(`
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}
142
+ `,this.textarea=this.el.querySelector(".cp-textarea");let n=this.el.querySelector(".cp-btn--comment"),o=this.el.querySelector(".cp-btn--remove"),i=this.el.querySelector(".cp-btn--cancel");this.backdrop.addEventListener("click",()=>this.handleCancel()),n.addEventListener("click",()=>this.handleComment()),o.addEventListener("click",()=>this.handleRemove()),i.addEventListener("click",()=>this.handleCancel()),this.textarea.addEventListener("keydown",a=>this.handleKeyDown(a)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener("keydown",a=>{if(a.key!=="Tab")return;let r=this.el.querySelectorAll('button, textarea, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let l=r[0],c=r[r.length-1];a.shiftKey&&document.activeElement===l?(a.preventDefault(),c.focus()):!a.shiftKey&&document.activeElement===c&&(a.preventDefault(),l.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,o=this.el.offsetWidth||320,i=this.el.offsetHeight||260,a=8,r=t.left+e+t.width/2-o/2;r=Math.max(a,r),r=Math.min(r,window.innerWidth+e-o-a);let l=window.innerHeight+n,c=t.bottom+n+a,p;c+i<=l?p=c:(p=t.top+n-i-a,p=Math.max(a,p)),this.el.style.left=`${r}px`,this.el.style.top=`${p}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){s(this,"store");this.store=t}escapeMd(t){return t.replace(/[`*_{}[\]()#+\-.!|~]/g,"\\$&")}exportMarkdown(){let e=[...this.store.getState().annotations].sort((r,l)=>r.createdAt-l.createdAt);if(e.length===0)return"No feedback provided.";let n=e.filter(r=>r.type==="COMMENT"),o=e.filter(r=>r.type==="DELETION"),i=e.filter(r=>r.type==="GLOBAL_COMMENT"),a=["## Reviewer Feedback",""];if(i.length>0){a.push("### General Notes","");for(let r of i)a.push(`- ${this.escapeMd(r.comment||"")}`),a.push("")}if(n.length>0){a.push("### Comments","");for(let r of n){let l=r.originalText.length>80?`${r.originalText.slice(0,80)}\u2026`:r.originalText;a.push(`- **${this.escapeMd(r.comment||"")}**`),a.push(` > "${this.escapeMd(l)}"`),a.push("")}}if(o.length>0){a.push("### Deletions","");for(let r of o){let l=r.originalText.length>80?`${r.originalText.slice(0,80)}\u2026`:r.originalText;a.push("- Remove this"),a.push(` > "${this.escapeMd(l)}"`),a.push("")}}return a.join(`
143
+ `).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((n,o)=>n.createdAt-o.createdAt);return JSON.stringify(e,null,2)}submitFeedback(t){let e=this.exportMarkdown(),n=this.exportJSON(),o=e==="No feedback provided."?e:`${e}
144
144
 
145
145
  \`\`\`json
146
146
  ${n}
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 d=document.createElement("style");d.id=w,d.textContent=`
147
+ \`\`\``;t("annotations",o)}getTotalCount(){let t=this.store.getState(),e=t.annotations.filter(i=>i.type==="COMMENT").length,n=t.annotations.filter(i=>i.type==="DELETION").length,o=t.annotations.filter(i=>i.type==="GLOBAL_COMMENT").length;return{comments:e,deletions:n,global:o,total:t.annotations.length}}};var L="aikit-annotation-highlight";function I(){if(document.getElementById(L))return;let d=document.createElement("style");d.id=L,d.textContent=`
148
148
  mark.hl-COMMENT {
149
149
  background: var(--dt-annotation-comment-bg, rgba(88, 166, 255, 0.15));
150
150
  border-bottom: 2px solid var(--dt-annotation-comment, #58a6ff);
@@ -185,7 +185,7 @@ ${n}
185
185
  50% { transform: scale(1.05); }
186
186
  100% { transform: scale(1); }
187
187
  }
188
- `,document.head.appendChild(d)}var y=class{constructor(t,e){s(this,"container");s(this,"store");s(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,l=null,c=0,p=a.nextNode();for(;p;){let f=(p.textContent||"").length,m=r+f;if(o===null&&m>e&&(o=p,i=e-r),m>=n){l=p,c=n-r;break}r=m,p=a.nextNode()}if(!o||!l)return null;let u=document.createRange();return u.setStart(o,Math.min(i,(o.textContent||"").length)),u.setEnd(l,Math.min(c,(l.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){s(this,"options");s(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),l=this.computeBlockOffset(n.endContainer,n.endOffset);if(i===null||l===null)return;let c={blockId:a,startOffset:i,endOffset:l,text:n.toString(),range:n};this.options.onSelection(c),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=`
188
+ `,document.head.appendChild(d)}var y=class{constructor(t,e){s(this,"container");s(this,"store");s(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 o=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null),i=0,a=null,r=0,l=null,c=0,p=o.nextNode();for(;p;){let f=(p.textContent||"").length,m=i+f;if(a===null&&m>e&&(a=p,r=e-i),m>=n){l=p,c=n-i;break}i=m,p=o.nextNode()}if(!a||!l)return null;let u=document.createRange();return u.setStart(a,Math.min(r,(a.textContent||"").length)),u.setEnd(l,Math.min(c,(l.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 o=document.createElement("mark");o.className=`hl-${t.type}`,o.dataset.annotationId=t.id,o.addEventListener("click",()=>{this.store.select(t.id)});try{n.surroundContents(o)}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 a=document.createRange();a.setStart(i.nextSibling||i,0),a.setEnd(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.previousSibling||n.endContainer,n.endOffset),a.surroundContents(o)}else throw new Error("Non-text range")}catch{let i=n.extractContents();o.append(i),n.insertNode(o)}}}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 z=new Set(["button","input","textarea","select"]),E=class{constructor(t){s(this,"options");s(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 o=this.findBlockId(n.startContainer);if(!o)return;let i=this.findBlockContainer(n.startContainer),a=this.findBlockContainer(n.endContainer);if(i!==a)return;let r=this.computeBlockOffset(n.startContainer,n.startOffset),l=this.computeBlockOffset(n.endContainer,n.endOffset);if(r===null||l===null)return;let c={blockId:o,startOffset:r,endOffset:l,text:n.toString(),range:n};this.options.onSelection(c),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 o=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=0,a=o.nextNode();for(;a;){if(a===t)return i+e;i+=(a.textContent||"").length,a=o.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?z.has(e.tagName.toLowerCase()):!1}};var D="aikit-annotation-sidebar",R=`
189
189
  .as-sidebar {
190
190
  width: var(--dt-annotation-sidebar-width, 300px);
191
191
  background: var(--dt-bg-secondary);
@@ -289,6 +289,9 @@ ${n}
289
289
  .as-card--DELETION {
290
290
  border-left: 2px solid var(--dt-annotation-deletion, #f85149);
291
291
  }
292
+ .as-card--GLOBAL_COMMENT {
293
+ border-left: 2px solid var(--dt-accent-fg, #6366f1);
294
+ }
292
295
 
293
296
  .as-card:hover {
294
297
  background: var(--dt-annotation-hover);
@@ -302,6 +305,18 @@ ${n}
302
305
  outline: 2px solid var(--dt-annotation-deletion, #f85149);
303
306
  outline-offset: -2px;
304
307
  }
308
+ .as-card--GLOBAL_COMMENT.as-card--selected {
309
+ outline: 2px solid var(--dt-accent-fg, #6366f1);
310
+ outline-offset: -2px;
311
+ }
312
+
313
+ .as-card-type-badge {
314
+ display: inline-block;
315
+ font-size: var(--dt-font-size-xs);
316
+ font-weight: 600;
317
+ color: var(--dt-text-tertiary);
318
+ margin-bottom: 2px;
319
+ }
305
320
 
306
321
  .as-card-excerpt {
307
322
  font-size: var(--dt-font-size-sm);
@@ -367,21 +382,89 @@ ${n}
367
382
  font-size: var(--dt-font-size-sm);
368
383
  padding: var(--dt-space-6) var(--dt-space-2);
369
384
  }
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){s(this,"el");s(this,"store");s(this,"exporter");s(this,"unsubscribe",null);s(this,"listEl");s(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=`
385
+
386
+ /* \u2500\u2500 Global comment footer \u2500\u2500 */
387
+ .as-footer {
388
+ border-top: 1px solid var(--dt-border-default);
389
+ padding: var(--dt-space-3);
390
+ flex-shrink: 0;
391
+ display: flex;
392
+ flex-direction: column;
393
+ gap: var(--dt-space-2);
394
+ }
395
+
396
+ .as-global-input {
397
+ font: inherit;
398
+ font-size: var(--dt-font-size-sm);
399
+ line-height: 1.4;
400
+ padding: var(--dt-space-2);
401
+ border: 1px solid var(--dt-border-default);
402
+ border-radius: var(--dt-radius-md);
403
+ background: var(--dt-bg-primary);
404
+ color: var(--dt-text-primary);
405
+ resize: vertical;
406
+ min-height: 2.5rem;
407
+ max-height: 6rem;
408
+ width: 100%;
409
+ box-sizing: border-box;
410
+ outline: none;
411
+ transition: border-color var(--dt-transition-fast);
412
+ }
413
+ .as-global-input:focus {
414
+ border-color: var(--dt-accent-fg);
415
+ }
416
+ .as-global-input::placeholder {
417
+ color: var(--dt-text-tertiary);
418
+ }
419
+
420
+ .as-global-btn {
421
+ display: inline-flex;
422
+ align-items: center;
423
+ justify-content: center;
424
+ gap: 4px;
425
+ padding: var(--dt-space-1) var(--dt-space-3);
426
+ border: 1px solid var(--dt-accent-fg);
427
+ border-radius: var(--dt-radius-md);
428
+ background: var(--dt-accent-emphasis);
429
+ color: #ffffff;
430
+ font-size: var(--dt-font-size-sm);
431
+ font-weight: 600;
432
+ cursor: pointer;
433
+ transition: opacity var(--dt-transition-fast);
434
+ font-family: inherit;
435
+ align-self: flex-end;
436
+ }
437
+ .as-global-btn:hover {
438
+ opacity: 0.9;
439
+ }
440
+ .as-global-btn:disabled {
441
+ opacity: 0.5;
442
+ cursor: default;
443
+ }
444
+ `,_='<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){s(this,"el");s(this,"store");s(this,"exporter");s(this,"unsubscribe",null);s(this,"listEl");s(this,"modeToggleBtn");s(this,"globalInput");s(this,"globalBtn");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.globalInput=this.el.querySelector(".as-global-input"),this.globalBtn=this.el.querySelector(".as-global-btn"),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}}),this.globalBtn.addEventListener("click",n=>{n.stopPropagation(),this.submitGlobalComment()}),this.globalInput.addEventListener("keydown",n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.submitGlobalComment())}),this.globalInput.addEventListener("input",()=>{this.updateGlobalBtnState()}),(t.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle(),this.updateGlobalBtnState()}destroy(){this.unsubscribe?.(),this.el.remove()}submitGlobalComment(){let t=this.globalInput.value.trim();t&&(this.store.addGeneralComment(t),this.globalInput.value="",this.updateGlobalBtnState())}updateGlobalBtnState(){this.globalBtn.disabled=this.globalInput.value.trim().length===0}render(){b(D,R);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=`
371
445
  <div class="as-header">
372
446
  <span class="as-header-title">Annotations</span>
373
447
  <span class="as-count-badge" aria-live="polite">${e.total}</span>
374
448
  <span class="as-header-spacer"></span>
375
- <button class="as-mode-toggle" aria-label="Toggle annotation mode">${$} Feedback</button>
449
+ <button class="as-mode-toggle" aria-label="Toggle annotation mode">${_} Feedback</button>
376
450
  <button class="as-close-btn" aria-label="Close sidebar">&times;</button>
377
451
  </div>
378
452
  <div class="as-list" role="list" aria-label="Annotation list"></div>
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=`
380
- <div class="as-card-excerpt">${g(a)}</div>
381
- ${t.comment?`<div class="as-card-comment">${g(t.comment)}</div>`:""}
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>
383
- <button class="as-delete-btn" aria-label="Delete annotation">&times;</button>
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 l of i)l!==o&&l.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(){s(this,"annotations",[]);s(this,"selectedId",null);s(this,"mode","selection");s(this,"isSidebarOpen",!1);s(this,"subscribers",new Set);s(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,l,c){let p={id:this.generateId(),type:t,blockId:e,startOffset:n,endOffset:a,originalText:r,comment:o,section:i,contextBefore:l,contextAfter:c,createdAt:Date.now()};return this.annotations.push(p),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:p}),p}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=`
453
+ <div class="as-footer">
454
+ <textarea class="as-global-input" placeholder="Add general feedback comment..." rows="2" maxlength="5000" aria-label="Add general comment"></textarea>
455
+ <button class="as-global-btn" disabled>Add Comment</button>
456
+ </div>
457
+ `,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 a=this.store.getState().mode==="feedback"?"selection":"feedback";this.store.setMode(a)}),t}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML="",e.length===0){let o=document.createElement("div");o.className="as-empty",o.textContent="No annotations yet. Select text in Feedback mode or add a general comment below.",this.listEl.appendChild(o);return}let n=[...e].sort((o,i)=>i.createdAt-o.createdAt);for(let o of n)this.listEl.appendChild(this.renderAnnotationItem(o))}renderAnnotationItem(t){let e=document.createElement("div");if(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"),t.type==="GLOBAL_COMMENT")e.innerHTML=`
458
+ <div class="as-card-type-badge">General Comment</div>
459
+ <div class="as-card-comment">${g(t.comment||"")}</div>
460
+ <div class="as-card-comment-detail">${g(t.comment||"")}</div>
461
+ <button class="as-delete-btn" aria-label="Delete annotation">&times;</button>
462
+ `;else{let i=t.originalText.length>60?`${t.originalText.slice(0,60)}\u2026`:t.originalText;e.innerHTML=`
463
+ <div class="as-card-excerpt">${g(i)}</div>
464
+ ${t.comment?`<div class="as-card-comment">${g(t.comment)}</div>`:""}
465
+ <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>
466
+ <button class="as-delete-btn" aria-label="Delete annotation">&times;</button>
467
+ `}return e.addEventListener("click",()=>{this.store.select(t.id);let i=e.querySelector(".as-card-comment-detail");if(i){i.classList.toggle("as-card-comment-detail--open");let a=this.listEl.querySelectorAll(".as-card-comment-detail--open");for(let r of a)r!==i&&r.classList.remove("as-card-comment-detail--open")}}),e.querySelector(".as-delete-btn").addEventListener("click",i=>{i.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 o=n.dataset.annotationId;n.classList.toggle("as-card--selected",o!==void 0&&o===t)}}};var T=class{constructor(){s(this,"annotations",[]);s(this,"selectedId",null);s(this,"mode","selection");s(this,"isSidebarOpen",!1);s(this,"subscribers",new Set);s(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,o,i,a,r,l,c){let p={id:this.generateId(),type:t,blockId:e,startOffset:n,endOffset:o,originalText:i,comment:a,section:r,contextBefore:l,contextAfter:c,createdAt:Date.now()};return this.annotations.push(p),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:p}),p}addGeneralComment(t){let e={id:this.generateId(),type:"GLOBAL_COMMENT",blockId:"",startOffset:0,endOffset:0,originalText:"",comment:t,createdAt:Date.now()};return this.annotations.push(e),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:e}),e}update(t,e){let n=this.annotations.find(o=>o.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 w=25,$="aikit-annotation-guide",q=`
385
468
  .as-guide {
386
469
  margin: 0 0 var(--dt-space-3) 0;
387
470
  padding: var(--dt-space-2) var(--dt-space-3);
@@ -398,7 +481,7 @@ ${n}
398
481
  .as-guide--visible {
399
482
  display: block;
400
483
  }
401
- `;function j(d){let{range:t}=d,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(d){let{container:t,mountTarget:e}=d,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 l=new y(t,a);l.start();let c=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}}),p=new k({store:a,exporter:r,mountTarget:e});return a.openSidebar(),{destroy(){n?.destroy(),n=null,o.remove(),c.destroy(),l.stop(),p.destroy(),a.destroy()},getStore(){return a},getExporter(){return r}}}document.addEventListener("DOMContentLoaded",()=>{let d=document.querySelector(".content")||document.querySelector("main"),t=d||document.body;if(!d||!(document.querySelector(".bk-actions")!==null))return;let n=t.parentElement;n?.classList.contains("shell-layout")||(n=document.createElement("div"),n.className="shell-layout",t.parentNode?.insertBefore(n,t),n.appendChild(t));let a="aikit-shell-layout";if(!document.getElementById(a)){let i=document.createElement("style");i.id=a,i.textContent=`
484
+ `;function j(d){let{range:t}=d,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 o,i;try{if(t.startContainer.nodeType===Node.TEXT_NODE&&t.startOffset>0){let a=t.startContainer.textContent||"",r=Math.max(0,t.startOffset-w);o=a.slice(r,t.startOffset)}if(t.endContainer.nodeType===Node.TEXT_NODE&&t.endOffset<(t.endContainer.textContent?.length||0)){let a=t.endContainer.textContent||"",r=Math.min(a.length,t.endOffset+w);i=a.slice(t.endOffset,r)}}catch{}return{section:e,contextBefore:o,contextAfter:i}}function A(d){let{container:t,mountTarget:e}=d,n=null,o=new T;o.setMode("feedback");let i=new x(o);b($,q);let a=document.createElement("div");a.className="as-guide",a.textContent="\u27B3 Ready. Select text to annotate or disable Feedback in the sidebar.",t.prepend(a);let r=()=>{let u=o.getState();a.classList.toggle("as-guide--visible",u.mode==="feedback"&&u.annotations.length===0)};r(),o.subscribe(()=>r());let l=new y(t,o);l.start();let c=new E({container:t,mode:()=>o.getState().mode,onSelection:u=>{let f=j(u);n?.destroy();let m=new v(u,{onSubmit:(h,S)=>{o.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)=>{o.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}}),p=new k({store:o,exporter:i,mountTarget:e});return o.openSidebar(),{destroy(){n?.destroy(),n=null,a.remove(),c.destroy(),l.stop(),p.destroy(),o.destroy()},getStore(){return o},getExporter(){return i}}}document.addEventListener("DOMContentLoaded",()=>{let d=document.querySelector(".content")||document.querySelector("main"),t=d||document.body;if(!d||!(document.querySelector(".bk-actions")!==null))return;let n=t.parentElement;n?.classList.contains("shell-layout")||(n=document.createElement("div"),n.className="shell-layout",t.parentNode?.insertBefore(n,t),n.appendChild(t));let o="aikit-shell-layout";if(!document.getElementById(o)){let r=document.createElement("style");r.id=o,r.textContent=`
402
485
  .shell-layout {
403
486
  flex: 1;
404
487
  display: flex;
@@ -425,4 +508,4 @@ ${C}
425
508
  .action-bar {
426
509
  margin-top: auto;
427
510
  }
428
- `,document.head.appendChild(i)}let r=A({container:t,mountTarget:n});r.getStore().subscribe(i=>{i.type==="sidebar-toggled"&&document.documentElement.setAttribute("data-annotation-sidebar",i.open?"open":"")}),r.getStore().getState().isSidebarOpen&&document.documentElement.setAttribute("data-annotation-sidebar","open"),window.__annotationLayer=r;let o=document.querySelectorAll(".bk-actions");if(o.length>0){let i=document.createElement("div");i.className="action-bar";let l=!1;for(let c of o)if(!c.querySelector('[data-action-row="multi"]')){for(;c.firstChild;)i.appendChild(c.firstChild);c.remove(),l=!0}if(l){let c=document.querySelector("main")||document.querySelector(".content");c&&(c.appendChild(i),c.style.paddingBottom="0")}}});})();
511
+ `,document.head.appendChild(r)}let i=A({container:t,mountTarget:n});i.getStore().subscribe(r=>{r.type==="sidebar-toggled"&&document.documentElement.setAttribute("data-annotation-sidebar",r.open?"open":"")}),i.getStore().getState().isSidebarOpen&&document.documentElement.setAttribute("data-annotation-sidebar","open"),window.__annotationLayer=i;let a=document.querySelectorAll(".bk-actions");if(a.length>0){let r=document.createElement("div");r.className="action-bar";let l=!1;for(let c of a)if(!c.querySelector('[data-action-row="multi"]')){for(;c.firstChild;)r.appendChild(c.firstChild);c.remove(),l=!0}if(l){let c=document.querySelector("main")||document.querySelector(".content");c&&(c.appendChild(r),c.style.paddingBottom="0")}}});})();
@@ -3540,8 +3540,8 @@ container holding the app. Specify either width or maxWidth, and either height o
3540
3540
  <button class="cp-btn cp-btn--remove" aria-label="Remove selection without comment">Remove</button>
3541
3541
  <button class="cp-btn cp-btn--comment" aria-label="Submit comment">Comment</button>
3542
3542
  </div>
3543
- `,this.textarea=this.el.querySelector(`.cp-textarea`);let n=this.el.querySelector(`.cp-btn--comment`),r=this.el.querySelector(`.cp-btn--remove`),i=this.el.querySelector(`.cp-btn--cancel`);this.backdrop.addEventListener(`click`,()=>this.handleCancel()),n.addEventListener(`click`,()=>this.handleComment()),r.addEventListener(`click`,()=>this.handleRemove()),i.addEventListener(`click`,()=>this.handleCancel()),this.textarea.addEventListener(`keydown`,e=>this.handleKeyDown(e)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener(`keydown`,e=>{if(e.key!==`Tab`)return;let t=this.el.querySelectorAll(`button, textarea, [tabindex]:not([tabindex="-1"])`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}positionNearSelection(){let e=this.result.range.getBoundingClientRect(),t=window.scrollX,n=window.scrollY,r=this.el.offsetWidth||320,i=this.el.offsetHeight||260,a=e.left+t+e.width/2-r/2;a=Math.max(8,a),a=Math.min(a,window.innerWidth+t-r-8);let o=window.innerHeight+n,s=e.bottom+n+8,c;s+i<=o?c=s:(c=e.top+n-i-8,c=Math.max(8,c)),this.el.style.left=`${a}px`,this.el.style.top=`${c}px`}handleComment(){let e=this.textarea.value.trim();this.options.onSubmit(this.result,e)}handleRemove(){let e=this.textarea.value.trim();this.options.onRemove(this.result,e)}handleCancel(){this.options.onDismiss()}handleKeyDown(e){e.key===`Escape`?(e.preventDefault(),this.handleCancel()):(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),this.handleComment())}},dw=class{store;constructor(e){this.store=e}exportMarkdown(){let e=[...this.store.getState().annotations].sort((e,t)=>e.createdAt-t.createdAt);if(e.length===0)return`No feedback provided.`;let t=e.filter(e=>e.type===`COMMENT`),n=e.filter(e=>e.type===`DELETION`),r=[`## Reviewer Feedback`,``];if(t.length>0){r.push(`### Comments`,``);for(let e of t){let t=e.originalText.length>80?`${e.originalText.slice(0,80)}\u2026`:e.originalText;r.push(`- **${e.comment}**`),r.push(` > "${t}"`),r.push(``)}}if(n.length>0){r.push(`### Deletions`,``);for(let e of n){let t=e.originalText.length>80?`${e.originalText.slice(0,80)}\u2026`:e.originalText;r.push(`- Remove this`),r.push(` > "${t}"`),r.push(``)}}return r.join(`
3544
- `).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((e,t)=>e.createdAt-t.createdAt);return JSON.stringify(e,null,2)}submitFeedback(e){let t=this.exportMarkdown(),n=this.exportJSON();e(`annotations`,t===`No feedback provided.`?t:`${t}\n\n\`\`\`json\n${n}\n\`\`\``)}getTotalCount(){let e=this.store.getState();return{comments:e.annotations.filter(e=>e.type===`COMMENT`).length,deletions:e.annotations.filter(e=>e.type===`DELETION`).length,total:e.annotations.length}}},fw=`aikit-annotation-highlight`;function pw(){if(document.getElementById(fw))return;let e=document.createElement(`style`);e.id=fw,e.textContent=`
3543
+ `,this.textarea=this.el.querySelector(`.cp-textarea`);let n=this.el.querySelector(`.cp-btn--comment`),r=this.el.querySelector(`.cp-btn--remove`),i=this.el.querySelector(`.cp-btn--cancel`);this.backdrop.addEventListener(`click`,()=>this.handleCancel()),n.addEventListener(`click`,()=>this.handleComment()),r.addEventListener(`click`,()=>this.handleRemove()),i.addEventListener(`click`,()=>this.handleCancel()),this.textarea.addEventListener(`keydown`,e=>this.handleKeyDown(e)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener(`keydown`,e=>{if(e.key!==`Tab`)return;let t=this.el.querySelectorAll(`button, textarea, [tabindex]:not([tabindex="-1"])`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}positionNearSelection(){let e=this.result.range.getBoundingClientRect(),t=window.scrollX,n=window.scrollY,r=this.el.offsetWidth||320,i=this.el.offsetHeight||260,a=e.left+t+e.width/2-r/2;a=Math.max(8,a),a=Math.min(a,window.innerWidth+t-r-8);let o=window.innerHeight+n,s=e.bottom+n+8,c;s+i<=o?c=s:(c=e.top+n-i-8,c=Math.max(8,c)),this.el.style.left=`${a}px`,this.el.style.top=`${c}px`}handleComment(){let e=this.textarea.value.trim();this.options.onSubmit(this.result,e)}handleRemove(){let e=this.textarea.value.trim();this.options.onRemove(this.result,e)}handleCancel(){this.options.onDismiss()}handleKeyDown(e){e.key===`Escape`?(e.preventDefault(),this.handleCancel()):(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),this.handleComment())}},dw=class{store;constructor(e){this.store=e}escapeMd(e){return e.replace(/[`*_{}[\]()#+\-.!|~]/g,`\\$&`)}exportMarkdown(){let e=[...this.store.getState().annotations].sort((e,t)=>e.createdAt-t.createdAt);if(e.length===0)return`No feedback provided.`;let t=e.filter(e=>e.type===`COMMENT`),n=e.filter(e=>e.type===`DELETION`),r=e.filter(e=>e.type===`GLOBAL_COMMENT`),i=[`## Reviewer Feedback`,``];if(r.length>0){i.push(`### General Notes`,``);for(let e of r)i.push(`- ${this.escapeMd(e.comment||``)}`),i.push(``)}if(t.length>0){i.push(`### Comments`,``);for(let e of t){let t=e.originalText.length>80?`${e.originalText.slice(0,80)}\u2026`:e.originalText;i.push(`- **${this.escapeMd(e.comment||``)}**`),i.push(` > "${this.escapeMd(t)}"`),i.push(``)}}if(n.length>0){i.push(`### Deletions`,``);for(let e of n){let t=e.originalText.length>80?`${e.originalText.slice(0,80)}\u2026`:e.originalText;i.push(`- Remove this`),i.push(` > "${this.escapeMd(t)}"`),i.push(``)}}return i.join(`
3544
+ `).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((e,t)=>e.createdAt-t.createdAt);return JSON.stringify(e,null,2)}submitFeedback(e){let t=this.exportMarkdown(),n=this.exportJSON();e(`annotations`,t===`No feedback provided.`?t:`${t}\n\n\`\`\`json\n${n}\n\`\`\``)}getTotalCount(){let e=this.store.getState();return{comments:e.annotations.filter(e=>e.type===`COMMENT`).length,deletions:e.annotations.filter(e=>e.type===`DELETION`).length,global:e.annotations.filter(e=>e.type===`GLOBAL_COMMENT`).length,total:e.annotations.length}}},fw=`aikit-annotation-highlight`;function pw(){if(document.getElementById(fw))return;let e=document.createElement(`style`);e.id=fw,e.textContent=`
3545
3545
  mark.hl-COMMENT {
3546
3546
  background: var(--dt-annotation-comment-bg, rgba(88, 166, 255, 0.15));
3547
3547
  border-bottom: 2px solid var(--dt-annotation-comment, #58a6ff);
@@ -3686,6 +3686,9 @@ container holding the app. Specify either width or maxWidth, and either height o
3686
3686
  .as-card--DELETION {
3687
3687
  border-left: 2px solid var(--dt-annotation-deletion, #f85149);
3688
3688
  }
3689
+ .as-card--GLOBAL_COMMENT {
3690
+ border-left: 2px solid var(--dt-accent-fg, #6366f1);
3691
+ }
3689
3692
 
3690
3693
  .as-card:hover {
3691
3694
  background: var(--dt-annotation-hover);
@@ -3699,6 +3702,18 @@ container holding the app. Specify either width or maxWidth, and either height o
3699
3702
  outline: 2px solid var(--dt-annotation-deletion, #f85149);
3700
3703
  outline-offset: -2px;
3701
3704
  }
3705
+ .as-card--GLOBAL_COMMENT.as-card--selected {
3706
+ outline: 2px solid var(--dt-accent-fg, #6366f1);
3707
+ outline-offset: -2px;
3708
+ }
3709
+
3710
+ .as-card-type-badge {
3711
+ display: inline-block;
3712
+ font-size: var(--dt-font-size-xs);
3713
+ font-weight: 600;
3714
+ color: var(--dt-text-tertiary);
3715
+ margin-bottom: 2px;
3716
+ }
3702
3717
 
3703
3718
  .as-card-excerpt {
3704
3719
  font-size: var(--dt-font-size-sm);
@@ -3764,7 +3779,66 @@ container holding the app. Specify either width or maxWidth, and either height o
3764
3779
  font-size: var(--dt-font-size-sm);
3765
3780
  padding: var(--dt-space-6) var(--dt-space-2);
3766
3781
  }
3767
- `,yw=`<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>`,bw=class{el;store;exporter;unsubscribe=null;listEl;modeToggleBtn;constructor(e){this.store=e.store,this.exporter=e.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(e=>{switch(e.type){case`annotation-added`:case`annotation-removed`:case`annotation-updated`:this.renderList(),this.updateHeader();break;case`selection-changed`:this.updateCardSelection(e.id);break;case`sidebar-toggled`:this.updateVisibility();break;case`mode-changed`:this.updateModeToggle();break}}),(e.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle()}destroy(){this.unsubscribe?.(),this.el.remove()}render(){aw(_w,vw);let e=document.createElement(`div`);return e.className=`as-sidebar`,e.setAttribute(`role`,`complementary`),e.setAttribute(`aria-label`,`Annotations`),e.innerHTML=`
3782
+
3783
+ /* ── Global comment footer ── */
3784
+ .as-footer {
3785
+ border-top: 1px solid var(--dt-border-default);
3786
+ padding: var(--dt-space-3);
3787
+ flex-shrink: 0;
3788
+ display: flex;
3789
+ flex-direction: column;
3790
+ gap: var(--dt-space-2);
3791
+ }
3792
+
3793
+ .as-global-input {
3794
+ font: inherit;
3795
+ font-size: var(--dt-font-size-sm);
3796
+ line-height: 1.4;
3797
+ padding: var(--dt-space-2);
3798
+ border: 1px solid var(--dt-border-default);
3799
+ border-radius: var(--dt-radius-md);
3800
+ background: var(--dt-bg-primary);
3801
+ color: var(--dt-text-primary);
3802
+ resize: vertical;
3803
+ min-height: 2.5rem;
3804
+ max-height: 6rem;
3805
+ width: 100%;
3806
+ box-sizing: border-box;
3807
+ outline: none;
3808
+ transition: border-color var(--dt-transition-fast);
3809
+ }
3810
+ .as-global-input:focus {
3811
+ border-color: var(--dt-accent-fg);
3812
+ }
3813
+ .as-global-input::placeholder {
3814
+ color: var(--dt-text-tertiary);
3815
+ }
3816
+
3817
+ .as-global-btn {
3818
+ display: inline-flex;
3819
+ align-items: center;
3820
+ justify-content: center;
3821
+ gap: 4px;
3822
+ padding: var(--dt-space-1) var(--dt-space-3);
3823
+ border: 1px solid var(--dt-accent-fg);
3824
+ border-radius: var(--dt-radius-md);
3825
+ background: var(--dt-accent-emphasis);
3826
+ color: #ffffff;
3827
+ font-size: var(--dt-font-size-sm);
3828
+ font-weight: 600;
3829
+ cursor: pointer;
3830
+ transition: opacity var(--dt-transition-fast);
3831
+ font-family: inherit;
3832
+ align-self: flex-end;
3833
+ }
3834
+ .as-global-btn:hover {
3835
+ opacity: 0.9;
3836
+ }
3837
+ .as-global-btn:disabled {
3838
+ opacity: 0.5;
3839
+ cursor: default;
3840
+ }
3841
+ `,yw=`<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>`,bw=class{el;store;exporter;unsubscribe=null;listEl;modeToggleBtn;globalInput;globalBtn;constructor(e){this.store=e.store,this.exporter=e.exporter,this.el=this.render(),this.listEl=this.el.querySelector(`.as-list`),this.modeToggleBtn=this.el.querySelector(`.as-mode-toggle`),this.globalInput=this.el.querySelector(`.as-global-input`),this.globalBtn=this.el.querySelector(`.as-global-btn`),this.unsubscribe=this.store.subscribe(e=>{switch(e.type){case`annotation-added`:case`annotation-removed`:case`annotation-updated`:this.renderList(),this.updateHeader();break;case`selection-changed`:this.updateCardSelection(e.id);break;case`sidebar-toggled`:this.updateVisibility();break;case`mode-changed`:this.updateModeToggle();break}}),this.globalBtn.addEventListener(`click`,e=>{e.stopPropagation(),this.submitGlobalComment()}),this.globalInput.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.submitGlobalComment())}),this.globalInput.addEventListener(`input`,()=>{this.updateGlobalBtnState()}),(e.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle(),this.updateGlobalBtnState()}destroy(){this.unsubscribe?.(),this.el.remove()}submitGlobalComment(){let e=this.globalInput.value.trim();e&&(this.store.addGeneralComment(e),this.globalInput.value=``,this.updateGlobalBtnState())}updateGlobalBtnState(){this.globalBtn.disabled=this.globalInput.value.trim().length===0}render(){aw(_w,vw);let e=document.createElement(`div`);return e.className=`as-sidebar`,e.setAttribute(`role`,`complementary`),e.setAttribute(`aria-label`,`Annotations`),e.innerHTML=`
3768
3842
  <div class="as-header">
3769
3843
  <span class="as-header-title">Annotations</span>
3770
3844
  <span class="as-count-badge" aria-live="polite">${this.exporter.getTotalCount().total}</span>
@@ -3773,12 +3847,21 @@ container holding the app. Specify either width or maxWidth, and either height o
3773
3847
  <button class="as-close-btn" aria-label="Close sidebar">&times;</button>
3774
3848
  </div>
3775
3849
  <div class="as-list" role="list" aria-label="Annotation list"></div>
3776
- `,e.querySelector(`.as-close-btn`).addEventListener(`click`,e=>{e.stopPropagation(),this.store.toggleSidebar(!1)}),e.querySelector(`.as-mode-toggle`).addEventListener(`click`,e=>{e.stopPropagation();let t=this.store.getState().mode===`feedback`?`selection`:`feedback`;this.store.setMode(t)}),e}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML=``,e.length===0){let e=document.createElement(`div`);e.className=`as-empty`,e.textContent=`No annotations yet. Select text in Feedback mode.`,this.listEl.appendChild(e);return}let t=[...e].sort((e,t)=>t.createdAt-e.createdAt);for(let e of t)this.listEl.appendChild(this.renderAnnotationItem(e))}renderAnnotationItem(e){let t=document.createElement(`div`);return t.className=`as-card as-card--${e.type}`,t.dataset.annotationId=e.id,this.store.getState().selectedId===e.id&&t.classList.add(`as-card--selected`),t.innerHTML=`
3777
- <div class="as-card-excerpt">${sw(e.originalText.length>60?`${e.originalText.slice(0,60)}\u2026`:e.originalText)}</div>
3778
- ${e.comment?`<div class="as-card-comment">${sw(e.comment)}</div>`:``}
3779
- <div class="as-card-comment-detail">${e.comment?sw(e.comment):`<em style="color:var(--dt-text-tertiary)">No comment — marked text only</em>`}</div>
3780
- <button class="as-delete-btn" aria-label="Delete annotation">&times;</button>
3781
- `,t.addEventListener(`click`,()=>{this.store.select(e.id);let n=t.querySelector(`.as-card-comment-detail`);if(n){n.classList.toggle(`as-card-comment-detail--open`);let e=this.listEl.querySelectorAll(`.as-card-comment-detail--open`);for(let t of e)t!==n&&t.classList.remove(`as-card-comment-detail--open`)}}),t.querySelector(`.as-delete-btn`).addEventListener(`click`,t=>{t.stopPropagation(),this.handleDelete(e.id)}),t}handleDelete(e){this.store.remove(e)}updateVisibility(){let e=this.store.getState();this.el.style.display=e.isSidebarOpen?`flex`:`none`}updateHeader(){let e=this.el.querySelector(`.as-count-badge`);if(e){let t=this.exporter.getTotalCount();e.textContent=String(t.total)}}updateModeToggle(){let e=this.store.getState().mode===`feedback`;this.modeToggleBtn.classList.toggle(`as-mode-toggle--active`,e),this.modeToggleBtn.setAttribute(`aria-pressed`,String(e)),this.modeToggleBtn.setAttribute(`aria-label`,e?`Disable annotation mode`:`Enable annotation mode`)}updateCardSelection(e){let t=this.el.querySelectorAll(`.as-card`);for(let n of t){let t=n.dataset.annotationId;n.classList.toggle(`as-card--selected`,t!==void 0&&t===e)}}},xw=class{annotations=[];selectedId=null;mode=`selection`;isSidebarOpen=!1;subscribers=new Set;idCounter=0;subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notify(e){for(let t of this.subscribers)t(e)}generateId(){return this.idCounter+=1,`ann-${this.idCounter}`}openSidebar(){this.isSidebarOpen=!0,this.notify({type:`sidebar-toggled`,open:!0})}add(e,t,n,r,i,a,o,s,c){let l={id:this.generateId(),type:e,blockId:t,startOffset:n,endOffset:r,originalText:i,comment:a,section:o,contextBefore:s,contextAfter:c,createdAt:Date.now()};return this.annotations.push(l),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:`sidebar-toggled`,open:!0})),this.notify({type:`annotation-added`,annotation:l}),l}update(e,t){let n=this.annotations.find(t=>t.id===e);n&&(Object.assign(n,t),this.notify({type:`annotation-updated`,id:e,changes:t}))}remove(e){let t=this.annotations.findIndex(t=>t.id===e);t!==-1&&(this.annotations.splice(t,1),this.notify({type:`annotation-removed`,id:e}))}select(e){this.selectedId=e,this.notify({type:`selection-changed`,id:e})}setMode(e){e!==this.mode&&(this.mode=e,this.notify({type:`mode-changed`,mode:e}))}toggleSidebar(e){this.isSidebarOpen=e===void 0?!this.isSidebarOpen:e,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}},Sw=25,Cw=`aikit-annotation-guide`,ww=`
3850
+ <div class="as-footer">
3851
+ <textarea class="as-global-input" placeholder="Add general feedback comment..." rows="2" maxlength="5000" aria-label="Add general comment"></textarea>
3852
+ <button class="as-global-btn" disabled>Add Comment</button>
3853
+ </div>
3854
+ `,e.querySelector(`.as-close-btn`).addEventListener(`click`,e=>{e.stopPropagation(),this.store.toggleSidebar(!1)}),e.querySelector(`.as-mode-toggle`).addEventListener(`click`,e=>{e.stopPropagation();let t=this.store.getState().mode===`feedback`?`selection`:`feedback`;this.store.setMode(t)}),e}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML=``,e.length===0){let e=document.createElement(`div`);e.className=`as-empty`,e.textContent=`No annotations yet. Select text in Feedback mode or add a general comment below.`,this.listEl.appendChild(e);return}let t=[...e].sort((e,t)=>t.createdAt-e.createdAt);for(let e of t)this.listEl.appendChild(this.renderAnnotationItem(e))}renderAnnotationItem(e){let t=document.createElement(`div`);return t.className=`as-card as-card--${e.type}`,t.dataset.annotationId=e.id,this.store.getState().selectedId===e.id&&t.classList.add(`as-card--selected`),e.type===`GLOBAL_COMMENT`?t.innerHTML=`
3855
+ <div class="as-card-type-badge">General Comment</div>
3856
+ <div class="as-card-comment">${sw(e.comment||``)}</div>
3857
+ <div class="as-card-comment-detail">${sw(e.comment||``)}</div>
3858
+ <button class="as-delete-btn" aria-label="Delete annotation">&times;</button>
3859
+ `:t.innerHTML=`
3860
+ <div class="as-card-excerpt">${sw(e.originalText.length>60?`${e.originalText.slice(0,60)}\u2026`:e.originalText)}</div>
3861
+ ${e.comment?`<div class="as-card-comment">${sw(e.comment)}</div>`:``}
3862
+ <div class="as-card-comment-detail">${e.comment?sw(e.comment):`<em style="color:var(--dt-text-tertiary)">No comment — marked text only</em>`}</div>
3863
+ <button class="as-delete-btn" aria-label="Delete annotation">&times;</button>
3864
+ `,t.addEventListener(`click`,()=>{this.store.select(e.id);let n=t.querySelector(`.as-card-comment-detail`);if(n){n.classList.toggle(`as-card-comment-detail--open`);let e=this.listEl.querySelectorAll(`.as-card-comment-detail--open`);for(let t of e)t!==n&&t.classList.remove(`as-card-comment-detail--open`)}}),t.querySelector(`.as-delete-btn`).addEventListener(`click`,t=>{t.stopPropagation(),this.handleDelete(e.id)}),t}handleDelete(e){this.store.remove(e)}updateVisibility(){let e=this.store.getState();this.el.style.display=e.isSidebarOpen?`flex`:`none`}updateHeader(){let e=this.el.querySelector(`.as-count-badge`);if(e){let t=this.exporter.getTotalCount();e.textContent=String(t.total)}}updateModeToggle(){let e=this.store.getState().mode===`feedback`;this.modeToggleBtn.classList.toggle(`as-mode-toggle--active`,e),this.modeToggleBtn.setAttribute(`aria-pressed`,String(e)),this.modeToggleBtn.setAttribute(`aria-label`,e?`Disable annotation mode`:`Enable annotation mode`)}updateCardSelection(e){let t=this.el.querySelectorAll(`.as-card`);for(let n of t){let t=n.dataset.annotationId;n.classList.toggle(`as-card--selected`,t!==void 0&&t===e)}}},xw=class{annotations=[];selectedId=null;mode=`selection`;isSidebarOpen=!1;subscribers=new Set;idCounter=0;subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notify(e){for(let t of this.subscribers)t(e)}generateId(){return this.idCounter+=1,`ann-${this.idCounter}`}openSidebar(){this.isSidebarOpen=!0,this.notify({type:`sidebar-toggled`,open:!0})}add(e,t,n,r,i,a,o,s,c){let l={id:this.generateId(),type:e,blockId:t,startOffset:n,endOffset:r,originalText:i,comment:a,section:o,contextBefore:s,contextAfter:c,createdAt:Date.now()};return this.annotations.push(l),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:`sidebar-toggled`,open:!0})),this.notify({type:`annotation-added`,annotation:l}),l}addGeneralComment(e){let t={id:this.generateId(),type:`GLOBAL_COMMENT`,blockId:``,startOffset:0,endOffset:0,originalText:``,comment:e,createdAt:Date.now()};return this.annotations.push(t),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:`sidebar-toggled`,open:!0})),this.notify({type:`annotation-added`,annotation:t}),t}update(e,t){let n=this.annotations.find(t=>t.id===e);n&&(Object.assign(n,t),this.notify({type:`annotation-updated`,id:e,changes:t}))}remove(e){let t=this.annotations.findIndex(t=>t.id===e);t!==-1&&(this.annotations.splice(t,1),this.notify({type:`annotation-removed`,id:e}))}select(e){this.selectedId=e,this.notify({type:`selection-changed`,id:e})}setMode(e){e!==this.mode&&(this.mode=e,this.notify({type:`mode-changed`,mode:e}))}toggleSidebar(e){this.isSidebarOpen=e===void 0?!this.isSidebarOpen:e,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}},Sw=25,Cw=`aikit-annotation-guide`,ww=`
3782
3865
  .as-guide {
3783
3866
  margin: 0 0 var(--dt-space-3) 0;
3784
3867
  padding: var(--dt-space-2) var(--dt-space-3);
@@ -5,4 +5,4 @@ import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as
5
5
  `).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){z.error(`Failed to upsert curated batch`,{batchSize:e.length,...o(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return z.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...o(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;z.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...o(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!b(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;x(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!b(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;S([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>C(e)).join(`/`);return t.split(`/`).every(e=>y.test(e))?`${R}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
6
6
  `).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,i){if(r.instance().isDegraded(`embedder`)){z.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:i,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){z.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:i,...o(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||l(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>L)throw Error(`Content exceeds maximum size of ${L/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}normalizeTags(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}sameTags(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}ensureCategoryPath(e,t){if(!e.startsWith(`${t}/`))throw Error(`Curated path "${e}" must stay within category "${t}"`)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return v(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
7
7
  `)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
8
- `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};const V=i(`server`);function H(e,t){return t?{version:e,...o(t)}:{version:e}}function U(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function W(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function G(){return W()?n({allowPositionals:!0,options:{transport:{type:`string`,default:U()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:U(),port:process.env.AIKIT_PORT??`3210`}}async function K(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=w(),n=G();if(process.on(`unhandledRejection`,e=>{V.error(`Unhandled rejection`,H(t,e))}),process.on(`uncaughtException`,e=>{V.error(`Uncaught exception — exiting`,H(t,e)),process.exit(1)}),V.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-CzScS-EZ.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-DmsOjBSR.js`);await e(t)}}K();export{T as a,k as i,I as n,E as o,F as r,O as s,B as t};
8
+ `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};const V=i(`server`);function H(e,t){return t?{version:e,...o(t)}:{version:e}}function U(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function W(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function G(){return W()?n({allowPositionals:!0,options:{transport:{type:`string`,default:U()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:U(),port:process.env.AIKIT_PORT??`3210`}}async function K(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=w(),n=G();if(process.on(`unhandledRejection`,e=>{V.error(`Unhandled rejection`,H(t,e))}),process.on(`uncaughtException`,e=>{V.error(`Uncaught exception — exiting`,H(t,e)),process.exit(1)}),V.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-BGcKUn5y.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-C66e05P_.js`);await e(t)}}K();export{T as a,k as i,I as n,E as o,F as r,O as s,B as t};
@@ -351,4 +351,4 @@ svg text{fill:var(--body);font-family:var(--sans);font-size:12px}
351
351
  <\/script>
352
352
  </body>
353
353
  </html>`}const U=`<!-- DIAGRAM:SVG -->`;function W(e){let t=e.indexOf(U);if(t===-1)return null;let n=t+20,r=e.indexOf(U,n);if(r===-1)return null;let i=e.slice(n,r).trim();if(i.startsWith(`<svg`))return i;let a=e.slice(Math.max(0,t),r+20),o=a.match(/viewBox="([^"]+)"/),s=o?o[1]:`0 0 1200 800`,c=a.match(/width="(\d+)"/),l=c?c[1]:`1200`,u=a.match(/height="(\d+)"/);return[`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${s}" width="${l}" height="${u?u[1]:`800`}">`,` <defs>`,` <style>`,` text { font-family: system-ui, -apple-system, sans-serif; }`,` .title { font-size: 20px; font-weight: 600; fill: #fff; }`,` .subtitle { font-size: 14px; fill: #94a3b8; }`,` </style>`,` </defs>`,i,`</svg>`].join(`
354
- `)}function he(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function ge(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=he(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=W(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const G=10*1024*1024,K=2e3;function _e(e){try{return JSON.stringify(e)}catch{return``}}function ve(e){switch(e.diagram_type){case`architecture`:return ae(e);case`workflow`:return H(e);case`sequence`:return R(e);case`dataflow`:return ce(e);case`lifecycle`:return P(e)}}function q(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s,detailData:c}=ve(e),l=c&&Object.keys(c).length>0?`\n<script id="diagram-node-data" type="application/json">${_e(c)}<\/script>`:``,u=e.meta?.palette===`warm`?`warm`:`technical`;return{html:me().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,u===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s).replace(`</body>`,`${l}\n</body>`),markdown:a?_(e):void 0}}function ye(e,t={}){return q(e,{...t,dualOutput:!1}).html}function be(e){return _(e)}function xe(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>G)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${G/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>K)throw Error(`Too many edges/connections: ${a.length} (max ${K})`)}function Se(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ce(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function we(){return Ce()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function Te(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=we();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-B3dZd6bx.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-COkJ2pX9.js`);await e(n)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,ge as exportDiagram,W as extractSvg,n as getSessionIdHeader,Te as main,r as readPositiveIntEnv,t as readVersion,ye as renderHtml,be as renderMd,q as renderToResult,e as resolveCorsOrigin,Se as sanitizeTitle,o as selectWorkspaceRoot,xe as validate};
354
+ `)}function he(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function ge(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=he(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=W(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const G=10*1024*1024,K=2e3;function _e(e){try{return JSON.stringify(e)}catch{return``}}function ve(e){switch(e.diagram_type){case`architecture`:return ae(e);case`workflow`:return H(e);case`sequence`:return R(e);case`dataflow`:return ce(e);case`lifecycle`:return P(e)}}function q(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s,detailData:c}=ve(e),l=c&&Object.keys(c).length>0?`\n<script id="diagram-node-data" type="application/json">${_e(c)}<\/script>`:``,u=e.meta?.palette===`warm`?`warm`:`technical`;return{html:me().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,u===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s).replace(`</body>`,`${l}\n</body>`),markdown:a?_(e):void 0}}function ye(e,t={}){return q(e,{...t,dualOutput:!1}).html}function be(e){return _(e)}function xe(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>G)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${G/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>K)throw Error(`Too many edges/connections: ${a.length} (max ${K})`)}function Se(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ce(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function we(){return Ce()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function Te(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=we();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-Cx4tvbmK.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-BmGuXkkF.js`);await e(n)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,ge as exportDiagram,W as extractSvg,n as getSessionIdHeader,Te as main,r as readPositiveIntEnv,t as readVersion,ye as renderHtml,be as renderMd,q as renderToResult,e as resolveCorsOrigin,Se as sanitizeTitle,o as selectWorkspaceRoot,xe as validate};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{n as e,t}from"./server-DUWF6mtP.js";export{t as buildPreludeInjection,e as generatePrelude};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./server-Bsceh-AT.js";export{t as buildPreludeInjection,e as generatePrelude};
@@ -0,0 +1 @@
1
+ import{r as e}from"./server-Bsceh-AT.js";export{e as createSamplingClient};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{r as e}from"./server-DUWF6mtP.js";export{e as createSamplingClient};