@vpxa/aikit 0.1.344 → 0.1.345
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/cli/dist/index.js +19 -19
- package/packages/cli/dist/{init-DgYgDXBw.js → init-XINdWZ5p.js} +1 -1
- package/packages/cli/dist/{templates-DEHhml1n.js → templates-Cjsh5cLs.js} +48 -16
- package/packages/core/dist/index.d.ts +269 -2
- package/packages/core/dist/index.js +1 -1
- package/packages/flows/dist/index.d.ts +141 -4
- package/packages/flows/dist/index.js +6 -6
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/config-BsS-77rp.js +2 -0
- package/packages/server/dist/config-Ds28Hvip.js +1 -0
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/prelude-DYBTvrwz.js +2 -0
- package/packages/server/dist/prelude-V2gaMyeg.js +1 -0
- package/packages/server/dist/promotion-DRnRfteq.js +3 -0
- package/packages/server/dist/promotion-DzVLWVtx.js +2 -0
- package/packages/server/dist/sampling-0YAQqixD.js +1 -0
- package/packages/server/dist/sampling-BQmYJ4pz.js +2 -0
- package/packages/server/dist/{server-qVK37TfU.js → server--QWu4dF1.js} +171 -169
- package/packages/server/dist/{server-2ntNwLtr.js → server-Cv8aM3Xx.js} +170 -170
- package/packages/server/dist/{server-http-BwaQWT2R.js → server-http-BF6fnIQ0.js} +1 -1
- package/packages/server/dist/{server-http-BXF275jD.js → server-http-DoIPqaqk.js} +1 -1
- package/packages/server/dist/{server-stdio-DVjY0Ebj.js → server-stdio-CFH9BET5.js} +1 -1
- package/packages/server/dist/{server-stdio-By2Kx_7Y.js → server-stdio-CXF39-d2.js} +1 -1
- package/packages/server/dist/{startup-maintenance-L9NUOBVy.js → startup-maintenance-CBJWiJ7p.js} +1 -1
- package/packages/server/dist/{startup-maintenance-DYmXBVTV.js → startup-maintenance-DX1yTfBa.js} +1 -1
- package/packages/server/dist/version-check-BjFqR01r.js +1 -0
- package/packages/server/dist/version-check-_2wmedTl.js +2 -0
- package/packages/tools/dist/index.d.ts +140 -1
- package/packages/tools/dist/index.js +87 -82
- package/scaffold/dist/adapters/_shared.mjs +9 -9
- package/scaffold/dist/definitions/agents.mjs +2 -2
- package/scaffold/dist/definitions/bodies.mjs +22 -13
- package/scaffold/dist/definitions/flows.mjs +28 -12
- package/scaffold/dist/definitions/protocols.mjs +38 -8
- package/scaffold/dist/definitions/skills/aikit.mjs +80 -17
- package/scaffold/dist/definitions/skills/docs.mjs +9 -0
- package/scaffold/dist/definitions/skills/lesson-learned.mjs +9 -0
- package/scaffold/dist/definitions/skills/multi-agents-development.mjs +10 -5
- package/packages/server/dist/config-B-wvmMyo.js +0 -1
- package/packages/server/dist/config-Bx85fwRX.js +0 -2
- package/packages/server/dist/prelude-DOxnDMN4.js +0 -2
- package/packages/server/dist/prelude-Dzih_AGV.js +0 -1
- package/packages/server/dist/promotion-RbjKfC88.js +0 -3
- package/packages/server/dist/promotion-l1L8Vf7U.js +0 -2
- package/packages/server/dist/version-check-2-tfmCnt.js +0 -2
- package/packages/server/dist/version-check-BKtLrLhw.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BNPHP-QC.js";import{a as o,i as s,m as c,n as l,o as u,r as d,t as f}from"./templates-
|
|
1
|
+
import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BNPHP-QC.js";import{a as o,i as s,m as c,n as l,o as u,r as d,t as f}from"./templates-Cjsh5cLs.js";import{appendFileSync as p,existsSync as m,mkdirSync as h,readFileSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as y,resolve as b}from"node:path";import{AIKIT_PATHS as x,EMBEDDING_DEFAULTS as S,isUserInstalled as C}from"../../core/dist/index.js";function w(e){return m(b(e,`.cursor`))?`cursor`:m(b(e,`.claude`))?`claude-code`:m(b(e,`.windsurf`))?`windsurf`:m(b(e,`.zed`))?`zed`:m(b(e,`.idea`))?`intellij`:m(b(e,`.opencode`))?`opencode`:m(b(e,`AGENTS.md`))?`hermes`:`copilot`}function T(e){let t=[];return m(b(e,`.cursor`))&&t.push(`cursor`),(m(b(e,`.claude`))||m(b(e,`CLAUDE.md`)))&&t.push(`claude-code`),m(b(e,`.windsurf`))&&t.push(`windsurf`),m(b(e,`.zed`))&&t.push(`zed`),m(b(e,`.idea`))&&t.push(`intellij`),m(b(e,`.gemini`))&&t.push(`gemini-cli`),(m(b(e,`.codex`))||m(b(e,`codex.md`)))&&t.push(`codex-cli`),(m(b(e,`.opencode`))||m(b(e,`OPENCODE.md`)))&&t.push(`opencode`),t.push(`copilot`),t.push(`hermes`),[...new Set(t)]}function E(e){return{servers:{[e]:{...s}}}}function D(e){let{type:t,...n}=s;return{mcpServers:{[e]:n}}}function O(e){let{type:t,...n}=s;return{context_servers:{[e]:{...n}}}}function k(e){let{type:t,...n}=s;return{mcp:{[e]:{type:`local`,command:[n.command,...n.args]}}}}const A={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=b(e,`.github`),r=b(n,`copilot-instructions.md`);h(n,{recursive:!0}),v(r,l(y(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){v(b(e,`AGENTS.md`),f(y(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},j={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=b(e,`CLAUDE.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},M={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.cursor`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=b(e,`.cursor`,`rules`),r=b(n,`aikit.mdc`);h(n,{recursive:!0});let i=y(e);v(r,`${l(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=b(n,`kb.mdc`);m(a)&&a!==r&&(_(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=b(e,`.windsurfrules`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.zed`),r=b(n,`settings.json`);if(h(n,{recursive:!0}),!m(r))v(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(g(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,...O(t).context_servers},v(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=b(e,`.rules`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},F={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=b(e,`.aiassistant`,`rules`),r=b(n,`aikit.md`);h(n,{recursive:!0});let i=y(e);v(r,`${l(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}},I={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.opencode`),r=b(n,`opencode.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .opencode/opencode.json`))},writeInstructions(e,t){let n=b(e,`OPENCODE.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated OPENCODE.md`)},writeAgentsMd(e,t){}},L={scaffoldDir:`general`,writeMcpConfig(e,t){},writeInstructions(e,t){let n=b(e,`AGENTS.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated AGENTS.md (Hermes)`)},writeAgentsMd(e,t){}};function R(e){switch(e){case`copilot`:return A;case`claude-code`:return j;case`cursor`:return M;case`windsurf`:return N;case`zed`:return P;case`intellij`:return F;case`opencode`:return I;case`hermes`:return L;case`gemini-cli`:case`codex-cli`:return A}}const z={serverName:o,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${x.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:S.model,dimensions:S.dimensions},store:{backend:`sqlite-vec`,path:x.data},curated:{path:x.aiCurated}};function B(e,t){let n=b(e,`aikit.config.json`);return m(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(v(n,`${JSON.stringify(z,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function V(e){let t=b(e,`.gitignore`),n=[{dir:`.flows/`,label:`AI Kit flow runs`}];if(m(t)){let e=g(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(p(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
|
|
2
2
|
`)}\n`,`utf-8`),console.log(` Added ${r.map(e=>e.dir).join(`, `)} to .gitignore`))}else v(t,`${n.map(e=>`# ${e.label}\n${e.dir}`).join(`
|
|
3
3
|
`)}\n`,`utf-8`),console.log(` Created .gitignore with AI Kit entries`)}function H(){return z.serverName}const U=[`decisions`,`patterns`,`conventions`,`troubleshooting`];function W(e){let t=b(e,`.ai`,`curated`);m(t)||(h(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of U){let n=b(t,e);m(n)||h(n,{recursive:!0})}console.log(` Created .ai/curated/{${U.join(`,`)}}/`)}function G(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 K(n){let i=process.cwd();if(!B(i,n.force))return;V(i);let a=H(),o=R(w(i));o.writeMcpConfig(i,a),o.writeInstructions(i,a),o.writeAgentsMd(i,a);let s=c(),l=JSON.parse(g(b(s,`package.json`),`utf-8`)).version;await t(i,s,[...u],l,n.force),await r(i,s,[...d],l,n.force);let f=T(i),p=new Set;for(let t of f){let r=G(t);p.has(r)||(p.add(r),await e(i,s,r,l,n.force))}W(i),console.log(`
|
|
4
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`),C()&&console.log(`
|
|
@@ -1,9 +1,9 @@
|
|
|
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}from"../../core/dist/index.js";import{createSqliteAdapter 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}from"../../core/dist/index.js";import{createSqliteAdapter as ee,createStateStore as te}from"../../store/dist/index.js";import{mkdir as o}from"node:fs/promises";var s=class extends Error{exitCode;constructor(e,t=1){super(e),this.exitCode=t,this.name=`CliError`}};function c(e){let t=e.indexOf(`--json`);return t===-1?!1:(e.splice(t,1),!0)}function l(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 ne(e=process.cwd()){let t=a(r(e));return await o(t,{recursive:!0}),te(await ee(r(t,`state.db`)))}function u(){let t=e(import.meta.url);try{return t.resolve(`@vpxa/aikit/package.json`)}catch{return r(i(import.meta.url),`..`,`..`,`..`,`..`,`package.json`)}}function d(){return n(u())}function re(){try{return JSON.parse(t(u(),`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function ie(){let t=e(import.meta.url);try{return r(n(t.resolve(`@aikit/server`)),`bin.js`)}catch{return r(d(),`packages`,`server`,`dist`,`bin.js`)}}function ae(e){let t=`--disable-warning=ExperimentalWarning`;return e?e.includes(`ExperimentalWarning`)?e:`${e} ${t}`:t}function f(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 p(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function m(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function h(){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 g(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function _(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function v(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 y(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),b(`tsc`,e.tsc.passed,e.tsc.errors),b(`biome`,e.biome.passed,e.biome.errors)}function b(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 x(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 S(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 C(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 w(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 T(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 E(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 D(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
|
|
6
|
-
`)}function
|
|
4
|
+
Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function O(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),M(`Imports`,e.imports),M(`Exports`,e.exports),M(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),M(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),M(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),M(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function k(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 A(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 j(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 M(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 N(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function P(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 F(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 oe=[`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(`;`),I=`aikit`,L={type:`stdio`,command:`node`,args:[`-e`,oe]},R=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],z=[`aikit-basic`,`aikit-advanced`,`_epilogue`],B={"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}},V=[{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 H(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 U=V.map(H);function W(){return[`| NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |`,`|---|---|---|`,...U.filter(e=>e.severity===`error`).map(e=>`| \`${e.forbidden}\` | \`${e.alternative}\` | ${e.reason} |`)].join(`
|
|
6
|
+
`)}function G(e){return`
|
|
7
7
|
## Flow Context Bootstrap
|
|
8
8
|
|
|
9
9
|
When dispatched as a subagent within an active flow:
|
|
@@ -22,17 +22,47 @@ When dispatched as a subagent within an active flow:
|
|
|
22
22
|
|
|
23
23
|
${e===`<PROFILE>`?`**Profile:** Check your role → implementer | documenter | reviewer | researcher | debugger`:`**Profile:** \`${e}\``}
|
|
24
24
|
|
|
25
|
-
---`}function
|
|
26
|
-
|
|
27
|
-
`)}const
|
|
28
|
-
|
|
25
|
+
---`}function K(){return"\n## Evidence Citation Protocol (tier-aware)\n\nNo FORGE `task_id` → skip `evidence_map`; use `file:line` citations only.\nDo not create your own `task_id` or run the gate.\n\n| Tier | Your responsibility |\n|------|---------------------|\n| Floor | Findings with `file.ts#Lxx` citations. No `evidence_map`. |\n| Standard | Add 2-4 CRITICAL/HIGH findings with receipts. |\n| Critical | Add all CRITICAL/HIGH findings; tag contract/security claims with `safety_gate`. |\n\n**Every response MUST include:**\n- `**FORGE Task ID:** <task_id>` (passed in by Orchestrator, or state \"not provided\")\n- `**Tier applied:** Floor | Standard | Critical`\n- `**Findings:** <list>` with `file:line` receipts\n- Verdict: `APPROVED` | `CHANGES_REQUESTED` | `BLOCKED`\n\nDo NOT create a new `evidence_map`, run `evidence_map({action:'gate'})`, or add non-critical noise."}function q(...e){return e.filter(Boolean).join(`
|
|
26
|
+
|
|
27
|
+
`)}const se=Object.freeze({version:1,l0MemoriesDir:`memories`,sessionStart:{requiredCards:[`workspace-core`],maxAdditionalCards:1,activeFlowPreference:`workflow-card`,totalTokenBudget:2100},retrievalOrder:[`l0`,`l1`,`l2-on-demand`,`l3-evidence-only`],noFlowFallback:`l0-plus-l2-with-turn-local-context`,degradedFallback:`prelude-manifest-canonical-markdown`,lifecycleAuthority:`opaque-owner-capability`,autoKnowledgeMode:`observer-only`,l0Budgets:Object.freeze({"workspace-core":{min:800,max:1200},architecture:{min:600,max:900},"testing-release":{min:600,max:900},"known-issues":{min:400,max:700},"workflow:*":{min:500,max:900}})});function J(e={}){let{audience:t=`agent`}=e,n=se,r=`## Layered Knowledge Protocol (v${n.version})
|
|
28
|
+
|
|
29
|
+
AI Kit delivers knowledge through four layers:
|
|
30
|
+
|
|
31
|
+
- **L0 — Generated Briefing Cards**: Fast, task-ready workspace setup. \`workspace-core\` auto-injected via \`status({ includePrelude: true })\`. If a flow is active, \`workflow:<flow>\` loaded via flow context (replaces task card). Total budget: ${n.sessionStart.totalTokenBudget} tokens.
|
|
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
|
+
- **L2 — Canonical Curated Knowledge**: Durable workspace archive managed by CuratedKnowledgeManager. Retrieve on demand via \`search()\` or \`knowledge({ action: 'read' })\`.
|
|
34
|
+
- **L3 — Evidence Archive**: Auto-knowledge observations and tool-output evidence. Inspect only for provenance, conflict review, or promotion assessment. Never auto-injected.
|
|
35
|
+
|
|
36
|
+
### Hot Path
|
|
37
|
+
1. Session start → \`status({ includePrelude: true })\` auto-injects \`workspace-core\`. If flow active, \`workflow:<flow>\` loaded via flow context. If no flow, may add one task card via \`stratum_card\`.
|
|
38
|
+
2. Active flow → use L1 snapshot + dispatch refs before broad retrieval.
|
|
39
|
+
3. Retrieve L2 on demand.
|
|
40
|
+
4. Inspect L3 only for evidence, provenance, or promotion.
|
|
41
|
+
|
|
42
|
+
### No-Flow Fallback
|
|
43
|
+
- Keep L1 absent; workspace-core auto-injected via status; optionally one task card.
|
|
44
|
+
- L2 on demand; turn-local scratch, no L1 synthesis.
|
|
45
|
+
|
|
46
|
+
### Degraded Fallback
|
|
47
|
+
- Missing L0 card → deterministic regeneration → status prelude + context manifest.
|
|
48
|
+
- Unavailable L1 → read persisted FlowRunMeta without mutation.
|
|
49
|
+
- Unavailable indexed L2 → read canonical curated markdown directly.
|
|
50
|
+
- Mark missing evidence unresolved; block promotion.
|
|
51
|
+
`;return t===`skill`?r+`
|
|
52
|
+
### Skill Routing
|
|
53
|
+
- Load L0 card families listed in \`LAYERED_KNOWLEDGE_OPERATING_POLICY.l0Budgets\`.
|
|
54
|
+
- Route L1 withdrawal by configured profile; never promote.
|
|
55
|
+
- Emit L3 evidence as observer-only; never navigate flow state.`:t===`flow`?r+`
|
|
56
|
+
### Step Contracts
|
|
57
|
+
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 ce=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 | `compact({ path, query })` | `read_file` to search |\n| Multiple files | `digest({ sources, query })` | Multiple `read_file` calls |\n| Reuse previous output | `compact({ 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) | `stratum_card`, `file_summary`, `compact` | 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 le=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()}${W()}${K()}`,`${G(`researcher`)}${Y()}`,`${G(`reviewer`)}${Y()}`,`${G(`reviewer`)}${Y()}`,J({audience:`agent`});const ue=/{\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(d(),`scaffold`,`definitions`,`exclusions.mjs`),n=t(e,`utf8`),i=Array.from(n.matchAll(ue),([,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 de(){return`## Permanent Exclusions
|
|
29
59
|
|
|
30
60
|
These capabilities are intentionally NOT provided by aikit. Each decision follows the Bitter Lesson: leverage computation and configurable tools over hand-crafted features.
|
|
31
61
|
|
|
32
62
|
| Capability | Rationale |
|
|
33
63
|
|-----------|-----------|
|
|
34
|
-
${
|
|
35
|
-
`)}`}function
|
|
64
|
+
${Q().map(({name:e,rationale:t})=>`| ${$(e)} | ${$(t)} |`).join(`
|
|
65
|
+
`)}`}function fe(e,t){return`# ${e} — Copilot Instructions
|
|
36
66
|
|
|
37
67
|
This project has an MCP server (\`${t}\`) providing 64 tools for search, analysis, memory, and validation.
|
|
38
68
|
**These tools REPLACE most native IDE tools.** You MUST use them.
|
|
@@ -79,6 +109,8 @@ Do NOT attempt complex multi-file tasks in the default agent mode. The Orchestra
|
|
|
79
109
|
**\`read_file\` is ONLY acceptable when you need exact line content FOR EDITING (before \`replace_string_in_file\`).**
|
|
80
110
|
Even then, use \`file_summary\` first to identify which lines to read.
|
|
81
111
|
|
|
112
|
+
${J({audience:`agent`})}
|
|
113
|
+
|
|
82
114
|
## Core Rules
|
|
83
115
|
|
|
84
116
|
1. **Recall before acting** — \`search({ query })\` for past decisions/conventions about the area you're changing. If a prior decision exists, **follow it** — don't silently override. Then \`scope_map({ task })\` for a reading plan.
|
|
@@ -87,7 +119,7 @@ Even then, use \`file_summary\` first to identify which lines to read.
|
|
|
87
119
|
4. **Validate** — \`check({})\` + \`test_run({})\` before presenting changes. \`blast_radius({ changed_files })\` for impact.
|
|
88
120
|
5. **Lifecycle** — Check \`status({})\` first. If onboard not run, run \`onboard({ path: "." })\`. After implementation, \`reindex({})\` + \`produce_knowledge({})\`. At session end, \`remember()\` checkpoint.
|
|
89
121
|
|
|
90
|
-
${
|
|
122
|
+
${de()}
|
|
91
123
|
|
|
92
124
|
## User Interaction Rules
|
|
93
125
|
|
|
@@ -105,7 +137,7 @@ When you need to explain something or ask for user input:
|
|
|
105
137
|
- Free-form text input always goes through elicitation, even when using \`present\` for the explanation
|
|
106
138
|
- Prefer the simplest method that adequately conveys the information
|
|
107
139
|
|
|
108
|
-
${
|
|
140
|
+
${ce}
|
|
109
141
|
|
|
110
142
|
## Communication Style
|
|
111
143
|
|
|
@@ -179,8 +211,8 @@ knowledge({ action: "remember", title: "Session checkpoint: <topic>", content:
|
|
|
179
211
|
search({ query: "SESSION CHECKPOINT", origin: "curated" })
|
|
180
212
|
\`\`\`
|
|
181
213
|
|
|
182
|
-
${
|
|
183
|
-
`}function
|
|
214
|
+
${le}
|
|
215
|
+
`}function pe(e,t){return`# ${e} — Agent Instructions
|
|
184
216
|
|
|
185
217
|
## AI Kit MCP Server (\`${t}\`)
|
|
186
218
|
|
|
@@ -296,4 +328,4 @@ Both ReactFlow viewers include an **AI Kit** attribution badge (bottom-right). A
|
|
|
296
328
|
## Full Documentation
|
|
297
329
|
|
|
298
330
|
For complete tool documentation (62 tools), workflow chains, search strategies, session protocol, and persistent memory patterns, load the \`aikit\` skill at session start.
|
|
299
|
-
`}export{
|
|
331
|
+
`}export{x as A,T as C,E as D,l as E,F,g as I,ae as L,A as M,h as N,v as O,ie as P,C as S,S as T,N as _,I as a,j as b,s as c,f as d,p as f,c as g,re as h,L as i,w as j,k,ne as l,d as m,fe as n,R as o,_ as p,z as r,B as s,pe as t,m as u,P as v,O as w,D as x,y};
|
|
@@ -118,7 +118,8 @@ declare const AIKIT_RUNTIME_PATHS: {
|
|
|
118
118
|
readonly state: "state"; /** Restore points for destructive operations */
|
|
119
119
|
readonly restorePoints: "restore-points"; /** Brainstorming sessions */
|
|
120
120
|
readonly brainstorm: "brainstorm"; /** Session handoff documents */
|
|
121
|
-
readonly handoffs: "handoffs";
|
|
121
|
+
readonly handoffs: "handoffs"; /** L0 generated briefing cards (workspace memories) */
|
|
122
|
+
readonly l0Cards: "memories";
|
|
122
123
|
};
|
|
123
124
|
/**
|
|
124
125
|
* Global-mode directory paths (under ~/.aikit/).
|
|
@@ -393,6 +394,19 @@ interface AikitConfig {
|
|
|
393
394
|
onboardDir?: string;
|
|
394
395
|
/** Resolved state directory path. User-level mode redirects this to the partition. Defaults to `.aikit/state` in workspace root. */
|
|
395
396
|
stateDir?: string;
|
|
397
|
+
/**
|
|
398
|
+
* L0 generated briefing card storage directory (relative to workspace partition root).
|
|
399
|
+
* Cards live under ~/.aikit/workspaces/<partition>/<l0CardDir>/.
|
|
400
|
+
* Defaults to AIKIT_RUNTIME_PATHS.l0Cards ('memories').
|
|
401
|
+
*/
|
|
402
|
+
l0CardDir?: string;
|
|
403
|
+
/**
|
|
404
|
+
* Layered knowledge lifecycle feature flag.
|
|
405
|
+
* - undefined or false: legacy mode (no capability enforcement, no backtrack/claim)
|
|
406
|
+
* - true: capability-required mutations, backtrack, claim enabled
|
|
407
|
+
* @default undefined (disabled)
|
|
408
|
+
*/
|
|
409
|
+
layeredKnowledge?: boolean;
|
|
396
410
|
/**
|
|
397
411
|
* All workspace roots provided by the MCP client (IDE).
|
|
398
412
|
* In multi-root workspaces this contains every folder.
|
|
@@ -645,6 +659,235 @@ declare class HealthBus extends EventEmitter {
|
|
|
645
659
|
private transition;
|
|
646
660
|
}
|
|
647
661
|
//#endregion
|
|
662
|
+
//#region packages/core/src/layered-knowledge-contract.d.ts
|
|
663
|
+
/**
|
|
664
|
+
* Layered Knowledge Delivery — Core Metadata Contract
|
|
665
|
+
*
|
|
666
|
+
* This module defines the versioned metadata contracts for L0-L3 knowledge layers.
|
|
667
|
+
* It is the single authoritative source for layer types, shapes, and field requirements.
|
|
668
|
+
* All other packages (server, flows, tools, scaffold) import from here; no competing
|
|
669
|
+
* local schemas are permitted for the same concepts.
|
|
670
|
+
*
|
|
671
|
+
* L0 card storage path is configured in AIKIT_RUNTIME_PATHS.l0Cards (constants.ts)
|
|
672
|
+
* and resolved at runtime by server config. Scaffold instructions reference the
|
|
673
|
+
* stratum_card / compact / status tools — NOT a hardcoded path.
|
|
674
|
+
*
|
|
675
|
+
* @module
|
|
676
|
+
*/
|
|
677
|
+
type KnowledgeLayerId = 'l0' | 'l1' | 'l2' | 'l3';
|
|
678
|
+
/**
|
|
679
|
+
* Shared metadata fields carried by all L0-L3 entries.
|
|
680
|
+
*/
|
|
681
|
+
interface LayeredKnowledgeBaseV1 {
|
|
682
|
+
schemaVersion: 1;
|
|
683
|
+
layer: KnowledgeLayerId;
|
|
684
|
+
workspaceId: string;
|
|
685
|
+
kind: string;
|
|
686
|
+
source: {
|
|
687
|
+
kind: 'tool' | 'document' | 'flow' | 'evidence';
|
|
688
|
+
ref: string;
|
|
689
|
+
};
|
|
690
|
+
createdAt: string;
|
|
691
|
+
updatedAt?: string;
|
|
692
|
+
topicKey?: string;
|
|
693
|
+
tags?: string[];
|
|
694
|
+
evidenceRefs?: string[];
|
|
695
|
+
freshness?: {
|
|
696
|
+
observedAt?: string;
|
|
697
|
+
ttlMs?: number;
|
|
698
|
+
supersededBy?: string | null;
|
|
699
|
+
};
|
|
700
|
+
quality?: {
|
|
701
|
+
confidence?: number;
|
|
702
|
+
impact?: 'low' | 'medium' | 'high';
|
|
703
|
+
actionability?: 'low' | 'medium' | 'high';
|
|
704
|
+
recurrence?: number;
|
|
705
|
+
sourceDiversity?: number;
|
|
706
|
+
};
|
|
707
|
+
promotionState?: 'candidate' | 'held' | 'promoted' | 'rejected' | 'superseded';
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Card families for L0 generated briefing cards.
|
|
711
|
+
*/
|
|
712
|
+
type BriefingCardType = 'workspace-core' | 'architecture' | 'testing-release' | 'known-issues' | `workflow:${string}`;
|
|
713
|
+
/**
|
|
714
|
+
* L0 card metadata. Cards are generated workspace caches under
|
|
715
|
+
* ~/.aikit/workspaces/<ws>/memories/ and never become canonical.
|
|
716
|
+
*/
|
|
717
|
+
interface BriefingCardMetadataV1 extends LayeredKnowledgeBaseV1 {
|
|
718
|
+
layer: 'l0';
|
|
719
|
+
cardType: BriefingCardType;
|
|
720
|
+
tokenBudget: number;
|
|
721
|
+
selectionReason: string;
|
|
722
|
+
referenceRefs?: string[];
|
|
723
|
+
}
|
|
724
|
+
type FlowContextProfileName = 'implementer' | 'documenter' | 'reviewer' | 'researcher' | 'debugger';
|
|
725
|
+
/**
|
|
726
|
+
* Read-only snapshot of active flow run state for the prelude and context manifest.
|
|
727
|
+
*/
|
|
728
|
+
interface FlowContextSnapshotV1 {
|
|
729
|
+
schemaVersion: 1;
|
|
730
|
+
flowSlug: string;
|
|
731
|
+
runId: string;
|
|
732
|
+
stepId: string | null;
|
|
733
|
+
stepIndex: number;
|
|
734
|
+
stepOrder: string[];
|
|
735
|
+
objective: string;
|
|
736
|
+
acceptanceCriteria: string[];
|
|
737
|
+
scope: string[];
|
|
738
|
+
exclusions: string[];
|
|
739
|
+
retrievedRefs: string[];
|
|
740
|
+
verifiedClaims: string[];
|
|
741
|
+
assumedClaims: string[];
|
|
742
|
+
unresolvedClaims: string[];
|
|
743
|
+
decisions: Array<{
|
|
744
|
+
id: string;
|
|
745
|
+
summary: string;
|
|
746
|
+
rationale: string;
|
|
747
|
+
}>;
|
|
748
|
+
artifacts: Array<{
|
|
749
|
+
name: string;
|
|
750
|
+
path: string;
|
|
751
|
+
status: 'draft' | 'final' | 'blocked';
|
|
752
|
+
}>;
|
|
753
|
+
stepSummaries: Array<{
|
|
754
|
+
stepId: string;
|
|
755
|
+
summary: string;
|
|
756
|
+
outcome: 'done' | 'skipped' | 'blocked';
|
|
757
|
+
}>;
|
|
758
|
+
failures: string[];
|
|
759
|
+
successPatterns: string[];
|
|
760
|
+
candidateLearnings: string[];
|
|
761
|
+
verifiedFinalOutcome: string | null;
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Atomic context update submitted by the capability holder during a step transition.
|
|
765
|
+
*/
|
|
766
|
+
interface FlowContextUpdateV1 {
|
|
767
|
+
schemaVersion: 1;
|
|
768
|
+
stepId: string;
|
|
769
|
+
summary?: string;
|
|
770
|
+
retrievedRefs?: string[];
|
|
771
|
+
verifiedClaims?: Array<{
|
|
772
|
+
claim: string;
|
|
773
|
+
evidenceRefs: string[];
|
|
774
|
+
}>;
|
|
775
|
+
assumedClaims?: string[];
|
|
776
|
+
unresolvedClaims?: string[];
|
|
777
|
+
decisions?: Array<{
|
|
778
|
+
id: string;
|
|
779
|
+
summary: string;
|
|
780
|
+
rationale: string;
|
|
781
|
+
}>;
|
|
782
|
+
artifacts?: Array<{
|
|
783
|
+
name: string;
|
|
784
|
+
path: string;
|
|
785
|
+
status: 'draft' | 'final' | 'blocked';
|
|
786
|
+
}>;
|
|
787
|
+
failures?: string[];
|
|
788
|
+
successPatterns?: string[];
|
|
789
|
+
candidateLearnings?: Array<{
|
|
790
|
+
topicKey: string;
|
|
791
|
+
lesson: string;
|
|
792
|
+
impact: 'low' | 'medium' | 'high';
|
|
793
|
+
evidenceRefs: string[];
|
|
794
|
+
}>;
|
|
795
|
+
verifiedFinalOutcome?: string;
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* L1 flow context metadata. Attached to the active run, not to canonical storage.
|
|
799
|
+
*/
|
|
800
|
+
interface FlowContextMetadataV1 extends LayeredKnowledgeBaseV1 {
|
|
801
|
+
layer: 'l1';
|
|
802
|
+
flowSlug: string;
|
|
803
|
+
runId: string;
|
|
804
|
+
stepId: string | null;
|
|
805
|
+
stepIndex: number;
|
|
806
|
+
objective: string;
|
|
807
|
+
acceptanceCriteria: string[];
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* L2 canonical curated knowledge metadata.
|
|
811
|
+
* Managed by CuratedKnowledgeManager; markdown is the sole canonical form.
|
|
812
|
+
*/
|
|
813
|
+
interface CuratedKnowledgeMetadataV1 extends LayeredKnowledgeBaseV1 {
|
|
814
|
+
layer: 'l2';
|
|
815
|
+
topicKey: string;
|
|
816
|
+
curatedMarkdownPath: string;
|
|
817
|
+
managedBy: 'CuratedKnowledgeManager';
|
|
818
|
+
promotionState: 'candidate' | 'held' | 'promoted' | 'rejected' | 'superseded';
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* L3 evidence and auto-knowledge metadata.
|
|
822
|
+
* Non-authoritative; supports promotion evaluation and review.
|
|
823
|
+
*/
|
|
824
|
+
interface EvidenceMetadataV1 extends LayeredKnowledgeBaseV1 {
|
|
825
|
+
layer: 'l3';
|
|
826
|
+
evidenceRefs: string[];
|
|
827
|
+
quality: NonNullable<LayeredKnowledgeBaseV1['quality']>;
|
|
828
|
+
}
|
|
829
|
+
type LayeredKnowledgeContractV1 = BriefingCardMetadataV1 | FlowContextMetadataV1 | CuratedKnowledgeMetadataV1 | EvidenceMetadataV1;
|
|
830
|
+
/**
|
|
831
|
+
* Declares which L0/L1/L2/L3 surfaces a built-in flow step consumes and produces.
|
|
832
|
+
*/
|
|
833
|
+
interface FlowStepKnowledgeContractV1 {
|
|
834
|
+
schemaVersion: 1;
|
|
835
|
+
contextProfile: FlowContextProfileName;
|
|
836
|
+
consumerProfiles?: Partial<Record<string, FlowContextProfileName>>;
|
|
837
|
+
inputs: {
|
|
838
|
+
l0CardTypes: BriefingCardType[];
|
|
839
|
+
l1Fields: Array<keyof FlowContextSnapshotV1>;
|
|
840
|
+
l2Refs: 'none' | 'on-demand' | 'required';
|
|
841
|
+
l3Evidence: 'none' | 'on-demand' | 'required';
|
|
842
|
+
};
|
|
843
|
+
updates: Array<keyof FlowContextUpdateV1>;
|
|
844
|
+
candidateLearnings: string[];
|
|
845
|
+
handoff: {
|
|
846
|
+
artifact: string;
|
|
847
|
+
requiredSnapshotFields: Array<keyof FlowContextSnapshotV1>;
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
interface FlowLifecycleMutationV1 {
|
|
851
|
+
schemaVersion: 1;
|
|
852
|
+
lifecycleOwnerToken: string;
|
|
853
|
+
currentToken: string;
|
|
854
|
+
contextUpdate?: FlowContextUpdateV1;
|
|
855
|
+
}
|
|
856
|
+
interface FlowBacktrackV1 extends FlowLifecycleMutationV1 {
|
|
857
|
+
targetStep: string;
|
|
858
|
+
}
|
|
859
|
+
interface FlowOwnerClaimV1 {
|
|
860
|
+
schemaVersion: 1;
|
|
861
|
+
currentToken: string;
|
|
862
|
+
}
|
|
863
|
+
interface FlowLifecycleAuditRecordV1 {
|
|
864
|
+
schemaVersion: 1;
|
|
865
|
+
event: 'claim' | 'backtrack' | 'reset' | 'final-consolidation';
|
|
866
|
+
at: string;
|
|
867
|
+
ownerTokenVersion: number;
|
|
868
|
+
targetStep?: string;
|
|
869
|
+
invalidatedExecutionTokens?: string[];
|
|
870
|
+
reason?: string;
|
|
871
|
+
}
|
|
872
|
+
/** Criteria for validating a layer metadata record. */
|
|
873
|
+
interface LayerValidationResult {
|
|
874
|
+
valid: boolean;
|
|
875
|
+
missingRequired: string[];
|
|
876
|
+
extraFields: string[];
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* Validate that a metadata record satisfies the required fields for its layer.
|
|
880
|
+
* This enforces the layer field requirements defined in LAYER_FIELD_REQUIREMENTS.
|
|
881
|
+
*/
|
|
882
|
+
declare function validateLayerMetadata(layer: KnowledgeLayerId, record: Record<string, unknown>): LayerValidationResult;
|
|
883
|
+
/**
|
|
884
|
+
* Required and optional field sets per layer.
|
|
885
|
+
*/
|
|
886
|
+
declare const LAYER_FIELD_REQUIREMENTS: Record<KnowledgeLayerId, {
|
|
887
|
+
required: string[];
|
|
888
|
+
optional: string[];
|
|
889
|
+
}>;
|
|
890
|
+
//#endregion
|
|
648
891
|
//#region packages/core/src/logger.d.ts
|
|
649
892
|
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
650
893
|
type LogListener = (entry: {
|
|
@@ -699,4 +942,28 @@ interface RetryOptions {
|
|
|
699
942
|
*/
|
|
700
943
|
declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
701
944
|
//#endregion
|
|
702
|
-
|
|
945
|
+
//#region packages/core/src/version-manager.d.ts
|
|
946
|
+
/**
|
|
947
|
+
* Shared version directory management for managed AI Kit installations.
|
|
948
|
+
*
|
|
949
|
+
* Both the CLI install command and the server's background auto-update
|
|
950
|
+
* operate on the same `~/.aikit/versions/v{version}` layout. This module
|
|
951
|
+
* provides a single source of truth for cleanup and sorting.
|
|
952
|
+
*/
|
|
953
|
+
/**
|
|
954
|
+
* Compare two `vX.Y.Z` strings for descending sort (newest first).
|
|
955
|
+
* Uses numeric compare instead of lexicographic to handle
|
|
956
|
+
* varying digit counts (e.g., v0.1.9 vs v0.1.10).
|
|
957
|
+
*/
|
|
958
|
+
declare function compareVersionDir(a: string, b: string): number;
|
|
959
|
+
/**
|
|
960
|
+
* Remove old version directories from `versionsDir`, keeping the specified
|
|
961
|
+
* version + 1 backup (the next newest). Best-effort — never throws.
|
|
962
|
+
*
|
|
963
|
+
* @param versionsDir Path to `~/.aikit/versions/` (or equivalent)
|
|
964
|
+
* @param keepVersion Raw semver string (no `v` prefix) to preserve.
|
|
965
|
+
* If omitted or `"0.0.0"`, cleanup is skipped.
|
|
966
|
+
*/
|
|
967
|
+
declare function cleanupOldVersions(versionsDir: string, keepVersion?: string): void;
|
|
968
|
+
//#endregion
|
|
969
|
+
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, isPermanent, isTransient, isUserInstalled, listWorkspaces, loadRegistry, lookupWorkspace, migrateLegacyWorkspaceLayout, registerWorkspace, resetLogDir, resolveLogDir, resolveStateDir, saveRegistry, serializeError, setDetailedErrorLoggingEnabled, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes, validateLayerMetadata, withRetry };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventEmitter as e}from"node:events";import{basename as t,extname as n,join as r,resolve as i}from"node:path";import{createHash as a}from"node:crypto";import{appendFileSync as o,closeSync as s,constants as c,copyFileSync as l,existsSync as u,lstatSync as ee,mkdirSync as d,openSync as te,readFileSync as ne,readdirSync as f,renameSync as p,rmSync as m,statSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{homedir as v}from"node:os";var re=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new y(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new y(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},y=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const b={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},x={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`},S={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},ie={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},ae={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},oe={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},se={backend:`sqlite-vec`,path:b.data,tableName:`knowledge`},ce=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],le={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},ue={maxResults:10,minScore:.25},de=/^[a-z][a-z0-9-]*$/,fe=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],C={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},pe=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],me=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function he(e){let r=n(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${b.aiContext}/`)?`produced-knowledge`:e.includes(`${b.aiCurated}/`)?`curated-knowledge`:pe.some(t=>t.test(e))?`test-code`:me.some(t=>t.test(e))?`cdk-stack`:r in C?C[r]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(r)?`code-other`:`unknown`}const w={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function T(e){return w[e]??`source`}function ge(e){return Object.entries(w).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`}},_e=class extends E{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},ve=class extends E{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},ye=class extends E{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},be=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 xe(e){return e instanceof D}function k(e){return e instanceof O}let A=!1;function j(e){try{return!ee(e).isSymbolicLink()}catch{return!1}}function M(e,t){if(h(e).isDirectory()){d(t,{recursive:!0});for(let n of f(e))N(i(e,n),i(t,n));m(e,{recursive:!0,force:!0});return}d(i(t,`..`),{recursive:!0}),l(e,t),g(e)}function Se(e,t){try{p(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!u(e)&&u(t))return;if(r!==`EXDEV`)throw n;M(e,t)}}function N(e,t){if(!u(e)||e===t||!j(e))return;let n=h(e);if(!u(t)){d(i(t,`..`),{recursive:!0}),Se(e,t);return}if(n.isDirectory()){d(t,{recursive:!0});for(let n of f(e))N(i(e,n),i(t,n));try{m(e,{recursive:!0,force:!0})}catch{}}}function P(e){if(u(e))try{f(e).length===0&&m(e,{recursive:!0,force:!0})}catch{}}function Ce(e){let t=i(e,x.data);d(t,{recursive:!0});for(let n of f(e))n!==x.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&N(i(e,n),i(t,n))}function F(e){return U(R(e))}function we(e){if(A)return;A=!0,d(e,{recursive:!0});let t=v(),n=i(t,S.legacyDataRoot),r=i(t,S.legacyStateRoot),a=i(e,S.workspaces),o=i(e,S.logs),s=i(e,S.state);if(u(n)&&n!==e){d(a,{recursive:!0});for(let t of f(n))N(i(n,t),t===S.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?i(e,t):i(a,t));P(n)}if(u(r)&&r!==e){for(let e of f(r))N(i(r,e),e===`logs`?o:i(s,e));P(r)}}function I(e){let t=i(e),n=F(t),r=i(n,x.data),a=i(L(),S.logs),o=[{from:i(t,S.legacyDataRoot),to:r},{from:i(t,S.legacyStateRoot),to:i(n,x.state)},{from:i(t,b.data),to:r},{from:i(t,b.state),to:i(n,x.state)},{from:i(t,b.aiCurated),to:i(n,x.curated)},{from:i(t,b.aiContext),to:i(n,x.onboard)},{from:i(t,b.restorePoints),to:i(n,x.restorePoints)},{from:i(t,b.brainstorm),to:i(n,x.brainstorm)},{from:i(t,b.handoffs),to:i(n,x.handoffs)},{from:i(t,b.logs),to:a}];d(n,{recursive:!0}),d(a,{recursive:!0}),Ce(n);for(let e of o)N(e.from,e.to);P(i(t,b.root)),P(i(t,b.ai)),P(i(t,b.brainstorm)),P(i(t,b.handoffs))}function Te(e){return I(e),i(U(V(e).partition),x.state)}function L(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??i(v(),S.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&we(t),t}function R(e){let n=i(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${a(`sha256`).update(n).digest(`hex`).slice(0,8)}`}function z(){let e=i(L(),S.registry);if(!u(e))return{version:1,workspaces:{}};let t=ne(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Ee(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=te(n,c.O_CREAT|c.O_EXCL|c.O_WRONLY);return _(e,`${process.pid}\n`),s(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=h(n);if(Date.now()-e>3e4){g(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function De(e){try{g(e)}catch{}}function B(e){let t=L();d(t,{recursive:!0});let n=i(t,S.registry),r=Ee(n);try{let t=`${n}.tmp`;_(t,JSON.stringify(e,null,2),`utf-8`),p(t,n)}finally{De(r)}}function V(e){let t=z(),n=R(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:i(e),registeredAt:r,lastAccessedAt:r},d(U(n),{recursive:!0}),B(t),t.workspaces[n]}function H(e){let t=z(),n=R(e);return t.workspaces[n]}function Oe(){let e=z();return Object.values(e.workspaces)}function U(e){return i(L(),S.workspaces,e)}function ke(){return u(i(L(),S.registry))}function W(){return i(L(),S.logs)}var Ae=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};const G={debug:0,info:1,warn:2,error:3},K=[];let q=process.env.AIKIT_LOG_LEVEL??`info`,J=!1,Y=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function je(){return Y?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let X;function Z(){return X||=W(),X}function Me(e){let t=e.toISOString().slice(0,10);return r(Z(),`${t}.jsonl`)}let Q=0;function Ne(){let e=Date.now();if(!(e-Q<36e5)){Q=e;try{let t=Z(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of f(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{g(r(t,e))}catch{}}catch{}}}function Pe(e,t){try{d(Z(),{recursive:!0}),o(Me(t),`${e}\n`),Ne()}catch{}}function Fe(e){q=e}function Ie(){return q}function Le(e){Y=e}function Re(){X=void 0}function ze(e){J=e}function Be(e){if(e instanceof Error){let t={error:e.message};return J?(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 Ve(e){return K.push(e),()=>{let t=K.indexOf(e);t>=0&&K.splice(t,1)}}function He(e){function t(t,n,r){if(G[t]<G[q])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of K)try{i({level:t,component:e,message:n,data:r})}catch{}je()&&(t===`warn`||t===`error`)&&Pe(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const $={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function Ue(e,t={}){let{maxAttempts:n=$.maxAttempts,baseDelayMs:r=$.baseDelayMs,maxDelayMs:i=$.maxDelayMs,jitterFraction:a=$.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 We(l)}throw s}function We(e){return new Promise(t=>setTimeout(t,e))}const Ge=[`indexed`,`curated`,`produced`],Ke=[`source`,`documentation`,`test`,`config`,`generated`],qe=[`auto`,`manual`,`smart`],Je=[`efficient`,`normal`,`full`],Ye=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`];export{S as AIKIT_GLOBAL_PATHS,b as AIKIT_PATHS,x as AIKIT_RUNTIME_PATHS,E as AikitError,de as CATEGORY_PATTERN,ie as CHUNK_SIZES,Ye as CONTENT_TYPES,re as CircuitBreaker,y as CircuitOpenError,be as ConfigError,fe as DEFAULT_CATEGORIES,ae as EMBEDDING_DEFAULTS,_e as EmbeddingError,le as FILE_LIMITS,Ae as HealthBus,qe as INDEX_MODES,ce as INSTALL_ARGS,ye as IndexError,Ge as KNOWLEDGE_ORIGINS,oe as MODEL_REGISTRY,O as PermanentError,ue as SEARCH_DEFAULTS,Ke as SOURCE_TYPES,se as STORE_DEFAULTS,ve as StoreError,Je as TOKEN_BUDGETS,D as TransientError,Ve as addLogListener,R as computePartitionKey,T as contentTypeToSourceType,He as createLogger,he as detectContentType,L as getGlobalDataDir,Ie as getLogLevel,U as getPartitionDir,F as getWorkspacePartitionDir,k as isPermanent,xe as isTransient,ke as isUserInstalled,Oe as listWorkspaces,z as loadRegistry,H as lookupWorkspace,I as migrateLegacyWorkspaceLayout,V as registerWorkspace,Re as resetLogDir,W as resolveLogDir,Te as resolveStateDir,B as saveRegistry,Be as serializeError,ze as setDetailedErrorLoggingEnabled,Le as setFileSinkEnabled,Fe as setLogLevel,ge as sourceTypeContentTypes,Ue as withRetry};
|
|
1
|
+
import{EventEmitter as e}from"node:events";import{basename as t,extname as n,join as r,resolve as i}from"node:path";import{createHash as a}from"node:crypto";import{appendFileSync as o,closeSync as s,constants as c,copyFileSync as l,existsSync as u,lstatSync as ee,mkdirSync as d,openSync as te,readFileSync as ne,readdirSync as f,renameSync as p,rmSync as m,statSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{homedir as v}from"node:os";var re=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new y(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new y(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},y=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const b={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},x={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},S={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},ie={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},ae={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},oe={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},se={backend:`sqlite-vec`,path:b.data,tableName:`knowledge`},ce=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],le={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},ue={maxResults:10,minScore:.25},de=/^[a-z][a-z0-9-]*$/,fe=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],C={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},pe=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],me=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function he(e){let r=n(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${b.aiContext}/`)?`produced-knowledge`:e.includes(`${b.aiCurated}/`)?`curated-knowledge`:pe.some(t=>t.test(e))?`test-code`:me.some(t=>t.test(e))?`cdk-stack`:r in C?C[r]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(r)?`code-other`:`unknown`}const w={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function ge(e){return w[e]??`source`}function _e(e){return Object.entries(w).filter(([,t])=>t===e).map(([e])=>e)}var T=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},ve=class extends T{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},ye=class extends T{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},be=class extends T{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},xe=class extends T{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},E=class extends T{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},D=class extends T{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function Se(e){return e instanceof E}function Ce(e){return e instanceof D}let O=!1;function we(e){try{return!ee(e).isSymbolicLink()}catch{return!1}}function Te(e,t){if(h(e).isDirectory()){d(t,{recursive:!0});for(let n of f(e))k(i(e,n),i(t,n));m(e,{recursive:!0,force:!0});return}d(i(t,`..`),{recursive:!0}),l(e,t),g(e)}function Ee(e,t){try{p(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!u(e)&&u(t))return;if(r!==`EXDEV`)throw n;Te(e,t)}}function k(e,t){if(!u(e)||e===t||!we(e))return;let n=h(e);if(!u(t)){d(i(t,`..`),{recursive:!0}),Ee(e,t);return}if(n.isDirectory()){d(t,{recursive:!0});for(let n of f(e))k(i(e,n),i(t,n));try{m(e,{recursive:!0,force:!0})}catch{}}}function A(e){if(u(e))try{f(e).length===0&&m(e,{recursive:!0,force:!0})}catch{}}function De(e){let t=i(e,x.data);d(t,{recursive:!0});for(let n of f(e))n!==x.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&k(i(e,n),i(t,n))}function j(e){return R(P(e))}function Oe(e){if(O)return;O=!0,d(e,{recursive:!0});let t=v(),n=i(t,S.legacyDataRoot),r=i(t,S.legacyStateRoot),a=i(e,S.workspaces),o=i(e,S.logs),s=i(e,S.state);if(u(n)&&n!==e){d(a,{recursive:!0});for(let t of f(n))k(i(n,t),t===S.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?i(e,t):i(a,t));A(n)}if(u(r)&&r!==e){for(let e of f(r))k(i(r,e),e===`logs`?o:i(s,e));A(r)}}function M(e){let t=i(e),n=j(t),r=i(n,x.data),a=i(N(),S.logs),o=[{from:i(t,S.legacyDataRoot),to:r},{from:i(t,S.legacyStateRoot),to:i(n,x.state)},{from:i(t,b.data),to:r},{from:i(t,b.state),to:i(n,x.state)},{from:i(t,b.aiCurated),to:i(n,x.curated)},{from:i(t,b.aiContext),to:i(n,x.onboard)},{from:i(t,b.restorePoints),to:i(n,x.restorePoints)},{from:i(t,b.brainstorm),to:i(n,x.brainstorm)},{from:i(t,b.handoffs),to:i(n,x.handoffs)},{from:i(t,b.logs),to:a}];d(n,{recursive:!0}),d(a,{recursive:!0}),De(n);for(let e of o)k(e.from,e.to);A(i(t,b.root)),A(i(t,b.ai)),A(i(t,b.brainstorm)),A(i(t,b.handoffs))}function ke(e){return M(e),i(R(L(e).partition),x.state)}function N(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??i(v(),S.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Oe(t),t}function P(e){let n=i(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${a(`sha256`).update(n).digest(`hex`).slice(0,8)}`}function F(){let e=i(N(),S.registry);if(!u(e))return{version:1,workspaces:{}};let t=ne(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Ae(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=te(n,c.O_CREAT|c.O_EXCL|c.O_WRONLY);return _(e,`${process.pid}\n`),s(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=h(n);if(Date.now()-e>3e4){g(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function je(e){try{g(e)}catch{}}function I(e){let t=N();d(t,{recursive:!0});let n=i(t,S.registry),r=Ae(n);try{let t=`${n}.tmp`;_(t,JSON.stringify(e,null,2),`utf-8`),p(t,n)}finally{je(r)}}function L(e){let t=F(),n=P(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:i(e),registeredAt:r,lastAccessedAt:r},d(R(n),{recursive:!0}),I(t),t.workspaces[n]}function Me(e){let t=F(),n=P(e);return t.workspaces[n]}function Ne(){let e=F();return Object.values(e.workspaces)}function R(e){return i(N(),S.workspaces,e)}function Pe(){return u(i(N(),S.registry))}function z(){return i(N(),S.logs)}var Fe=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 Ie(e,t){let n=B[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const B={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`]}},V={debug:0,info:1,warn:2,error:3},H=[];let U=process.env.AIKIT_LOG_LEVEL??`info`,W=!1,G=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function Le(){return G?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let K;function q(){return K||=z(),K}function Re(e){let t=e.toISOString().slice(0,10);return r(q(),`${t}.jsonl`)}let J=0;function ze(){let e=Date.now();if(!(e-J<36e5)){J=e;try{let t=q(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of f(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{g(r(t,e))}catch{}}catch{}}}function Be(e,t){try{d(q(),{recursive:!0}),o(Re(t),`${e}\n`),ze()}catch{}}function Ve(e){U=e}function He(){return U}function Ue(e){G=e}function We(){K=void 0}function Ge(e){W=e}function Ke(e){if(e instanceof Error){let t={error:e.message};return W?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function qe(e){return H.push(e),()=>{let t=H.indexOf(e);t>=0&&H.splice(t,1)}}function Y(e){function t(t,n,r){if(V[t]<V[U])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of H)try{i({level:t,component:e,message:n,data:r})}catch{}Le()&&(t===`warn`||t===`error`)&&Be(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 Je(e,t={}){let{maxAttempts:n=X.maxAttempts,baseDelayMs:r=X.baseDelayMs,maxDelayMs:i=X.maxDelayMs,jitterFraction:a=X.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof E),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof E&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await Ye(l)}throw s}function Ye(e){return new Promise(t=>setTimeout(t,e))}const Xe=[`indexed`,`curated`,`produced`],Ze=[`source`,`documentation`,`test`,`config`,`generated`],Qe=[`auto`,`manual`,`smart`],Z=[`efficient`,`normal`,`full`],$e=[`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=Y(`core:version-manager`);function $(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function et(e,t){try{if(!u(e)||!t||t===`0.0.0`)return;let n=f(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort($),i=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)i.add(e);for(let t of n)i.has(t)||(m(r(e,t),{recursive:!0,force:!0}),Q.debug(`Cleaned old version: ${t}`))}catch(e){Q.warn(`Version directory cleanup failed`,{error:e})}}export{S as AIKIT_GLOBAL_PATHS,b as AIKIT_PATHS,x as AIKIT_RUNTIME_PATHS,T as AikitError,de as CATEGORY_PATTERN,ie as CHUNK_SIZES,$e as CONTENT_TYPES,re as CircuitBreaker,y as CircuitOpenError,xe as ConfigError,fe as DEFAULT_CATEGORIES,ae as EMBEDDING_DEFAULTS,ve as EmbeddingError,le as FILE_LIMITS,Fe as HealthBus,Qe as INDEX_MODES,ce as INSTALL_ARGS,be as IndexError,Xe as KNOWLEDGE_ORIGINS,B as LAYER_FIELD_REQUIREMENTS,oe as MODEL_REGISTRY,D as PermanentError,ue as SEARCH_DEFAULTS,Ze as SOURCE_TYPES,se as STORE_DEFAULTS,ye as StoreError,Z as TOKEN_BUDGETS,E as TransientError,qe as addLogListener,et as cleanupOldVersions,$ as compareVersionDir,P as computePartitionKey,ge as contentTypeToSourceType,Y as createLogger,he as detectContentType,N as getGlobalDataDir,He as getLogLevel,R as getPartitionDir,j as getWorkspacePartitionDir,Ce as isPermanent,Se as isTransient,Pe as isUserInstalled,Ne as listWorkspaces,F as loadRegistry,Me as lookupWorkspace,M as migrateLegacyWorkspaceLayout,L as registerWorkspace,We as resetLogDir,z as resolveLogDir,ke as resolveStateDir,I as saveRegistry,Ke as serializeError,Ge as setDetailedErrorLoggingEnabled,Ue as setFileSinkEnabled,Ve as setLogLevel,_e as sourceTypeContentTypes,Ie as validateLayerMetadata,Je as withRetry};
|