@vpxa/aikit 0.1.370 → 0.1.371
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/claude-desktop/dist/manifest.json +1 -1
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/index.js +2 -2
- package/packages/server/dist/{server-stdio-BwEcanZf.js → server-stdio-D4t_s4AF.js} +1 -1
- package/packages/server/dist/{workspace-bootstrap-B57Oz40_.js → workspace-bootstrap-CzMf5CGB.js} +1 -1
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"manifest_version": "0.3",
|
|
3
3
|
"name": "AI Kit",
|
|
4
4
|
"display_name": "AI Kit",
|
|
5
|
-
"version": "0.1.
|
|
5
|
+
"version": "0.1.371",
|
|
6
6
|
"description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "AnVPX",
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as n}from"node:util";import{HealthBus as r,createLogger as i,safeCwdOrHome as a,serializeError as o}from"../../core/dist/index.js";import{readFileSync as s}from"node:fs";import{dirname as c,isAbsolute as l,join as u,resolve as d}from"node:path";import{mkdir as f,readFile as p,readdir as m,stat as h,unlink as g,writeFile as _}from"node:fs/promises";import{createHash as v}from"node:crypto";import{GIT_REF_SLUG_PATTERN as y,gitAvailable as b,gitCommitToRef as x,gitExec as S,slugForRef as C}from"../../tools/dist/index.js";function w(){try{let t=d(c(e(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(s(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function T(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function E(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const D=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function O({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?D.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function k({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function A(t){return t.startsWith(`file://`)?e(t):t}function j(e){let t=d(e);return process.platform===`win32`?t.toLowerCase():t}function M(e){let t=new Map;for(let n of e){let e=A(n.uri);t.set(j(e),e)}return[...t.values()].sort((e,t)=>j(e).localeCompare(j(t)))}function N({config:e,roots:t}){let n=M(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=j(r),t=n.find(t=>j(t)===e);if(t)return t}return n[0]}function P({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=M(r);if(i.length===0)return!1;let a=N({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:o&&j(o)===j(a)?`configured-source`:`stable-sorted-root`}),n(e,a),e.allRoots=i,!0}async function F({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:s,server:c,startInit:l,timeoutMs:u=5e3,getCwd:d=()=>process.env.AIKIT_WORKSPACE_ROOT??a(),version:f=`0.0.0`}){let p=!1,m=!1,h,g=c.server,_=e=>{let t=o(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)||n.includes(`timed out`)},v=()=>{p||(p=!0,l())},y=()=>{m||t!==`auto`||(m=!0,(async()=>{try{await s()}catch(e){n.error(`Initial index failed`,{version:f,...o(e)})}})())}
|
|
2
|
+
import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as n}from"node:util";import{HealthBus as r,createLogger as i,safeCwdOrHome as a,serializeError as o}from"../../core/dist/index.js";import{readFileSync as s}from"node:fs";import{dirname as c,isAbsolute as l,join as u,resolve as d}from"node:path";import{mkdir as f,readFile as p,readdir as m,stat as h,unlink as g,writeFile as _}from"node:fs/promises";import{createHash as v}from"node:crypto";import{GIT_REF_SLUG_PATTERN as y,gitAvailable as b,gitCommitToRef as x,gitExec as S,slugForRef as C}from"../../tools/dist/index.js";function w(){try{let t=d(c(e(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(s(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function T(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function E(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const D=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function O({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?D.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function k({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function A(t){return t.startsWith(`file://`)?e(t):t}function j(e){let t=d(e);return process.platform===`win32`?t.toLowerCase():t}function M(e){let t=new Map;for(let n of e){let e=A(n.uri);t.set(j(e),e)}return[...t.values()].sort((e,t)=>j(e).localeCompare(j(t)))}function N({config:e,roots:t}){let n=M(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=j(r),t=n.find(t=>j(t)===e);if(t)return t}return n[0]}function P({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=M(r);if(i.length===0)return!1;let a=N({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:o&&j(o)===j(a)?`configured-source`:`stable-sorted-root`}),n(e,a),e.allRoots=i,!0}async function F({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:s,server:c,startInit:l,timeoutMs:u=5e3,getCwd:d=()=>process.env.AIKIT_WORKSPACE_ROOT??a(),version:f=`0.0.0`}){let p=!1,m=!1,h,g=c.server,_=e=>{let t=o(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)||n.includes(`timed out`)},v=()=>{p||(p=!0,l())},y=()=>{m||t!==`auto`||(m=!0,(async()=>{try{await s()}catch(e){n.error(`Initial index failed`,{version:f,...o(e)})}})())};v();let b=t=>t.length===0||(h&&=(clearTimeout(h),void 0),!P({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(v(),y(),!0);try{if(b((await g.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(t){if(_(t)){let r=e.sources?.[0]?.path;r?(n.debug(`MCP roots/list not supported; using configured source path`,{version:f,configuredRoot:r,cwd:d(),...o(t)}),v(),y()):(n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:f,cwd:d(),...o(t)}),P({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:d()}]})&&(v(),y()));return}n.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:f,cwd:d(),...o(t)})}g.setNotificationHandler(r,async()=>{try{b((await g.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,{version:f,...o(e)})}}),h=setTimeout(()=>{let t=e.sources?.[0]?.path;if(t)n.debug(`Timed out waiting for roots/list_changed; using configured source path`,{configuredRoot:t}),v(),y();else{let t=d();n.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),P({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(v(),y())}},u)}var I=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await f(this.baseDir,{recursive:!0})}async read(e){let t=u(this.baseDir,e);try{return await p(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=u(this.baseDir,e);await f(c(r),{recursive:!0}),await _(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=u(this.baseDir,e);try{return await g(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=u(this.baseDir,e),r;try{r=await m(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=u(this.baseDir,r);try{let e=await h(i);t.push({path:r,size:e.size,mtimeMs:e.mtimeMs})}catch{}}}return t}async exists(e){let t=u(this.baseDir,e);try{return await h(t),!0}catch{return!1}}async listDirectories(){try{return(await m(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}};const L=50*1024,R=`refs/aikit/knowledge`,z=i(`server`);var B=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new I(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.normalizeTags(r),a=this.slugify(e),o=await this.uniqueRelativePath(n,a),s=new Date().toISOString(),c={title:e,category:n,tags:i,created:s,updated:s,version:1,origin:`curated`,changelog:[{version:1,date:s,reason:`Initial creation`}]},l=this.serializeFile(t,c);try{await this.adapter.write(o,l,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${o}" — retry the operation`):e}return this.gitCommitKnowledge(o,l,`remember: ${e}\n\nCategory: ${n}\nTags: ${i.join(`, `)}`),await this.indexCuratedFileBestEffort(o,t,c,`remember`),{path:o}}async upsertAutoKnowledge(e,t,n,r,i=[],a=`Auto-knowledge refresh`){e=this.guardPath(e),this.validateCategoryName(r),this.validateContentSize(n),this.ensureCategoryPath(e,r);let o=this.normalizeTags(i),s=await this.adapter.read(e);if(s==null){let i=new Date().toISOString(),a={title:t,category:r,tags:o,created:i,updated:i,version:1,origin:`curated`,changelog:[{version:1,date:i,reason:`Initial creation`}]},s=this.serializeFile(n,a);try{await this.adapter.write(e,s,{exclusive:!0})}catch(t){throw t.code===`EEXIST`?Error(`Concurrent write collision for "${e}" — retry the operation`):t}return this.gitCommitKnowledge(e,s,`remember: ${t}\n\nCategory: ${r}\nTags: ${o.join(`, `)}`),await this.indexCuratedFileBestEffort(e,n,a,`remember`),{path:e,status:`created`,version:1}}let{frontmatter:c,content:l}=this.parseFile(s),u=this.normalizeTags(c.tags??[]),d=t.trim()||c.title;if(l===n&&c.category===r&&c.title===d&&this.sameTags(u,o))return{path:e,status:`unchanged`,version:c.version??1};let f=(c.version??1)+1,p=new Date().toISOString();c.title=d,c.category=r,c.tags=o,c.version=f,c.updated=p,c.changelog=[...c.changelog??[],{version:f,date:p,reason:a}];let m=this.serializeFile(n,c);return await this.adapter.write(e,m),this.gitCommitKnowledge(e,m,`update(v${f}): ${c.title}\n\nReason: ${a}\nVersion: ${f}`),await this.indexCuratedFileBestEffort(e,n,c,`update`),{path:e,status:`updated`,version:f}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{z.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...o(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!b(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=S([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
|
|
3
3
|
`).filter(Boolean).map(e=>{let[t,n,...r]=e.split(`|`);return{sha:t,date:n,message:r.join(`|`)}}):[]}async diff(e,t,n){if(e=this.guardPath(e),!b(this.curatedDir))return``;if(!n){let r=await this.history(e,2);if(r.length===0)return``;n=r[0].sha,r.length>1&&!t&&(t=r[1].sha)}return t&&n?S([`diff`,`${t}:entry.md`,`${n}:entry.md`],this.curatedDir)??``:n?S([`show`,`${n}:entry.md`],this.curatedDir)??``:``}async recover(e){if(e=this.guardPath(e),await this.adapter.exists(e))throw Error(`Entry already exists on filesystem: ${e}. Use update() instead.`);if(!b(this.curatedDir))return null;let t=this.knowledgeRefForPath(e);if(!t)return null;let n=S([`show`,`${t}:entry.md`],this.curatedDir);if(!n)return null;await this.adapter.write(e,n);let{frontmatter:r,content:i}=this.parseFile(n);return await this.indexCuratedFile(e,i,r),{path:e,version:r.version??1}}async listOrphaned(){if(!b(this.curatedDir))return[];let e=S([`for-each-ref`,`--format=%(refname)|%(subject)`,`${R}/`],this.curatedDir);if(!e)return[];let t=[];for(let n of e.split(`
|
|
4
4
|
`).filter(Boolean)){let[e,...r]=n.split(`|`),i=r.join(`|`),a=`${e.replace(`${R}/`,``)}.md`;await this.adapter.exists(a)||t.push({ref:e,path:a,lastMessage:i})}return t}async read(e){e=this.guardPath(e);let t=await this.adapter.read(e);if(t==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:n,content:r}=this.parseFile(t),i=e.split(`/`)[0];return{path:e,title:n.title??e,category:i,tags:n.tags??[],version:n.version??1,created:n.created??``,updated:n.updated??``,contentPreview:r.slice(0,200),content:r}}async list(e){return(await this.listPage(e)).entries}async listPage(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);for(let r of t)n.push({path:r.path,category:e,mtimeMs:r.mtimeMs??0})}let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit),a=(e?.order??`asc`)===`desc`?-1:1,o=e?.orderBy??`path`;if(o===`path`||o===`updated`){let t=this.sortCandidateMetadata(n,o,a);if(e?.tag){let n=i==null?void 0:r+i+1,{entries:a,scannedAll:o}=await this.readCandidateEntries(t,{tag:e.tag,maxMatches:n}),s=i==null?a.slice(r):a.slice(r,r+i),c=i!=null&&(a.length>r+s.length||!o);return{entries:s,totalCount:o?a.length:r+s.length+ +!!c,totalCountIsExact:o,limit:i,offset:r,hasMore:c}}let s=i==null?t.slice(r):t.slice(r,r+i),{entries:c}=await this.readCandidateEntries(s);return{entries:c,totalCount:t.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+c.length<t.length}}let{entries:s}=await this.readCandidateEntries(n,{tag:e?.tag}),c=s.sort((e,t)=>{switch(o){case`created`:return(Date.parse(e.created)-Date.parse(t.created))*a;case`updated`:return(Date.parse(e.updated)-Date.parse(t.updated))*a;case`path`:return e.path.localeCompare(t.path)*a;default:return 0}}),l=i==null?c.slice(r):c.slice(r,r+i);return{entries:l,totalCount:c.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+l.length<c.length}}async count(e){if(e?.tag)return(await this.listPage({...e,limit:void 0})).totalCount;let t=e?.category?[e.category]:await this.discoverCategories(),n=0;for(let e of t)n+=(await this.adapter.list(e)).length;return n}async listPaths(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);n.push(...t.map(e=>e.path))}n.sort((e,t)=>e.localeCompare(t));let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit);return i==null?n.slice(r):n.slice(r,r+i)}sortCandidateMetadata(e,t,n){return[...e].sort((e,r)=>t===`updated`?(e.mtimeMs-r.mtimeMs)*n:e.path.localeCompare(r.path)*n)}async readCandidateEntries(e,t){let n=[];for(let r of e){let e=await this.adapter.read(r.path);if(e==null)continue;let{frontmatter:i,content:a}=this.parseFile(e),o=i.tags??[];if(!(t?.tag&&!o.includes(t.tag))&&(n.push({path:r.path,title:i.title??r.path,category:r.category,tags:o,version:i.version??1,created:i.created??``,updated:i.updated??``,contentPreview:a.slice(0,200)}),t?.maxMatches!=null&&n.length>=t.maxMatches))return{entries:n,scannedAll:!1}}return{entries:n,scannedAll:!0}}async reindexAll(){let e=await this.discoverCategories(),t=[],n=[];for(let r of e){let e=await this.adapter.list(r);for(let r of e){let e=r.path;try{let r=await this.adapter.read(e);if(r==null){t.push(`${e}: read failed`);continue}let{frontmatter:i,content:a}=this.parseFile(r);n.push({relativePath:e,content:a,frontmatter:i})}catch(n){z.error(`Failed to read curated file`,{relativePath:e,...o(n)}),t.push(`${e}: read failed`)}}}if(n.length===0)return{indexed:0,errors:t};let r=new Date().toISOString(),i=0;for(let e=0;e<n.length;e+=16){let a=n.slice(e,e+16);i+=await this.embedAndUpsertBatch(a,r,t)}return{indexed:i,errors:t}}async embedAndUpsertBatch(e,t,n){try{let r=await this.embedder.embedBatch(e.map(e=>e.content)),i=e.map(e=>{let n=`.ai/curated/${e.relativePath}`;return{id:this.hashId(n,0),content:e.content,sourcePath:n,contentType:`curated-knowledge`,headingPath:e.frontmatter.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.content.split(`
|
|
5
5
|
`).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){z.error(`Failed to upsert curated batch`,{batchSize:e.length,...o(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return z.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...o(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;z.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...o(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!b(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;x(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!b(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;S([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>C(e)).join(`/`);return t.split(`/`).every(e=>y.test(e))?`${R}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,i as t,n,r,t as i}from"./server-utils-De-aZNQa.js";import{n as a,r as o,t as s}from"./workspace-bootstrap-
|
|
1
|
+
import{a as e,i as t,n,r,t as i}from"./server-utils-De-aZNQa.js";import{n as a,r as o,t as s}from"./workspace-bootstrap-CzMf5CGB.js";import{t as c}from"./curated-manager-CBKTmAjM.js";import{pathToFileURL as l}from"node:url";import{parseArgs as u}from"node:util";import{createLogger as d,serializeError as f}from"../../core/dist/index.js";import{join as p,resolve as m}from"node:path";import{mkdir as h,writeFile as g}from"node:fs/promises";function _(e){if(!e.meta?.title)return`# Diagram
|
|
2
2
|
|
|
3
3
|
*Missing metadata*
|
|
4
4
|
`;if(!e.diagram_type)return`# Diagram
|
|
@@ -351,4 +351,4 @@ svg text{fill:var(--body);font-family:var(--sans);font-size:12px}
|
|
|
351
351
|
<\/script>
|
|
352
352
|
</body>
|
|
353
353
|
</html>`}const U=`<!-- DIAGRAM:SVG -->`;function W(e){let t=e.indexOf(U);if(t===-1)return null;let n=t+20,r=e.indexOf(U,n);if(r===-1)return null;let i=e.slice(n,r).trim();if(i.startsWith(`<svg`))return i;let a=e.slice(Math.max(0,t),r+20),o=a.match(/viewBox="([^"]+)"/),s=o?o[1]:`0 0 1200 800`,c=a.match(/width="(\d+)"/),l=c?c[1]:`1200`,u=a.match(/height="(\d+)"/);return[`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${s}" width="${l}" height="${u?u[1]:`800`}">`,` <defs>`,` <style>`,` text { font-family: system-ui, -apple-system, sans-serif; }`,` .title { font-size: 20px; font-weight: 600; fill: #fff; }`,` .subtitle { font-size: 14px; fill: #94a3b8; }`,` </style>`,` </defs>`,i,`</svg>`].join(`
|
|
354
|
-
`)}function he(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function ge(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=he(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=W(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const G=10*1024*1024,K=2e3;function _e(e){try{return JSON.stringify(e)}catch{return``}}function ve(e){switch(e.diagram_type){case`architecture`:return ae(e);case`workflow`:return H(e);case`sequence`:return R(e);case`dataflow`:return ce(e);case`lifecycle`:return P(e)}}function q(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s,detailData:c}=ve(e),l=c&&Object.keys(c).length>0?`\n<script id="diagram-node-data" type="application/json">${_e(c)}<\/script>`:``,u=e.meta?.palette===`warm`?`warm`:`technical`;return{html:me().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,u===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s).replace(`</body>`,`${l}\n</body>`),markdown:a?_(e):void 0}}function ye(e,t={}){return q(e,{...t,dualOutput:!1}).html}function be(e){return _(e)}function xe(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>G)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${G/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>K)throw Error(`Too many edges/connections: ${a.length} (max ${K})`)}function Se(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ce(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function we(){return Ce()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function Te(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=we();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-BOP-H7O4.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-
|
|
354
|
+
`)}function he(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function ge(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=he(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=W(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const G=10*1024*1024,K=2e3;function _e(e){try{return JSON.stringify(e)}catch{return``}}function ve(e){switch(e.diagram_type){case`architecture`:return ae(e);case`workflow`:return H(e);case`sequence`:return R(e);case`dataflow`:return ce(e);case`lifecycle`:return P(e)}}function q(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s,detailData:c}=ve(e),l=c&&Object.keys(c).length>0?`\n<script id="diagram-node-data" type="application/json">${_e(c)}<\/script>`:``,u=e.meta?.palette===`warm`?`warm`:`technical`;return{html:me().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,u===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s).replace(`</body>`,`${l}\n</body>`),markdown:a?_(e):void 0}}function ye(e,t={}){return q(e,{...t,dualOutput:!1}).html}function be(e){return _(e)}function xe(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>G)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${G/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>K)throw Error(`Too many edges/connections: ${a.length} (max ${K})`)}function Se(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ce(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function we(){return Ce()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function Te(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=we();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-BOP-H7O4.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-D4t_s4AF.js`);await e(n)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,ge as exportDiagram,W as extractSvg,n as getSessionIdHeader,Te as main,r as readPositiveIntEnv,t as readVersion,ye as renderHtml,be as renderMd,q as renderToResult,e as resolveCorsOrigin,Se as sanitizeTitle,o as selectWorkspaceRoot,xe as validate};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./workspace-bootstrap-
|
|
1
|
+
import{n as e}from"./workspace-bootstrap-CzMf5CGB.js";import{n as t,t as n}from"./startup-maintenance-CT6Z3734.js";import{t as r}from"./repair-json-B6Q_HRoP.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return s.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-D3rRPB9X.js`),import(`./server-B6T0DJPk.js`),import(`./version-check-C7xqQr9o.js`),import(`@modelcontextprotocol/sdk/types.js`)]),h=i();o(h.logging?.errorDetails===!0),h.configError&&s.warn(`Config load failure`,{error:h.configError}),s.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path}),p(),setInterval(f,1440*60*1e3).unref();let g=u(h),_=d(h,g),{server:v,startInit:y,ready:b,runInitialIndex:x}=_,{StdioServerTransport:S}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),C=new S;if(typeof C._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);C._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await v.connect(C),s.debug(`MCP server started`,{transport:`stdio`}),await e({config:h,indexMode:g,log:s,rootsChangedNotificationSchema:m,reconfigureForWorkspace:l,runInitialIndex:x,server:v,startInit:y,version:r});let w=null,T=null,E=!1,D=async e=>{E||(E=!0,s.info(`Shutdown signal received`,{signal:e}),w&&=(clearTimeout(w),null),T?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await C.close().catch(()=>void 0),await v.close().catch(()=>void 0),_.aikit&&await Promise.all([_.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),_.aikit.graphStore.close().catch(()=>{}),_.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),_.aikit.store.close().catch(()=>{})]),process.exit(0))},O=()=>{w&&clearTimeout(w),w=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=_.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),w.unref&&w.unref()};O(),process.stdin.on(`data`,()=>O()),process.stdin.on(`end`,()=>void D(`stdin-end`)),process.stdin.on(`close`,()=>void D(`stdin-close`)),process.stdin.on(`error`,()=>void D(`stdin-error`)),process.on(`SIGINT`,()=>void D(`SIGINT`)),process.on(`SIGTERM`,()=>void D(`SIGTERM`)),b.catch(e=>{s.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),g===`smart`?b.then(async()=>{try{if(!_.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(_.aikit.indexer,h,_.aikit.store);T=t;let n=_.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),_.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:g}),n(b,()=>_.aikit?{curated:_.aikit.curated,stateStore:_.aikit.stateStore}:null,r)}export{l as startStdioMode};
|
package/packages/server/dist/{workspace-bootstrap-B57Oz40_.js → workspace-bootstrap-CzMf5CGB.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fileURLToPath as e}from"node:url";import{safeCwdOrHome as t,serializeError as n}from"../../core/dist/index.js";import{resolve as r}from"node:path";function i(t){return t.startsWith(`file://`)?e(t):t}function a(e){let t=r(e);return process.platform===`win32`?t.toLowerCase():t}function o(e){let t=new Map;for(let n of e){let e=i(n.uri);t.set(a(e),e)}return[...t.values()].sort((e,t)=>a(e).localeCompare(a(t)))}function s({config:e,roots:t}){let n=o(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=a(r),t=n.find(t=>a(t)===e);if(t)return t}return n[0]}function c({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=o(r);if(i.length===0)return!1;let c=s({config:e,roots:i.map(e=>({uri:e}))});if(!c)return!1;let l=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:c,rootCount:i.length,selectedBy:l&&a(l)===a(c)?`configured-source`:`stable-sorted-root`}),n(e,c),e.allRoots=i,!0}async function l({config:e,indexMode:r,log:i,rootsChangedNotificationSchema:a,reconfigureForWorkspace:o,runInitialIndex:s,server:l,startInit:u,timeoutMs:d=5e3,getCwd:f=()=>process.env.AIKIT_WORKSPACE_ROOT??t(),version:p=`0.0.0`}){let m=!1,h=!1,g,_=l.server,v=e=>{let t=n(e),r=`${String(e)} ${String(t.message??``)}`.toLowerCase();return r.includes(`method not found`)||r.includes(`not supported`)||r.includes(`unsupported`)||r.includes(`unknown method`)||r.includes(`roots/list`)||r.includes(`timed out`)},y=()=>{m||(m=!0,u())},b=()=>{h||r!==`auto`||(h=!0,(async()=>{try{await s()}catch(e){i.error(`Initial index failed`,{version:p,...n(e)})}})())}
|
|
1
|
+
import{fileURLToPath as e}from"node:url";import{safeCwdOrHome as t,serializeError as n}from"../../core/dist/index.js";import{resolve as r}from"node:path";function i(t){return t.startsWith(`file://`)?e(t):t}function a(e){let t=r(e);return process.platform===`win32`?t.toLowerCase():t}function o(e){let t=new Map;for(let n of e){let e=i(n.uri);t.set(a(e),e)}return[...t.values()].sort((e,t)=>a(e).localeCompare(a(t)))}function s({config:e,roots:t}){let n=o(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=a(r),t=n.find(t=>a(t)===e);if(t)return t}return n[0]}function c({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=o(r);if(i.length===0)return!1;let c=s({config:e,roots:i.map(e=>({uri:e}))});if(!c)return!1;let l=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:c,rootCount:i.length,selectedBy:l&&a(l)===a(c)?`configured-source`:`stable-sorted-root`}),n(e,c),e.allRoots=i,!0}async function l({config:e,indexMode:r,log:i,rootsChangedNotificationSchema:a,reconfigureForWorkspace:o,runInitialIndex:s,server:l,startInit:u,timeoutMs:d=5e3,getCwd:f=()=>process.env.AIKIT_WORKSPACE_ROOT??t(),version:p=`0.0.0`}){let m=!1,h=!1,g,_=l.server,v=e=>{let t=n(e),r=`${String(e)} ${String(t.message??``)}`.toLowerCase();return r.includes(`method not found`)||r.includes(`not supported`)||r.includes(`unsupported`)||r.includes(`unknown method`)||r.includes(`roots/list`)||r.includes(`timed out`)},y=()=>{m||(m=!0,u())},b=()=>{h||r!==`auto`||(h=!0,(async()=>{try{await s()}catch(e){i.error(`Initial index failed`,{version:p,...n(e)})}})())};y();let x=t=>t.length===0||(g&&=(clearTimeout(g),void 0),!c({config:e,log:i,reconfigureForWorkspace:o,roots:t}))?!1:(y(),b(),!0);try{if(x((await _.listRoots()).roots))return;i.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(t){if(v(t)){let r=e.sources?.[0]?.path;r?(i.debug(`MCP roots/list not supported; using configured source path`,{version:p,configuredRoot:r,cwd:f(),...n(t)}),y(),b()):(i.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:p,cwd:f(),...n(t)}),c({config:e,log:i,reconfigureForWorkspace:o,roots:[{uri:f()}]})&&(y(),b()));return}i.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:p,cwd:f(),...n(t)})}_.setNotificationHandler(a,async()=>{try{x((await _.listRoots()).roots)}catch(e){i.warn(`roots/list retry failed after notification`,{version:p,...n(e)})}}),g=setTimeout(()=>{let t=e.sources?.[0]?.path;if(t)i.debug(`Timed out waiting for roots/list_changed; using configured source path`,{configuredRoot:t}),y(),b();else{let t=f();i.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),c({config:e,log:i,reconfigureForWorkspace:o,roots:[{uri:t}]})&&(y(),b())}},d)}export{l as n,s as r,c as t};
|