@vpxa/aikit 0.1.80 → 0.1.82
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/README.md +52 -0
- package/package.json +1 -1
- package/packages/chunker/dist/index.js +6 -6
- package/packages/cli/dist/index.js +2 -2
- package/packages/cli/dist/user-C05ypatU.js +5 -0
- package/packages/core/dist/index.d.ts +26 -0
- package/packages/flows/dist/index.d.ts +8 -0
- package/packages/flows/dist/index.js +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/server-DyCYX0nU.js +1277 -0
- package/packages/server/dist/{version-check-D4j0Pykd.js → version-check-AMfxaZUw.js} +1 -1
- package/scaffold/dist/definitions/bodies.mjs +44 -0
- package/packages/cli/dist/user-vbJwa7x2.js +0 -5
- package/packages/server/dist/server-VgZC6Q43.js +0 -1277
package/README.md
CHANGED
|
@@ -436,6 +436,58 @@ changes to take effect.
|
|
|
436
436
|
}
|
|
437
437
|
```
|
|
438
438
|
|
|
439
|
+
### Server Configuration
|
|
440
|
+
|
|
441
|
+
The aikit MCP server also supports these SDK v2 configuration options in `aikit.config.json`:
|
|
442
|
+
|
|
443
|
+
#### Feature Groups (`features`)
|
|
444
|
+
|
|
445
|
+
Restrict the server to specific tool categories:
|
|
446
|
+
|
|
447
|
+
```json
|
|
448
|
+
{
|
|
449
|
+
"features": ["search", "knowledge", "execution"]
|
|
450
|
+
}
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
When set, only tools belonging to the specified categories are registered, plus the base tools: `status`, `config`, `guide`, and `health`. Valid category names match the tool metadata categories exposed by the server.
|
|
454
|
+
|
|
455
|
+
#### Read-Only Mode (`readOnly`)
|
|
456
|
+
|
|
457
|
+
Prevent the server from modifying the codebase:
|
|
458
|
+
|
|
459
|
+
```json
|
|
460
|
+
{
|
|
461
|
+
"readOnly": true
|
|
462
|
+
}
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
When enabled, tools annotated with `readOnlyHint: false` are excluded. This filters out mutating tools such as `remember`, `update`, `forget`, `codemod`, and `rename`. The `config` tool is also limited to its `view` action.
|
|
466
|
+
|
|
467
|
+
#### Server Instructions (`serverInstructions`)
|
|
468
|
+
|
|
469
|
+
Override the auto-generated MCP server instructions:
|
|
470
|
+
|
|
471
|
+
```json
|
|
472
|
+
{
|
|
473
|
+
"serverInstructions": "Custom instructions for the LLM about this server"
|
|
474
|
+
}
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
If not set, the server auto-generates instructions that list the available tool categories and note any active restrictions.
|
|
478
|
+
|
|
479
|
+
#### Tool Profiles (`toolProfile`)
|
|
480
|
+
|
|
481
|
+
Select a predefined tool profile:
|
|
482
|
+
|
|
483
|
+
```json
|
|
484
|
+
{
|
|
485
|
+
"toolProfile": "safe"
|
|
486
|
+
}
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
Available profiles: `full` (default), `safe`, `research`, `minimal`, `discovery`.
|
|
490
|
+
|
|
439
491
|
## Architecture
|
|
440
492
|
|
|
441
493
|
```text
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as r,createLogger as i}from"../../core/dist/index.js";import{existsSync as a,readFileSync as o}from"node:fs";import{fileURLToPath as s}from"node:url";const c=e(s(import.meta.url));function l(){let e=[n(c,`..`,`..`,`wasm`),n(c,`..`,`wasm`)];for(let t of e)if(a(n(t,`tree-sitter.wasm`)))return t;return e[0]}const u=l(),d={".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`},f=new Set(Object.keys(d));function p(e){let t=d[e];if(!t)return null;let r=n(u,t);return a(r)?r:null}function m(){let e=n(u,`tree-sitter.wasm`);return a(e)?e:null}const h=i(`wasm-runtime`);async function g(){let e=await import(`web-tree-sitter`),t=typeof e.default?.init==`function`?e.default:e.Parser;if(!t||typeof t.init!=`function`)throw Error(`Unsupported web-tree-sitter export shape: ${Object.keys(e).join(`, `)}`);return t}var _=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;static async initialize(){if(e.instance)return e.instance;let t=new e;return await t.init()?(e.instance=t,t):null}static get(){return e.instance}static async ensure(){let t=e.get();if(t)return t;let n=await e.initialize();if(!n)throw Error(`Failed to initialize WASM tree-sitter runtime`);return n}static dispose(){e.instance&&=(e.instance.parser?.delete(),e.instance.parser=null,e.instance.languages.clear(),e.instance.loadedGrammars.clear(),null)}async init(){try{let e=m();if(!e)return h.warn(`Parser WASM file not found`),!1;let t=await g();return await t.init({locateFile:()=>e}),this.parser=new t,h.info(`WASM tree-sitter parser initialized`),!0}catch(e){return h.warn(`Failed to initialize WASM tree-sitter`,{error:String(e)}),!1}}async loadLanguage(e){let t=this.languages.get(e);if(t)return t;let n=p(e);if(!n)return null;let r=this.loadedGrammars.get(n);if(r)return this.languages.set(e,r),r;try{let t=await(await g()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),h.info(`Loaded grammar`,{ext:e}),t}catch(t){return h.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(e,t){if(!this.parser)return null;let n=await this.loadLanguage(t);return n?(this.parser.setLanguage(n),this.parser.parse(e)):null}hasLanguage(e){return f.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function ee(){return await _.initialize()!==null}const v=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),y=new Set([`call_expression`,`new_expression`,`call`]);function b(e,n){let r=t(n).toLowerCase(),i=_.get();if(i?.isLanguageLoaded(r)){let t=i.getParser(),a=i.getLanguage(r);if(t&&a){t.setLanguage(a);let r=t.parse(e);if(r){let e=[];return x(r.rootNode,n,`<module>`,e),e}}}return null}function x(e,t,n,r){if(!e)return;let i=n;if(v.has(e.type)&&(i=
|
|
1
|
+
import{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as r,createLogger as i}from"../../core/dist/index.js";import{existsSync as a,readFileSync as o}from"node:fs";import{fileURLToPath as s}from"node:url";const c=e(s(import.meta.url));function l(){let e=[n(c,`..`,`..`,`wasm`),n(c,`..`,`wasm`)];for(let t of e)if(a(n(t,`tree-sitter.wasm`)))return t;return e[0]}const u=l(),d={".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`},f=new Set(Object.keys(d));function p(e){let t=d[e];if(!t)return null;let r=n(u,t);return a(r)?r:null}function m(){let e=n(u,`tree-sitter.wasm`);return a(e)?e:null}const h=i(`wasm-runtime`);async function g(){let e=await import(`web-tree-sitter`),t=typeof e.default?.init==`function`?e.default:e.Parser;if(!t||typeof t.init!=`function`)throw Error(`Unsupported web-tree-sitter export shape: ${Object.keys(e).join(`, `)}`);return t}var _=class e{static instance=null;parser=null;languages=new Map;loadedGrammars=new Map;static async initialize(){if(e.instance)return e.instance;let t=new e;return await t.init()?(e.instance=t,t):null}static get(){return e.instance}static async ensure(){let t=e.get();if(t)return t;let n=await e.initialize();if(!n)throw Error(`Failed to initialize WASM tree-sitter runtime`);return n}static dispose(){e.instance&&=(e.instance.parser?.delete(),e.instance.parser=null,e.instance.languages.clear(),e.instance.loadedGrammars.clear(),null)}async init(){try{let e=m();if(!e)return h.warn(`Parser WASM file not found`),!1;let t=await g();return await t.init({locateFile:()=>e}),this.parser=new t,h.info(`WASM tree-sitter parser initialized`),!0}catch(e){return h.warn(`Failed to initialize WASM tree-sitter`,{error:String(e)}),!1}}async loadLanguage(e){let t=this.languages.get(e);if(t)return t;let n=p(e);if(!n)return null;let r=this.loadedGrammars.get(n);if(r)return this.languages.set(e,r),r;try{let t=await(await g()).Language.load(n);return this.loadedGrammars.set(n,t),this.languages.set(e,t),h.info(`Loaded grammar`,{ext:e}),t}catch(t){return h.warn(`Failed to load grammar`,{ext:e,error:String(t)}),null}}async parse(e,t){if(!this.parser)return null;let n=await this.loadLanguage(t);return n?(this.parser.setLanguage(n),this.parser.parse(e)):null}hasLanguage(e){return f.has(e)}isLanguageLoaded(e){return this.languages.has(e)}getParser(){return this.parser}getLanguage(e){return this.languages.get(e)??null}};async function ee(){return await _.initialize()!==null}const v=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`function_declaration`,`method_declaration`,`function_item`,`method_declaration`,`constructor_declaration`]),y=new Set([`call_expression`,`new_expression`,`call`]);function b(e,n){let r=t(n).toLowerCase(),i=_.get();if(i?.isLanguageLoaded(r)){let t=i.getParser(),a=i.getLanguage(r);if(t&&a){t.setLanguage(a);let r=t.parse(e);if(r){let e=[];return x(r.rootNode,n,`<module>`,e),e}}}return null}function x(e,t,n,r){if(!e)return;let i=n;if(v.has(e.type)&&(i=S(e)??n),y.has(e.type)){let n=C(e);n&&r.push({callerFile:t,callerName:i,calleeName:n,line:(e.startPosition?.row??0)+1})}for(let n=0;n<(e.childCount??0);n++){let a=e.child(n);a&&x(a,t,i,r)}}function S(e){for(let t=0;t<(e.childCount??0);t++){let n=e.child(t);if(n&&(n.type===`identifier`||n.type===`property_identifier`||n.type===`name`))return n.text??null}return null}function C(e){let t=e.childForFieldName?.(`function`)??e.child(0);return t?t.type===`identifier`||t.type===`name`?t.text??null:t.type===`member_expression`||t.type===`attribute`?(t.childForFieldName?.(`property`)??t.childForFieldName?.(`attribute`))?.text??null:e.type===`new_expression`?e.child(1)?.text??null:null:null}var w=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=this.findDeclarationBoundaries(e);if(n.length===0)return this.fallbackChunk(e,t);let r=[];for(let i=0;i<n.length;i++){let a=n[i].offset,o=i+1<n.length?n[i+1].offset:e.length,s=e.slice(a,o).trim();if(s=`// File: ${t.sourcePath}\n`+s,s.length>this.maxChunkSize){let n=this.splitByLines(s,this.maxChunkSize),i=this.getLineNumber(e,a);for(let e of n){let n=e.split(`
|
|
2
2
|
`).length;r.push({text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:i,endLine:i+n-1}),i+=n}}else{let n=this.getLineNumber(e,a);r.push({text:s,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:n,endLine:n+s.split(`
|
|
3
3
|
`).length-1})}}if(n[0].offset>0){let i=e.slice(0,n[0].offset).trim();i.length>0&&r.unshift({text:`// File: ${t.sourcePath}\n${i}`,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:0,startLine:1,endLine:this.getLineNumber(e,n[0].offset)-1})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}findDeclarationBoundaries(e){let t=/^(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|const|enum|abstract\s+class)\s+(\w+)/gm,n=[],r;for(;(r=t.exec(e))!==null;){let t=e.lastIndexOf(`
|
|
4
4
|
`,r.index-1)+1,i=t,a=e.slice(0,t).split(`
|
|
@@ -8,17 +8,17 @@ import{dirname as e,extname as t,join as n}from"node:path";import{CHUNK_SIZES as
|
|
|
8
8
|
`),r=[],i=[],a=0;for(let e of n)a+e.length+1>t&&i.length>0?(r.push(i.join(`
|
|
9
9
|
`)),i=[e],a=e.length):(i.push(e),a+=e.length+1);return i.length>0&&r.push(i.join(`
|
|
10
10
|
`)),r}getLineNumber(e,t){return e.slice(0,t).split(`
|
|
11
|
-
`).length}},
|
|
11
|
+
`).length}},T=class{maxChunkSize;overlap;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.default.max,this.overlap=e?.overlap??r.default.overlap}chunk(e,t){if(e.length<=this.maxChunkSize)return[{text:e,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.split(`
|
|
12
12
|
`).length}];let n=e.split(`
|
|
13
13
|
`),r=[],i=[],a=0,o=1;for(let e=0;e<n.length;e++){let s=n[e];if(a+s.length+1>this.maxChunkSize&&i.length>0){r.push({text:i.join(`
|
|
14
14
|
`),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1});let e=[],n=0;for(let t=i.length-1;t>=0&&!(n+i[t].length+1>this.overlap);t--)e.unshift(i[t]),n+=i[t].length+1;o=o+i.length-e.length,i=[...e,s],a=n+s.length+1}else i.push(s),a+=s.length+1}return i.length>0&&r.push({text:i.join(`
|
|
15
|
-
`),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1}),r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}},
|
|
15
|
+
`),sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:r.length,totalChunks:0,startLine:o,endLine:o+i.length-1}),r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}},E=class{maxChunkSize;minChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.markdown.max,this.minChunkSize=e?.minChunkSize??r.markdown.min}chunk(e,t){let n=this.splitByHeadings(e),r=[];for(let e of n){if(e.text.trim().length<this.minChunkSize&&r.length>0){let t=r[r.length-1];t.text+=`\n\n${e.text}`,t.endLine=e.endLine;continue}if(e.text.length>this.maxChunkSize){let n=this.splitByParagraphs(e.text,this.maxChunkSize),i=e.startLine;for(let a of n){let n=a.split(`
|
|
16
16
|
`).length;r.push({text:a,sourcePath:t.sourcePath,contentType:t.contentType,headingPath:e.headingPath,chunkIndex:r.length,totalChunks:0,startLine:i,endLine:i+n-1}),i+=n}}else r.push({text:e.text,sourcePath:t.sourcePath,contentType:t.contentType,headingPath:e.headingPath,chunkIndex:r.length,totalChunks:0,startLine:e.startLine,endLine:e.endLine})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}splitByHeadings(e){let t=e.split(`
|
|
17
|
-
`),n=[],r=null,i=[],a=!1;for(let e=0;e<t.length;e++){/^```/.test(t[e])&&(a=!a);let o=a?null:t[e].match(/^(#{1,6})\s+(.+)/);if(o){r&&n.push(r);let a=o[1].length,s=o[2].trim();for(;i.length>=a;)i.pop();i.push(`${`#`.repeat(a)} ${s}`),r={text:t[e],headingPath:i.join(` > `),startLine:e+1,endLine:e+1}}else r?(r.text+=`\n${t[e]}`,r.endLine=e+1):r={text:t[e],headingPath:`(intro)`,startLine:e+1,endLine:e+1}}return r&&n.push(r),n}splitByParagraphs(e,t){let n=e.split(/\n\n+/),r=[],i=``;for(let e of n)`${i}\n\n${e}`.length>t&&i.length>0?(r.push(i.trim()),i=e):i=i?`${i}\n\n${e}`:e;return i.trim()&&r.push(i.trim()),r}};const
|
|
17
|
+
`),n=[],r=null,i=[],a=!1;for(let e=0;e<t.length;e++){/^```/.test(t[e])&&(a=!a);let o=a?null:t[e].match(/^(#{1,6})\s+(.+)/);if(o){r&&n.push(r);let a=o[1].length,s=o[2].trim();for(;i.length>=a;)i.pop();i.push(`${`#`.repeat(a)} ${s}`),r={text:t[e],headingPath:i.join(` > `),startLine:e+1,endLine:e+1}}else r?(r.text+=`\n${t[e]}`,r.endLine=e+1):r={text:t[e],headingPath:`(intro)`,startLine:e+1,endLine:e+1}}return r&&n.push(r),n}splitByParagraphs(e,t){let n=e.split(/\n\n+/),r=[],i=``;for(let e of n)`${i}\n\n${e}`.length>t&&i.length>0?(r.push(i.trim()),i=e):i=i?`${i}\n\n${e}`:e;return i.trim()&&r.push(i.trim()),r}};const te=new Set([`function_declaration`,`class_declaration`,`interface_declaration`,`type_alias_declaration`,`enum_declaration`,`lexical_declaration`,`variable_declaration`,`export_statement`,`function_definition`,`class_definition`,`decorated_definition`,`class_declaration`,`interface_declaration`,`enum_declaration`,`function_declaration`,`method_declaration`,`type_declaration`,`function_item`,`struct_item`,`enum_item`,`trait_item`,`impl_item`,`const_item`,`static_item`,`type_item`]),ne=new Set([`import_statement`,`import_from_statement`,`import_declaration`,`package_declaration`,`use_declaration`,`extern_crate_declaration`,`import_spec`,`package_clause`]);var D=class{maxChunkSize;constructor(e){this.maxChunkSize=e?.maxChunkSize??r.code.max}chunk(e,t){let n=_.get();if(!n)return this.singleChunk(e,t);let r=this.extractExt(t.sourcePath),i=n.getLanguage(r);if(!i)return this.singleChunk(e,t);let a=n.getParser();if(!a)return this.singleChunk(e,t);a.setLanguage(i);let o=a.parse(e);if(!o)return this.singleChunk(e,t);let s=this.findAstBoundaries(o.rootNode,e);return s.length===0?this.singleChunk(e,t):this.buildChunks(s,e,t)}findAstBoundaries(e,t){let n=[];for(let t of e.children){if(!t.isNamed)continue;let e=te.has(t.type),r=ne.has(t.type);(e||r)&&n.push({startOffset:t.startIndex,endOffset:t.endIndex,startLine:t.startPosition.row+1,endLine:t.endPosition.row+1,isPreamble:r})}return n}buildChunks(e,t,n){let r=[],i=null,a=0,o=0;for(let s of e){if(s.isPreamble){i===null&&(i=s.startLine),a=s.endOffset,o=s.endLine;continue}if(i!==null){let e=t.slice(0,a).trim();e.length>0&&r.push({text:`// File: ${n.sourcePath}\n${e}`,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:o}),i=null}let e=t.slice(s.startOffset,s.endOffset).trim();if(e=`// File: ${n.sourcePath}\n`+e,e.length>this.maxChunkSize){let t=this.splitByLines(e,this.maxChunkSize),i=s.startLine;for(let e of t){let t=e.split(`
|
|
18
18
|
`).length;r.push({text:e,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:i+t-1}),i+=t}}else r.push({text:e,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:s.startLine,endLine:s.endLine})}if(i!==null){let e=t.slice(0,a).trim();e.length>0&&r.push({text:`// File: ${n.sourcePath}\n${e}`,sourcePath:n.sourcePath,contentType:n.contentType,chunkIndex:0,totalChunks:0,startLine:i,endLine:o})}return r.map((e,t)=>({...e,chunkIndex:t,totalChunks:r.length}))}splitByLines(e,t){let n=e.split(`
|
|
19
19
|
`),r=[],i=[],a=0;for(let e of n)a+e.length+1>t&&i.length>0&&(r.push(i.join(`
|
|
20
20
|
`)),i=[],a=0),i.push(e),a+=e.length+1;return i.length>0&&r.push(i.join(`
|
|
21
21
|
`)),r}extractExt(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}singleChunk(e,t){return[{text:`// File: ${t.sourcePath}\n${e}`,sourcePath:t.sourcePath,contentType:t.contentType,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.split(`
|
|
22
|
-
`).length}]}};async function re(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new T;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:if(f.has(t)){let e=await _.initialize();if(e)return await e.loadLanguage(t),new D}return new C;default:return new w}}function ie(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new T;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:return _.get()?.isLanguageLoaded(t)?new D:new C;default:return new w}}const O=i(`query-executor`),k=e(s(import.meta.url));function A(){let e=n(k,`..`,`queries`);if(a(e))return e;let t=n(k,`..`,`..`,`src`,`queries`);return a(t)?t:e}const j=A(),M={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var N=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>P(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>F(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>P(e))}getOrCompile(e,t,n){let r=M[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw O.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let r=`${e}:${t}`,i=this.scmCache.get(r);if(i!==void 0)return i;let a=n(j,e,`${t}.scm`);try{let e=o(a,`utf-8`);return this.scmCache.set(r,e),e}catch{return O.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return n(j,e)}};function P(e){let t=new Map;for(let n of e.captures)t.set(n.name,F(n));return{pattern:e.pattern,captures:t}}function F(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}const I=new N,L=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`method_declaration`,`constructor_declaration`,`function_declaration`,`method_declaration`,`function_item`]);async function R(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?I.execute(i.rootNode,a,t,`calls`).map(e=>z(e,i.rootNode,n)).filter(e=>e!==null):[]}function z(e,t,n){let r=e.captures.get(`callee`);if(!r)return null;let i=e.captures.get(`node`);return{callerFile:n,callerName:B(i?.node??r.node),calleeName:r.text,line:(i?.startLine??r.startLine)+1}}function B(e){let t=e.parent;for(;t;){if(L.has(t.type)){let e=V(t);if(e)return e}t=t.parent}return`<module>`}function V(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}const H=new N,U={handler:`lambda-handler`,lambdaHandler:`lambda-handler`,main:`main`,__name__:`main`,app:`server`,server:`server`,router:`server`,urlpatterns:`server`,init:`main`},W={SpringBootApplication:`server`,RestController:`server`,Controller:`server`};async function G(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=H.execute(i.rootNode,a,t,`entry-points`),s=[],c=new Set;for(let e of o){let r=K(e,t,n);if(r){let e=`${r.name}:${r.type}`;c.has(e)||(c.add(e),s.push(r))}}return s}function K(e,t,n){let r=e.captures.get(`name`);if(!r)return null;let i=r.text,a=e.captures.get(`_parent`);if(a){let e=a.text;if([`Construct`,`Stack`,`NestedStack`,`Stage`].includes(e))return{name:i,type:`cdk-construct`,filePath:n}}let o=e.captures.get(`_ann`);if(o){let e=W[o.text];if(e)return{name:i,type:e,filePath:n}}let s=U[i];return s?{name:i,type:s,filePath:n}:t===`.go`&&i.toLowerCase().startsWith(`handle`)?{name:i,type:`server`,filePath:n,trigger:`HTTP handler`}:{name:i,type:`main`,filePath:n}}const q=new N;async function J(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=q.execute(i.rootNode,a,t,`imports`),s=[];for(let e of o){let r=e.captures.get(`source`);if(!r){let r=e.captures.get(`node`);if(r){let e=oe(r.text,t);e&&s.push({source:e.source,specifiers:e.specifiers,filePath:n,isExternal:X(e.source,t),confidence:`high`})}continue}let i=r.text,a=Y(i,t),o=ae(e.captures.get(`node`)?.text??``,t,a);s.push({source:a,specifiers:o,filePath:n,isExternal:X(a,t),confidence:`high`})}return s}function Y(e,t){let n=e.replace(/^['"`]|['"`]$/g,``);return t===`.go`&&(n=n.replace(/^"|"$/g,``)),n}function X(e,t){return t===`.py`?!e.startsWith(`.`):t===`.go`?e.includes(`/`)||e.includes(`.`):t===`.java`?!0:t===`.rs`?!e.startsWith(`self`)&&!e.startsWith(`super`)&&!e.startsWith(`crate`):!e.startsWith(`.`)&&!e.startsWith(`/`)}function ae(e,t,n){if(!e)return[n];if(t===`.py`){let t=e.match(/import\s+(.+)$/m);return t?t[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean):[n]}if(t===`.java`){let e=n.split(`.`);return[e[e.length-1]]}if(t===`.go`){let e=n.split(`/`);return[e[e.length-1]]}if(t===`.rs`){if(n.includes(`{`)){let e=n.match(/\{([^}]+)\}/);if(e)return e[1].split(`,`).map(e=>e.trim()).filter(Boolean)}let e=n.split(`::`);return[e[e.length-1]]}let r=e.match(/\{([^}]+)\}/);if(r)return r[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean);let i=e.match(/import\s+(\w+)/);return i?[i[1]]:[n]}function oe(e,t){if(t===`.py`){let t=e.match(/^import\s+([\w.]+)/);if(t)return{source:t[1],specifiers:[t[1]]}}return null}const se=new N;async function ce(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=se.execute(i.rootNode,a,t,`patterns`),s=new Map;for(let e of o){let r=le(e,t);if(!r)continue;let i=e.captures.get(`name`),a=`${n}:${(e.captures.get(`node`)?.startLine??i?.startLine??0)+1}`,o=s.get(r.pattern);o?o.locations.push(a):s.set(r.pattern,{description:r.description,locations:[a]})}let c=[];for(let[e,{description:t,locations:n}]of s)c.push({pattern:e,description:t,locations:n,confidence:`high`});return c}function le(e,t){let n=e.captures.get(`name`)?.text;if(!n)return null;let r=e.captures.get(`node`)?.nodeType??``;if(/^(create|build)[A-Z]/.test(n)||/^(of|from|new)[A-Z]/.test(n))return{pattern:`factory`,description:`Factory function/method`};if(/^(register|bind)$/.test(n))return{pattern:`dependency-injection`,description:`DI container registration`};if(/^(Injectable|Component|Service|Controller|Module|Singleton|Repository|Bean)$/.test(n))return{pattern:`dependency-injection`,description:`Framework DI annotation`};if(/^(Map|WeakMap|Set)$/.test(n))return{pattern:`cached-instance`,description:`Cached Map/Set instance`};if(t===`.py`){if(n===`__new__`)return{pattern:`singleton`,description:`Singleton pattern (__new__ override)`};if(n===`__enter__`)return{pattern:`context-manager`,description:`Context manager pattern`};if(r===`decorated_definition`)return{pattern:`decorator`,description:`Decorator usage`}}if(t===`.go`){if(r===`type_declaration`)return{pattern:`interface`,description:`Interface definition`};if(r===`go_statement`)return{pattern:`concurrency`,description:`Goroutine concurrency pattern`};if(n===`make`)return{pattern:`concurrency`,description:`Channel/make pattern`}}if(t===`.rs`){if(r===`impl_item`)return{pattern:`trait-impl`,description:`Trait implementation`};if(r===`attribute_item`){if(n===`derive`)return{pattern:`derive`,description:`Derive macro attribute`};if(n===`test`)return{pattern:`test`,description:`Test attribute`}}}if(t===`.java`){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`marker_annotation`)return{pattern:`dependency-injection`,description:`Framework DI annotation`}}if(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t)){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`decorator`)return{pattern:`decorator`,description:`Framework decorator pattern`}}return{pattern:r||`unknown`,description:`Detected pattern: ${n}`}}const ue=new Set([`function_declaration`,`method_definition`,`arrow_function`,`class_declaration`,`function_definition`,`class_definition`,`method_declaration`,`constructor_declaration`,`class_declaration`,`function_declaration`,`method_declaration`,`function_item`,`impl_item`]);async function de(e,t,n){let r=await(await _.ensure()).parse(e,t);if(!r)return[{name:`<module>`,type:`module`,line:1}];let i=fe(r.rootNode,n-1);if(!i)return[{name:`<module>`,type:`module`,line:1}];let a=[];return pe(i,a),a.push({name:`<module>`,type:`module`,line:1}),a}function fe(e,t){let n=null;function r(e){if(e.startPosition.row<=t&&e.endPosition.row>=t){n=e;for(let t of e.children)r(t)}}return r(e),n}function pe(e,t){let n=e.parent;for(;n;){if(ue.has(n.type)){let e=me(n),r=he(n.type);t.push({name:e??`<anonymous>`,type:r,line:n.startPosition.row+1})}n=n.parent}}function me(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`type_identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}function he(e){return e.includes(`class`)||e===`impl_item`?`class`:`function`}const ge=new N,_e={function_declaration:`function`,class_declaration:`class`,interface_declaration:`interface`,type_alias_declaration:`type`,enum_declaration:`enum`,lexical_declaration:`const`,method_definition:`method`,public_field_definition:`variable`,field_definition:`variable`,function_definition:`function`,class_definition:`class`,expression_statement:`variable`,method_declaration:`method`,constructor_declaration:`method`,field_declaration:`variable`,type_spec:`type`,type_declaration:`type`,const_spec:`const`,var_spec:`variable`,function_item:`function`,struct_item:`class`,enum_item:`enum`,trait_item:`interface`,impl_item:`type`,const_item:`const`,static_item:`variable`,type_item:`type`};async function ve(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?ye(ge.execute(i.rootNode,a,t,`symbols`),t,n):[]}function ye(e,t,n){let r=new Map;for(let n of e){let e=n.captures.get(`name`);if(!e)continue;let i=`${e.text}:${(n.captures.get(`node`)?.startLine??e.startLine)+1}`,a=be(n,t),o=r.get(i);(!o||!o.exported&&a)&&r.set(i,{match:n,exported:a})}let i=[];for(let{match:e,exported:a}of r.values()){let r=e.captures.get(`name`),o=e.captures.get(`node`);if(!r)continue;let s=_e[o?.nodeType??r.nodeType]??`variable`,c=(o?.startLine??r.startLine)+1,l=xe(s,o?.node,t),u=o?.node??r.node;i.push({name:r.text,kind:l,exported:a,filePath:n,line:c,signature:Se(o?.node,l),returnType:Te(o?.node,l),jsdoc:Ee(u),decorators:De(u),typeBody:Oe(o?.node,l)})}return i}function be(e,t){if(e.captures.has(`exported`))return!0;let n=e.captures.get(`name`)?.text;if(!n)return!1;if(t===`.py`)return!n.startsWith(`_`);if(t===`.go`)return/^[A-Z]/.test(n);if(t===`.java`){let t=e.captures.get(`node`)?.text??``;return/\bpublic\b/.test(t)}return!1}function xe(e,t,n){if(n===`.go`&&e===`type`&&t?.children){let e=t.type===`type_declaration`?t.children.flatMap(e=>e.children??[]):t.children;for(let t of e){if(t.type===`interface_type`)return`interface`;if(t.type===`struct_type`)return`class`}}return e}function Se(e,t){if(e){if(t===`function`||t===`method`)return Z(e);if(t===`class`)return Ce(e);if(t===`interface`)return we(e)}}function Z(e){let t=e.childForFieldName(`parameters`)??e.childForFieldName(`parameter_list`),n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`),r=e.childForFieldName(`result`);if(!t){for(let t of e.children)if(t.type===`formal_parameters`||t.type===`parameter_list`||t.type===`parameters`){let e=t.text;return n&&(e+=n.text),r&&(e+=` ${r.text}`),e.length>120?`${e.slice(0,117)}...`:e}return}let i=t.text;return n&&(i+=n.text),r&&(i+=` ${r.text}`),i.length>120?`${i.slice(0,117)}...`:i}function Ce(e){let t=e.childForFieldName(`body`)??e.childForFieldName(`field_declaration_list`);if(!t){for(let t of e.children)if(t.type===`struct_type`||t.type===`class_body`)return Q(t);return}return Q(t)}function Q(e){let t=[];for(let n of e.children){if(n.type===`method_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`field_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function we(e){let t=e.childForFieldName(`body`);if(!t){for(let t of e.children)if(t.type===`interface_type`)return $(t);return}return $(t)}function $(e){let t=[];for(let n of e.children){if(n.type===`property_signature`||n.type===`method_signature`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_spec`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_signature_item`||n.type===`declaration_list`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function Te(e,t){if(!e||t!==`function`&&t!==`method`)return;let n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`);if(n){let e=n.text.replace(/^:\s*/,``).trim();return e.length>200?`${e.slice(0,200)}…`:e}let r=e.childForFieldName(`result`);if(r)return r.text.trim()}function Ee(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e);if(n<=0)return;let r=t.children[n-1];if(r){if(r.type===`comment`||r.type===`block_comment`||r.type===`doc_comment`)return r.text.replace(/^\/\*\*?\s*|\s*\*\/$/g,``).split(`
|
|
22
|
+
`).length}]}};async function re(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new E;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:if(f.has(t)){let e=await _.initialize();if(e)return await e.loadLanguage(t),new D}return new w;default:return new T}}function ie(e){let t=e.toLowerCase();switch(t){case`.md`:case`.mdx`:return new E;case`.ts`:case`.tsx`:case`.mts`:case`.cts`:case`.js`:case`.jsx`:case`.mjs`:case`.cjs`:case`.py`:case`.go`:case`.rs`:case`.java`:return _.get()?.isLanguageLoaded(t)?new D:new w;default:return new T}}const O=i(`query-executor`),k=e(s(import.meta.url));function A(e=k){let t=[n(e,`..`,`queries`),n(e,`..`,`src`,`queries`)];for(let e of t)if(a(e))return e;return t[0]}const j=A(),M={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var N=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>P(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>F(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>P(e))}getOrCompile(e,t,n){let r=M[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw O.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let r=`${e}:${t}`,i=this.scmCache.get(r);if(i!==void 0)return i;let a=n(j,e,`${t}.scm`);try{let e=o(a,`utf-8`);return this.scmCache.set(r,e),e}catch{return O.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),this.scmCache.set(r,``),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return n(j,e)}};function P(e){let t=new Map;for(let n of e.captures)t.set(n.name,F(n));return{pattern:e.pattern,captures:t}}function F(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}const I=new N,L=new Set([`function_declaration`,`method_definition`,`arrow_function`,`function_definition`,`method_declaration`,`constructor_declaration`,`function_declaration`,`method_declaration`,`function_item`]);async function R(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?I.execute(i.rootNode,a,t,`calls`).map(e=>z(e,i.rootNode,n)).filter(e=>e!==null):[]}function z(e,t,n){let r=e.captures.get(`callee`);if(!r)return null;let i=e.captures.get(`node`);return{callerFile:n,callerName:B(i?.node??r.node),calleeName:r.text,line:(i?.startLine??r.startLine)+1}}function B(e){let t=e.parent;for(;t;){if(L.has(t.type)){let e=V(t);if(e)return e}t=t.parent}return`<module>`}function V(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}const H=new N,U={handler:`lambda-handler`,lambdaHandler:`lambda-handler`,main:`main`,__name__:`main`,app:`server`,server:`server`,router:`server`,urlpatterns:`server`,init:`main`},W={SpringBootApplication:`server`,RestController:`server`,Controller:`server`};async function G(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=H.execute(i.rootNode,a,t,`entry-points`),s=[],c=new Set;for(let e of o){let r=K(e,t,n);if(r){let e=`${r.name}:${r.type}`;c.has(e)||(c.add(e),s.push(r))}}return s}function K(e,t,n){let r=e.captures.get(`name`);if(!r)return null;let i=r.text,a=e.captures.get(`_parent`);if(a){let e=a.text;if([`Construct`,`Stack`,`NestedStack`,`Stage`].includes(e))return{name:i,type:`cdk-construct`,filePath:n}}let o=e.captures.get(`_ann`);if(o){let e=W[o.text];if(e)return{name:i,type:e,filePath:n}}let s=U[i];return s?{name:i,type:s,filePath:n}:t===`.go`&&i.toLowerCase().startsWith(`handle`)?{name:i,type:`server`,filePath:n,trigger:`HTTP handler`}:{name:i,type:`main`,filePath:n}}const q=new N;async function J(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=q.execute(i.rootNode,a,t,`imports`),s=[];for(let e of o){let r=e.captures.get(`source`);if(!r){let r=e.captures.get(`node`);if(r){let e=oe(r.text,t);e&&s.push({source:e.source,specifiers:e.specifiers,filePath:n,isExternal:X(e.source,t),confidence:`high`})}continue}let i=r.text,a=Y(i,t),o=ae(e.captures.get(`node`)?.text??``,t,a);s.push({source:a,specifiers:o,filePath:n,isExternal:X(a,t),confidence:`high`})}return s}function Y(e,t){let n=e.replace(/^['"`]|['"`]$/g,``);return t===`.go`&&(n=n.replace(/^"|"$/g,``)),n}function X(e,t){return t===`.py`?!e.startsWith(`.`):t===`.go`?e.includes(`/`)||e.includes(`.`):t===`.java`?!0:t===`.rs`?!e.startsWith(`self`)&&!e.startsWith(`super`)&&!e.startsWith(`crate`):!e.startsWith(`.`)&&!e.startsWith(`/`)}function ae(e,t,n){if(!e)return[n];if(t===`.py`){let t=e.match(/import\s+(.+)$/m);return t?t[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean):[n]}if(t===`.java`){let e=n.split(`.`);return[e[e.length-1]]}if(t===`.go`){let e=n.split(`/`);return[e[e.length-1]]}if(t===`.rs`){if(n.includes(`{`)){let e=n.match(/\{([^}]+)\}/);if(e)return e[1].split(`,`).map(e=>e.trim()).filter(Boolean)}let e=n.split(`::`);return[e[e.length-1]]}let r=e.match(/\{([^}]+)\}/);if(r)return r[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean);let i=e.match(/import\s+(\w+)/);return i?[i[1]]:[n]}function oe(e,t){if(t===`.py`){let t=e.match(/^import\s+([\w.]+)/);if(t)return{source:t[1],specifiers:[t[1]]}}return null}const se=new N;async function ce(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);if(!a)return[];let o=se.execute(i.rootNode,a,t,`patterns`),s=new Map;for(let e of o){let r=le(e,t);if(!r)continue;let i=e.captures.get(`name`),a=`${n}:${(e.captures.get(`node`)?.startLine??i?.startLine??0)+1}`,o=s.get(r.pattern);o?o.locations.push(a):s.set(r.pattern,{description:r.description,locations:[a]})}let c=[];for(let[e,{description:t,locations:n}]of s)c.push({pattern:e,description:t,locations:n,confidence:`high`});return c}function le(e,t){let n=e.captures.get(`name`)?.text;if(!n)return null;let r=e.captures.get(`node`)?.nodeType??``;if(/^(create|build)[A-Z]/.test(n)||/^(of|from|new)[A-Z]/.test(n))return{pattern:`factory`,description:`Factory function/method`};if(/^(register|bind)$/.test(n))return{pattern:`dependency-injection`,description:`DI container registration`};if(/^(Injectable|Component|Service|Controller|Module|Singleton|Repository|Bean)$/.test(n))return{pattern:`dependency-injection`,description:`Framework DI annotation`};if(/^(Map|WeakMap|Set)$/.test(n))return{pattern:`cached-instance`,description:`Cached Map/Set instance`};if(t===`.py`){if(n===`__new__`)return{pattern:`singleton`,description:`Singleton pattern (__new__ override)`};if(n===`__enter__`)return{pattern:`context-manager`,description:`Context manager pattern`};if(r===`decorated_definition`)return{pattern:`decorator`,description:`Decorator usage`}}if(t===`.go`){if(r===`type_declaration`)return{pattern:`interface`,description:`Interface definition`};if(r===`go_statement`)return{pattern:`concurrency`,description:`Goroutine concurrency pattern`};if(n===`make`)return{pattern:`concurrency`,description:`Channel/make pattern`}}if(t===`.rs`){if(r===`impl_item`)return{pattern:`trait-impl`,description:`Trait implementation`};if(r===`attribute_item`){if(n===`derive`)return{pattern:`derive`,description:`Derive macro attribute`};if(n===`test`)return{pattern:`test`,description:`Test attribute`}}}if(t===`.java`){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`marker_annotation`)return{pattern:`dependency-injection`,description:`Framework DI annotation`}}if(/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t)){if(r===`class_declaration`)return{pattern:`singleton`,description:`Singleton pattern (private constructor)`};if(r===`decorator`)return{pattern:`decorator`,description:`Framework decorator pattern`}}return{pattern:r||`unknown`,description:`Detected pattern: ${n}`}}const ue=new Set([`function_declaration`,`method_definition`,`arrow_function`,`class_declaration`,`function_definition`,`class_definition`,`method_declaration`,`constructor_declaration`,`class_declaration`,`function_declaration`,`method_declaration`,`function_item`,`impl_item`]);async function de(e,t,n){let r=await(await _.ensure()).parse(e,t);if(!r)return[{name:`<module>`,type:`module`,line:1}];let i=fe(r.rootNode,n-1);if(!i)return[{name:`<module>`,type:`module`,line:1}];let a=[];return pe(i,a),a.push({name:`<module>`,type:`module`,line:1}),a}function fe(e,t){let n=null;function r(e){if(e.startPosition.row<=t&&e.endPosition.row>=t){n=e;for(let t of e.children)r(t)}}return r(e),n}function pe(e,t){let n=e.parent;for(;n;){if(ue.has(n.type)){let e=me(n),r=he(n.type);t.push({name:e??`<anonymous>`,type:r,line:n.startPosition.row+1})}n=n.parent}}function me(e){let t=e.childForFieldName(`name`);if(t)return t.text;for(let t of e.children)if(t.type===`identifier`||t.type===`type_identifier`||t.type===`property_identifier`||t.type===`field_identifier`)return t.text;return null}function he(e){return e.includes(`class`)||e===`impl_item`?`class`:`function`}const ge=new N,_e={function_declaration:`function`,class_declaration:`class`,interface_declaration:`interface`,type_alias_declaration:`type`,enum_declaration:`enum`,lexical_declaration:`const`,method_definition:`method`,public_field_definition:`variable`,field_definition:`variable`,function_definition:`function`,class_definition:`class`,expression_statement:`variable`,method_declaration:`method`,constructor_declaration:`method`,field_declaration:`variable`,type_spec:`type`,type_declaration:`type`,const_spec:`const`,var_spec:`variable`,function_item:`function`,struct_item:`class`,enum_item:`enum`,trait_item:`interface`,impl_item:`type`,const_item:`const`,static_item:`variable`,type_item:`type`};async function ve(e,t,n=``){let r=await _.ensure(),i=await r.parse(e,t);if(!i)return[];let a=r.getLanguage(t);return a?ye(ge.execute(i.rootNode,a,t,`symbols`),t,n):[]}function ye(e,t,n){let r=new Map;for(let n of e){let e=n.captures.get(`name`);if(!e)continue;let i=`${e.text}:${(n.captures.get(`node`)?.startLine??e.startLine)+1}`,a=be(n,t),o=r.get(i);(!o||!o.exported&&a)&&r.set(i,{match:n,exported:a})}let i=[];for(let{match:e,exported:a}of r.values()){let r=e.captures.get(`name`),o=e.captures.get(`node`);if(!r)continue;let s=_e[o?.nodeType??r.nodeType]??`variable`,c=(o?.startLine??r.startLine)+1,l=xe(s,o?.node,t),u=o?.node??r.node;i.push({name:r.text,kind:l,exported:a,filePath:n,line:c,signature:Se(o?.node,l),returnType:Te(o?.node,l),jsdoc:Ee(u),decorators:De(u),typeBody:Oe(o?.node,l)})}return i}function be(e,t){if(e.captures.has(`exported`))return!0;let n=e.captures.get(`name`)?.text;if(!n)return!1;if(t===`.py`)return!n.startsWith(`_`);if(t===`.go`)return/^[A-Z]/.test(n);if(t===`.java`){let t=e.captures.get(`node`)?.text??``;return/\bpublic\b/.test(t)}return!1}function xe(e,t,n){if(n===`.go`&&e===`type`&&t?.children){let e=t.type===`type_declaration`?t.children.flatMap(e=>e.children??[]):t.children;for(let t of e){if(t.type===`interface_type`)return`interface`;if(t.type===`struct_type`)return`class`}}return e}function Se(e,t){if(e){if(t===`function`||t===`method`)return Z(e);if(t===`class`)return Ce(e);if(t===`interface`)return we(e)}}function Z(e){let t=e.childForFieldName(`parameters`)??e.childForFieldName(`parameter_list`),n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`),r=e.childForFieldName(`result`);if(!t){for(let t of e.children)if(t.type===`formal_parameters`||t.type===`parameter_list`||t.type===`parameters`){let e=t.text;return n&&(e+=n.text),r&&(e+=` ${r.text}`),e.length>120?`${e.slice(0,117)}...`:e}return}let i=t.text;return n&&(i+=n.text),r&&(i+=` ${r.text}`),i.length>120?`${i.slice(0,117)}...`:i}function Ce(e){let t=e.childForFieldName(`body`)??e.childForFieldName(`field_declaration_list`);if(!t){for(let t of e.children)if(t.type===`struct_type`||t.type===`class_body`)return Q(t);return}return Q(t)}function Q(e){let t=[];for(let n of e.children){if(n.type===`method_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`field_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_definition`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function we(e){let t=e.childForFieldName(`body`);if(!t){for(let t of e.children)if(t.type===`interface_type`)return $(t);return}return $(t)}function $(e){let t=[];for(let n of e.children){if(n.type===`property_signature`||n.type===`method_signature`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_declaration`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`method_spec`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}if(n.type===`function_signature_item`||n.type===`declaration_list`){let e=n.childForFieldName(`name`);e&&t.push(e.text)}}if(t.length===0)return;let n=t.join(`, `);return n.length>120?`${n.slice(0,117)}...`:n}function Te(e,t){if(!e||t!==`function`&&t!==`method`)return;let n=e.childForFieldName(`return_type`)??e.childForFieldName(`type`);if(n){let e=n.text.replace(/^:\s*/,``).trim();return e.length>200?`${e.slice(0,200)}…`:e}let r=e.childForFieldName(`result`);if(r)return r.text.trim()}function Ee(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e);if(n<=0)return;let r=t.children[n-1];if(r){if(r.type===`comment`||r.type===`block_comment`||r.type===`doc_comment`)return r.text.replace(/^\/\*\*?\s*|\s*\*\/$/g,``).split(`
|
|
23
23
|
`).map(e=>e.replace(/^\s*\*\s?/,``).trim()).filter(e=>e.length>0&&!e.startsWith(`@`))[0]?.slice(0,200)||void 0;if(e.children[0]?.type===`expression_statement`){let t=e.children[0].children[0];if(t&&(t.type===`string`||t.type===`concatenated_string`))return t.text.replace(/^['"`]{1,3}|['"`]{1,3}$/g,``).trim().split(`
|
|
24
|
-
`)[0]?.trim()?.slice(0,200)||void 0}}}function De(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e),r=[];for(let e=n-1;e>=0;e--){let n=t.children[e];if(n.type===`decorator`||n.type===`annotation`||n.type===`marker_annotation`){let e=n.text.trim();r.unshift(e.length>100?`${e.slice(0,100)}…`:e)}else if(n.type!==`comment`&&n.type!==`block_comment`&&n.type!==`doc_comment`)break}return r.length>0?r:void 0}function Oe(e,t){if(!e||t!==`interface`&&t!==`type`)return;let n=e.childForFieldName(`body`)??e.childForFieldName(`value`)??e.children.find(e=>e.type===`object_type`||e.type===`interface_body`||e.type===`type_body`);if(!n)return;let r=n.text.replace(/\n\s*/g,` `).replace(/\s+/g,` `).trim();return r.length>500?`${r.slice(0,500)}…`:r}export{
|
|
24
|
+
`)[0]?.trim()?.slice(0,200)||void 0}}}function De(e){let t=e.parent;if(!t?.children)return;let n=t.children.indexOf(e),r=[];for(let e=n-1;e>=0;e--){let n=t.children[e];if(n.type===`decorator`||n.type===`annotation`||n.type===`marker_annotation`){let e=n.text.trim();r.unshift(e.length>100?`${e.slice(0,100)}…`:e)}else if(n.type!==`comment`&&n.type!==`block_comment`&&n.type!==`doc_comment`)break}return r.length>0?r:void 0}function Oe(e,t){if(!e||t!==`interface`&&t!==`type`)return;let n=e.childForFieldName(`body`)??e.childForFieldName(`value`)??e.children.find(e=>e.type===`object_type`||e.type===`interface_body`||e.type===`type_body`);if(!n)return;let r=n.text.replace(/\n\s*/g,` `).replace(/\s+/g,` `).trim();return r.length>500?`${r.slice(0,500)}…`:r}export{w as CodeChunker,T as GenericChunker,E as MarkdownChunker,N as QueryExecutor,f as SUPPORTED_EXTENSIONS,D as WasmChunker,_ as WasmRuntime,re as createChunker,ie as createChunkerSync,G as detectEntryPoints,ce as detectPatterns,b as extractCallEdges,R as extractCalls,J as extractImports,ve as extractSymbols,ee as initializeWasm,p as resolveGrammarPath,m as resolveParserWasmPath,de as resolveScopes};
|
|
@@ -9,7 +9,7 @@ Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.p
|
|
|
9
9
|
Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let{graphStore:n}=await Y(),r=N(e,`--type`,``),i=N(e,`--name`,``),a=N(e,`--node-id`,``),o=N(e,`--edge-type`,``),s=N(e,`--direction`,`both`),c=M(e,`--depth`,2),l=M(e,`--limit`,50),u=N(e,`--source-path`,``),d={stats:`stats`,"find-nodes":`find_nodes`,"find-edges":`find_edges`,neighbors:`neighbors`,traverse:`traverse`,delete:`delete`,clear:`clear`}[t];d||(console.error(`Unknown graph action: ${t}`),console.error(`Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let f=await ge(n,{action:d,nodeType:r||void 0,namePattern:i||void 0,sourcePath:u||void 0,nodeId:a||void 0,edgeType:o||void 0,direction:s,maxDepth:c,limit:l});if(console.log(f.summary),f.nodes&&f.nodes.length>0){console.log(`
|
|
10
10
|
Nodes:`);for(let e of f.nodes){let t=Object.keys(e.properties).length>0?` ${JSON.stringify(e.properties)}`:``;console.log(` ${e.name} (${e.type}, id: ${e.id})${t}`)}}if(f.edges&&f.edges.length>0){console.log(`
|
|
11
11
|
Edges:`);for(let e of f.edges){let t=e.weight===1?``:` (weight: ${e.weight})`;console.log(` ${e.fromId} --[${e.type}]--> ${e.toId}${t}`)}}f.stats&&(console.log(`\nNode types: ${JSON.stringify(f.stats.nodeTypes)}`),console.log(`Edge types: ${JSON.stringify(f.stats.edgeTypes)}`)),f.deleted!==void 0&&console.log(`Deleted: ${f.deleted}`)}}],Ot=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=N(e,`--category`,``).trim(),n=I(N(e,`--tags`,``)),r=e.shift()?.trim()??``,i=await F(),a=i.trim().length>0?i:e.join(` `).trim();(!r||!t||!a.trim())&&(console.error(`Usage: aikit remember <title> --category <cat> [--tags tag1,tag2]`),process.exit(1));let{curated:o}=await Y(),s=await o.remember(r,a,t,n);console.log(`Stored curated entry`),console.log(` Path: ${s.path}`),console.log(` Category: ${t}`),n.length>0&&console.log(` Tags: ${n.join(`, `)}`)}},{name:`forget`,description:`Remove a curated entry`,usage:`aikit forget <path> --reason <reason>`,run:async e=>{let t=N(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await Y(),i=await r.forget(n,t);console.log(`Removed curated entry: ${i.path}`)}},{name:`read`,description:`Read a curated entry`,usage:`aikit read <path>`,run:async e=>{let t=e.shift()?.trim()??``;t||(console.error(`Usage: aikit read <path>`),process.exit(1));let{curated:n}=await Y(),r=await n.read(t);console.log(r.title),console.log(`─`.repeat(60)),console.log(`Path: ${r.path}`),console.log(`Category: ${r.category}`),console.log(`Version: ${r.version}`),console.log(`Tags: ${r.tags.length>0?r.tags.join(`, `):`None`}`),console.log(``),console.log(r.content)}},{name:`list`,description:`List curated entries`,usage:`aikit list [--category <cat>] [--tag <tag>]`,run:async e=>{let t=N(e,`--category`,``).trim()||void 0,n=N(e,`--tag`,``).trim()||void 0,{curated:r}=await Y(),i=await r.list({category:t,tag:n});if(i.length===0){console.log(`No curated entries found.`);return}console.log(`Curated entries (${i.length})`),console.log(`─`.repeat(60));for(let e of i){console.log(e.path),console.log(` ${e.title}`),console.log(` Category: ${e.category} | Version: ${e.version}`),console.log(` Tags: ${e.tags.length>0?e.tags.join(`, `):`None`}`);let t=e.contentPreview.replace(/\s+/g,` `).trim();t&&console.log(` Preview: ${t}`),console.log(``)}}},{name:`update`,description:`Update a curated entry`,usage:`aikit update <path> --reason <reason>`,run:async e=>{let t=N(e,`--reason`,``).trim(),n=e.shift()?.trim()??``,r=await F();(!n||!t||!r.trim())&&(console.error(`Usage: aikit update <path> --reason <reason>`),process.exit(1));let{curated:i}=await Y(),a=await i.update(n,r,t);console.log(`Updated curated entry`),console.log(` Path: ${a.path}`),console.log(` Version: ${a.version}`)}},{name:`compact`,description:`Compress text for context`,usage:`aikit compact <query> [--path <file>] [--max-chars N] [--segmentation paragraph|sentence|line]`,run:async e=>{let t=M(e,`--max-chars`,3e3),n=N(e,`--path`,``).trim()||void 0,r=N(e,`--segmentation`,`paragraph`),i=e.join(` `).trim(),a=n?void 0:await F();(!i||!n&&!a?.trim())&&(console.error(`Usage: aikit compact <query> --path <file> OR cat file | aikit compact <query>`),process.exit(1));let{embedder:o}=await Y(),s=await ie(o,{text:a,path:n,query:i,maxChars:t,segmentation:r});console.log(`Compressed ${s.originalChars} chars to ${s.compressedChars} chars`),console.log(`Ratio: ${(s.ratio*100).toFixed(1)}% | Segments: ${s.segmentsKept}/${s.segmentsTotal}`),console.log(``),console.log(s.text)}}],kt=[{name:`search`,description:`Search the AI Kit index`,usage:`aikit search <query> [--limit N] [--mode hybrid|semantic|keyword] [--graph-hops 0-3]`,run:async e=>{let t=M(e,`--limit`,5),n=N(e,`--mode`,`hybrid`),r=M(e,`--graph-hops`,0),i=e.join(` `).trim();i||(console.error(`Usage: aikit search <query>`),process.exit(1));let{embedder:a,store:o,graphStore:s}=await Y(),c=await a.embedQuery(i),l;if(n===`keyword`)l=await o.ftsSearch(i,{limit:t});else if(n===`semantic`)l=await o.search(c,{limit:t});else{let[e,n]=await Promise.all([o.search(c,{limit:t*2}),o.ftsSearch(i,{limit:t*2}).catch(()=>[])]);l=U(e,n).slice(0,t)}if(l.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of l){console.log(`\n${`─`.repeat(60)}`),console.log(`[${(t*100).toFixed(1)}%] ${e.sourcePath}:${e.startLine}-${e.endLine}`),console.log(` Type: ${e.contentType} | Origin: ${e.origin}`),e.tags.length>0&&console.log(` Tags: ${e.tags.join(`, `)}`),console.log(``);let n=e.content.length>500?`${e.content.slice(0,500)}...`:e.content;console.log(n)}if(console.log(`\n${`─`.repeat(60)}`),console.log(`${l.length} result(s) found.`),r>0&&l.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(s,l.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:r,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${r} hop${r>1?`s`:``}):\n`);for(let e of t){console.log(` ${e.sourcePath}:`);for(let t of e.graphContext.nodes.slice(0,5))console.log(` → ${t.name} (${t.type})`);for(let t of e.graphContext.edges.slice(0,5))console.log(` → ${t.fromId} --[${t.type}]--> ${t.toId}`)}}}catch(e){console.error(`[graph] augmentation failed: ${e.message}`)}}},{name:`find`,description:`Run federated search across indexed content and files`,usage:`aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`,run:async e=>{let t=M(e,`--limit`,10),n=N(e,`--glob`,``).trim()||void 0,r=N(e,`--pattern`,``).trim()||void 0,i=e.join(` `).trim()||void 0;!i&&!n&&!r&&(console.error(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`),process.exit(1));let{embedder:a,store:o}=await Y(),s=await g(a,o,{query:i,glob:n,pattern:r,limit:t});if(s.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${s.strategies.join(`, `)}`),console.log(`Results: ${s.results.length} shown (${s.totalFound} total)`);for(let e of s.results){let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``;console.log(`\n[${e.source}] ${e.path}${t}`),console.log(` Score: ${(e.score*100).toFixed(1)}%`),e.preview&&console.log(` ${e.preview.replace(/\s+/g,` `).trim()}`)}}},{name:`scope-map`,description:`Generate a reading plan for a task`,usage:`aikit scope-map <task> [--max-files N]`,run:async e=>{let t=M(e,`--max-files`,15),n=e.join(` `).trim();n||(console.error(`Usage: aikit scope-map <task> [--max-files N]`),process.exit(1));let{embedder:r,store:i}=await Y(),a=await Fe(r,i,{task:n,maxFiles:t});console.log(`Task: ${a.task}`),console.log(`Files: ${a.files.length}`),console.log(`Estimated tokens: ${a.totalEstimatedTokens}`),console.log(``),console.log(`Reading order:`);for(let e of a.readingOrder)console.log(` ${e}`);for(let[e,t]of a.files.entries())console.log(`\n${e+1}. ${t.path}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}% | Tokens: ${t.estimatedTokens}`),console.log(` Why: ${t.reason}`),t.focusRanges.length>0&&console.log(` Focus: ${at(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=M(e,`--limit`,20),n=e.join(` `).trim();n||(console.error(`Usage: aikit symbol <name> [--limit N]`),process.exit(1));let{embedder:r,store:i}=await Y();ht(await Ve(r,i,{name:n,limit:t}))}},{name:`trace`,description:`Trace forward/backward flow for a symbol or file location`,usage:`aikit trace <start> [--direction forward|backward|both] [--max-depth N]`,run:async e=>{let t=N(e,`--direction`,`both`).trim()||`both`,n=M(e,`--max-depth`,3),r=e.join(` `).trim();(!r||![`forward`,`backward`,`both`].includes(t))&&(console.error(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`),process.exit(1));let{embedder:i,store:a}=await Y();dt(await Ue(i,a,{start:r,direction:t,maxDepth:n}))}},{name:`examples`,description:`Find real code examples of a symbol or pattern`,usage:`aikit examples <query> [--limit N] [--content-type type]`,run:async e=>{let t=M(e,`--limit`,5),n=N(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();r||(console.error(`Usage: aikit examples <query> [--limit N] [--content-type type]`),process.exit(1));let{embedder:i,store:a}=await Y();ft(await pe(i,a,{query:r,limit:t,contentType:n}))}},{name:`dead-symbols`,description:`Find exported symbols that appear to be unused`,usage:`aikit dead-symbols [--limit N]`,run:async e=>{let t=M(e,`--limit`,100),{embedder:n,store:r}=await Y();pt(await fe(n,r,{limit:t}))}},{name:`lookup`,description:`Look up indexed content by record ID or source path`,usage:`aikit lookup <id>`,run:async e=>{let t=e.join(` `).trim();t||(console.error(`Usage: aikit lookup <id>`),process.exit(1));let{store:n}=await Y(),r=await n.getById(t);if(r){console.log(r.id),console.log(`─`.repeat(60)),console.log(`Path: ${r.sourcePath}`),console.log(`Chunk: ${r.chunkIndex+1}/${r.totalChunks}`),console.log(`Lines: ${r.startLine}-${r.endLine}`),console.log(`Type: ${r.contentType} | Origin: ${r.origin}`),r.tags.length>0&&console.log(`Tags: ${r.tags.join(`, `)}`),console.log(``),console.log(r.content);return}let i=await n.getBySourcePath(t);if(i.length===0){console.log(`No indexed content found for: ${t}`);return}i.sort((e,t)=>e.chunkIndex-t.chunkIndex),console.log(t),console.log(`─`.repeat(60)),console.log(`Chunks: ${i.length} | Type: ${i[0].contentType}`);for(let e of i){let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;console.log(`\nChunk ${e.chunkIndex+1}/${e.totalChunks}${t}`),console.log(e.content)}}}],X=s(u(import.meta.url));function Z(e){let t=e;for(let e=0;e<10;e++){try{let e=c(t,`package.json`);if(r(e)&&JSON.parse(a(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=s(t);if(e===t)break;t=e}return l(e,`..`,`..`,`..`)}const At=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async()=>{let{isUserInstalled:e,getGlobalDataDir:t,computePartitionKey:n,listWorkspaces:r}=await import(`../../core/dist/index.js`),{existsSync:i}=await import(`node:fs`),a=process.cwd(),o=e(),s=i(l(a,`.vscode`,`mcp.json`)),c,u;if(o&&s)c=`workspace (overrides user-level for this workspace)`,u=l(a,`.aikit-data`);else if(o){let e=n(a);c=i(l(a,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,u=l(t(),e)}else c=`workspace`,u=l(a,`.aikit-data`);if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${c}`),console.log(` Data: ${u}`),o&&!s){let e=r();console.log(` Registry: ${e.length} workspace(s) enrolled`)}try{let{store:e}=await Y(),t=await e.getStats(),n=await e.listSourcePaths();console.log(` Records: ${t.totalRecords}`),console.log(` Files: ${t.totalFiles}`),console.log(` Indexed: ${t.lastIndexedAt??`Never`}`),console.log(` Backend: ${t.storeBackend}`),console.log(` Model: ${t.embeddingModel}`),console.log(``),console.log(`Content Types:`);for(let[e,n]of Object.entries(t.contentTypeBreakdown))console.log(` ${e}: ${n}`);if(n.length>0){console.log(``),console.log(`Files (${n.length} total):`);for(let e of n.slice(0,20))console.log(` ${e}`);n.length>20&&console.log(` ... and ${n.length-20} more`)}}catch{console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.")}o&&!s&&!i(l(a,`AGENTS.md`))&&(console.log(``),console.log(" Action: Run `npx @vpxa/aikit init` to add AGENTS.md and copilot-instructions.md"))}},{name:`reindex`,description:`Re-index the AI Kit index from configured sources`,usage:`aikit reindex [--full]`,run:async e=>{let t=e.includes(`--full`),{store:n,indexer:r,curated:i,config:a}=await Y();console.log(`Indexing sources...`);let o=e=>{e.phase===`chunking`&&e.currentFile&&process.stdout.write(`\r [${e.filesProcessed+1}/${e.filesTotal}] ${e.currentFile}`),e.phase===`done`&&process.stdout.write(`
|
|
12
|
-
`)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=l(Z(X),`packages`,`server`,`dist`,`index.js`),n=N(e,`--transport`,`stdio`),r=N(e,`--port`,`3210`),i=tt(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--user|--workspace] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--guide`),i=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),r){let{guideProject:e}=await import(`./init-CuRXmyD9.js`);await e();return}if(t){let{initUser:e}=await import(`./user-
|
|
13
|
-
Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=_e(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=Me({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}Ne().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{je(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=l(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),u=`http://localhost:${r}/_dashboard/`,d=`http://localhost:${r}/health`,f=!1;for(let e=0;e<30;e+=1){try{if((await fetch(d)).ok){f=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(f||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${u}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,u],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[u],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=l(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),u=`http://localhost:${r}/settings/`,d=`http://localhost:${r}/health`,f=!1;for(let e=0;e<30;e+=1){try{if((await fetch(d)).ok){f=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(f||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${u}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,u],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[u],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}}];function jt(e){let t=e;for(let e=0;e<10;e++){try{let e=c(t,`package.json`);if(r(e)&&JSON.parse(a(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=s(t);if(e===t)break;t=e}return l(e,`..`,`..`,`..`)}const Mt=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{let{initUser:n}=await import(`./user-vbJwa7x2.js`);await n({force:!0});let i=process.cwd(),o=r(l(i,`.github`,`.aikit-scaffold.json`)),c=r(l(i,`.github`,`agents`)),d=r(l(i,`.github`,`prompts`)),f=r(l(i,`.claude`,`commands`));if(o||c||d||f){let{initScaffoldOnly:e}=await import(`./init-CuRXmyD9.js`);await e({force:!0})}if(r(l(i,`.github`,`skills`))){let{smartCopySkills:n}=await import(`./scaffold-WMQ2uQ48.js`),r=jt(s(u(import.meta.url))),o=JSON.parse(a(l(r,`package.json`),`utf-8`)).version;await n(i,r,[...e],o,!0);let{smartCopyFlows:c}=await import(`./scaffold-WMQ2uQ48.js`);await c(i,r,[...t],o,!0)}}}],Nt=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=I(N(e,`--files`,``)),r=N(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=Pe(i,n,{description:r});console.log(`Saved workset: ${e.name}`),B(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=me(i);if(!e){console.log(`No workset found: ${i}`);return}B(e);return}case`list`:{let e=Te();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)B(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ce(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=d(i,n);console.log(`Updated workset: ${e.name}`),B(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=ke(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),B(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();switch(t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1)),t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),r=t.trim()?``:await F(),i=Be(n,gt(t||r));console.log(`Stored stash entry: ${i.key}`),console.log(` Type: ${i.type}`),console.log(` Stored: ${i.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=Re(n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=ze();if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=Le(n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=Ie();console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=Se();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=N(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=ye(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=we(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=be(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=Ce(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=xe(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=Ee();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=w(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Oe(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=De(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=E(n,t);console.log(`Marked "${r.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=D(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=O(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=C(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=T(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],Q=[...kt,...Ot,...nt,...Dt,...At,...xt,...yt,...Nt,...bt,...Mt,...q];Q.push({name:`help`,description:`Show available commands`,run:async()=>{$()}});async function Pt(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){$();return}if(n===`--version`||n===`-v`){let e=l(s(u(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(a(e,`utf-8`));console.log(t.version);return}let r=Q.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),$(),process.exit(1));try{await r.run(t)}finally{let e=Et();e&&await e.store.close()}}function $(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
12
|
+
`)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=l(Z(X),`packages`,`server`,`dist`,`index.js`),n=N(e,`--transport`,`stdio`),r=N(e,`--port`,`3210`),i=tt(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--user|--workspace] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--guide`),i=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),r){let{guideProject:e}=await import(`./init-CuRXmyD9.js`);await e();return}if(t){let{initUser:e}=await import(`./user-C05ypatU.js`);await e({force:i})}else if(n){let{initProject:e}=await import(`./init-CuRXmyD9.js`);await e({force:i})}else{let{initSmart:e}=await import(`./init-CuRXmyD9.js`);await e({force:i})}}},{name:`check`,description:`Run incremental typecheck and lint`,usage:`aikit check [--cwd <dir>] [--files f1,f2] [--skip-types] [--skip-lint] [--detail summary|errors|full]`,run:async e=>{let t=N(e,`--cwd`,``).trim()||void 0,n=N(e,`--files`,``),r=N(e,`--detail`,`full`)||`full`,i=n.split(`,`).map(e=>e.trim()).filter(Boolean),a=!1;e.includes(`--skip-types`)&&(e.splice(e.indexOf(`--skip-types`),1),a=!0);let o=!1;e.includes(`--skip-lint`)&&(e.splice(e.indexOf(`--skip-lint`),1),o=!0);let s=await m({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});st(s),s.passed||(process.exitCode=1)}},{name:`batch`,description:`Execute built-in operations from JSON input`,usage:`aikit batch [--file path] [--concurrency N]`,run:async e=>{let t=N(e,`--file`,``).trim()||void 0,n=(()=>{let t=e.indexOf(`--concurrency`);if(t===-1||t+1>=e.length)return 0;let n=Number.parseInt(e.splice(t,2)[1],10);return Number.isNaN(n)?0:n})(),r=await rt(t);r.trim()||(console.error(`Usage: aikit batch [--file path] [--concurrency N]`),process.exit(1));let i=it(r),a=n>0?n:i.concurrency,o=i.operations.some(e=>e.type!==`check`)?await Y():null,s=await p(i.operations,async e=>vt(e,o),{concurrency:a});console.log(JSON.stringify(s,null,2)),s.some(e=>e.status===`error`)&&(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=ve(e.shift());console.log(`Project Health: ${t.path}`),console.log(`─`.repeat(50));for(let e of t.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${t.score}% — ${t.summary}`)}},{name:`audit`,description:`Run a unified project audit (structure, deps, patterns, health, dead symbols, check)`,usage:`aikit audit [path] [--checks structure,dependencies,patterns,health,dead_symbols,check,entry_points] [--detail summary|full]`,run:async e=>{let{store:t,embedder:n}=await Y(),r=N(e,`--detail`,`summary`)||`summary`,i=N(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await f(t,n,{path:e.shift()||`.`,checks:a,detail:r});if(o.ok){if(console.log(o.summary),o.next&&o.next.length>0){console.log(`
|
|
13
|
+
Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=_e(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=Me({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}Ne().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{je(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=l(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),u=`http://localhost:${r}/_dashboard/`,d=`http://localhost:${r}/health`,f=!1;for(let e=0;e<30;e+=1){try{if((await fetch(d)).ok){f=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(f||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${u}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,u],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[u],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=l(Z(X),`packages`,`server`,`dist`,`index.js`),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),u=`http://localhost:${r}/settings/`,d=`http://localhost:${r}/health`,f=!1;for(let e=0;e<30;e+=1){try{if((await fetch(d)).ok){f=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(f||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${u}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,u],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[u],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}}];function jt(e){let t=e;for(let e=0;e<10;e++){try{let e=c(t,`package.json`);if(r(e)&&JSON.parse(a(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=s(t);if(e===t)break;t=e}return l(e,`..`,`..`,`..`)}const Mt=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{let{initUser:n}=await import(`./user-C05ypatU.js`);await n({force:!0});let i=process.cwd(),o=r(l(i,`.github`,`.aikit-scaffold.json`)),c=r(l(i,`.github`,`agents`)),d=r(l(i,`.github`,`prompts`)),f=r(l(i,`.claude`,`commands`));if(o||c||d||f){let{initScaffoldOnly:e}=await import(`./init-CuRXmyD9.js`);await e({force:!0})}if(r(l(i,`.github`,`skills`))){let{smartCopySkills:n}=await import(`./scaffold-WMQ2uQ48.js`),r=jt(s(u(import.meta.url))),o=JSON.parse(a(l(r,`package.json`),`utf-8`)).version;await n(i,r,[...e],o,!0);let{smartCopyFlows:c}=await import(`./scaffold-WMQ2uQ48.js`);await c(i,r,[...t],o,!0)}}}],Nt=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=I(N(e,`--files`,``)),r=N(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=Pe(i,n,{description:r});console.log(`Saved workset: ${e.name}`),B(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=me(i);if(!e){console.log(`No workset found: ${i}`);return}B(e);return}case`list`:{let e=Te();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)B(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ce(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=d(i,n);console.log(`Updated workset: ${e.name}`),B(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=ke(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),B(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();switch(t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1)),t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),r=t.trim()?``:await F(),i=Be(n,gt(t||r));console.log(`Stored stash entry: ${i.key}`),console.log(` Type: ${i.type}`),console.log(` Stored: ${i.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=Re(n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=ze();if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=Le(n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=Ie();console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=Se();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=N(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=ye(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=we(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=be(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=Ce(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=xe(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=Ee();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=w(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=Oe(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=De(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=E(n,t);console.log(`Marked "${r.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=D(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=O(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=C(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=T(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],Q=[...kt,...Ot,...nt,...Dt,...At,...xt,...yt,...Nt,...bt,...Mt,...q];Q.push({name:`help`,description:`Show available commands`,run:async()=>{$()}});async function Pt(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){$();return}if(n===`--version`||n===`-v`){let e=l(s(u(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(a(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=Q.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=Q.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),$(),process.exit(1));try{await r.run(t)}finally{let e=Et();e&&await e.store.close()}}function $(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
|
|
14
14
|
`),console.log(`Usage: aikit <command> [options]
|
|
15
15
|
`),console.log(`Commands:`);let e=Math.max(...Q.map(e=>e.name.length));for(let t of Q)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{Pt as run};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as e,n as t,r as n}from"./constants-B8_CApx0.js";import{n as r,t as i}from"./templates-ArdAVWoY.js";import{loadAdapter as a,n as o,r as s,smartCopyFromMemory as c,t as l}from"./scaffold-WMQ2uQ48.js";import{existsSync as u,mkdirSync as d,readFileSync as f,rmSync as p,unlinkSync as m,writeFileSync as h}from"node:fs";import{dirname as g,join as _,resolve as v}from"node:path";import{fileURLToPath as y}from"node:url";import{getGlobalDataDir as b,saveRegistry as x}from"../../core/dist/index.js";import{execFileSync as S}from"node:child_process";import{homedir as C}from"node:os";function w(e){let t=e;for(let e=0;e<10;e++){try{let e=_(t,`package.json`);if(u(e)&&JSON.parse(f(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=g(t);if(e===t)break;t=e}return v(e,`..`,`..`,`..`)}function T(){let e={...t};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=S(`which`,[`npx`],{encoding:`utf-8`,timeout:3e3}).trim();t&&u(t)&&(e.command=t)}catch{}}return e}function E(){let e=C(),t=process.platform,n=[],r=v(e,`.copilot`),i=v(r,`instructions`),a=v(e,`.claude`),o=v(e,`.cursor`),s=v(e,`.windsurf`);if(t===`win32`){let t=process.env.APPDATA??v(e,`AppData`,`Roaming`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}else if(t===`darwin`){let t=v(e,`Library`,`Application Support`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}else{let t=process.env.XDG_CONFIG_HOME??v(e,`.config`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}if(n.push({ide:`Claude Code`,configDir:v(e,`.claude`),mcpConfigPath:v(e,`.claude`,`mcp.json`),globalScaffoldRoot:a,instructionsRoot:null}),n.push({ide:`Copilot CLI`,configDir:r,mcpConfigPath:v(r,`mcp-config.json`),globalScaffoldRoot:null,instructionsRoot:null}),t===`darwin`){let e={"VS Code":`/Applications/Visual Studio Code.app`,"VS Code Insiders":`/Applications/Visual Studio Code - Insiders.app`,VSCodium:`/Applications/VSCodium.app`,Cursor:`/Applications/Cursor.app`,"Cursor Nightly":`/Applications/Cursor Nightly.app`,Windsurf:`/Applications/Windsurf.app`};return n.filter(t=>u(t.configDir)||e[t.ide]&&u(e[t.ide]))}return n.filter(e=>u(e.configDir))}function D(e,t,n=!1){let{mcpConfigPath:r,configDir:i}=e,a=T(),o={};if(u(r)){try{let e=f(r,`utf-8`);o=JSON.parse(e)}catch{let e=`${r}.bak`;h(e,f(r,`utf-8`),`utf-8`),console.log(` Backed up invalid ${r} to ${e}`),o={}}if((o.servers??o.mcpServers??{})[t]&&!n){console.log(` ${e.ide}: ${t} already configured (use --force to update)`);return}}let s=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`,`Windsurf`]).has(e.ide)?`servers`:`mcpServers`,c=o[s]??{};e.ide===`Copilot CLI`?c[t]={...a,tools:[`*`]}:c[t]=a,o[s]=c,d(i,{recursive:!0}),h(r,`${JSON.stringify(o,null,2)}\n`,`utf-8`),console.log(` ${e.ide}: configured ${t} in ${r}`)}const O=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function k(t,n=!1){if(!O.has(t.ide))return;let r=v(t.configDir,`settings.json`),i={};if(u(r))try{let e=f(r,`utf-8`);i=JSON.parse(e)}catch{console.log(` ${t.ide}: skipped settings.json (invalid JSON)`);return}let a=!1;for(let[t,r]of Object.entries(e))if(typeof r==`object`&&r){let e=typeof i[t]==`object`&&i[t]!==null?i[t]:{},n={...e,...r};JSON.stringify(n)!==JSON.stringify(e)&&(i[t]=n,a=!0)}else (n||!(t in i))&&(i[t]=r,a=!0);a&&(h(r,`${JSON.stringify(i,null,2)}\n`,`utf-8`),console.log(` ${t.ide}: updated settings.json`))}async function A(e,t,n,f,m=!1){let g=new Set;for(let e of t)e.globalScaffoldRoot&&g.add(e.globalScaffoldRoot);if(g.size===0){console.log(` No IDEs with global scaffold support detected.`);return}let _=await a(e,`copilot`),y=new Map;for(let e of _){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=y.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),y.set(n,r)}let b=await a(e,`skills`),x=new Map;for(let e of b){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t),r=x.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),x.set(n,r)}let S=await a(e,`flows`),w=new Map;for(let e of S){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t),r=w.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),w.set(n,r)}let T=(e,t)=>{let n=y.get(t);if(!n||n.length===0)return;let r=v(e,`.aikit-scaffold.json`),i=o(r)??l(f);i.version=f,c(n,v(e,t),i,t,m),s(r,i)};for(let e of g){T(e,`agents`),T(e,`prompts`);{let t=v(e,`.aikit-scaffold.json`),n=o(t)??l(f);n.version=f;for(let[t,r]of x)c(r,v(e,`skills`,t),n,`skills/${t}`,m);s(t,n)}{let t=v(e,`.aikit-scaffold.json`),n=o(t)??l(f);n.version=f;for(let t of w.keys()){let n=v(e,`flows`,t,`skills`);u(n)&&(p(n,{recursive:!0,force:!0}),console.log(` ${e}: migrated ${t} flow to steps/ layout`))}for(let[t,r]of w)c(r,v(e,`flows`,t),n,`flows/${t}`,m);s(t,n)}console.log(` ${e}: scaffold updated (${x.size} skills)`)}let E=new Set,D=r(`aikit`,n),O=i(`aikit`,n);for(let e of t){if(!e.globalScaffoldRoot)continue;let t=e.globalScaffoldRoot;if(e.ide===`Claude Code`){let e=v(t,`CLAUDE.md`);h(e,`${D}\n---\n\n${O}`,`utf-8`),E.add(e)}else if(e.ide===`VS Code`||e.ide===`VS Code Insiders`||e.ide===`VSCodium`){let n=e.instructionsRoot??t;d(n,{recursive:!0});let r=v(n,`copilot-instructions.md`);E.has(r)||(h(r,`---\napplyTo: "**"\n---\n\n${D}\n---\n\n${O}`,`utf-8`),E.add(r));let i=v(C(),`.github`),a=v(i,`copilot-instructions.md`);E.has(a)||(d(i,{recursive:!0}),h(a,`${D}\n---\n\n${O}`,`utf-8`),E.add(a)),T(e.configDir,`prompts`)}else if(e.ide===`Cursor`||e.ide===`Cursor Nightly`){let e=v(t,`rules`);d(e,{recursive:!0});let n=v(e,`aikit.mdc`);E.has(n)||(h(n,`${D}\n---\n\n${O}`,`utf-8`),E.add(n))}else if(e.ide===`Windsurf`){let e=v(t,`rules`);d(e,{recursive:!0});let n=v(e,`aikit.md`);E.has(n)||(h(n,`${D}\n---\n\n${O}`,`utf-8`),E.add(n))}}E.size>0&&console.log(` Instruction files: ${[...E].join(`, `)}`)}function j(e){let t=[];for(let n of e){if(!n.globalScaffoldRoot)continue;let e=n.globalScaffoldRoot;if(n.ide===`VS Code`||n.ide===`VS Code Insiders`||n.ide===`VSCodium`){let r=n.instructionsRoot??e;t.push(v(r,`kb.instructions.md`)),t.push(v(r,`aikit.instructions.md`))}else n.ide===`Cursor`||n.ide===`Cursor Nightly`?t.push(v(e,`rules`,`kb.mdc`)):n.ide===`Windsurf`&&t.push(v(e,`rules`,`kb.md`))}for(let e of t)u(e)&&(m(e),console.log(` Removed legacy file: ${e}`))}async function M(e){let t=n,r=w(g(y(import.meta.url))),i=JSON.parse(f(v(r,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${i}...\n`);let a=b();d(a,{recursive:!0}),console.log(` Global data store: ${a}`),x({version:1,workspaces:{}}),console.log(` Created registry.json`);let o=E();if(o.length===0)console.log(`
|
|
2
|
+
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${o.length} IDE(s):`);for(let n of o)D(n,t,e.force),k(n,e.force)}console.log(`
|
|
3
|
+
Installing scaffold files:`),await A(r,o,t,i,e.force),j(o),console.log(`
|
|
4
|
+
User-level AI Kit installation complete!`),console.log(`
|
|
5
|
+
Next steps:`),console.log(` 1. Open any workspace in your IDE`),console.log(` 2. The AI Kit server will auto-start and index the workspace`),console.log(` 3. Agents, prompts, skills & instructions are available globally`),console.log(` 4. No per-workspace init needed — just open a project and start coding`)}export{M as initUser};
|
|
@@ -207,6 +207,32 @@ interface KBConfig {
|
|
|
207
207
|
onboardDir?: string;
|
|
208
208
|
/** Resolved state directory path. User-level mode redirects this to the partition. Defaults to `.aikit-state` in workspace root. */
|
|
209
209
|
stateDir?: string;
|
|
210
|
+
/**
|
|
211
|
+
* All workspace roots provided by the MCP client (IDE).
|
|
212
|
+
* In multi-root workspaces this contains every folder.
|
|
213
|
+
* `sources[0].path` remains the primary root; this field enables
|
|
214
|
+
* tools to discover which root the user is working in.
|
|
215
|
+
*/
|
|
216
|
+
allRoots?: string[];
|
|
217
|
+
/**
|
|
218
|
+
* Feature groups to expose. When set, only tools in these categories are
|
|
219
|
+
* registered. Intersects with the active tool profile.
|
|
220
|
+
* Valid categories: search, analysis, knowledge, compression, forge,
|
|
221
|
+
* presentation, execution, manipulation, session, git, process, system,
|
|
222
|
+
* meta, utilities, web, queue, flow.
|
|
223
|
+
*/
|
|
224
|
+
features?: string[];
|
|
225
|
+
/**
|
|
226
|
+
* When true, tools with `readOnlyHint: false` are excluded from
|
|
227
|
+
* registration. The `config` tool becomes report-only. Immutable at
|
|
228
|
+
* runtime (set once at startup).
|
|
229
|
+
*/
|
|
230
|
+
readOnly?: boolean;
|
|
231
|
+
/**
|
|
232
|
+
* Custom server instructions string. When non-empty, replaces the
|
|
233
|
+
* auto-generated instructions passed to the MCP client.
|
|
234
|
+
*/
|
|
235
|
+
serverInstructions?: string;
|
|
210
236
|
/** Enterprise RAG bridge configuration (optional) */
|
|
211
237
|
er?: {
|
|
212
238
|
/** Whether ER integration is enabled */enabled: boolean; /** Base URL of the ER API (e.g., https://xxx.execute-api.region.amazonaws.com/prod) */
|
|
@@ -127,6 +127,10 @@ interface FlowState {
|
|
|
127
127
|
phase: FlowPhase;
|
|
128
128
|
/** Whether the current step is an epilogue (injected) step */
|
|
129
129
|
isEpilogue: boolean;
|
|
130
|
+
/** Workspace roots participating in this flow run (multi-root support) */
|
|
131
|
+
roots?: string[];
|
|
132
|
+
/** The canonical workspace root that owns this flow run */
|
|
133
|
+
primaryRoot?: string;
|
|
130
134
|
}
|
|
131
135
|
/** Persisted meta.json for a flow run under .flows/{slug}/ */
|
|
132
136
|
interface FlowRunMeta {
|
|
@@ -160,6 +164,10 @@ interface FlowRunMeta {
|
|
|
160
164
|
completedEpilogueSteps: string[];
|
|
161
165
|
/** Skipped epilogue step IDs */
|
|
162
166
|
skippedEpilogueSteps: string[];
|
|
167
|
+
/** Workspace roots participating in this flow run (multi-root support). When set, the flow state is synchronized across all listed roots. */
|
|
168
|
+
roots?: string[];
|
|
169
|
+
/** The canonical workspace root that owns this flow run */
|
|
170
|
+
primaryRoot?: string;
|
|
163
171
|
}
|
|
164
172
|
/** Summary of a flow run for listing */
|
|
165
173
|
interface FlowRunSummary {
|
|
@@ -12,4 +12,4 @@ ${j}`}var N=class{injectPreamble(e,t){let r=M(t);if(!n(e)){u(e,`${r}\n`,`utf-8`)
|
|
|
12
12
|
|
|
13
13
|
`),`utf-8`)}getTargetFiles(e){let t=[],r=p(e,`.github`,`copilot-instructions.md`);n(r)&&t.push(r);let i=p(e,`CLAUDE.md`);n(i)&&t.push(i);let a=p(e,`AGENTS.md`);return n(a)&&t.push(a),t}};function P(e){if(!e||typeof e!=`object`||!(`stderr`in e))return``;let t=e.stderr;return Buffer.isBuffer(t)?t.toString().trim():typeof t==`string`?t.trim():``}function F(e){try{return new URL(e).hostname}catch{}return e.match(/^[^@]+@([^:]+):/)?.[1]??`<host>`}function I(e,t,n){let r=[`Git operation failed for: ${e}`],i=F(e),a=t.includes(`ETIMEDOUT`)||t.includes(`SIGTERM`)||t.toLowerCase().includes(`timed out`),o=n.includes(`Authentication failed`)||n.includes(`could not read Username`)||n.includes(`terminal prompts disabled`)||n.includes(`401`)||n.includes(`403`)||n.includes(`Permission denied`),s=n.includes(`SSL certificate`)||n.includes(`unable to access`)&&n.includes(`SSL`),c=n.includes(`Could not resolve host`)||n.includes(`Name or service not known`),l=n.includes(`SAML`)||n.includes(`single sign-on`);return o||l?(r.push(``),r.push(`Cause: Authentication required or credentials not configured.`),r.push(``),r.push(`To fix this, ensure git can access this repository:`),r.push(``),r.push(` Option 1 - SSH key:`),r.push(` 1. Generate an SSH key: ssh-keygen -t ed25519`),r.push(` 2. Add the public key to your Git hosting account`),r.push(` 3. Use the SSH URL instead: git@<host>:<org>/<repo>.git`),r.push(``),r.push(` Option 2 - Personal Access Token (PAT):`),r.push(` 1. Create a PAT in your Git hosting Settings > Developer settings > Tokens`),r.push(` 2. For GitHub Enterprise with SAML SSO, authorize the token for your org`),r.push(` 3. Configure git credentials:`),r.push(` git config --global credential.helper store`),r.push(` git clone ${e} (enter PAT as password)`),r.push(``),r.push(` Option 3 - Git Credential Manager:`),r.push(` 1. Install: https://github.com/git-ecosystem/git-credential-manager`),r.push(` 2. Run: git clone ${e}`),r.push(` 3. Follow the browser-based auth prompt`),r.push(``),r.push(`After configuring credentials, retry: aikit flow add ${e}`)):a?(r.push(``),r.push(`Cause: Connection timed out - the server did not respond within 60 seconds.`),r.push(``),r.push(`Possible reasons:`),r.push(` - The repository requires VPN access. Ensure your VPN is connected`),r.push(` - The host is behind a firewall or corporate proxy`),r.push(` - The URL may be incorrect`),r.push(``),r.push(`Diagnostics:`),r.push(` 1. Verify the URL is correct: ${e}`),r.push(` 2. Test connectivity: git ls-remote ${e}`),r.push(` 3. If behind a proxy, configure git:`),r.push(` git config --global http.proxy http://proxy:port`),r.push(``),r.push(`If this is a corporate/internal host, you may need to:`),r.push(` - Connect to the corporate VPN`),r.push(` - Add the host to your SSH config or git config`),r.push(` - Ask your IT team to allowlist your machine`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):s?(r.push(``),r.push(`Cause: SSL/TLS certificate verification failed.`),r.push(``),r.push(`This often happens with corporate proxies or self-signed certificates.`),r.push(``),r.push(`To fix:`),r.push(` 1. If your company uses a custom CA, add it:`),r.push(` git config --global http.sslCAInfo /path/to/ca-bundle.crt`),r.push(` 2. As a last resort (not recommended for production):`),r.push(` git config --global http.sslVerify false`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):c?(r.push(``),r.push(`Cause: Cannot resolve hostname.`),r.push(``),r.push(`Check:`),r.push(` 1. Is the URL correct? ${e}`),r.push(` 2. Are you connected to the internet/VPN?`),r.push(` 3. Can you resolve the host? ping ${i}`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):(r.push(``),r.push(`Error: ${t}`),n&&r.push(`Details: ${n}`),r.push(``),r.push(`Troubleshooting:`),r.push(` 1. Verify the URL is a valid git repository: git ls-remote ${e}`),r.push(` 2. Check your git credentials and network connectivity`),r.push(` 3. If the repo requires auth, configure credentials first (PAT or SSH key)`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)),r.join(`
|
|
14
14
|
`)}function L(){try{return _(`git`,[`credential-manager`,`--version`],{stdio:`pipe`,timeout:5e3}).status===0}catch{return!1}}function R(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`authentication failed`)||n.includes(`could not read username`)||n.includes(`saml sso`)||n.includes(`terminal prompts disabled`)||n.includes(`host key verification failed`)||n.includes(`permission denied`)||n.includes(`403`)||n.includes(`401`)}var z=class{constructor(e){this.flowsDir=e}clone(e,t){let r=this.repoNameFromUrl(e),i=p(this.flowsDir,r);if(n(i))if(!n(p(i,`.git`)))o(i,{recursive:!0,force:!0});else return{success:!1,error:`Flow "${r}" already installed at ${i}. Use update instead.`};try{if(this.ensureFlowsDir(),t){let n=process.platform===`win32`?`bat`:`sh`,r=p(v(),`git-askpass-${Date.now()}.${n}`);process.platform===`win32`?u(r,`@echo ${t}`,{mode:448}):u(r,`#!/bin/sh\necho "${t}"`,{mode:448});try{let t=_(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:r}});if(t.status!==0){let e=t.stderr?.toString().trim()??``;throw Error(e||t.error?.message||`git clone failed`)}}finally{try{l(r)}catch{}}}else{let t=_(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}});if(t.status!==0){let e=t.stderr?.toString().trim()??``;throw Error(e||t.error?.message||`git clone failed`)}}return{success:!0,data:i}}catch(r){n(i)&&o(i,{recursive:!0,force:!0});let a=P(r),s=r instanceof Error?r.message:String(r);if(!t&&R(s,a)&&L()){let t=F(e)||e;console.log(`\nAuthentication required for ${t}.\nGit Credential Manager detected - opening browser for login...\n(If a browser window does not open, check your terminal for a device code.)\n`);try{if(this.ensureFlowsDir(),_(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0,data:i};n(i)&&o(i,{recursive:!0,force:!0})}catch{n(i)&&o(i,{recursive:!0,force:!0})}}return{success:!1,error:I(e,s,a)}}}update(e){if(!n(e))return{success:!1,error:`Install path not found: ${e}`};try{return g(`git pull --ff-only`,{cwd:e,stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}}),{success:!0}}catch(t){let n=e;try{n=g(`git remote get-url origin`,{cwd:e,stdio:`pipe`,timeout:1e4}).toString().trim()}catch{}let r=P(t),i=t instanceof Error?t.message:String(t);if(R(i,r)&&L()){let t=F(n)||n;console.log(`\nAuthentication required for ${t}.\nGit Credential Manager detected - opening browser for login...\n`);try{if(_(`git`,[`pull`,`--ff-only`],{cwd:e,stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0}}catch{}}return{success:!1,error:I(n,i,r)}}}copyLocal(e,r){let i=p(this.flowsDir,r);if(n(i))return{success:!1,error:`Flow "${r}" already installed at ${i}`};try{return this.ensureFlowsDir(),t(e,i,{recursive:!0}),{success:!0,data:i}}catch(e){return{success:!1,error:`Copy failed: ${e instanceof Error?e.message:String(e)}`}}}remove(e){if(!n(e))return{success:!0};try{return o(e,{recursive:!0,force:!0}),{success:!0}}catch(e){return{success:!1,error:`Remove failed: ${e instanceof Error?e.message:String(e)}`}}}runInstallDeps(e){for(let t of e)try{if(t.startsWith(`npm:`)){g(`npx skills add ${t.slice(4)} -g`,{stdio:`pipe`,timeout:12e4});continue}if(t.endsWith(`.git`)||t.includes(`github.com`)){g(`npx skills add ${t} -g`,{stdio:`pipe`,timeout:12e4});continue}return{success:!1,error:`Unknown install entry format: ${t}`}}catch(e){return{success:!1,error:`Install dependency failed for "${t}": ${e instanceof Error?e.message:String(e)}`}}return{success:!0}}getLocalCommit(e){try{return g(`git rev-parse HEAD`,{cwd:e,stdio:`pipe`,timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).toString().trim()||null}catch{return null}}getRemoteCommit(e){try{return g(`git ls-remote origin HEAD`,{cwd:e,stdio:`pipe`,timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).toString().trim().split(/\s+/)[0]||null}catch{return null}}hasUpdates(e){let t=this.getLocalCommit(e);if(!t)return{success:!1,error:`Could not determine local commit (not a git repo?)`};let n=this.getRemoteCommit(e);return n?{success:!0,data:{localCommit:t,remoteCommit:n,hasUpdates:t!==n}}:{success:!1,error:`Could not reach remote to check for updates`}}repoNameFromUrl(e){return d(e).replace(/\.git$/,``)}ensureFlowsDir(){n(this.flowsDir)||r(this.flowsDir,{recursive:!0})}};const B=[new T,new C,new w,new E];function V(e){let t=B.find(t=>t.format===e);if(!t)throw Error(`No adapter for format: ${e}`);return t}function H(e){for(let t of B)if(t.detect(e))return t;return null}var U=class{async load(e,t){if(!n(e))return{success:!1,error:`Source directory not found: ${e}`};let r=H(e);if(!r)return{success:!1,error:`No format adapter matches source: ${e}`};try{let n=await r.parse(e,t),i=this.validate(n);return i.success?{success:!0,data:{manifest:n,format:r.format}}:i}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}async loadWithFormat(e,t,n){let r=V(t);try{let t=await r.parse(e,n),i=this.validate(t);return i.success?{success:!0,data:t}:i}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}validate(e){let t=[];e.name?.trim()||t.push(`Missing flow name`),e.version?.trim()||t.push(`Missing flow version`),e.steps?.length||t.push(`Flow must have at least one step`);let n=new Set(e.steps.map(e=>e.id));for(let r of e.steps??[]){r.id?.trim()||t.push(`Step missing id`),r.instruction?.trim()||t.push(`Step "${r.id}" missing instruction path`);for(let e of r.requires??[])n.has(e)||t.push(`Step "${r.id}" requires unknown step "${e}"`)}return n.size!==(e.steps?.length??0)&&t.push(`Duplicate step IDs found`),t.length>0?{success:!1,error:`Validation failed:\n${t.join(`
|
|
15
|
-
`)}`}:{success:!0}}};function W(){return k().map(e=>({name:e.manifest.name,version:e.manifest.version,source:`builtin`,sourceType:`builtin`,installPath:e.scaffoldDir,format:`native`,registeredAt:`1970-01-01T00:00:00.000Z`,updatedAt:`1970-01-01T00:00:00.000Z`,manifest:e.manifest}))}var G=class{constructor(e){this.registryPath=e}load(){if(!n(this.registryPath))return{version:1,flows:{}};try{let e=i(this.registryPath,`utf-8`);return JSON.parse(e)}catch{return{version:1,flows:{}}}}save(e){let t=f(this.registryPath);n(t)||r(t,{recursive:!0}),u(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}register(e){let t=this.load();return t.flows[e.name]=e,this.save(t),{success:!0}}unregister(e){let t=this.load();return t.flows[e]?(delete t.flows[e],this.save(t),{success:!0}):{success:!1,error:`Flow "${e}" not found in registry`}}get(e){return this.load().flows[e]||(W().find(t=>t.name===e)??null)}list(){let e=this.load(),t=new Set(Object.keys(e.flows)),n=Object.values(e.flows);for(let e of W())t.has(e.name)||n.push(e);return n}has(e){return e in this.load().flows?!0:W().some(t=>t.name===e)}},K=class{constructor(e,t={before:[],after:[]}){this.flowsDir=e,this.epilogueConfig=t}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`flow`}generateSlug(e){let t=this.slugify(e);if(!n(p(this.flowsDir,t)))return t;for(let e=2;e<=100;e+=1){let r=`${t}-${e}`;if(!n(p(this.flowsDir,r)))return r}throw Error(`Unable to allocate a flow run slug for topic "${e}"`)}getMetaPath(e){return p(this.flowsDir,e,`meta.json`)}buildStepSequence(e){return[...this.epilogueConfig.before.map(e=>({id:e.id,phase:`before`})),...e.steps.map(e=>({id:e.id,phase:`flow`})),...this.epilogueConfig.after.map(e=>({id:e.id,phase:`after`}))]}readMeta(e){let t=this.getMetaPath(e);if(!n(t))return null;try{let e=i(t,`utf-8`);return JSON.parse(e)}catch{return null}}writeMeta(e,t){let i=p(this.flowsDir,e);n(i)||r(i,{recursive:!0}),u(this.getMetaPath(e),JSON.stringify(t,null,2),`utf-8`)}normalizeMeta(e){let t=e;return t.completedTokens??=[],t.executionLog??=[],t}hasCompletedExecution(e,t){return e.executionLog.some(n=>n.stepId===t&&e.completedTokens.includes(n.token))}markCrashedExecution(e){let t=e.currentToken;if(!(!t||e.completedTokens.includes(t)))for(let n=e.executionLog.length-1;n>=0;--n){let r=e.executionLog[n];if(r.token===t&&r.outcome===`in-progress`){r.outcome=`crashed`;break}}}finalizeCurrentStep(e,t,n){let r=e.currentToken;if(r){e.completedTokens.includes(r)||e.completedTokens.push(r);for(let i=e.executionLog.length-1;i>=0;--i){let a=e.executionLog[i];if(a.token===r){a.completedAt=n,a.outcome=t;break}}}e.currentToken=void 0}activateStep(e,t,n,r){let i=n;for(;i<t.length;){let n=t[i];if(e.currentStep=n.id,e.phase=n.phase,r?.force||!this.hasCompletedExecution(e,n.id)){this.markCrashedExecution(e);let t=Date.now(),r=new Date(t).toISOString(),i=`${n.id}-${t}`;e.currentToken=i,e.executionLog.push({stepId:n.id,token:i,startedAt:r,outcome:`in-progress`});return}n.phase===`flow`?e.completedSteps.includes(n.id)||e.completedSteps.push(n.id):e.completedEpilogueSteps.includes(n.id)||e.completedEpilogueSteps.push(n.id),i+=1}e.currentStep=null,e.currentToken=void 0,e.status=`completed`,e.phase=`after`}findActiveRun(){if(!n(this.flowsDir))return null;for(let e of a(this.flowsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=this.readMeta(e.name);if(t?.status===`active`)return{slug:e.name,meta:t}}return null}metaToState(e,t){let n=this.normalizeMeta(t),r=n.phase??`flow`;return{flow:n.flow,status:n.status,currentStep:n.currentStep,currentToken:n.currentToken,completedSteps:n.completedSteps,completedTokens:n.completedTokens,skippedSteps:n.skippedSteps,executionLog:n.executionLog,artifacts:n.artifacts,startedAt:n.startedAt,updatedAt:n.updatedAt,slug:e,runDir:p(this.flowsDir,e),topic:n.topic,phase:r,isEpilogue:r!==`flow
|
|
15
|
+
`)}`}:{success:!0}}};function W(){return k().map(e=>({name:e.manifest.name,version:e.manifest.version,source:`builtin`,sourceType:`builtin`,installPath:e.scaffoldDir,format:`native`,registeredAt:`1970-01-01T00:00:00.000Z`,updatedAt:`1970-01-01T00:00:00.000Z`,manifest:e.manifest}))}var G=class{constructor(e){this.registryPath=e}load(){if(!n(this.registryPath))return{version:1,flows:{}};try{let e=i(this.registryPath,`utf-8`);return JSON.parse(e)}catch{return{version:1,flows:{}}}}save(e){let t=f(this.registryPath);n(t)||r(t,{recursive:!0}),u(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}register(e){let t=this.load();return t.flows[e.name]=e,this.save(t),{success:!0}}unregister(e){let t=this.load();return t.flows[e]?(delete t.flows[e],this.save(t),{success:!0}):{success:!1,error:`Flow "${e}" not found in registry`}}get(e){return this.load().flows[e]||(W().find(t=>t.name===e)??null)}list(){let e=this.load(),t=new Set(Object.keys(e.flows)),n=Object.values(e.flows);for(let e of W())t.has(e.name)||n.push(e);return n}has(e){return e in this.load().flows?!0:W().some(t=>t.name===e)}},K=class{constructor(e,t={before:[],after:[]}){this.flowsDir=e,this.epilogueConfig=t}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`flow`}generateSlug(e){let t=this.slugify(e);if(!n(p(this.flowsDir,t)))return t;for(let e=2;e<=100;e+=1){let r=`${t}-${e}`;if(!n(p(this.flowsDir,r)))return r}throw Error(`Unable to allocate a flow run slug for topic "${e}"`)}getMetaPath(e){return p(this.flowsDir,e,`meta.json`)}buildStepSequence(e){return[...this.epilogueConfig.before.map(e=>({id:e.id,phase:`before`})),...e.steps.map(e=>({id:e.id,phase:`flow`})),...this.epilogueConfig.after.map(e=>({id:e.id,phase:`after`}))]}readMeta(e){let t=this.getMetaPath(e);if(!n(t))return null;try{let e=i(t,`utf-8`);return JSON.parse(e)}catch{return null}}writeMeta(e,t){let i=p(this.flowsDir,e);n(i)||r(i,{recursive:!0}),u(this.getMetaPath(e),JSON.stringify(t,null,2),`utf-8`)}normalizeMeta(e){let t=e;return t.completedTokens??=[],t.executionLog??=[],t}hasCompletedExecution(e,t){return e.executionLog.some(n=>n.stepId===t&&e.completedTokens.includes(n.token))}markCrashedExecution(e){let t=e.currentToken;if(!(!t||e.completedTokens.includes(t)))for(let n=e.executionLog.length-1;n>=0;--n){let r=e.executionLog[n];if(r.token===t&&r.outcome===`in-progress`){r.outcome=`crashed`;break}}}finalizeCurrentStep(e,t,n){let r=e.currentToken;if(r){e.completedTokens.includes(r)||e.completedTokens.push(r);for(let i=e.executionLog.length-1;i>=0;--i){let a=e.executionLog[i];if(a.token===r){a.completedAt=n,a.outcome=t;break}}}e.currentToken=void 0}activateStep(e,t,n,r){let i=n;for(;i<t.length;){let n=t[i];if(e.currentStep=n.id,e.phase=n.phase,r?.force||!this.hasCompletedExecution(e,n.id)){this.markCrashedExecution(e);let t=Date.now(),r=new Date(t).toISOString(),i=`${n.id}-${t}`;e.currentToken=i,e.executionLog.push({stepId:n.id,token:i,startedAt:r,outcome:`in-progress`});return}n.phase===`flow`?e.completedSteps.includes(n.id)||e.completedSteps.push(n.id):e.completedEpilogueSteps.includes(n.id)||e.completedEpilogueSteps.push(n.id),i+=1}e.currentStep=null,e.currentToken=void 0,e.status=`completed`,e.phase=`after`}findActiveRun(){if(!n(this.flowsDir))return null;for(let e of a(this.flowsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=this.readMeta(e.name);if(t?.status===`active`)return{slug:e.name,meta:t}}return null}metaToState(e,t){let n=this.normalizeMeta(t),r=n.phase??`flow`;return{flow:n.flow,status:n.status,currentStep:n.currentStep,currentToken:n.currentToken,completedSteps:n.completedSteps,completedTokens:n.completedTokens,skippedSteps:n.skippedSteps,executionLog:n.executionLog,artifacts:n.artifacts,startedAt:n.startedAt,updatedAt:n.updatedAt,slug:e,runDir:p(this.flowsDir,e),topic:n.topic,phase:r,isEpilogue:r!==`flow`,roots:n.roots,primaryRoot:n.primaryRoot}}start(e,t,n){let i=this.findActiveRun();if(i)return{success:!1,error:`Flow "${i.meta.flow}" is already active. Reset it first.`};let a=this.buildStepSequence(t);if(!a.length)return{success:!1,error:`Flow has no steps`};try{let i=(n??t.description)||e,o=this.generateSlug(i),s=p(this.flowsDir,o),c=new Date().toISOString(),l=a[0],u={id:o,flow:e,flowVersion:t.version,topic:i,status:`active`,currentStep:l.id,currentToken:void 0,completedSteps:[],completedTokens:[],skippedSteps:[],executionLog:[],artifactsDir:t.artifacts_dir,artifacts:{},startedAt:c,updatedAt:c,phase:l.phase,completedEpilogueSteps:[],skippedEpilogueSteps:[]};return this.activateStep(u,a,0),r(s,{recursive:!0}),r(p(s,t.artifacts_dir),{recursive:!0}),this.writeMeta(o,u),{success:!0,data:this.metaToState(o,u)}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}step(e,t){let n=this.findActiveRun();if(!n)return{success:!1,error:`No active flow`};if(n.meta.status!==`active`)return{success:!1,error:`Flow is ${n.meta.status}, not active`};if(!n.meta.currentStep)return{success:!1,error:`No current step`};let r=n.meta.currentStep,i=this.buildStepSequence(t),a=i.findIndex(e=>e.id===r);if(a===-1)return{success:!1,error:`Current step "${n.meta.currentStep}" not found in manifest`};let o=i[a],s=new Date().toISOString(),c=this.normalizeMeta(n.meta);switch(e){case`next`:o.phase===`flow`?c.completedSteps.includes(r)||c.completedSteps.push(r):c.completedEpilogueSteps.includes(r)||c.completedEpilogueSteps.push(r),this.finalizeCurrentStep(c,`completed`,s),this.activateStep(c,i,a+1);break;case`skip`:o.phase===`flow`?c.skippedSteps.includes(r)||c.skippedSteps.push(r):c.skippedEpilogueSteps.includes(r)||c.skippedEpilogueSteps.push(r),this.finalizeCurrentStep(c,`skipped`,s),this.activateStep(c,i,a+1);break;case`redo`:this.markCrashedExecution(c),o.phase===`flow`?(c.completedSteps=c.completedSteps.filter(e=>e!==r),c.skippedSteps=c.skippedSteps.filter(e=>e!==r)):(c.completedEpilogueSteps=c.completedEpilogueSteps.filter(e=>e!==r),c.skippedEpilogueSteps=c.skippedEpilogueSteps.filter(e=>e!==r)),c.currentToken=void 0,this.activateStep(c,i,a,{force:!0});break}return c.updatedAt=s,this.writeMeta(n.slug,c),{success:!0,data:this.metaToState(n.slug,c)}}getStatus(){let e=this.findActiveRun();return e?{success:!0,data:this.metaToState(e.slug,e.meta)}:{success:!1,error:`No active flow`}}reset(){let e=this.findActiveRun();return e?(e.meta.status=`abandoned`,e.meta.currentStep=null,e.meta.updatedAt=new Date().toISOString(),this.writeMeta(e.slug,e.meta),{success:!0}):{success:!0}}recordArtifact(e,t){let n=this.findActiveRun();return n?(n.meta.artifacts[e]=t,n.meta.updatedAt=new Date().toISOString(),this.writeMeta(n.slug,n.meta),{success:!0}):{success:!1,error:`No active flow`}}listRuns(e){if(!n(this.flowsDir))return[];let t=[];for(let n of a(this.flowsDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let r=this.readMeta(n.name);r&&(e?.flow&&r.flow!==e.flow||e?.status&&r.status!==e.status||t.push({id:n.name,flow:r.flow,topic:r.topic,status:r.status,currentStep:r.currentStep,startedAt:r.startedAt,updatedAt:r.updatedAt}))}return t.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}},q=class{createSymlinks(t,i,a,o){let s=this.getTargets(t,i);for(let t of s){n(t.baseDir)||r(t.baseDir,{recursive:!0});for(let r of o.agents){let i=p(a,r);if(!n(i))continue;let o=this.getAgentStem(r),s=p(t.baseDir,`${o}${t.extension}`);n(s)&&l(s);let u=m(f(s),i);try{c(u,s,`file`)}catch{try{e(i,s)}catch(e){console.warn(`Failed to create symlink or copy fallback for ${i}: ${e instanceof Error?e.message:String(e)}`)}}}}}removeSymlinks(e,t){let r=this.getTargets(e,t);for(let e of r)if(n(e.baseDir))try{let t=a(e.baseDir,{withFileTypes:!0});for(let n of t)!n.isFile()&&!n.isSymbolicLink()||l(p(e.baseDir,n.name));a(e.baseDir).length===0&&s(e.baseDir)}catch{}}getTargets(e,t){return[{ide:`copilot`,baseDir:p(e,`.github`,`agents`,`flows`,t),extension:`.agent.md`},{ide:`claude-code`,baseDir:p(e,`.claude`,`agents`,`flows`,t),extension:`.md`}]}getAgentStem(e){return d(e).replace(/\.agent\.md$/,``).replace(/\.md$/,``)}};export{C as ClaudePluginAdapter,w as CopilotAdapter,U as FlowLoader,G as FlowRegistryManager,K as FlowStateMachine,N as FoundationIntegration,z as GitInstaller,T as NativeAdapter,E as OpenSpecAdapter,q as SymlinkManager,k as getBuiltinFlows};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./curated-manager-DX-_oJg0.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-C5IU9Lau.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-0OCkdgRe.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-
|
|
1
|
+
import{t as e}from"./curated-manager-DX-_oJg0.js";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{parseArgs as o}from"node:util";import{createLogger as s,serializeError as c}from"../../core/dist/index.js";const l=n(i(import.meta.url)),u=(()=>{try{let e=r(l,`..`,`..`,`..`,`package.json`);return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}})(),d=s(`server`);function f(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}const{values:p}=(()=>{let e=process.argv[1];if(!e)return!1;try{return import.meta.url===a(e).href}catch{return!1}})()?o({allowPositionals:!0,options:{transport:{type:`string`,default:f()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}):{values:{transport:f(),port:process.env.AIKIT_PORT??`3210`}};async function m(){if(process.on(`unhandledRejection`,e=>{d.error(`Unhandled rejection`,c(e))}),d.info(`Starting MCP AI Kit server`,{version:u}),p.transport===`http`){let[{default:e},{loadConfig:t,resolveIndexMode:n},{registerDashboardRoutes:r,resolveDashboardDir:i},{registerSettingsRoutes:a,resolveSettingsDir:o},{createSettingsRouter:s}]=await Promise.all([import(`express`),import(`./config-C5IU9Lau.js`),import(`./dashboard-static-BfIe0Si1.js`),import(`./settings-static-BosGZSPf.js`),import(`./routes-0OCkdgRe.js`)]),l=t();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path});let u=e();u.use(e.json());let f=Number(p.port);u.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.AIKIT_CORS_ORIGIN??`http://localhost:${f}`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),r(u,i(),d);let m=new Date().toISOString();u.use(`/settings/api`,s({log:d,mcpInfo:()=>({transport:`http`,port:f,pid:process.pid,startedAt:m})})),a(u,o(),d),u.get(`/health`,(e,t)=>{t.json({status:`ok`})});let h=!1,g=null,_=null,v=null,y=Promise.resolve();u.post(`/mcp`,async(e,t)=>{if(!h||!_||!v){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let n=y,r;y=new Promise(e=>{r=e}),await n;try{let n=new v({sessionIdGenerator:void 0});await _.connect(n),await n.handleRequest(e,t,e.body),n.close()}catch(e){if(d.error(`MCP handler error`,c(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{r()}}),u.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),u.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let b=u.listen(f,`127.0.0.1`,()=>{d.info(`MCP server listening`,{url:`http://127.0.0.1:${f}/mcp`,port:f}),setTimeout(async()=>{try{let[{createLazyServer:e,ALL_TOOL_NAMES:t},{StreamableHTTPServerTransport:r},{checkForUpdates:i,autoUpgradeScaffold:a}]=await Promise.all([import(`./server-DyCYX0nU.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-AMfxaZUw.js`)]);i(),a();let o=n(l),s=e(l,o);_=s.server,v=r,h=!0,d.info(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:t.length,resourceCount:2}),s.startInit(),o===`auto`?s.ready.then(async()=>{try{let e=l.sources.map(e=>e.path).join(`, `);d.info(`Running initial index`,{sourcePaths:e}),await s.runInitialIndex(),d.info(`Initial index complete`)}catch(e){d.error(`Initial index failed; will retry on aikit_reindex`,c(e))}}).catch(e=>d.error(`AI Kit init or indexing failed`,c(e))):o===`smart`?s.ready.then(async()=>{try{if(!s.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`);g=new e(s.kb.indexer,l,s.kb.store),g.start(),s.setSmartScheduler(g),d.info(`Smart index scheduler started (HTTP mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit initialization failed`,c(e))):(s.ready.catch(e=>d.error(`AI Kit initialization failed`,c(e))),d.info(`Initial full indexing skipped in HTTP mode`,{indexMode:o}))}catch(e){d.error(`Failed to load server modules`,c(e))}},100)}),x=async e=>{d.info(`Shutdown signal received`,{signal:e}),g?.stop(),b.close(),_&&await _.close(),process.exit(0)};process.on(`SIGINT`,()=>x(`SIGINT`)),process.on(`SIGTERM`,()=>x(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:r},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-C5IU9Lau.js`),import(`./server-DyCYX0nU.js`),import(`./version-check-AMfxaZUw.js`),import(`@modelcontextprotocol/sdk/types.js`)]),l=e();d.info(`Config loaded`,{sourceCount:l.sources.length,storePath:l.store.path}),a(),o();let u=n(l),f=r(l,u),{server:p,startInit:m,ready:h,runInitialIndex:g}=f,{StdioServerTransport:_}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),v=new _;await p.connect(v),d.info(`MCP server started`,{transport:`stdio`});let y=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?i(n):n;return d.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(l,r),l.allRoots=e.map(e=>{let t=e.uri;return t.startsWith(`file://`)?i(t):t}),!0},b=!1;try{b=y((await p.server.listRoots()).roots),b||d.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){d.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...c(e)}),b=!0}b||=await new Promise(e=>{let t=setTimeout(()=>{d.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),e(!1)},5e3);p.server.setNotificationHandler(s,async()=>{clearTimeout(t);try{e(y((await p.server.listRoots()).roots))}catch(t){d.warn(`roots/list retry failed after notification`,c(t)),e(!1)}})}),m();let x=null,S=()=>{x&&clearTimeout(x),x=setTimeout(()=>{d.info(`Auto-shutdown: no activity for 30 minutes — exiting`),process.exit(0)},18e5),x.unref&&x.unref()};S(),process.stdin.on(`data`,()=>S()),h.catch(e=>{d.error(`Initialization failed — server will continue with limited tools`,c(e))}),u===`auto`?g().catch(e=>d.error(`Initial index failed`,c(e))):u===`smart`?h.then(async()=>{try{if(!f.kb)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(f.kb.indexer,l,f.kb.store);t.start(),f.setSmartScheduler(t),d.info(`Smart index scheduler started (stdio mode)`)}catch(e){d.error(`Failed to start smart index scheduler`,c(e))}}).catch(e=>d.error(`AI Kit init failed for smart scheduler`,c(e))):d.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:u})}}m().catch(e=>{d.error(`Fatal error`,c(e)),process.exit(1)});export{e as CuratedKnowledgeManager};
|