@vpxa/aikit 0.1.358 → 0.1.360
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.
- package/package.json +1 -1
- package/packages/analyzers/dist/index.d.ts +1 -1
- package/packages/cli/dist/index.js +19 -19
- package/packages/cli/dist/init-C_WzeMTD.js +7 -0
- package/packages/cli/dist/{templates-Bu7dZtk_.js → templates-DUUaYk_d.js} +13 -12
- package/packages/core/dist/index.d.ts +43 -2
- package/packages/core/dist/index.js +1 -1
- package/packages/present/dist/annotation-layer.js +10 -10
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/observations-CfglxBMB.js +6 -0
- package/packages/server/dist/observations-CrQU_HVm.js +5 -0
- package/packages/server/dist/prelude-CNOjd5qt.js +2 -0
- package/packages/server/dist/prelude-Dki25eYn.js +1 -0
- package/packages/server/dist/sampling-B8NwOv_z.js +1 -0
- package/packages/server/dist/sampling-DOOgTH1B.js +2 -0
- package/packages/server/dist/{server-D5eu57oU.js → server-C2n9kQMF.js} +178 -183
- package/packages/server/dist/{server-D7gZ4K_H.js → server-CizTllz1.js} +178 -183
- package/packages/server/dist/{server-http-AarbD3gm.js → server-http-BaMUtb5Y.js} +1 -1
- package/packages/server/dist/{server-http-wnYmWFkC.js → server-http-Dd2uCMBi.js} +1 -1
- package/packages/server/dist/{server-stdio-BWoMqXU8.js → server-stdio-B5rk-PAI.js} +1 -1
- package/packages/server/dist/{server-stdio-CBGO6XiO.js → server-stdio-CtR4QNT3.js} +1 -1
- package/packages/tools/dist/index.js +69 -69
- package/scaffold/AUTOMATION-BOUNDARY-ANALYSIS.md +78 -0
- package/scaffold/dist/adapters/_shared.mjs +7 -6
- package/scaffold/dist/adapters/claude-code.mjs +7 -7
- package/scaffold/dist/adapters/claude-desktop.mjs +7 -0
- package/scaffold/dist/adapters/gemini.mjs +6 -6
- package/scaffold/dist/adapters/hermes.mjs +5 -5
- package/scaffold/dist/adapters/hooks.mjs +1 -1
- package/scaffold/dist/adapters/opencode.mjs +7 -7
- package/scaffold/dist/definitions/exec-hooks.mjs +1 -1
- package/scaffold/dist/definitions/platform-capabilities.mjs +1 -0
- package/scaffold/dist/definitions/protocols.mjs +7 -6
- package/scaffold/dist/definitions/skills/aikit.mjs +4 -4
- package/scaffold/general/hooks/scripts/_runtime.mjs +87 -15
- package/scaffold/general/hooks/scripts/freshness-signal.mjs +196 -0
- package/scaffold/general/hooks/scripts/privacy-guard.mjs +19 -6
- package/scaffold/general/hooks/scripts/scope-guard.mjs +160 -0
- package/scaffold/general/hooks/scripts/scout-guard.mjs +18 -14
- package/packages/cli/dist/init-CWLiK7bC.js +0 -7
- package/packages/server/dist/prelude-DetbWo8R.js +0 -1
- package/packages/server/dist/prelude-hfAEi93R.js +0 -2
- package/packages/server/dist/sampling-CWjnUevo.js +0 -2
- package/packages/server/dist/sampling-CnE3owSt.js +0 -1
- package/scaffold/general/hooks/scripts/post-edit-check.mjs +0 -36
- package/scaffold/general/hooks/scripts/pre-compact-save.mjs +0 -13
- package/scaffold/general/hooks/scripts/session-init.mjs +0 -85
- package/scaffold/general/hooks/scripts/session-learn.mjs +0 -53
- package/scaffold/general/hooks/scripts/session-observer.mjs +0 -77
- package/scaffold/general/hooks/scripts/subagent-context.mjs +0 -59
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BNPHP-QC.js";import{_ as o,a as s,c,i as l,n as u,o as d,r as f,t as p}from"./templates-DUUaYk_d.js";import{appendFileSync as m,existsSync as h,mkdirSync as g,readFileSync as _,unlinkSync as v,writeFileSync as y}from"node:fs";import{basename as b,dirname as x,resolve as S}from"node:path";import{homedir as C}from"node:os";import{AIKIT_PATHS as w,EMBEDDING_DEFAULTS as T,isUserInstalled as E}from"../../core/dist/index.js";function D(e){return h(S(e,`.cursor`))?`cursor`:h(S(e,`.claude`))?`claude-code`:h(S(e,`.windsurf`))?`windsurf`:h(S(e,`.zed`))?`zed`:h(S(e,`.idea`))?`intellij`:h(S(e,`.opencode`))?`opencode`:h(S(e,`AGENTS.md`))?`hermes`:`copilot`}function O(e){let t=[];return h(S(e,`.cursor`))&&t.push(`cursor`),(h(S(e,`.claude`))||h(S(e,`CLAUDE.md`)))&&t.push(`claude-code`),h(S(e,`.windsurf`))&&t.push(`windsurf`),h(S(e,`.zed`))&&t.push(`zed`),h(S(e,`.idea`))&&t.push(`intellij`),h(S(e,`.gemini`))&&t.push(`gemini-cli`),(h(S(e,`.codex`))||h(S(e,`codex.md`)))&&t.push(`codex-cli`),(h(S(e,`.opencode`))||h(S(e,`OPENCODE.md`)))&&t.push(`opencode`),t.push(`copilot`),t.push(`hermes`),[...new Set(t)]}function k(e){return{servers:{[e]:{...l}}}}function A(e){let{type:t,...n}=l;return{mcpServers:{[e]:n}}}function j(e){let{type:t,...n}=l;return{context_servers:{[e]:{...n}}}}function M(e){let{type:t,...n}=l;return{mcp:{[e]:{type:`local`,command:[n.command,...n.args]}}}}const N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.vscode`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=S(e,`.github`),r=S(n,`copilot-instructions.md`);g(n,{recursive:!0}),y(r,u(b(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){y(S(e,`AGENTS.md`),p(b(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},P=`Orchestrator`;function F(e){let{command:t,args:n}=l;return{[e]:{command:t,args:[...n],type:`stdio`,env:{}}}}function I(e,t){let n=t??S(C(),`.claude`),r=S(n,`settings.json`),i=S(n,`..`,`.claude.json`),a=F(e),o;if(!h(i))o={};else try{o=JSON.parse(_(i,`utf-8`))}catch{console.warn(` ⚠ ${i} invalid JSON — overwriting`),o={}}g(x(i),{recursive:!0}),o.mcpServers={...o.mcpServers||{},...a},y(i,`${JSON.stringify(o,null,2)}\n`,`utf-8`),console.log(` Updated ${i} — ${e} MCP server`);let s;if(!h(r))g(n,{recursive:!0}),s={agent:P};else{try{s=JSON.parse(_(r,`utf-8`))}catch{console.warn(` ⚠ ${r} invalid JSON — overwriting`),s={}}delete s.mcpServers}s.agent=P;let l=S(n,`hooks`,`scripts`).replace(/\\/g,`/`);try{let e=c(`claude`,l);e.hooks&&Object.keys(e.hooks).length>0&&(s.hooks=e.hooks)}catch{console.warn(` ⚠ Failed to generate hooks block`)}y(r,`${JSON.stringify(s,null,2)}\n`,`utf-8`),console.log(` Updated ${r} — default agent + hooks`)}const L={scaffoldDir:`general`,writeMcpConfig(e,t){I(t);let n=S(e,`.mcp.json`);h(n)||(y(n,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=S(e,`CLAUDE.md`),r=b(e);y(n,`${u(r,t)}\n---\n\n${p(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},R={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.cursor`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=S(e,`.cursor`,`rules`),r=S(n,`aikit.mdc`);g(n,{recursive:!0});let i=b(e);y(r,`${u(i,t)}\n---\n\n${p(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=S(n,`kb.mdc`);h(a)&&a!==r&&(v(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},z={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.vscode`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=S(e,`.windsurfrules`),r=b(e);y(n,`${u(r,t)}\n---\n\n${p(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},B={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.zed`),r=S(n,`settings.json`);if(g(n,{recursive:!0}),!h(r))y(r,`${JSON.stringify(j(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(_(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...j(t).context_servers},y(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=S(e,`.rules`),r=b(e);y(n,`${u(r,t)}\n---\n\n${p(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},V={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`mcp.json`);h(n)||(y(n,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=S(e,`.aiassistant`,`rules`),r=S(n,`aikit.md`);g(n,{recursive:!0});let i=b(e);y(r,`${u(i,t)}\n---\n\n${p(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}},H={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.opencode`),r=S(n,`opencode.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(M(t),null,2)}\n`,`utf-8`),console.log(` Created .opencode/opencode.json`))},writeInstructions(e,t){let n=S(e,`OPENCODE.md`),r=b(e);y(n,`${u(r,t)}\n---\n\n${p(r,t)}`,`utf-8`),console.log(` Updated OPENCODE.md`)},writeAgentsMd(e,t){}},U={scaffoldDir:`general`,writeMcpConfig(e,t){},writeInstructions(e,t){let n=S(e,`AGENTS.md`),r=b(e);y(n,`${u(r,t)}\n---\n\n${p(r,t)}`,`utf-8`),console.log(` Updated AGENTS.md (Hermes)`)},writeAgentsMd(e,t){}};function W(e){switch(e){case`copilot`:return N;case`claude-code`:return L;case`cursor`:return R;case`windsurf`:return z;case`zed`:return B;case`intellij`:return V;case`opencode`:return H;case`hermes`:return U;case`gemini-cli`:case`codex-cli`:return N}}const G={serverName:s,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${w.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:T.model,dimensions:T.dimensions},store:{backend:`sqlite-vec`,path:w.data},curated:{path:w.aiCurated}};function K(e,t){let n=S(e,`aikit.config.json`);return h(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(y(n,`${JSON.stringify(G,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function q(e){let t=S(e,`.gitignore`),n=[{dir:`.flows/`,label:`AI Kit flow runs`}];if(h(t)){let e=_(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(m(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
|
|
2
|
+
`)}\n`,`utf-8`),console.log(` Added ${r.map(e=>e.dir).join(`, `)} to .gitignore`))}else y(t,`${n.map(e=>`# ${e.label}\n${e.dir}`).join(`
|
|
3
|
+
`)}\n`,`utf-8`),console.log(` Created .gitignore with AI Kit entries`)}function J(){return G.serverName}const Y=[`decisions`,`patterns`,`conventions`,`troubleshooting`];function X(e){let t=S(e,`.ai`,`curated`);h(t)||(g(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of Y){let n=S(t,e);h(n)||g(n,{recursive:!0})}console.log(` Created .ai/curated/{${Y.join(`,`)}}/`)}function Z(e){switch(e){case`zed`:return`zed`;case`intellij`:return`intellij`;case`claude-code`:return`claude-code`;case`gemini-cli`:return`gemini`;case`codex-cli`:return`codex`;case`opencode`:return`opencode`;case`hermes`:return`hermes`;default:return`copilot`}}async function Q(n){let i=process.cwd();if(S(i)===S(C())){console.log(` Skipping workspace init: cannot scaffold the home directory.`),console.log(" Use `aikit init` (without --workspace) for user-level setup.");return}if(!K(i,n.force))return;q(i);let a=J(),s=W(D(i));s.writeMcpConfig(i,a),s.writeInstructions(i,a),s.writeAgentsMd(i,a);let c=o(),l=JSON.parse(_(S(c,`package.json`),`utf-8`)).version;await t(i,c,[...d],l,n.force),await r(i,c,[...f],l,n.force);let u=O(i),p=new Set;for(let t of u){let r=Z(t);p.has(r)||(p.add(r),await e(i,c,r,l,n.force))}X(i),console.log(`
|
|
4
|
+
AI Kit initialized! Next steps:`),console.log(` aikit reindex Index your codebase`),console.log(` aikit search Search indexed content`),console.log(` aikit serve Start MCP server for IDE integration`),E()&&console.log(`
|
|
5
|
+
Note: User-level AI Kit is also installed. This workspace uses its own local data store.`)}async function ee(e){E()?await $(e):await Q(e)}async function $(t){let n=process.cwd();if(S(n)===S(C())){console.log(` Skipping workspace scaffold: cannot scaffold the home directory.`);return}let i=J(),a=W(D(n));a.writeInstructions(n,i),a.writeAgentsMd(n,i);let s=o(),c=JSON.parse(_(S(s,`package.json`),`utf-8`)).version,l=O(n),u=new Set;for(let r of l){let i=Z(r);u.has(i)||(u.add(i),await e(n,s,i,c,t.force))}await r(n,s,[...f],c,t.force),X(n),q(n),console.log(`
|
|
6
|
+
Workspace scaffolded for user-level AI Kit! Files added:`),console.log(` Instruction files (AGENTS.md, copilot-instructions.md, etc.)`),console.log(` .ai/curated/ directories`),console.log(` .github/agents/ & .github/prompts/`),console.log(`
|
|
7
|
+
The user-level AI Kit server will auto-index this workspace when opened in your IDE.`)}async function te(){let e=process.cwd(),t=O(e),r=o(),s=[...await i(e,r,[...d])],c=new Set;for(let i of t){let t=Z(i);c.has(t)||(c.add(t),s.push(...await n(e,r,t)))}s.push(...await a(e,r,[...f]));let l={summary:{total:s.length,new:s.filter(e=>e.status===`new`).length,outdated:s.filter(e=>e.status===`outdated`).length,current:s.filter(e=>e.status===`current`).length},files:s};console.log(JSON.stringify(l,null,2))}export{te as guideProject,Q as initProject,$ as initScaffoldOnly,ee as initSmart};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{resolveStateDir as a,safeCwdOrHome as
|
|
2
|
-
`))console.log(` ${e}`)}}function
|
|
1
|
+
import{createRequire as e}from"node:module";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{resolveStateDir as a,safeCwdOrHome as o}from"../../core/dist/index.js";import{createSqliteAdapter as s,createStateStore as c}from"../../store/dist/index.js";import{mkdir as l}from"node:fs/promises";var u=class extends Error{exitCode;constructor(e,t=1){super(e),this.exitCode=t,this.name=`CliError`}};function d(e){let t=e.indexOf(`--json`);return t===-1?!1:(e.splice(t,1),!0)}function f(e){let t=new WeakSet;console.log(JSON.stringify(e,(e,n)=>{if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return typeof n==`bigint`?String(n):n},2))}async function p(e=o()){let t=a(r(e));return await l(t,{recursive:!0}),c(await s(r(t,`state.db`)))}function m(){let t=e(import.meta.url);try{return t.resolve(`@vpxa/aikit/package.json`)}catch{return r(i(import.meta.url),`..`,`..`,`..`,`..`,`package.json`)}}function h(){return n(m())}function g(){try{return JSON.parse(t(m(),`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function ee(){let t=e(import.meta.url);try{return r(n(t.resolve(`@aikit/server`)),`bin.js`)}catch{return r(h(),`packages`,`server`,`dist`,`bin.js`)}}function te(e){let t=`--disable-warning=ExperimentalWarning`;return e?e.includes(`ExperimentalWarning`)?e:`${e} ${t}`:t}function ne(e,t,n){let r=e.indexOf(t);if(r===-1||r+1>=e.length)return n;let i=Number.parseInt(e.splice(r,2)[1],10);return Number.isNaN(i)?n:i}function re(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function ie(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function ae(){if(process.stdin.isTTY)return``;let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`)}function oe(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function se(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function _(e){switch(e.tool){case`tsc`:case`biome`:console.log(`${e.tool} errors: ${e.errors.length}`);for(let t of e.errors){let e=[t.line,t.column].filter(e=>e!==void 0).join(`:`),n=e?`${t.file}:${e}`:t.file,r=t.code?` ${t.code}`:``;console.log(`- ${n} [${t.severity}${r}] ${t.message}`)}return;case`vitest`:console.log(`Vitest summary`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.duration!==void 0&&console.log(` Duration: ${e.summary.duration}ms`);for(let t of e.summary.tests)t.status===`fail`&&(console.log(`- ${t.name}${t.file?` (${t.file})`:``}`),t.error&&console.log(` ${t.error}`));return;case`git-status`:console.log(`Branch: ${e.status.branch??`unknown`}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` ${t.status} ${t.file}`);console.log(`Unstaged: ${e.status.unstaged.length}`);for(let t of e.status.unstaged)console.log(` ${t.status} ${t.file}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` ?? ${t}`);return}}function v(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),y(`tsc`,e.tsc.passed,e.tsc.errors),y(`biome`,e.biome.passed,e.biome.errors)}function y(e,t,n){console.log(`${e}: ${t?`passed`:`${n.length} issue(s)`}`);for(let e of n){let t=[e.line,e.column].filter(e=>e!==void 0).join(`:`),n=t?`${e.file}:${t}`:e.file,r=e.code?` ${e.code}`:``;console.log(` - ${n} [${e.severity}${r}] ${e.message}`)}}function b(e){console.log(`Vitest: ${e.passed?`passed`:`failed`}`),console.log(` Duration: ${e.durationMs}ms`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.suites!==void 0&&console.log(` Suites: ${e.summary.suites}`);let t=e.summary.tests.filter(e=>e.status===`fail`);if(t.length!==0){console.log(`Failed tests:`);for(let e of t)console.log(` - ${e.name}${e.file?` (${e.file})`:``}`),e.error&&console.log(` ${e.error}`)}}function x(e){console.log(`Branch: ${e.branch}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` - ${t}`);console.log(`Modified: ${e.status.modified.length}`);for(let t of e.status.modified)console.log(` - ${t}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` - ${t}`);if(console.log(``),console.log(`Recent commits:`),e.recentCommits.length===0)console.log(` none`);else for(let t of e.recentCommits)console.log(` - ${t.hash} ${t.message}`),console.log(` ${t.author} @ ${t.date}`);e.diff&&(console.log(``),console.log(`Diff stat:`),console.log(e.diff))}function S(e){if(e.length===0){console.log(`No diff files found.`);return}for(let t of e){let e=t.oldPath?` (from ${t.oldPath})`:``;console.log(`${t.path}${e}`),console.log(` Status: ${t.status}`),console.log(` Changes: +${t.additions} -${t.deletions}`),console.log(` Hunks: ${t.hunks.length}`);for(let e of t.hunks){let t=e.header?` ${e.header}`:``;console.log(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${t}`)}}}function C(e){if(console.log(`Start: ${e.start}`),console.log(`Direction: ${e.direction}`),console.log(`Depth reached: ${e.depth}`),console.log(`Nodes: ${e.nodes.length}`),e.nodes.length===0){console.log(`No trace nodes found.`);return}for(let t of e.nodes)console.log(` - [${t.relationship}] ${t.path}:${t.line} ${t.symbol}`)}function w(e){if(console.log(`Query: ${e.query}`),console.log(`Examples: ${e.examples.length} shown (${e.totalFound} total)`),e.examples.length===0){console.log(`No matching examples found.`);return}for(let t of e.examples){console.log(``),console.log(`${t.path}:${t.startLine}-${t.endLine}`),console.log(` Context: ${t.context}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}%`);for(let e of t.content.split(`
|
|
2
|
+
`))console.log(` ${e}`)}}function T(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(` `)}`:``}`),console.log(` PID: ${e.pid??`unknown`}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function E(e){if(console.log(`Exports scanned: ${e.totalExports}`),console.log(`Dead in source: ${e.totalDeadSource} (actionable)`),console.log(`Dead in docs: ${e.totalDeadDocs} (informational)`),e.totalDeadSource===0&&e.totalDeadDocs===0){console.log(`No dead symbols found.`);return}if(e.deadInSource.length>0){console.log(`
|
|
3
3
|
Dead in source (actionable):`);for(let t of e.deadInSource)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}if(e.deadInDocs.length>0){console.log(`
|
|
4
|
-
Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function
|
|
5
|
-
`))console.log(` ${t}`)}function O(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function k(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function A(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function j(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score)}const M=[`const{spawn:s}=require('child_process')`,`const{existsSync:e,readFileSync:r}=require('fs')`,`const{join:j}=require('path')`,`const{homedir:h}=require('os')`,`const n=process.env.NODE_OPTIONS||'';if(!n.includes('ExperimentalWarning'))process.env.NODE_OPTIONS=n?(n+' --disable-warning=ExperimentalWarning'):'--disable-warning=ExperimentalWarning'`,`const l=(c,a,o={})=>{const p=s(c,a,{stdio:'inherit',env:process.env,...o});p.once('error',q=>{try{process.stderr.write('aikit: failed to start MCP server - '+q.message)}catch{}process.exit(1)});p.once('exit',(q,g)=>process.exit(g==='SIGINT'?130:g==='SIGTERM'?143:(q??1)));for(const g of ['SIGINT','SIGTERM'])process.once(g,()=>{if(!p.killed)p.kill(g)})}`,`const f=j(h(),'.aikit','current-version.json');if(e(f)){try{const{version:g}=JSON.parse(r(f,'utf-8'));const p=j(h(),'.aikit','versions','v'+g,'packages','server','dist','bin.js');if(!e(p))throw Error('Local install not found at '+p);l(process.execPath,[p,'serve'])}catch(c){try{process.stderr.write('aikit: local install failed - '+c.message+'. Run: aikit install')}catch{}process.exit(1)}}else{const c=process.platform==='win32'?'npx.cmd':'npx';l(c,['-y','@vpxa/aikit@latest','serve'],process.platform==='win32'?{shell:true}:{})}`].join(`;`),N=`aikit`,P={type:`stdio`,command:`node`,args:[`-e`,M]},F=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],I=[`aikit-basic`,`aikit-advanced`,`_epilogue`],L={"chat.agentFilesLocations":{"~/.claude/agents":!1},"chat.useClaudeMdFile":!1,"github.copilot.chat.copilotMemory.enabled":!0,"chat.customAgentInSubagent.enabled":!0,"chat.useNestedAgentsMdFiles":!0,"chat.useAgentSkills":!0,"github.copilot.chat.switchAgent.enabled":!0,"workbench.browser.enableChatTools":!0,"chat.mcp.apps.enabled":!0,"chat.instructionsFilesLocations":{"~/.copilot/instructions":!0,".github/instructions":!0,".claude/rules":!1,"~/.claude/rules":!1}},R=[`copilot`,`claude`,`copilotCli`,`hermes`],z={SessionStart:{copilot:`SessionStart`,claude:`SessionStart`,copilotCli:`sessionStart`,hermes:`SessionStart`},PreToolUse:{copilot:`PreToolUse`,claude:`PreToolUse`,copilotCli:`preToolUse`,hermes:`PreToolUse`},PostToolUse:{copilot:`PostToolUse`,claude:`PostToolUse`,copilotCli:`postToolUse`,hermes:`PostToolUse`},SubagentStart:{copilot:`SubagentStart`,claude:`SubagentStart`,copilotCli:`subagentStart`,hermes:`SubagentStart`},PreCompact:{copilot:`PreCompact`,claude:`PreCompact`,copilotCli:`preCompact`,hermes:`PreCompact`},Stop:{copilot:`Stop`,claude:`Stop`,copilotCli:`stop`,hermes:`Stop`}},B={fileRead:{copilot:[`read_file`,`readFile`],claude:[`Read`],copilotCli:[`read_file`],hermes:[`read_file`]},fileWrite:{copilot:[`editFiles`,`replace_string_in_file`,`create_file`],claude:[`Write`,`Edit`],copilotCli:[`editFiles`,`replace_string_in_file`],hermes:[`write_file`,`patch`]},fileSearch:{copilot:[`grep_search`,`semantic_search`,`find`],claude:[`Bash`],copilotCli:[`grep_search`],hermes:[`search_files`]}},V={"privacy-guard":{id:`privacy-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads of secret-bearing env files, key material, SSH paths, and credential artifacts.`,script:`privacy-guard.mjs`,matcher:[`fileRead`],scope:`user`,patterns:[`.env`,`*.pem`,`*.key`,`id_rsa*`,`.ssh/*`,`*credentials*`,`*.secret`]},"scout-guard":{id:`scout-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads and searches inside generated, dependency, and git object directories.`,script:`scout-guard.mjs`,matcher:[`fileRead`,`fileSearch`],scope:`user`,patterns:[`node_modules/`,`dist/`,`.git/objects/`,`vendor/`,`build/`]},"subagent-context":{id:`subagent-context`,event:`SubagentStart`,tier:`efficiency`,description:`Injects compact project context into each subagent spawn to reduce repeated discovery.`,script:`subagent-context.mjs`,scope:`user`},"pre-compact-save":{id:`pre-compact-save`,event:`PreCompact`,tier:`efficiency`,description:`Persists critical state before context compaction truncates recent session history.`,script:`pre-compact-save.mjs`,scope:`user`},"post-edit-check":{id:`post-edit-check`,event:`PostToolUse`,tier:`nudge`,description:`After repeated file edits, injects a validation reminder so checks are not skipped.`,script:`post-edit-check.mjs`,matcher:[`fileWrite`],scope:`user`},"session-init":{id:`session-init`,event:`SessionStart`,tier:`nudge`,description:`Detects project stack and injects workspace metadata and environment context at startup.`,script:`session-init.mjs`,scope:`user`},"session-observer":{id:`session-observer`,event:`PostToolUse`,tier:`efficiency`,description:`Captures tool usage patterns for autonomous lesson extraction. Writes to session buffer.`,script:`session-observer.mjs`,scope:`user`},"session-learn":{id:`session-learn`,event:`Stop`,tier:`efficiency`,description:`Nudges final pattern analysis on buffered observations at session end.`,script:`session-learn.mjs`,scope:`user`}},de={PreCompact:3e3,PostToolUse:3e3},H={copilot:`hooks.json`,copilotCli:`hooks.json`,hermes:`hooks.json`},U=R;function W(e){if(!U.includes(e))throw Error(`Unknown platform: "${e}". Supported: ${U.join(`, `)}. Add it to SUPPORTED_PLATFORMS in exec-hooks.mjs first, then add entries to HOOK_EVENTS and HOOK_TOOL_MATCHERS. Add FILE_NAMES in generateHooks if file-producing.`);for(let[t,n]of Object.entries(z))if(!(e in n))throw Error(`Platform "${e}" is missing from HOOK_EVENTS.${t}. Add a "${e}" key to HOOK_EVENTS.${t} in exec-hooks.mjs.`);for(let[t,n]of Object.entries(B))if(!(e in n))throw Error(`Platform "${e}" is missing from HOOK_TOOL_MATCHERS.${t}. Add a "${e}" key to HOOK_TOOL_MATCHERS.${t} in exec-hooks.mjs.`)}function fe(e,t){return(e.matcher||[]).flatMap(e=>{let n=B[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function G(e,t,n,r){let i=`${n}/${e.script}`;return fe(e,r),r===`copilot`?{event:t,steps:[{type:`command`,command:`node`,args:[i],timeout:de[e.event]||5e3}]}:r===`claude`?{type:`command`,command:`node ${i}`}:{command:`node`,args:[i]}}function pe(e,t){W(e);let n={};for(let r of Object.values(V)){let i=z[r.event]?.[e];if(!i){console.warn(`[aikit] Unsupported hook event ${r.event} for ${e} — skipping`);continue}n[i]||=[],n[i].push(G(r,i,t,e))}return{hooks:n}}function me(e,t){if(W(e),e===`copilot`){let n=Object.values(V).flatMap(n=>{let r=z[n.event]?.[e];return r?G(n,r,t,e):(console.warn(`[aikit] Unsupported hook event ${n.event} for ${e} — skipping`),[])});return[{path:H[e],content:JSON.stringify({hooks:n},null,2)}]}if(e===`claude`)return[];if(!(e in H))throw Error(`Platform "${e}" is missing from FILE_NAMES. Add "${e}: '<filename>'" to FILE_NAMES in adapters/hooks.mjs.`);let n={};for(let r of Object.values(V)){let i=z[r.event]?.[e];if(!i){console.warn(`[aikit] Unsupported hook event ${r.event} for ${e} — skipping`);continue}n[i]||=[],n[i].push(G(r,i,t,e))}return[{path:H[e],content:JSON.stringify({hooks:n},null,2)}]}function he(){return[`_runtime.mjs`,...Object.values(V).map(e=>e.script)]}const ge=[{id:`no-grep-search`,toolName:`grep_search`,description:`grep_search / semantic_search → use search`,alternative:`search({ query })`,reason:`Hybrid search across all indexed + curated content — richer results than grep`,severity:`error`,action:`redirect`},{id:`no-semantic-search`,toolName:`semantic_search`,description:`semantic_search → use search`,alternative:`search({ query })`,reason:`Hybrid search across all indexed + curated content — vector + FTS fusion`,severity:`error`,action:`redirect`},{id:`no-grep-symbol`,toolName:`grep_search`,description:`grep_search for a symbol → use symbol`,alternative:`symbol({ name })`,reason:`Definition + references with scope and call context`,severity:`error`,action:`redirect`,heuristic:`grep_search for a specific symbol name`},{id:`no-read-file-understanding`,toolName:`read_file`,description:`read_file to understand a file → use file_summary`,alternative:`file_summary({ path })`,reason:`Structure, exports, imports — 10x fewer tokens than raw file reads`,severity:`error`,action:`warn`,heuristic:`read_file with range > 50 lines and no subsequent edit`},{id:`no-read-file-find-code`,toolName:`read_file`,description:`read_file to find specific code → use compact`,alternative:`compact({ path, query })`,reason:`Fresh compression: compact({ path, query }); query is required unless ref is supplied`,severity:`error`,action:`warn`,heuristic:`read_file to locate specific code without editing`},{id:`no-read-file-multiple`,toolName:`read_file`,description:`Multiple read_file calls → use digest`,alternative:`digest({ sources, query: "<task description>" })`,reason:`Compresses multiple files into token-budgeted summary`,severity:`error`,action:`warn`,heuristic:`consecutive read_file calls on different files without edits`},{id:`no-read-file-large`,toolName:`read_file`,description:`read_file (>50 lines to understand) → use file_summary → compact → digest`,alternative:`file_summary → compact → digest`,reason:`Use compressed context, not raw reads — 10x fewer tokens`,severity:`warning`,action:`warn`,heuristic:`read_file with endLine - startLine > 50 and no subsequent edit on same file`},{id:`no-ctxc-misuse`,toolName:`compact`,description:`Cached ctxc ref to refocus prior output → use compact with ref`,alternative:`compact({ ref }) or compact({ ref, query? })`,reason:`ctxc_... values are reversible refs, not ids or file paths. Prefer enrich: true on follow-up retrieval`,severity:`error`,action:`warn`,heuristic:`using ctxc_ value as a file path instead of as a ref`},{id:`no-terminal-test`,toolName:`run_in_terminal`,description:`run_in_terminal for tests → use test_run`,alternative:`test_run({})`,reason:`Run tests with structured output — no shell needed`,severity:`error`,action:`redirect`,commandPatterns:[`vitest`,`jest`,`mocha`,`pnpm test`,`npm test`]},{id:`no-terminal-typecheck`,toolName:`run_in_terminal`,description:`run_in_terminal for tsc/lint → use check`,alternative:`check({})`,reason:`Typecheck + lint combined, summary output — no shell needed`,severity:`error`,action:`redirect`,commandPatterns:[`\\btsc\\b`,`pnpm check`,`pnpm typecheck`,`pnpm lint`,`biome`]},{id:`no-terminal-grep`,toolName:`run_in_terminal`,description:`run_in_terminal for find/grep → use find or search`,alternative:`find({ pattern }) or search({ query })`,reason:`No shell needed, richer results with AI Kit search`,severity:`error`,action:`redirect`,commandPatterns:[`\\bgrep\\b`,`\\bfind\\b`,`\\brg\\b`,`Select-String`]},{id:`no-terminal-code-edits`,toolName:`run_in_terminal`,description:`run_in_terminal for code edits → use replace_string_in_file`,alternative:`replace_string_in_file`,reason:`Avoid shell-edit loops; use native edit tool instead`,severity:`error`,action:`redirect`,commandPatterns:[`sed`,`awk`,`Set-Content`,`Out-File`,`>>`,`\\| tee`]},{id:`no-edit-without-reading`,toolName:`replace_string_in_file`,description:`Editing without reading → use file_summary then targeted read_file`,alternative:`file_summary({ path }) → read_file({ path, offset, limit })`,reason:`Safer edits: understand structure before modifying`,severity:`error`,action:`warn`,heuristic:`replace_string_in_file on a file not previously read`},{id:`no-get-changed-files`,toolName:`get_changed_files`,description:`get_changed_files → use run_in_terminal with git diff`,alternative:"run_in_terminal with `git diff <specific-file>`",reason:`Diff only target file instead of all uncommitted diffs (100K+ tokens)`,severity:`error`,action:`redirect`},{id:`no-fetch-webpage`,toolName:`fetch_webpage`,description:`fetch_webpage → use web_fetch`,alternative:`web_fetch({ url })`,reason:`Readability extract + token budget — richer output than raw fetch`,severity:`error`,action:`redirect`},{id:`no-subagent-present`,toolName:`present`,description:`present (from subagent) → return structured text`,alternative:`Return findings as structured text`,reason:`Subagent present calls are invisible to the user (only Orchestrator should present)`,severity:`error`,action:`warn`,heuristic:`present called in subagent context`},{id:`no-apply-patch`,toolName:`apply_patch`,description:`apply_patch → use native edit tool`,alternative:`edit file tool`,reason:`AI Kit does not manage apply_patch; use the host environment edit tool`,severity:`warning`,action:`warn`},{id:`no-memory-native`,toolName:`memory`,description:`memory tool → use knowledge tool`,alternative:`knowledge (remember / search / list)`,reason:`AI Kit knowledge tool provides persistent cross-session memory with categories and tags`,severity:`warning`,action:`warn`}];function _e(e){let t=e.toolName;if(e.commandPatterns&&e.commandPatterns.length>0){let n=e.description.match(/^(.*?)\s*→/);n&&(t=n[1].trim())}else if(e.heuristic){let n=e.description.match(/^(.*?)\s*→/);n&&(t=n[1].trim())}return{id:e.id,forbidden:t,alternative:e.alternative,severity:e.severity,reason:e.reason,matchPattern:e.commandPatterns?null:e.toolName,commandPatterns:e.commandPatterns??null,heuristic:e.heuristic??null}}const ve=ge.map(_e);function ye(){return[`| NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |`,`|---|---|---|`,...ve.filter(e=>e.severity===`error`).map(e=>`| \`${e.forbidden}\` | \`${e.alternative}\` | ${e.reason} |`)].join(`
|
|
4
|
+
Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function D(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),j(`Imports`,e.imports),j(`Exports`,e.exports),j(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),j(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),j(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),j(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function O(e){if(console.log(`Symbol: ${e.name}`),e.definedIn?console.log(`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`):console.log(`Defined in: not found`),console.log(``),console.log(`Imported by:`),e.importedBy.length===0)console.log(` none`);else for(let t of e.importedBy)console.log(` - ${t.path}:${t.line} ${t.importStatement}`);if(console.log(``),console.log(`Referenced in:`),e.referencedIn.length===0)console.log(` none`);else for(let t of e.referencedIn)console.log(` - ${t.path}:${t.line} ${t.context}`)}function k(e){console.log(e.name),console.log(` Files: ${e.files.length}`),console.log(` Updated: ${e.updated}`),e.description&&console.log(` Description: ${e.description}`);for(let t of e.files)console.log(` - ${t}`)}function A(e){let t=Array.isArray(e.data.files)?e.data.files.filter(e=>typeof e==`string`):[];if(console.log(e.id),console.log(` Label: ${e.label}`),console.log(` Created: ${e.createdAt}`),e.notes&&console.log(` Notes: ${e.notes}`),t.length>0){console.log(` Files: ${t.length}`);for(let e of t)console.log(` - ${e}`)}console.log(` Data:`);for(let t of JSON.stringify(e.data,null,2).split(`
|
|
5
|
+
`))console.log(` ${t}`)}function j(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function M(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function N(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function P(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score)}const F=[`copilot`,`claude`,`copilotCli`,`hermes`],I={SessionStart:{copilot:`SessionStart`,claude:`SessionStart`,copilotCli:`sessionStart`,hermes:`SessionStart`},PreToolUse:{copilot:`PreToolUse`,claude:`PreToolUse`,copilotCli:`preToolUse`,hermes:`PreToolUse`},PostToolUse:{copilot:`PostToolUse`,claude:`PostToolUse`,copilotCli:`postToolUse`,hermes:`PostToolUse`},SubagentStart:{copilot:`SubagentStart`,claude:`SubagentStart`,copilotCli:`subagentStart`,hermes:`SubagentStart`},PreCompact:{copilot:`PreCompact`,claude:`PreCompact`,copilotCli:`preCompact`,hermes:`PreCompact`},Stop:{copilot:`Stop`,claude:`Stop`,copilotCli:`stop`,hermes:`Stop`}},L={fileRead:{copilot:[`read_file`,`readFile`],claude:[`Read`],copilotCli:[`read_file`],hermes:[`read_file`]},fileWrite:{copilot:[`editFiles`,`replace_string_in_file`,`create_file`],claude:[`Edit`,`Write`,`MultiEdit`],copilotCli:[`editFiles`,`replace_string_in_file`],hermes:[`write_file`,`patch`]},fileSearch:{copilot:[`grep_search`,`semantic_search`,`find`],claude:[`Bash`],copilotCli:[`grep_search`],hermes:[`search_files`]}},R={"privacy-guard":{id:`privacy-guard`,event:`PreToolUse`,category:`guard`,description:`Deny reads of secret-bearing files: .env, .pem, .key, .ssh/*, credentials, tokens, .netrc.`,llmBenefit:`Prevents accidental leakage of API keys, tokens, and credentials into conversation context.`,script:`privacy-guard.mjs`,matcher:[`fileRead`],outputBudgetLines:0,executionModel:`child-process`,scope:`user`,failurePolicy:`deny-closed`,supportedPlatforms:[`copilot`,`claude`,`copilotCli`,`hermes`],unsupportedBehavior:`Reject via agent instruction — no native hook runtime available`,evidenceRequirements:`Hook script tested against known secret patterns`,rollbackBehavior:`Remove from settings.json hooks block and delete script file`},"scout-guard":{id:`scout-guard`,event:`PreToolUse`,category:`guard`,description:`Deny reads inside generated/dependency directories: node_modules/, dist/, .git/objects/, vendor/, build/.`,llmBenefit:`Keeps context clean by preventing reads of irrelevant generated or vendored files.`,script:`scout-guard.mjs`,matcher:[`fileRead`,`fileSearch`],outputBudgetLines:0,executionModel:`child-process`,scope:`user`,failurePolicy:`deny-closed`,supportedPlatforms:[`copilot`,`claude`,`copilotCli`,`hermes`],unsupportedBehavior:`Reject via agent instruction — no native hook runtime available`,evidenceRequirements:`Hook script tested against known generated directory patterns`,rollbackBehavior:`Remove from settings.json hooks block and delete script file`},"freshness-signal":{id:`freshness-signal`,event:`SessionStart`,category:`signal`,description:`Check workspace state freshness at session start: onboard staleness, active flow, scaffold drift.`,llmBenefit:`Avoids working with stale onboard data or drifting scaffold state.`,script:`freshness-signal.mjs`,outputBudgetLines:5,executionModel:`child-process`,scope:`user`,silentWhenHealthy:!0,failurePolicy:`allow-open`,matcher:[],supportedPlatforms:[`copilot`,`claude`,`copilotCli`,`hermes`],unsupportedBehavior:`Skip — no native hook runtime on this platform`,evidenceRequirements:`None (signal-only, no enforcement)`,rollbackBehavior:`Remove from settings.json hooks block`},"scope-guard":{id:`scope-guard`,event:`PostToolUse`,category:`signal`,description:`After file writes, detect edit drift: files changed outside flow scope, too many files, scaffold source/dist mismatch.`,llmBenefit:`Prevents accidental scope creep, over-editing, and scaffold drift during a session.`,script:`scope-guard.mjs`,matcher:[`fileWrite`],outputBudgetLines:5,executionModel:`child-process`,scope:`user`,silentWhenHealthy:!0,failurePolicy:`allow-open`,supportedPlatforms:[`copilot`,`claude`,`copilotCli`,`hermes`],unsupportedBehavior:`Skip — no native hook runtime on this platform`,evidenceRequirements:`None (signal-only, no enforcement)`,rollbackBehavior:`Remove from settings.json hooks block`}},z={PreCompact:3e3,PostToolUse:3e3},B={copilot:`hooks.json`,copilotCli:`hooks.json`,hermes:`hooks.json`},V=F;function H(e){if(!V.includes(e))throw Error(`Unknown platform: "${e}". Supported: ${V.join(`, `)}. Add it to SUPPORTED_PLATFORMS in exec-hooks.mjs first, then add entries to HOOK_EVENTS and HOOK_TOOL_MATCHERS. Add FILE_NAMES in generateHooks if file-producing.`);for(let[t,n]of Object.entries(I))if(!(e in n))throw Error(`Platform "${e}" is missing from HOOK_EVENTS.${t}. Add a "${e}" key to HOOK_EVENTS.${t} in exec-hooks.mjs.`);for(let[t,n]of Object.entries(L))if(!(e in n))throw Error(`Platform "${e}" is missing from HOOK_TOOL_MATCHERS.${t}. Add a "${e}" key to HOOK_TOOL_MATCHERS.${t} in exec-hooks.mjs.`)}function U(e,t){return(e.matcher||[]).flatMap(e=>{let n=L[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function W(e,t,n,r){let i=`${n}/${e.script}`;if(r===`claude`){let t=U(e,r);return{matcher:t.length>0?t.join(`|`):``,hooks:[{type:`command`,command:`node ${JSON.stringify(i)}`}]}}return r===`copilot`?{event:t,steps:[{type:`command`,command:`node`,args:[i],timeout:z[e.event]||5e3}]}:{command:`node`,args:[i]}}function ce(e,t){H(e);let n={};for(let r of Object.values(R)){let i=I[r.event]?.[e];if(!i){console.warn(`[aikit] Unsupported hook event ${r.event} for ${e} — skipping`);continue}n[i]||=[],n[i].push(W(r,i,t,e))}return{hooks:n}}function G(e,t){if(H(e),e===`claude`)return[];if(e===`copilot`){let n=Object.values(R).flatMap(n=>{let r=I[n.event]?.[e];return r?W(n,r,t,e):(console.warn(`[aikit] Unsupported hook event ${n.event} for ${e} — skipping`),[])});return[{path:B[e],content:JSON.stringify({hooks:n},null,2)}]}if(!(e in B))throw Error(`Platform "${e}" is missing from FILE_NAMES. Add "${e}: '<filename>'" to FILE_NAMES in adapters/hooks.mjs.`);let n={};for(let r of Object.values(R)){let i=I[r.event]?.[e];if(!i){console.warn(`[aikit] Unsupported hook event ${r.event} for ${e} — skipping`);continue}n[i]||=[],n[i].push(W(r,i,t,e))}return[{path:B[e],content:JSON.stringify({hooks:n},null,2)}]}function le(){return[`_runtime.mjs`,...Object.values(R).map(e=>e.script)]}const ue=[`const{spawn:s}=require('child_process')`,`const{existsSync:e,readFileSync:r}=require('fs')`,`const{join:j}=require('path')`,`const{homedir:h}=require('os')`,`const n=process.env.NODE_OPTIONS||'';if(!n.includes('ExperimentalWarning'))process.env.NODE_OPTIONS=n?(n+' --disable-warning=ExperimentalWarning'):'--disable-warning=ExperimentalWarning'`,`const l=(c,a,o={})=>{const p=s(c,a,{stdio:'inherit',env:process.env,...o});p.once('error',q=>{try{process.stderr.write('aikit: failed to start MCP server - '+q.message)}catch{}process.exit(1)});p.once('exit',(q,g)=>process.exit(g==='SIGINT'?130:g==='SIGTERM'?143:(q??1)));for(const g of ['SIGINT','SIGTERM'])process.once(g,()=>{if(!p.killed)p.kill(g)})}`,`const f=j(h(),'.aikit','current-version.json');if(e(f)){try{const{version:g}=JSON.parse(r(f,'utf-8'));const p=j(h(),'.aikit','versions','v'+g,'packages','server','dist','bin.js');if(!e(p))throw Error('Local install not found at '+p);l(process.execPath,[p,'serve'])}catch(c){try{process.stderr.write('aikit: local install failed - '+c.message+'. Run: aikit install')}catch{}process.exit(1)}}else{const c=process.platform==='win32'?'npx.cmd':'npx';l(c,['-y','@vpxa/aikit@latest','serve'],process.platform==='win32'?{shell:true}:{})}`].join(`;`),de=`aikit`,fe={type:`stdio`,command:`node`,args:[`-e`,ue]},pe=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],me=[`aikit-basic`,`aikit-advanced`,`_epilogue`],he={"chat.agentFilesLocations":{"~/.claude/agents":!1},"chat.useClaudeMdFile":!1,"github.copilot.chat.copilotMemory.enabled":!0,"chat.customAgentInSubagent.enabled":!0,"chat.useNestedAgentsMdFiles":!0,"chat.useAgentSkills":!0,"github.copilot.chat.switchAgent.enabled":!0,"workbench.browser.enableChatTools":!0,"chat.mcp.apps.enabled":!0,"chat.instructionsFilesLocations":{"~/.copilot/instructions":!0,".github/instructions":!0,".claude/rules":!1,"~/.claude/rules":!1}},ge=[{id:`no-grep-search`,toolName:`grep_search`,description:`grep_search / semantic_search → use search`,alternative:`search({ query })`,reason:`Hybrid search across all indexed + curated content — richer results than grep`,severity:`error`,action:`redirect`},{id:`no-semantic-search`,toolName:`semantic_search`,description:`semantic_search → use search`,alternative:`search({ query })`,reason:`Hybrid search across all indexed + curated content — vector + FTS fusion`,severity:`error`,action:`redirect`},{id:`no-grep-symbol`,toolName:`grep_search`,description:`grep_search for a symbol → use symbol`,alternative:`symbol({ name })`,reason:`Definition + references with scope and call context`,severity:`error`,action:`redirect`,heuristic:`grep_search for a specific symbol name`},{id:`no-read-file-understanding`,toolName:`read_file`,description:`read_file to understand a file → use file_summary`,alternative:`file_summary({ path })`,reason:`Structure, exports, imports — 10x fewer tokens than raw file reads`,severity:`error`,action:`warn`,heuristic:`read_file with range > 50 lines and no subsequent edit`},{id:`no-read-file-find-code`,toolName:`read_file`,description:`read_file to find specific code → use compact`,alternative:`compact({ path, query })`,reason:`Fresh compression: compact({ path, query }); query is required unless ref is supplied`,severity:`error`,action:`warn`,heuristic:`read_file to locate specific code without editing`},{id:`no-read-file-multiple`,toolName:`read_file`,description:`Multiple read_file calls → use digest`,alternative:`digest({ sources, query: "<task description>" })`,reason:`Compresses multiple files into token-budgeted summary`,severity:`error`,action:`warn`,heuristic:`consecutive read_file calls on different files without edits`},{id:`no-read-file-large`,toolName:`read_file`,description:`read_file (>50 lines to understand) → use file_summary → compact → digest`,alternative:`file_summary → compact → digest`,reason:`Use compressed context, not raw reads — 10x fewer tokens`,severity:`warning`,action:`warn`,heuristic:`read_file with endLine - startLine > 50 and no subsequent edit on same file`},{id:`no-ctxc-misuse`,toolName:`compact`,description:`Cached ctxc ref to refocus prior output → use compact with ref`,alternative:`compact({ ref }) or compact({ ref, query? })`,reason:`ctxc_... values are reversible refs, not ids or file paths. Prefer enrich: true on follow-up retrieval`,severity:`error`,action:`warn`,heuristic:`using ctxc_ value as a file path instead of as a ref`},{id:`no-terminal-test`,toolName:`run_in_terminal`,description:`run_in_terminal for tests → use test_run`,alternative:`test_run({})`,reason:`Run tests with structured output — no shell needed`,severity:`error`,action:`redirect`,commandPatterns:[`vitest`,`jest`,`mocha`,`pnpm test`,`npm test`]},{id:`no-terminal-typecheck`,toolName:`run_in_terminal`,description:`run_in_terminal for tsc/lint → use check`,alternative:`check({})`,reason:`Typecheck + lint combined, summary output — no shell needed`,severity:`error`,action:`redirect`,commandPatterns:[`\\btsc\\b`,`pnpm check`,`pnpm typecheck`,`pnpm lint`,`biome`]},{id:`no-terminal-grep`,toolName:`run_in_terminal`,description:`run_in_terminal for find/grep → use find or search`,alternative:`find({ pattern }) or search({ query })`,reason:`No shell needed, richer results with AI Kit search`,severity:`error`,action:`redirect`,commandPatterns:[`\\bgrep\\b`,`\\bfind\\b`,`\\brg\\b`,`Select-String`]},{id:`no-terminal-code-edits`,toolName:`run_in_terminal`,description:`run_in_terminal for code edits → use replace_string_in_file`,alternative:`replace_string_in_file`,reason:`Avoid shell-edit loops; use native edit tool instead`,severity:`error`,action:`redirect`,commandPatterns:[`sed`,`awk`,`Set-Content`,`Out-File`,`>>`,`\\| tee`]},{id:`no-edit-without-reading`,toolName:`replace_string_in_file`,description:`Editing without reading → use file_summary then targeted read_file`,alternative:`file_summary({ path }) → read_file({ path, offset, limit })`,reason:`Safer edits: understand structure before modifying`,severity:`error`,action:`warn`,heuristic:`replace_string_in_file on a file not previously read`},{id:`no-get-changed-files`,toolName:`get_changed_files`,description:`get_changed_files → use run_in_terminal with git diff`,alternative:"run_in_terminal with `git diff <specific-file>`",reason:`Diff only target file instead of all uncommitted diffs (100K+ tokens)`,severity:`error`,action:`redirect`},{id:`no-fetch-webpage`,toolName:`fetch_webpage`,description:`fetch_webpage → use web_fetch`,alternative:`web_fetch({ url })`,reason:`Readability extract + token budget — richer output than raw fetch`,severity:`error`,action:`redirect`},{id:`no-subagent-present`,toolName:`present`,description:`present (from subagent) → return structured text`,alternative:`Return findings as structured text`,reason:`Subagent present calls are invisible to the user (only Orchestrator should present)`,severity:`error`,action:`warn`,heuristic:`present called in subagent context`},{id:`no-apply-patch`,toolName:`apply_patch`,description:`apply_patch → use native edit tool`,alternative:`edit file tool`,reason:`AI Kit does not manage apply_patch; use the host environment edit tool`,severity:`warning`,action:`warn`},{id:`no-memory-native`,toolName:`memory`,description:`memory tool → use knowledge tool`,alternative:`knowledge (remember / search / list)`,reason:`AI Kit knowledge tool provides persistent cross-session memory with categories and tags`,severity:`warning`,action:`warn`}];function _e(e){let t=e.toolName;if(e.commandPatterns&&e.commandPatterns.length>0){let n=e.description.match(/^(.*?)\s*→/);n&&(t=n[1].trim())}else if(e.heuristic){let n=e.description.match(/^(.*?)\s*→/);n&&(t=n[1].trim())}return{id:e.id,forbidden:t,alternative:e.alternative,severity:e.severity,reason:e.reason,matchPattern:e.commandPatterns?null:e.toolName,commandPatterns:e.commandPatterns??null,heuristic:e.heuristic??null}}const ve=ge.map(_e);function ye(){return[`| NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |`,`|---|---|---|`,...ve.filter(e=>e.severity===`error`).map(e=>`| \`${e.forbidden}\` | \`${e.alternative}\` | ${e.reason} |`)].join(`
|
|
6
6
|
`)}function K(e){return`
|
|
7
7
|
## Flow Context Bootstrap
|
|
8
8
|
|
|
@@ -28,23 +28,24 @@ ${e===`<PROFILE>`?`**Profile:** Check your role → implementer | documenter | r
|
|
|
28
28
|
|
|
29
29
|
AI Kit delivers knowledge through four layers:
|
|
30
30
|
|
|
31
|
-
- **L0 — Generated Briefing Cards**: Fast, task-ready workspace setup. \`workspace-core\` available as local resource \`aikit://l0/workspace-core\` (full card) and via \`status({ includePrelude: true })\` (compact summary), both populated after \`onboard({ path, mode: 'generate' })\` runs for the workspace. If workspaceCore null → run onboard first. If a flow is active, \`workflow:<flow>\` loaded via flow context (replaces task card). Total budget: ${n.sessionStart.totalTokenBudget} tokens.
|
|
31
|
+
- **L0 — Generated Briefing Cards**: Fast, task-ready workspace setup. \`workspace-core\` available as local resource \`aikit://l0/workspace-core\` (full card) and via \`status({ includePrelude: true })\` (compact summary), both populated after \`onboard({ path, mode: 'generate' })\` runs for the workspace. Treat this card as already-loaded workspace context: consume it before broad \`search\`, \`scope_map\`, \`digest\`, or repeated \`file_summary\`. If workspaceCore null → run onboard first. If a flow is active, \`workflow:<flow>\` loaded via flow context (replaces task card). Total budget: ${n.sessionStart.totalTokenBudget} tokens.
|
|
32
32
|
- **L1 — Flow Working Context**: Active run state, current step, and role-filtered dispatch context. Withdraw via \`knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>', budget: 6000 })\`.
|
|
33
33
|
- **L2 — Canonical Curated Knowledge**: Durable workspace archive managed by CuratedKnowledgeManager. Retrieve on demand via \`search()\` or \`knowledge({ action: 'read' })\`.
|
|
34
34
|
- **L3 — Evidence Archive**: Auto-knowledge observations and tool-output evidence. Inspect only for provenance, conflict review, or promotion assessment. Never auto-injected.
|
|
35
35
|
|
|
36
36
|
### Hot Path
|
|
37
|
-
1. Session start → fetch \`aikit://l0/workspace-core\` resource (full card) or \`status({ includePrelude: true })\` (compact summary). Prerequisite: \`onboard({ path, mode: 'generate' })\` must have run for the workspace. If workspaceCore null → run onboard first, then status again.
|
|
38
|
-
2.
|
|
39
|
-
3.
|
|
40
|
-
4.
|
|
37
|
+
1. Session start → fetch \`aikit://l0/workspace-core\` resource (full card) or \`status({ includePrelude: true })\` (compact summary). Prerequisite: \`onboard({ path, mode: 'generate' })\` must have run for the workspace. If workspaceCore null → run onboard first, then status again.
|
|
38
|
+
2. Before broad repo scans, extract and reuse the L0 facts: workspace shape, package map, tool surfaces, key entry points, constraints, and known pitfalls. If L0 answers enough, skip \`scope_map\`/wide \`search\` and go straight to task-specific retrieval.
|
|
39
|
+
3. If flow active, \`workflow:<flow>\` loaded via flow context; use L1 snapshot + dispatch refs before broad retrieval. If no flow, may add one task card via \`file_summary\`.
|
|
40
|
+
4. Retrieve L2 on demand.
|
|
41
|
+
5. Inspect L3 only for evidence, provenance, or promotion.
|
|
41
42
|
|
|
42
43
|
### No-Flow Fallback
|
|
43
44
|
- Keep L1 absent; workspace-core available via status after onboard; optionally one task card.
|
|
44
45
|
- L2 on demand; turn-local scratch, no L1 synthesis.
|
|
45
46
|
|
|
46
47
|
### Degraded Fallback
|
|
47
|
-
- Missing L0 card
|
|
48
|
+
- Missing L0 card after regeneration → use \`status({ includePrelude: true })\` as compact fallback, then only task-specific L2 retrieval; do not replace L0 with a workspace-wide scan.
|
|
48
49
|
- Unavailable L1 → read persisted FlowRunMeta without mutation.
|
|
49
50
|
- Unavailable indexed L2 → read canonical curated markdown directly.
|
|
50
51
|
- Mark missing evidence unresolved; block promotion.
|
|
@@ -55,7 +56,7 @@ AI Kit delivers knowledge through four layers:
|
|
|
55
56
|
- Emit L3 evidence as observer-only; never navigate flow state.`:t===`flow`?r+`
|
|
56
57
|
### Step Contracts
|
|
57
58
|
Each built-in flow step declares knowledge inputs (L0 card types, L1 fields, L2 refs, L3 evidence), context updates, candidate learnings, and handoff artifacts. The step knowledge contract drives role-aware L1 projection.`:r}const Se=q(`## Output Rules (HARD RULE)`,`**Plain text is allowed only when ALL are true:**`,` - Response is 1-2 short sentences.`,` - No table, list, checklist, plan, report, verdict, review, summary, progress, evidence map, or batch result is being returned.`,` - No user approval, mandatory stop, or choice is needed.`,"Follow the **Presentation Priority** (1st Inline Visual - `present({ schemaVersion: 1, title, blocks })` → 2nd Interactive - `present({ schemaVersion: 1, title, blocks, actions })` → 3rd Plain Text). Only tiny status/questions that pass the gate above → plain text (Priority 3). Prefer `present` for all others, especially summaries, comparisons, reports, task plans, verdicts, and progress.");function Y(){return'## Tool Preference — AI Kit First (HARD RULE)\n\n**Never start with `read_file`, `grep_search`, `semantic_search`, or `run_in_terminal`. AI Kit tools replace all of these.**\n\n| Need | Use | NEVER |\n|------|-----|-------|\n| Structure of a file | `file_summary({ path })` | `read_file` to "understand" it |\n| Find specific code | `file_summary({ files, tier: \'T2\', query })` | `read_file` to search |\n| Multiple files | `digest({ sources, query })` | Multiple `read_file` calls |\n| Reuse previous output | `file_summary({ ref, query })` with `enrich:true` | Re-reading same file |\n| Search codebase | `search({ query })` | `grep_search` / `semantic_search` |\n| Find a symbol | `symbol({ name })` | `grep_search` |\n| Trace data flow | `trace({ items: [{start, direction}] })` | Manual code tracing |\n| Module relationships | `graph({action:\'neighbors\', node_id})` | Manual import tracing |\n| Typecheck + lint | `check({})` | `run_in_terminal tsc` / biome |\n| Run tests | `test_run({})` | `run_in_terminal vitest` |\n| Impact analysis | `blast_radius({ changed_files })` | Manual caller tracing |\n| Complexity metrics | `measure({ path })` | Line counting / wc |\n| L0 briefing card (workspace-core) | `aikit://l0/workspace-core` resource (full card), `file_summary` | Raw file discovery |\n| L0 briefing card (known issues) | `search({ query: "known issues" })` + `knowledge({ action: "lesson" })` | Manual history review |\n| Web research | `web_search({ queries })` + `web_fetch({ urls })` | `fetch_webpage` |\n\n`read_file` is ONLY acceptable when you need exact line content FOR EDITING (before `replace_string_in_file`).\n\nEven then, use `file_summary` first to identify which lines to read.'}const Ce=q(`## AI Kit Recovery`,"If AI Kit tools are unavailable or missing, run `npx -y @vpxa/aikit@latest init --user`, then reload the client so the `aikit` MCP server and user instructions become available.");`${Y()}${ye()}${be()}`,`${K(`researcher`)}${Y()}`,`${K(`reviewer`)}${Y()}`,`${K(`reviewer`)}${Y()}`,J({audience:`agent`});const we=/{\s*name:\s*'((?:\\.|[^'])*)',\s*rationale:\s*'((?:\\.|[^'])*)',\s*bitterLessonSafe:\s*(?:true|false),\s*}/g;let X=null;function Z(e){return e.replace(/\\'/g,`'`).replace(/\\n/g,`
|
|
58
|
-
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\\\/g,`\\`)}function Q(){if(X)return X;let e=r(
|
|
59
|
+
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\\\/g,`\\`)}function Q(){if(X)return X;let e=r(h(),`scaffold`,`definitions`,`exclusions.mjs`),n=t(e,`utf8`),i=Array.from(n.matchAll(we),([,e,t])=>({name:Z(e),rationale:Z(t)}));if(i.length===0)throw Error(`Failed to parse permanent exclusions from ${e}`);return X=i,i}function $(e){return e.replace(/\|/g,`\\|`).replace(/\r?\n+/g,` `).trim()}function Te(){return`## Permanent Exclusions
|
|
59
60
|
|
|
60
61
|
These capabilities are intentionally NOT provided by aikit. Each decision follows the Bitter Lesson: leverage computation and configurable tools over hand-crafted features.
|
|
61
62
|
|
|
@@ -328,4 +329,4 @@ Both ReactFlow viewers include an **AI Kit** attribution badge (bottom-right). A
|
|
|
328
329
|
## Full Documentation
|
|
329
330
|
|
|
330
331
|
For complete tool documentation (62 tools), workflow chains, search strategies, session protocol, and persistent memory patterns, load the \`aikit\` skill at session start.
|
|
331
|
-
`}export{
|
|
332
|
+
`}export{T as A,te as B,A as C,D,w as E,k as F,ae as I,ee as L,O as M,b as N,x as O,C as P,P as R,v as S,S as T,h as _,de as a,M as b,ce as c,u as d,p as f,se as g,re as h,fe as i,_ as j,f as k,G as l,ne as m,Ee as n,pe as o,ie as p,me as r,he as s,De as t,le as u,g as v,E as w,N as x,d as y,oe as z};
|
|
@@ -701,6 +701,38 @@ declare class HealthBus extends EventEmitter {
|
|
|
701
701
|
* @module
|
|
702
702
|
*/
|
|
703
703
|
type KnowledgeLayerId = 'l0' | 'l1' | 'l2' | 'l3';
|
|
704
|
+
/**
|
|
705
|
+
* Evidence grade — separates fact reliability from instruction treatment.
|
|
706
|
+
*
|
|
707
|
+
* 'A' — High confidence: multiple observations, diverse sources, high recurrence.
|
|
708
|
+
* Suitable for automated treatment when platform capability allows.
|
|
709
|
+
* 'B' — Moderate confidence: some observations or limited sources.
|
|
710
|
+
* Best kept as manual or optional treatment — LLM judgment still valuable.
|
|
711
|
+
* 'C' — Low confidence: single observation, low recurrence, or no source diversity.
|
|
712
|
+
* Background signal only — must not drive instruction decisions.
|
|
713
|
+
*
|
|
714
|
+
* EvidenceGrade is set at extraction time by the extractor based on observed
|
|
715
|
+
* quality signals (recurrence, diversity, confidence). It is NOT derived from
|
|
716
|
+
* instruction treatment decisions — the two axes are independent.
|
|
717
|
+
*/
|
|
718
|
+
type EvidenceGrade = 'A' | 'B' | 'C';
|
|
719
|
+
/**
|
|
720
|
+
* Instruction treatment — separates rendering behavior from fact quality.
|
|
721
|
+
*
|
|
722
|
+
* 'pinned' — Always shown, regardless of capability level or evidence grade.
|
|
723
|
+
* Used for security policy or user preference overrides.
|
|
724
|
+
* 'manual' — Shown because LLM judgment is required (query composition,
|
|
725
|
+
* scope narration, handoff synthesis).
|
|
726
|
+
* 'default' — Normal level-based or capability-driven rendering.
|
|
727
|
+
* The default when no treatment is explicitly set.
|
|
728
|
+
* 'omit' — Not rendered. Used when the instruction is genuinely irrelevant
|
|
729
|
+
* for this platform or context.
|
|
730
|
+
*
|
|
731
|
+
* InstructionTreatment is set by platform adapters or user preference, NOT
|
|
732
|
+
* derived from EvidenceGrade. A high-grade fact (A) can have 'manual' treatment
|
|
733
|
+
* (because the LLM must still decide how to act on it).
|
|
734
|
+
*/
|
|
735
|
+
type InstructionTreatment = 'pinned' | 'manual' | 'default' | 'omit';
|
|
704
736
|
/**
|
|
705
737
|
* Shared metadata fields carried by all L0-L3 entries.
|
|
706
738
|
*/
|
|
@@ -728,9 +760,18 @@ interface LayeredKnowledgeBaseV1 {
|
|
|
728
760
|
impact?: 'low' | 'medium' | 'high';
|
|
729
761
|
actionability?: 'low' | 'medium' | 'high';
|
|
730
762
|
recurrence?: number;
|
|
731
|
-
sourceDiversity?: number;
|
|
763
|
+
sourceDiversity?: number; /** Evidence grade at extraction time. Independent from instruction treatment. */
|
|
764
|
+
evidenceGrade?: EvidenceGrade;
|
|
732
765
|
};
|
|
733
766
|
promotionState?: 'candidate' | 'held' | 'promoted' | 'rejected' | 'superseded';
|
|
767
|
+
/** Traceability for fact→treatment decisions. Populated when a promotion decision is made. */
|
|
768
|
+
decision?: {
|
|
769
|
+
reason: string;
|
|
770
|
+
decidedAt: string;
|
|
771
|
+
decidedBy: string; /** Specific evidence reference that triggered this decision (subset of top-level evidenceRefs). */
|
|
772
|
+
evidenceRef?: string; /** Instruction treatment override resulting from this decision. */
|
|
773
|
+
instructionTreatment?: InstructionTreatment;
|
|
774
|
+
};
|
|
734
775
|
}
|
|
735
776
|
/**
|
|
736
777
|
* Card families for L0 generated briefing cards.
|
|
@@ -1011,4 +1052,4 @@ declare function compareVersionDir(a: string, b: string): number;
|
|
|
1011
1052
|
*/
|
|
1012
1053
|
declare function cleanupOldVersions(versionsDir: string, keepVersion?: string): void;
|
|
1013
1054
|
//#endregion
|
|
1014
|
-
export { AIKIT_GLOBAL_PATHS, AIKIT_PATHS, AIKIT_RUNTIME_PATHS, AikitConfig, AikitError, BriefingCardMetadataV1, BriefingCardType, CATEGORY_PATTERN, CHUNK_SIZES, CONTENT_TYPES, ChunkMetadata, CircuitBreaker, CircuitBreakerOptions, CircuitOpenError, CircuitState, ConfigError, ContentType, CuratedKnowledgeMetadataV1, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, EmbeddingError, EvidenceMetadataV1, FILE_LIMITS, FlowBacktrackV1, FlowContextMetadataV1, FlowContextProfileName, FlowContextSnapshotV1, FlowContextUpdateV1, FlowLifecycleAuditRecordV1, FlowLifecycleMutationV1, FlowOwnerClaimV1, FlowStepKnowledgeContractV1, GlobalRegistry, HealthBus, HealthEvent, HealthStatus, INDEX_MODES, INSTALL_ARGS, IndexError, IndexMode, IndexStats, KNOWLEDGE_ORIGINS, KnowledgeLayerId, KnowledgeOrigin, KnowledgeRecord, LAYER_FIELD_REQUIREMENTS, LayerValidationResult, LayeredKnowledgeBaseV1, LayeredKnowledgeContractV1, LogLevel, LogListener, MODEL_REGISTRY, PermanentError, RawChunk, RegistryEntry, RetryOptions, SEARCH_DEFAULTS, SOURCE_TYPES, STORE_DEFAULTS, SearchResult, SourceType, StoreError, SubsystemHealth, SupersessionConfig, TOKEN_BUDGETS, TokenBudget, TransientError, addLogListener, cleanupOldVersions, compareVersionDir, computePartitionKey, contentTypeToSourceType, createLogger, detectContentType, getGlobalDataDir, getLogLevel, getPartitionDir, getWorkspacePartitionDir, hashPath, isPermanent, isTransient, isUserInstalled, listWorkspaces, loadRegistry, lookupWorkspace, migrateLegacyWorkspaceLayout, normalizePathForHash, registerWorkspace, resetLogDir, resolveLogDir, resolveStateDir, safeCwd, safeCwdOrHome, saveRegistry, serializeError, setDetailedErrorLoggingEnabled, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes, validateLayerMetadata, withRetry };
|
|
1055
|
+
export { AIKIT_GLOBAL_PATHS, AIKIT_PATHS, AIKIT_RUNTIME_PATHS, AikitConfig, AikitError, BriefingCardMetadataV1, BriefingCardType, CATEGORY_PATTERN, CHUNK_SIZES, CONTENT_TYPES, ChunkMetadata, CircuitBreaker, CircuitBreakerOptions, CircuitOpenError, CircuitState, ConfigError, ContentType, CuratedKnowledgeMetadataV1, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, EmbeddingError, EvidenceGrade, EvidenceMetadataV1, FILE_LIMITS, FlowBacktrackV1, FlowContextMetadataV1, FlowContextProfileName, FlowContextSnapshotV1, FlowContextUpdateV1, FlowLifecycleAuditRecordV1, FlowLifecycleMutationV1, FlowOwnerClaimV1, FlowStepKnowledgeContractV1, GlobalRegistry, HealthBus, HealthEvent, HealthStatus, INDEX_MODES, INSTALL_ARGS, IndexError, IndexMode, IndexStats, InstructionTreatment, KNOWLEDGE_ORIGINS, KnowledgeLayerId, KnowledgeOrigin, KnowledgeRecord, LAYER_FIELD_REQUIREMENTS, LayerValidationResult, LayeredKnowledgeBaseV1, LayeredKnowledgeContractV1, LogLevel, LogListener, MODEL_REGISTRY, PermanentError, RawChunk, RegistryEntry, RetryOptions, SEARCH_DEFAULTS, SOURCE_TYPES, STORE_DEFAULTS, SearchResult, SourceType, StoreError, SubsystemHealth, SupersessionConfig, TOKEN_BUDGETS, TokenBudget, TransientError, addLogListener, cleanupOldVersions, compareVersionDir, computePartitionKey, contentTypeToSourceType, createLogger, detectContentType, getGlobalDataDir, getLogLevel, getPartitionDir, getWorkspacePartitionDir, hashPath, isPermanent, isTransient, isUserInstalled, listWorkspaces, loadRegistry, lookupWorkspace, migrateLegacyWorkspaceLayout, normalizePathForHash, registerWorkspace, resetLogDir, resolveLogDir, resolveStateDir, safeCwd, safeCwdOrHome, saveRegistry, serializeError, setDetailedErrorLoggingEnabled, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes, validateLayerMetadata, withRetry };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventEmitter as e}from"node:events";import{basename as t,dirname as n,extname as r,join as i,resolve as a,sep as o}from"node:path";import{createHash as s}from"node:crypto";import{appendFileSync as c,closeSync as l,constants as u,copyFileSync as ee,existsSync as d,lstatSync as te,mkdirSync as f,openSync as ne,readFileSync as re,readdirSync as p,renameSync as m,rmSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{homedir as y}from"node:os";import{fileURLToPath as ie}from"node:url";var ae=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new b(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new b(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},b=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const x={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},S={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},C={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},oe={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},se={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},ce={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},le={backend:`sqlite-vec`,path:x.data,tableName:`knowledge`},ue=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],de={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},fe={maxResults:10,minScore:.25},pe=/^[a-z][a-z0-9-]*$/,me=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],w={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},he=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],ge=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function _e(e){let n=r(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${x.aiContext}/`)?`produced-knowledge`:e.includes(`${x.aiCurated}/`)?`curated-knowledge`:he.some(t=>t.test(e))?`test-code`:ge.some(t=>t.test(e))?`cdk-stack`:n in w?w[n]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(n)?`code-other`:`unknown`}const T={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function ve(e){return T[e]??`source`}function ye(e){return Object.entries(T).filter(([,t])=>t===e).map(([e])=>e)}var E=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},be=class extends E{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},xe=class extends E{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},Se=class extends E{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},Ce=class extends E{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},D=class extends E{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},O=class extends E{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function we(e){return e instanceof D}function Te(e){return e instanceof O}let k=!1;function Ee(e){try{return!te(e).isSymbolicLink()}catch{return!1}}function De(e,t){if(g(e).isDirectory()){f(t,{recursive:!0});for(let n of p(e))A(a(e,n),a(t,n));h(e,{recursive:!0,force:!0});return}f(a(t,`..`),{recursive:!0}),ee(e,t),_(e)}function Oe(e,t){try{m(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!d(e)&&d(t))return;if(r!==`EXDEV`)throw n;De(e,t)}}function A(e,t){if(!d(e)||e===t||!Ee(e))return;let n=g(e);if(!d(t)){f(a(t,`..`),{recursive:!0}),Oe(e,t);return}if(!n.isDirectory())return;f(t,{recursive:!0});let r;try{r=p(e)}catch{return}for(let n of r)A(a(e,n),a(t,n));try{h(e,{recursive:!0,force:!0})}catch{}}function j(e){if(d(e))try{p(e).length===0&&h(e,{recursive:!0,force:!0})}catch{}}function ke(e){let t=a(e,S.data);f(t,{recursive:!0});for(let n of p(e))n!==S.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&A(a(e,n),a(t,n))}function M(e){return B(I(e))}function Ae(e){if(k)return;k=!0,f(e,{recursive:!0});let t=y(),n=a(t,C.legacyDataRoot),r=a(t,C.legacyStateRoot),i=a(e,C.workspaces),o=a(e,C.logs),s=a(e,C.state);if(d(n)&&n!==e){f(i,{recursive:!0});for(let t of p(n))A(a(n,t),t===C.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?a(e,t):a(i,t));j(n)}if(d(r)&&r!==e){for(let e of p(r))A(a(r,e),e===`logs`?o:a(s,e));j(r)}}function N(e){let t=a(e),n=M(t),r=a(n,S.data),i=a(P(),C.logs),o=[{from:a(t,C.legacyDataRoot),to:r},{from:a(t,C.legacyStateRoot),to:a(n,S.state)},{from:a(t,x.data),to:r},{from:a(t,x.state),to:a(n,S.state)},{from:a(t,x.aiCurated),to:a(n,S.curated)},{from:a(t,x.aiContext),to:a(n,S.onboard)},{from:a(t,x.restorePoints),to:a(n,S.restorePoints)},{from:a(t,x.brainstorm),to:a(n,S.brainstorm)},{from:a(t,x.handoffs),to:a(n,S.handoffs)},{from:a(t,x.logs),to:i}];f(n,{recursive:!0}),f(i,{recursive:!0}),ke(n);for(let e of o)A(e.from,e.to);j(a(t,x.root)),j(a(t,x.ai)),j(a(t,x.brainstorm)),j(a(t,x.handoffs))}function je(e){return N(e),a(B(z(e).partition),S.state)}function P(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??a(y(),C.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Ae(t),t}function F(e){return Ne()?e.toLowerCase():e}function I(e){let n=a(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${s(`sha256`).update(F(n)).digest(`hex`).slice(0,8)}`}function Me(e,t=12){let n=a(e);return s(`sha256`).update(F(n)).digest(`hex`).slice(0,t)}function Ne(){return process.platform===`win32`||process.platform===`darwin`}function L(){let e=a(P(),C.registry);if(!d(e))return{version:1,workspaces:{}};let t=re(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Pe(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ne(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function Fe(e){try{_(e)}catch{}}function R(e){let t=P();f(t,{recursive:!0});let n=a(t,C.registry),r=Pe(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{Fe(r)}}function z(e){let t=L(),n=I(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:a(e),registeredAt:r,lastAccessedAt:r},f(B(n),{recursive:!0}),R(t),t.workspaces[n]}function Ie(e){let t=L(),n=I(e);return t.workspaces[n]}function Le(){let e=L();return Object.values(e.workspaces)}function B(e){return a(P(),C.workspaces,e)}function Re(){return d(a(P(),C.registry))}function V(){return a(P(),C.logs)}var ze=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};function Be(e,t){let n=H[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const H={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`]}},U={debug:0,info:1,warn:2,error:3},W=[];let G=process.env.AIKIT_LOG_LEVEL??`info`,K=!1,q=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function Ve(){return q?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let J;function Y(){return J||=V(),J}function He(e){let t=e.toISOString().slice(0,10);return i(Y(),`${t}.jsonl`)}let Ue=0;function We(){let e=Date.now();if(!(e-Ue<36e5)){Ue=e;try{let t=Y(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of p(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(i(t,e))}catch{}}catch{}}}function Ge(e,t){try{f(Y(),{recursive:!0}),c(He(t),`${e}\n`),We()}catch{}}function Ke(e){G=e}function qe(){return G}function Je(e){q=e}function Ye(){J=void 0}function Xe(e){K=e}function Ze(e){if(e instanceof Error){let t={error:e.message};return K?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function Qe(e){return W.push(e),()=>{let t=W.indexOf(e);t>=0&&W.splice(t,1)}}function $e(e){function t(t,n,r){if(U[t]<U[G])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of W)try{i({level:t,component:e,message:n,data:r})}catch{}Ve()&&(t===`warn`||t===`error`)&&Ge(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const X={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function et(e,t={}){let{maxAttempts:n=X.maxAttempts,baseDelayMs:r=X.baseDelayMs,maxDelayMs:i=X.maxDelayMs,jitterFraction:a=X.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof D),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof D&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await tt(l)}throw s}function tt(e){return new Promise(t=>setTimeout(t,e))}let Z;function nt(){return Z===void 0&&(Z=y()),Z}function rt(){try{return process.cwd()}catch{return null}}function it(){return rt()??nt()}const at=[`indexed`,`curated`,`produced`],ot=[`source`,`documentation`,`test`,`config`,`generated`],st=[`auto`,`manual`,`smart`],ct=[`efficient`,`normal`,`full`],lt=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`],Q=$e(`core:version-manager`);function $(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function ut(e){let t=a(e),r=n(ie(import.meta.url)),i=process.cwd();return a(r).startsWith(t+o)||a(i).startsWith(t+o)||a(r)===t||a(i)===t}function dt(e,t){try{if(!d(e)||!t||t===`0.0.0`)return;let n=p(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort($),r=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)r.add(e);for(let t of n)if(!r.has(t)){let n=i(e,t);if(ut(n)){Q.debug(`Skipping ${t} — currently in use by running process`);continue}h(n,{recursive:!0,force:!0}),Q.debug(`Cleaned old version: ${t}`)}}catch(e){Q.debug(`Version directory cleanup failed`,{error:e})}}export{C as AIKIT_GLOBAL_PATHS,x as AIKIT_PATHS,S as AIKIT_RUNTIME_PATHS,E as AikitError,pe as CATEGORY_PATTERN,oe as CHUNK_SIZES,lt as CONTENT_TYPES,ae as CircuitBreaker,b as CircuitOpenError,Ce as ConfigError,me as DEFAULT_CATEGORIES,se as EMBEDDING_DEFAULTS,be as EmbeddingError,de as FILE_LIMITS,ze as HealthBus,st as INDEX_MODES,ue as INSTALL_ARGS,Se as IndexError,at as KNOWLEDGE_ORIGINS,H as LAYER_FIELD_REQUIREMENTS,ce as MODEL_REGISTRY,O as PermanentError,fe as SEARCH_DEFAULTS,ot as SOURCE_TYPES,le as STORE_DEFAULTS,xe as StoreError,ct as TOKEN_BUDGETS,D as TransientError,Qe as addLogListener,dt as cleanupOldVersions,$ as compareVersionDir,I as computePartitionKey,ve as contentTypeToSourceType,$e as createLogger,_e as detectContentType,P as getGlobalDataDir,qe as getLogLevel,B as getPartitionDir,M as getWorkspacePartitionDir,Me as hashPath,Te as isPermanent,we as isTransient,Re as isUserInstalled,Le as listWorkspaces,L as loadRegistry,Ie as lookupWorkspace,N as migrateLegacyWorkspaceLayout,F as normalizePathForHash,z as registerWorkspace,Ye as resetLogDir,V as resolveLogDir,je as resolveStateDir,rt as safeCwd,it as safeCwdOrHome,R as saveRegistry,Ze as serializeError,Xe as setDetailedErrorLoggingEnabled,Je as setFileSinkEnabled,Ke as setLogLevel,ye as sourceTypeContentTypes,Be as validateLayerMetadata,et as withRetry};
|
|
1
|
+
import{EventEmitter as e}from"node:events";import{basename as t,dirname as n,extname as r,join as i,resolve as a,sep as o}from"node:path";import{createHash as s}from"node:crypto";import{appendFileSync as c,closeSync as l,constants as u,copyFileSync as ee,existsSync as d,lstatSync as te,mkdirSync as f,openSync as ne,readFileSync as re,readdirSync as p,renameSync as m,rmSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{homedir as y}from"node:os";import{fileURLToPath as ie}from"node:url";var ae=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new b(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new b(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},b=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const x={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},S={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},C={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},oe={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},se={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},ce={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},le={backend:`sqlite-vec`,path:x.data,tableName:`knowledge`},ue=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],de={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},fe={maxResults:10,minScore:.25},pe=/^[a-z][a-z0-9-]*$/,me=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],w={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},he=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],ge=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function _e(e){let n=r(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${x.aiContext}/`)?`produced-knowledge`:e.includes(`${x.aiCurated}/`)?`curated-knowledge`:he.some(t=>t.test(e))?`test-code`:ge.some(t=>t.test(e))?`cdk-stack`:n in w?w[n]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(n)?`code-other`:`unknown`}const T={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function ve(e){return T[e]??`source`}function ye(e){return Object.entries(T).filter(([,t])=>t===e).map(([e])=>e)}var E=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},be=class extends E{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},xe=class extends E{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},Se=class extends E{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},Ce=class extends E{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},D=class extends E{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},O=class extends E{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function we(e){return e instanceof D}function Te(e){return e instanceof O}let k=!1;function Ee(e){try{return!te(e).isSymbolicLink()}catch{return!1}}function De(e,t){if(g(e).isDirectory()){f(t,{recursive:!0});for(let n of p(e))A(a(e,n),a(t,n));h(e,{recursive:!0,force:!0});return}f(a(t,`..`),{recursive:!0}),ee(e,t),_(e)}function Oe(e,t){try{m(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!d(e)&&d(t))return;if(r!==`EXDEV`)throw n;De(e,t)}}function A(e,t){if(!d(e)||e===t||!Ee(e))return;let n=g(e);if(!d(t)){f(a(t,`..`),{recursive:!0}),Oe(e,t);return}if(!n.isDirectory())return;f(t,{recursive:!0});let r;try{r=p(e)}catch{return}for(let n of r)A(a(e,n),a(t,n));try{h(e,{recursive:!0,force:!0})}catch{}}function j(e){if(d(e))try{p(e).length===0&&h(e,{recursive:!0,force:!0})}catch{}}function ke(e){let t=a(e,S.data);f(t,{recursive:!0});for(let n of p(e))n!==S.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&A(a(e,n),a(t,n))}function M(e){return B(I(e))}function Ae(e){if(k)return;k=!0,f(e,{recursive:!0});let t=y(),n=a(t,C.legacyDataRoot),r=a(t,C.legacyStateRoot),i=a(e,C.workspaces),o=a(e,C.logs),s=a(e,C.state);if(d(n)&&n!==e){f(i,{recursive:!0});for(let t of p(n))A(a(n,t),t===C.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?a(e,t):a(i,t));j(n)}if(d(r)&&r!==e){for(let e of p(r))A(a(r,e),e===`logs`?o:a(s,e));j(r)}}function N(e){let t=a(e),n=M(t),r=a(n,S.data),i=a(P(),C.logs),o=[{from:a(t,C.legacyDataRoot),to:r},{from:a(t,C.legacyStateRoot),to:a(n,S.state)},{from:a(t,x.data),to:r},{from:a(t,x.state),to:a(n,S.state)},{from:a(t,x.aiCurated),to:a(n,S.curated)},{from:a(t,x.aiContext),to:a(n,S.onboard)},{from:a(t,x.restorePoints),to:a(n,S.restorePoints)},{from:a(t,x.brainstorm),to:a(n,S.brainstorm)},{from:a(t,x.handoffs),to:a(n,S.handoffs)},{from:a(t,x.logs),to:i}];f(n,{recursive:!0}),f(i,{recursive:!0}),ke(n);for(let e of o)A(e.from,e.to);j(a(t,x.root)),j(a(t,x.ai)),j(a(t,x.brainstorm)),j(a(t,x.handoffs))}function je(e){return N(e),a(B(z(e).partition),S.state)}function P(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??a(y(),C.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Ae(t),t}function F(e){return Ne()?e.toLowerCase():e}function I(e){let n=a(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${s(`sha256`).update(F(n)).digest(`hex`).slice(0,8)}`}function Me(e,t=12){let n=a(e);return s(`sha256`).update(F(n)).digest(`hex`).slice(0,t)}function Ne(){return process.platform===`win32`||process.platform===`darwin`}function L(){let e=a(P(),C.registry);if(!d(e))return{version:1,workspaces:{}};let t=re(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Pe(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ne(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function Fe(e){try{_(e)}catch{}}function R(e){let t=P();f(t,{recursive:!0});let n=a(t,C.registry),r=Pe(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{Fe(r)}}function z(e){let t=L(),n=I(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:a(e),registeredAt:r,lastAccessedAt:r},f(B(n),{recursive:!0}),R(t),t.workspaces[n]}function Ie(e){let t=L(),n=I(e);return t.workspaces[n]}function Le(){let e=L();return Object.values(e.workspaces)}function B(e){return a(P(),C.workspaces,e)}function Re(){return d(a(P(),C.registry))}function V(){return a(P(),C.logs)}var ze=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};function Be(e,t){let n=H[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const H={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`,`quality`,`decision`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`,`decision`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`,`decision`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`,`decision`]}},U={debug:0,info:1,warn:2,error:3},W=[];let G=process.env.AIKIT_LOG_LEVEL??`info`,K=!1,q=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function Ve(){return q?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let J;function Y(){return J||=V(),J}function He(e){let t=e.toISOString().slice(0,10);return i(Y(),`${t}.jsonl`)}let Ue=0;function We(){let e=Date.now();if(!(e-Ue<36e5)){Ue=e;try{let t=Y(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of p(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(i(t,e))}catch{}}catch{}}}function Ge(e,t){try{f(Y(),{recursive:!0}),c(He(t),`${e}\n`),We()}catch{}}function Ke(e){G=e}function qe(){return G}function Je(e){q=e}function Ye(){J=void 0}function Xe(e){K=e}function Ze(e){if(e instanceof Error){let t={error:e.message};return K?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function Qe(e){return W.push(e),()=>{let t=W.indexOf(e);t>=0&&W.splice(t,1)}}function $e(e){function t(t,n,r){if(U[t]<U[G])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of W)try{i({level:t,component:e,message:n,data:r})}catch{}Ve()&&(t===`warn`||t===`error`)&&Ge(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const X={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function et(e,t={}){let{maxAttempts:n=X.maxAttempts,baseDelayMs:r=X.baseDelayMs,maxDelayMs:i=X.maxDelayMs,jitterFraction:a=X.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof D),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof D&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await tt(l)}throw s}function tt(e){return new Promise(t=>setTimeout(t,e))}let Z;function nt(){return Z===void 0&&(Z=y()),Z}function rt(){try{return process.cwd()}catch{return null}}function it(){return rt()??nt()}const at=[`indexed`,`curated`,`produced`],ot=[`source`,`documentation`,`test`,`config`,`generated`],st=[`auto`,`manual`,`smart`],ct=[`efficient`,`normal`,`full`],lt=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`],Q=$e(`core:version-manager`);function $(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function ut(e){let t=a(e),r=n(ie(import.meta.url)),i=process.cwd();return a(r).startsWith(t+o)||a(i).startsWith(t+o)||a(r)===t||a(i)===t}function dt(e,t){try{if(!d(e)||!t||t===`0.0.0`)return;let n=p(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort($),r=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)r.add(e);for(let t of n)if(!r.has(t)){let n=i(e,t);if(ut(n)){Q.debug(`Skipping ${t} — currently in use by running process`);continue}h(n,{recursive:!0,force:!0}),Q.debug(`Cleaned old version: ${t}`)}}catch(e){Q.debug(`Version directory cleanup failed`,{error:e})}}export{C as AIKIT_GLOBAL_PATHS,x as AIKIT_PATHS,S as AIKIT_RUNTIME_PATHS,E as AikitError,pe as CATEGORY_PATTERN,oe as CHUNK_SIZES,lt as CONTENT_TYPES,ae as CircuitBreaker,b as CircuitOpenError,Ce as ConfigError,me as DEFAULT_CATEGORIES,se as EMBEDDING_DEFAULTS,be as EmbeddingError,de as FILE_LIMITS,ze as HealthBus,st as INDEX_MODES,ue as INSTALL_ARGS,Se as IndexError,at as KNOWLEDGE_ORIGINS,H as LAYER_FIELD_REQUIREMENTS,ce as MODEL_REGISTRY,O as PermanentError,fe as SEARCH_DEFAULTS,ot as SOURCE_TYPES,le as STORE_DEFAULTS,xe as StoreError,ct as TOKEN_BUDGETS,D as TransientError,Qe as addLogListener,dt as cleanupOldVersions,$ as compareVersionDir,I as computePartitionKey,ve as contentTypeToSourceType,$e as createLogger,_e as detectContentType,P as getGlobalDataDir,qe as getLogLevel,B as getPartitionDir,M as getWorkspacePartitionDir,Me as hashPath,Te as isPermanent,we as isTransient,Re as isUserInstalled,Le as listWorkspaces,L as loadRegistry,Ie as lookupWorkspace,N as migrateLegacyWorkspaceLayout,F as normalizePathForHash,z as registerWorkspace,Ye as resetLogDir,V as resolveLogDir,je as resolveStateDir,rt as safeCwd,it as safeCwdOrHome,R as saveRegistry,Ze as serializeError,Xe as setDetailedErrorLoggingEnabled,Je as setFileSinkEnabled,Ke as setLogLevel,ye as sourceTypeContentTypes,Be as validateLayerMetadata,et as withRetry};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AnnotationInit=(()=>{var N=Object.defineProperty;var O=(
|
|
1
|
+
"use strict";var AnnotationInit=(()=>{var N=Object.defineProperty;var O=(d,t,e)=>t in d?N(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e;var s=(d,t,e)=>O(d,typeof t!="symbol"?t+"":t,e);var C=`
|
|
2
2
|
.action-bar {
|
|
3
3
|
flex-shrink: 0;
|
|
4
4
|
position: sticky;
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
.action-bar .bk-multi-select {
|
|
33
33
|
max-width: 10rem;
|
|
34
34
|
}
|
|
35
|
-
`;function b(
|
|
35
|
+
`;function b(d,t){if(document.getElementById(d))return;let e=document.createElement("style");e.id=d,e.textContent=t,document.head.appendChild(e)}var M=document.createElement("div");function g(d){return M.textContent=d,M.innerHTML}var H="aikit-annotation-popover",B=`
|
|
36
36
|
.cp-backdrop {
|
|
37
37
|
position: fixed;
|
|
38
38
|
top: 0;
|
|
@@ -130,7 +130,7 @@
|
|
|
130
130
|
.cp-btn--remove:hover {
|
|
131
131
|
background: var(--dt-annotation-deletion-bg);
|
|
132
132
|
}
|
|
133
|
-
`,v=class{constructor(t,e){
|
|
133
|
+
`,v=class{constructor(t,e){s(this,"el");s(this,"textarea");s(this,"result");s(this,"backdrop");s(this,"options");this.result=t,this.options=e,b(H,B),this.backdrop=document.createElement("div"),this.backdrop.className="cp-backdrop",this.el=document.createElement("div"),this.el.className="cp-popover",this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label","Feedback on selection"),this.el.innerHTML=`
|
|
134
134
|
<div class="cp-header">Feedback</div>
|
|
135
135
|
<div class="cp-excerpt">${this.escapeText(t.text)}</div>
|
|
136
136
|
<textarea class="cp-textarea" placeholder="Add a comment (optional)..." aria-label="Comment text"></textarea>
|
|
@@ -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
|
|
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
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}
|
|
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
|
|
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=`
|
|
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(
|
|
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=`
|
|
189
189
|
.as-sidebar {
|
|
190
190
|
width: var(--dt-annotation-sidebar-width, 300px);
|
|
191
191
|
background: var(--dt-bg-secondary);
|
|
@@ -367,7 +367,7 @@ ${n}
|
|
|
367
367
|
font-size: var(--dt-font-size-sm);
|
|
368
368
|
padding: var(--dt-space-6) var(--dt-space-2);
|
|
369
369
|
}
|
|
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){
|
|
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=`
|
|
371
371
|
<div class="as-header">
|
|
372
372
|
<span class="as-header-title">Annotations</span>
|
|
373
373
|
<span class="as-count-badge" aria-live="polite">${e.total}</span>
|
|
@@ -381,7 +381,7 @@ ${n}
|
|
|
381
381
|
${t.comment?`<div class="as-card-comment">${g(t.comment)}</div>`:""}
|
|
382
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
383
|
<button class="as-delete-btn" aria-label="Delete annotation">×</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
|
|
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=`
|
|
385
385
|
.as-guide {
|
|
386
386
|
margin: 0 0 var(--dt-space-3) 0;
|
|
387
387
|
padding: var(--dt-space-2) var(--dt-space-3);
|
|
@@ -398,7 +398,7 @@ ${n}
|
|
|
398
398
|
.as-guide--visible {
|
|
399
399
|
display: block;
|
|
400
400
|
}
|
|
401
|
-
`;function j(
|
|
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=`
|
|
402
402
|
.shell-layout {
|
|
403
403
|
flex: 1;
|
|
404
404
|
display: flex;
|
|
@@ -425,4 +425,4 @@ ${C}
|
|
|
425
425
|
.action-bar {
|
|
426
426
|
margin-top: auto;
|
|
427
427
|
}
|
|
428
|
-
`,document.head.appendChild(
|
|
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")}}});})();
|
|
@@ -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-
|
|
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-Dd2uCMBi.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-CtR4QNT3.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={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};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-
|
|
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={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};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-BaMUtb5Y.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-B5rk-PAI.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};
|